-
Notifications
You must be signed in to change notification settings - Fork 80
/
app.js
1983 lines (1696 loc) · 68.1 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable */
// set variables for environment
let express = require('express'),
extend = require('extend'), // equivalent of $.extend()
app = express(),
path = require('path'),
mmm = require('mmm'),
fs = require('fs'),
http = require('http'),
BASE_PATH = process.env.BASEPATH || '/',
fullBasePath = function (req) {
const fullPath = (`${req.protocol}://${req.headers.host.replace('/', '')}${BASE_PATH}`);
return fullPath;
},
getJSONFile = require(path.resolve(__dirname, 'demoapp', 'js', 'getJSONFile')),
packageJSON = getJSONFile(path.resolve('package.json'));
app.set('view engine', 'html');
app.set('views', [
path.join(__dirname, 'components'),
path.join(__dirname, 'views'),
]);
mmm.setEngine('hogan.js');
app.engine('html', mmm.__express);
// Because you're the type of developer who cares about this sort of thing!
app.enable('strict routing');
// Serve static assets
app.use(express.static('public')); // non-generated
app.use('/ids-css', express.static('./node_modules/ids-css/dist')); // ids-css
app.use(express.static(path.join('docs', 'static-website'))); // generated by building documentation
app.use(express.static('demoapp'));
app.use(express.static('dist', {
etag: false
})); // generated by build
// Create the express router with the same settings as the app.
const router = express.Router({
strict: true
});
// ===========================================
// Default Options / Custom Middleware
// ===========================================
const defaults = {
enableLiveReload: true,
layout: 'layout',
locale: 'en-US',
title: 'SoHo XI',
basepath: BASE_PATH,
version: packageJSON.version
};
// Option Handling - Custom Middleware
// Writes a set of default options the 'req' object. These options are always eventually passed to the HTML template.
// In some cases, these options can be modified based on query parameters. Check the default route for these options.
const optionHandler = function (req, res, next) {
res.opts = extend({}, defaults);
// Change Locale (which also changes right-to-left text setting)
if (req.query.locale && req.query.locale.length > 0) {
res.opts.locale = req.query.locale;
console.log(`Changing Route Parameter "locale" to be "${res.opts.locale}".`);
}
// Normally we will use an external file for loading SVG Icons and Patterns.
// Setting 'inlineSVG' to true will use the deprecated method of using SVG icons, which was to bake them into the HTML markup.
res.opts.inlineSVG = true;
// Global settings for forcing a 'no frills' layout for test pages.
// This means no header with page title, hamburger, theme swap settings, etc.
if (req.query.nofrills && req.query.nofrills.length > 0) {
res.opts.nofrillslayout = true;
console.log('"No-frills" layout active.');
}
// Set the theme and colorScheme
// Fx: http://localhost:4000/controls/modal?colors=9279a6,ffffff&theme=dark
if (req.query.theme && req.query.theme.length > 0) {
res.opts.theme = req.query.theme;
console.log(`Setting Theme to ${res.opts.theme}`);
} else {
res.opts.theme = 'light';
}
if (req.query.colors && req.query.colors.length > 0) {
res.opts.colors = req.query.colors;
console.log(`Setting Colors to ${res.opts.colors}`);
}
// Sets a simulated response delay for API Calls
if (req.query.delay && !isNaN(req.query.delay) && req.query.delay.length > 0) {
res.opts.delay = req.query.delay;
}
// Uses the minified version of the Soho library instead of the uncompressed version
if (req.query.minify && req.query.minify.length > 0) {
res.opts.minify = true;
console.log(`Using the minified version of "sohoxi.js"`);
}
if (req.query.font && req.query.font.length > 0) {
res.opts.font = req.query.font;
console.log(`Using the ${req.query.font} font`);
}
next();
};
// Simple Middleware that simulates a delayed response by setting a timeout before returning the next middleware.
const responseThrottler = function (req, res, next) {
if (!res.opts.delay) {
return next();
}
function delayedResponse() {
console.log('Delayed request continuing...');
return next();
}
console.log(`Delaying the response time of this request by ${res.opts.delay}ms...`);
setTimeout(delayedResponse, res.opts.delay);
};
// Simple Middleware that passes API data back as a template option if we're on a certain page
const globalDataHandler = function (req, res, next) {
const url = req.url;
function isComponentRoute(componentName) {
return new RegExp(componentName, 'g').test(url);
}
if (isComponentRoute('dropdown')) {
res.opts.dropdownListData = require(path.resolve('demoapp', 'js', 'getJunkDropdownData'));
}
next();
};
// Simple Middleware for logging some meta-data about the request to the console
const timestampLogger = function (req, res, next) {
console.log(`${Date.now()} - ${req.method}: ${req.url}`);
next();
};
// Simple Middleware for handling errors
const errorHandler = function (err, req, res, next) {
if (!err) {
return next();
}
console.error(err.stack);
if (res.headersSent) {
return next(err);
}
res.status(500).send(`<h2>Internal Server Error</h2><p>${err.stack}</p>`);
};
// place optionHandler() first to augment all 'res' objects with an 'opts' object
app.use(optionHandler);
app.use(globalDataHandler);
app.use(responseThrottler);
app.use(router);
app.use(timestampLogger);
app.use(errorHandler);
// Strips the '.html' from a file path and returns the target route name without it
function stripHtml(routeParam) {
const noHtml = routeParam.replace(/\.html/, '');
return noHtml;
}
function setHtml(routeParam) {
return `${stripHtml(routeParam)}.html`;
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
}
/**
* Checks the target file path for its type (is it a file, a directory, etc)
* http://stackoverflow.com/questions/15630770/node-js-check-if-path-is-file-or-directory
* @param {string} type - 'file' or 'folder'
* @param {string} filePath - a string representing the relative path of the item to be checked
* @returns {boolean}
*/
function is(type, filePath) {
let types = ['file', 'folder'],
defaultType = types[0],
mappings = {
file: { methodName: 'isFile' },
directory: { methodName: 'isDirectory' }
// TODO: Add More (symbolic link, etc)
};
if (!type) {
console.warn(`No type defined. Using the default type of "${defaultType}".`);
type = defaultType;
}
if (!mappings[type]) {
console.error(`Provided type "${type}" is not in the list of valid types.`);
return false;
}
// Add beginning slash if it doesn't exist
if (filePath.indexOf('/') !== 0) {
filePath = `/${filePath}`;
}
let targetPath = __dirname + filePath,
methodName = mappings[type].methodName;
try {
return fs.statSync(targetPath)[methodName]();
} catch (e) {
console.info(`File Path "${targetPath}" is not a ${type}.`);
return false;
}
}
/**
* Checks a path to see if it has a trailing slash.
* @param {string} path
* @returns {boolean}
*/
function hasTrailingSlash(path) {
if (!path || typeof path !== 'string') {
return false;
}
return path.substr(path.length - 1) === '/';
}
/**
* Filters an array of paths and detects if they actually exist
* @private
* @param {Object[]} pathDefs -
* @param {string} link -
* @param {string} directoryPrepender - prepends the "link" portion with a directory that is not processed by the filter
*/
function filterUnusablePaths(pathDefs, excludes, directoryPrepender) {
const truePaths = [];
if (excludes === undefined) {
excludes = [];
}
pathDefs.forEach((pathDef) => {
pathDef.link = pathDef.link.replace(/\/\//g, '/');
// console.log('Checking path: "' + pathDef.link + '"');
let match = false;
excludes.forEach((exclude) => {
if (pathDef.link.match(exclude)) {
match = true;
}
});
if (match) {
return;
}
// Add the directory into the link.
if (directoryPrepender) {
pathDef.link = directoryPrepender + pathDef.link;
}
truePaths.push(pathDef);
});
return truePaths;
}
/**
* @private
* @param {string} text
*/
function formatPath(text) {
return text.replace(/-/g, ' ').replace(/\.html/, '');
}
/**
* @private
* @param {object} pathDef
* @param {string} pathDef.link
* @param {string} pathDef.type
* @param {string} pathDef.labelColor
*/
function pathMapper(pathDef) {
let href = pathDef.link.replace(/\\/g, '/').replace(/\/\//g, '/'),
icon;
if (href.indexOf(BASE_PATH) !== 0) {
href = BASE_PATH + href;
}
if (is('directory', href.replace(BASE_PATH, ''))) {
icon = '#icon-folder';
if (href.charAt(href.length - 1) !== '/') {
href = `${href}/`;
}
}
const mappedPath = {
href,
text: formatPath(pathDef.link)
};
if (pathDef.text) {
mappedPath.text = pathDef.text;
}
if (icon) {
mappedPath.icon = icon;
}
if (pathDef.type && pathDef.type.length) {
mappedPath.pageType = pathDef.type;
mappedPath.labelColor = pathDef.labelColor || 'graphite07';
}
return mappedPath;
}
/**
* Excluded file names that should never appear in the DemoApp List Pages
*/
const GENERAL_LISTING_EXCLUDES = [
/(_)?(layout)(\s)?(\.html)?/gm, // matches any filename that begins with "layout" (fx: "layout***.html")
/footer\.html/,
/_header\.html/,
/(api.md$)/,
/(api.html$)/,
/partial/,
/functional/,
/unit/,
/\.DS_Store/
];
/**
* @private
* @param {string} type
*/
function getFolderContents(type, dir) { // type, dir, folderName
let paths = [];
try {
paths = fs.readdirSync(dir);
} catch (e) {
// Handle 'No Directory' errors
if (e.code === 'ENOENT') {
// console.log('No '+ folderName +' Folder found for "' + type + '');
paths = [];
} else {
throw e;
}
}
return paths;
}
/**
* Returns a listing of both "examples" and "tests" for a particular type of component.
* @param {string} type - the component/layout/pattern type
* @param {object} req
* @param {object} res
* @param {function} next
* @param {array} [extraExcludes]
* @returns {?}
*/
function getFullListing(type, req, res, next, extraExcludes) {
let allPaths = [],
componentPaths,
testPaths;
if (!extraExcludes) {
extraExcludes = [];
}
// Add Component-specific file name filters
// (\D|\W|\S).*?('+ type +')\.(html)+ - pick up all files that end with 'type' before the extension.
extraExcludes = extraExcludes.concat([
new RegExp(`[^-](_)?(${type})\.(html)`),
new RegExp('(\d|\w|\s|-)*?\.(scss|js|md)')
]);
function componentTextFormatter(path) {
path = path.replace('test-', '').replace('example-', '');
return formatPath(path);
}
// Search the "/components/<type>" folder for all tests/examples located here
componentPaths = getFolderContents(type, `components/${type}/`, 'Components');
componentPaths.forEach((path, i) => {
const isTest = path.substr(0, 5) === 'test-';
componentPaths[i] = {
text: componentTextFormatter(path),
link: `components/${type}/${path}`,
type: isTest ? 'test' : 'example',
labelColor: isTest ? 'azure07' : 'ruby07'
};
});
componentPaths = filterUnusablePaths(componentPaths, GENERAL_LISTING_EXCLUDES.concat(extraExcludes).concat([
/[^-.]index\.html/,
]));
// TODO: Handle the test paths the same way as before.
// Search the legacy "tests" folder for any relevant tests
testPaths = getFolderContents(type, `views/tests/${type}/`, 'Tests');
testPaths.forEach((path, i) => {
testPaths[i] = {
text: formatPath(path),
link: `tests/${type}/${path}`,
type: 'test',
labelColor: 'amber07'
};
});
testPaths = filterUnusablePaths(testPaths, GENERAL_LISTING_EXCLUDES.concat(extraExcludes));
// Combine the arrays and filter out the junk
allPaths = allPaths.concat(componentPaths).concat(testPaths);
const opts = extend({}, res.opts, {
subtitle: `All Examples & Tests for ${type}`,
paths: allPaths.map(pathMapper)
});
res.render('listing', opts);
next();
}
/**
* Returns a directory listing as page content with working links
* @param {string} directory
* @param {object} req
* @param {object} res
* @param {function} next
* @param {array} [extraExcludes] - List of files names to exclude
*/
function getDirectoryListing(directory, req, res, next, extraExcludes) {
if (!extraExcludes) {
extraExcludes = [];
}
fs.readdir(`./views/${directory}`, (err, paths) => {
if (err) {
// console.log(err);
res.render(err);
return next();
}
const strippedDir = hasTrailingSlash(directory) ? directory.substring(0, (directory.length - 1)) : directory;
// Strip out paths that aren't going to ever work
paths.forEach((path, i) => {
paths[i] = {
text: path,
link: path
};
});
const directoryPrepender = `/${strippedDir}/`;
paths = filterUnusablePaths(paths, GENERAL_LISTING_EXCLUDES.concat(extraExcludes), directoryPrepender);
const opts = extend({}, res.opts, {
subtitle: `Listing for ${directory}`,
paths: paths.map(pathMapper)
});
res.render('listing', opts);
next();
});
}
// ======================================
// Main Routing and Param Handling
// ======================================
router.get('/', (req, res, next) => {
const opts = res.opts;
opts.basepath = fullBasePath(req);
res.redirect(`${BASE_PATH}kitchen-sink`);
next();
});
router.get('/kitchen-sink', (req, res, next) => {
const opts = res.opts;
opts.basepath = fullBasePath(req);
res.render('kitchen-sink', res.opts);
next();
});
// ======================================
// Controls Section -> Now just in as a redirect
// ======================================
const controlOpts = {
layout: 'controls/layout',
subtitle: 'Style',
};
function defaultControlsRoute(req, res, next) {
const opts = extend({}, res.opts, controlOpts);
opts.subtitle = 'Full Index';
res.render('components/index', opts);
next();
}
router.get('/controls/:control', (req, res, next) => {
let controlName = '',
opts = extend({}, res.opts, controlOpts);
if (!req.params.control) {
return defaultControlsRoute(req, res, next);
}
controlName = stripHtml(req.params.control);
opts.subtitle = toTitleCase(controlName.charAt(0).toUpperCase() + controlName.slice(1).replace('-', ' '));
// Specific Changes for certain controls
opts.subtitle = opts.subtitle.replace('Contextualactionpanel', 'Contextual Action Panel');
if (controlName.indexOf('masthead') !== -1) {
opts.layout = 'controls/masthead-layout';
}
if (res.opts.nofrillslayout) {
opts.layout = 'tests/layout-noheader';
}
// Handle Redirects to new Structure
if (!fs.existsSync(`views/controls/${controlName}.html`)) {
if (controlName === 'buttons') {
controlName = 'button';
}
res.redirect(`${BASE_PATH}components/${controlName}/example-index`);
}
res.render(`controls/${controlName}`, opts);
next();
});
router.get('/controls/', defaultControlsRoute);
router.get('/controls', defaultControlsRoute);
// ======================================
// Components Section
// ======================================
const componentOpts = {
layout: 'layout',
subtitle: 'Style',
};
/**
* Detects the existence of a layout file inside of a subfolder that should be used
* instead of the default layout file in the root.
* @param {object} opts - Express's res.opts
* @param {string} component - the name of the component
* @returns {object}
*/
function addDefaultFolderLayout(opts, component) {
let layoutFileNames = ['_layout.html', 'layout.html'],
layoutPath;
for (let i = 0; i < layoutFileNames.length; i++) {
layoutPath = `components/${component}/${layoutFileNames[i]}`;
if (fs.existsSync(layoutPath)) {
opts.layout = stripHtml(`${component}/${layoutFileNames[i]}`);
console.log(`layout for this folder changed to "${opts.layout}".`);
}
}
return opts;
}
/**
* Reroutes '/components/{componentName}' and `/components/{componentName}/index` to
* the generated Docs folder.
*/
function defaultDocsRoute(req, res, next) {
const opts = extend({}, res.opts, componentOpts);
opts.layout = null;
opts.basepath = fullBasePath(req);
const componentName = stripHtml(req.params.component);
res.render(`${componentName}.html`, opts);
next();
}
/**
* Handles routing to the Components/Docs section.
*/
function componentRoute(req, res, next) {
let componentName = '';
let exampleName = '';
let opts = extend({}, res.opts, componentOpts);
opts.basepath = fullBasePath(req);
if (!req.params.component) {
return defaultDocsRoute(req, res, next);
}
componentName = stripHtml(req.params.component);
opts.subtitle = toTitleCase(componentName.charAt(0).toUpperCase() + componentName.slice(1).replace('-', ' '));
// If no example, end on the main component docs page.
if (!req.params.example) {
return defaultDocsRoute(req, res, next);
}
exampleName = req.params.example;
if (req.params.example !== undefined && exampleName.substr(0, 7) === 'partial') {
opts.layout = '';
}
if (exampleName === 'list') {
return getFullListing(componentName, req, res, next);
}
// Double check this folder for an alternative layout file.
opts = addDefaultFolderLayout(opts, componentName);
if (componentName === 'applicationmenu' && (exampleName.indexOf('example-') > -1 || exampleName.indexOf('test-') > -1)) {
opts.layout = null;
}
if (componentName === 'header') {
if (exampleName.indexOf('test-header-gauntlet') > -1) {
opts.layout = 'header/layout-header-gauntlet';
}
}
// Override any of these changes to layouts if the "No Frills" option was set by the user.
if (res.opts.nofrillslayout) {
opts.layout = 'tests/layout-noheader';
}
if (req.params.example !== undefined) {
res.render(`${componentName}/${req.params.example}`, opts);
}
next();
}
function reDirectSlashRoute(req, res, next) {
if (req.url.substr(-1) === '/' && req.url.length > 1) {
let componentName = stripHtml(req.params.component);
let exampleName = req.params.example;
if (exampleName !== undefined) {
res.render(301, `${fullBasePath(req) + componentName}/${exampleName}`);
}
res.redirect(301, fullBasePath(req) + componentName);
}
next();
}
// Redirect "/component/component{.html}" to "/component.html"
app.get('/components/:component', function(req, res, next) {
var compName = stripHtml(req.params.component);
res.redirect(`/components/${compName}.html`);
});
router.get('/components/:component/:example', componentRoute);
router.get('/components/:component/:example/', reDirectSlashRoute);
router.get('/components/', reDirectSlashRoute);
router.get('/components', defaultDocsRoute);
// ======================================
// Patterns Section
// ======================================
router.get('/patterns*', (req, res, next) => {
let opts = extend({}, res.opts, {
layout: 'patterns/layout',
subtitle: 'Patterns'
}),
end = req.url.replace(/\/patterns(\/)?/g, '');
// Don't capture any query params for the View Render
end = end.replace(/\?(.*)/, '');
if (!end || !end.length || end === '/') {
const exclude = [
'step-process.html',
'step-process-markup.html'
];
getDirectoryListing('patterns/', req, res, next, exclude);
return;
}
res.render(`patterns/${end}`, opts);
next();
});
// =========================================
// Test Pages
// =========================================
const testOpts = {
subtitle: 'Tests',
layout: 'tests/layout'
};
function testsRouteHandler(req, res, next) {
let opts = extend({}, res.opts, testOpts),
end = req.url.replace(/\/tests(\/)?/, '');
// remove query params for our checking
end = end.replace(/\?(.*)/, '');
if (!end || !end.length || end === '/') {
getDirectoryListing('tests/', req, res, next);
return;
}
let directory = `tests/${end}`;
if (hasTrailingSlash(directory)) {
if (is('directory', `/views/${directory}`)) {
getDirectoryListing(directory, req, res, next);
return;
}
directory = directory.substr(0, directory.length - 1);
}
// Custom configurations for some test folders
if (directory.match(/components\/base-tag/)) {
opts.usebasehref = true;
}
if (directory.match(/tests\/composite-form/)) {
opts.layout = 'tests/composite-form/_layout';
}
if (directory.match(/tests\/call-to-action-header/)) {
opts.layout = 'tests/call-to-action-header/layout';
}
if (directory.match(/tests\/distribution/)) {
opts.amd = true;
opts.layout = null; // No layout for this one on purpose.
opts.subtitle = 'AMD Tests';
}
if (directory.match(/tests\/datagrid-fixed-header/)) {
opts.layout = 'tests/layout-noscroll';
}
if (directory.match(/tests\/masthead/)) {
opts.layout = 'tests/masthead/layout';
}
if (directory.match(/tests\/place\/scrolling\/container-is-body/)) {
opts.layout = 'tests/place/scrolling/layout-body';
}
if (directory.match(/tests\/place\/scrolling\/container-is-nested/)) {
opts.layout = 'tests/place/scrolling/layout-nested';
}
if (directory.match(/tests\/signin/)) {
opts.layout = 'tests/layout-noheader';
}
if (directory.match(/tests\/tabs-module/)) {
opts.layout = 'tests/tabs-module/layout';
}
if (directory.match(/tests\/tabs-header/)) {
opts.layout = 'tests/tabs-header/layout';
}
if (directory.match(/tests\/tabs-vertical/)) {
opts.layout = 'tests/tabs-vertical/layout';
}
// Global 'no-header' layout setting takes precedent
if (res.opts.nofrillslayout || directory.match(/tests\/patterns/)) {
opts.layout = 'tests/layout-noheader';
}
// No trailing slash. Check for an index file. If no index file, do directory listing
if (is('directory', `/views/${directory}`)) {
if (is('file', `/views/${directory}/index`)) {
res.render(`${directory}/index`, opts);
return next();
}
getDirectoryListing(directory, req, res, next);
return;
}
// Handle Redirects to new Structure
let component = req.params.component,
example = req.params.example;
if (example && component) {
let path = `components/${component}/example-${setHtml(example)}`;
if (fs.existsSync(path)) {
res.redirect(BASE_PATH + path);
next();
return;
}
path = `components/${component}/test-${setHtml(example)}`;
if (fs.existsSync(path)) {
res.redirect(BASE_PATH + path);
next();
return;
}
}
res.render(directory, opts);
next();
}
// Tests Index Page and controls sub pages
router.get('/tests/:component/:example', testsRouteHandler);
router.get('/tests/:component/', testsRouteHandler);
router.get('/tests/:component', testsRouteHandler);
router.get('/tests/', testsRouteHandler);
router.get('/tests', testsRouteHandler);
// =========================================
// Layouts Pages
// =========================================
const layoutOpts = {
subtitle: 'Layouts',
layout: 'layouts/layout'
};
function defaultLayoutRouteHandler(req, res, next) {
const exclude = [
'_masthead.html',
'header-only.html',
'header-scroll.html',
'header-sticky.html'
];
getDirectoryListing('layouts/', req, res, next, exclude);
}
function layoutRouteHandler(req, res, next) {
let pageName = '',
opts = extend({}, res.opts, layoutOpts),
layout = req.params.layout;
if (!layout || !layout.length) {
return defaultLayoutRouteHandler(req, res, next);
}
pageName = stripHtml(req.params.layout);
opts.subtitle = toTitleCase(pageName.charAt(0).toUpperCase() + pageName.slice(1).replace('-', ' '));
res.render(`layouts/${layout}`, opts);
next();
}
router.get('/layouts/:layout', layoutRouteHandler);
router.get('/layouts', defaultLayoutRouteHandler);
// =========================================
// Examples Pages
// =========================================
const exampleOpts = {
subtitle: 'Examples',
layout: 'examples/layout'
};
function exampleRouteHandler(req, res, next) {
let opts = extend({}, res.opts, exampleOpts),
folder = req.params.folder,
example = req.params.example,
path = req.url;
// A missing category means both no category and no test page. Simply show the directory listing.
if (!folder || !folder.length) {
getDirectoryListing('examples/', req, res, next);
return;
}
// A missing testpage with a category defined will either:
// - Show a directory listing if there is no test page associated with the current path
// - Show a test page
if (!example || !example.length) {
if (hasTrailingSlash(path)) {
if (is('directory', `examples/${folder}/`)) {
getDirectoryListing(`examples/${folder}/`, req, res, next);
return;
}
}
res.render(`examples/${folder}`, opts);
next();
return;
}
// if testpage and category are both defined, should be able to show a valid testpage
res.render(`examples/${folder}/${example}`, opts);
next();
}
router.get('/examples/:folder/:example', exampleRouteHandler);
router.get('/examples/:folder/', exampleRouteHandler);
router.get('/examples/:folder', exampleRouteHandler);
router.get('/examples/', exampleRouteHandler);
router.get('/examples', exampleRouteHandler);
// =========================================
// Collection of Performance Tests Pages
// =========================================
router.get('/performance-tests', (req, res, next) => {
let performanceOpts = { subtitle: 'Performance Tests' },
opts = extend({}, res.opts, performanceOpts);
res.render('performance-tests/index', opts);
next();
});
// =========================================
// Angular Support Test Pages
// =========================================
const angularOpts = {
subtitle: 'Angular',
layout: 'angular/layout'
};
router.get('/angular*', (req, res, next) => {
let opts = extend({}, res.opts, angularOpts),
end = req.url.replace(/\/angular(\/)?/, '');
if (!end || !end.length || end === '/') {
getDirectoryListing('angular/', req, res, next);
return;
}
res.render(`angular/${end}`, opts);
next();
});
// =========================================
// Fake 'API' Calls for use with AJAX-ready Controls
// =========================================
// Sample Json call that returns States
// Example Call: http://localhost:4000/api/states?term=al
router.get('/api/states', (req, res, next) => {
let states = [],
allStates = getJSONFile(path.resolve('demoapp', 'data', 'states.json'));
function done() {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(states));
next();
}
if (!req || !req.query || !req.query.term) {
states = allStates;
return done();
}
for (let i = 0; i < allStates.length; i++) {
if (allStates[i].label.toLowerCase().indexOf(req.query.term.toLowerCase()) > -1) {
states.push(allStates[i]);
}
}
done();
});
// Sample People
router.get('/api/people', (req, res, next) => {
const people = getJSONFile(path.resolve('demoapp', 'data', 'people.json'));
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(people));
next();
});
// Sample Product
router.get('/api/product', (req, res, next) => {
let products = getJSONFile(path.resolve('demoapp', 'data', 'products.json'));
if (req.query.limit) {
products = products.slice(0, req.query.limit);
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(products));
next();
});
// Sample Supplies
router.get('/api/supplies', (req, res, next) => {
const supplies = getJSONFile(path.resolve('demoapp', 'data', 'supplies.json'));