-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstyledoc.js
More file actions
1439 lines (1248 loc) · 55.3 KB
/
styledoc.js
File metadata and controls
1439 lines (1248 loc) · 55.3 KB
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
/**
* StyleDoc
* Parser and showcase generator for JavaDoc-like comments in CSS, LESS, SASS etc.
*
* @see https://github.com/thybzi/styledoc
* @author Evgeni Dmitriev <thybzi@gmail.com>
* @version 0.0.8
* @requires jQuery 1.11.1+ or 2.1.1+,
* or jQuery 1.7.x+ with Sizzle tokenize() exposed: https://github.com/jquery/sizzle/issues/242
* @requires mustache.js
* Inspired with concept idea of https://github.com/Joony/styledoc/
*
* @todo revise list of supported tags
* @todo more sophisticated applying of pseudo-class modifiers (instead of adding an attribute)?
* @todo spaces in selectors (better than wrapping to {})
* @todo enable multiple @example, applying to item best matching one
* @todo parent and sibling selectors
* @todo catch exceptions
* @todo optimize code
* @todo make more examples/demos
* @todo write more tests
* @todo hide methods that seem to be private?
*/
(function (root, factory) {
if ((typeof define === "function") && define.amd) {
// AMD
define(["jquery", "mustache"], function ($, Mustache) {
return factory(root, $, Mustache);
});
} else if ((typeof module !== "undefined") && module.exports) {
// Node, CommonJS-like
module.exports = factory(root, require("jquery"), require("mustache"));
} else {
// Browser globals (root is window)
root.styledoc = factory(root, root.jQuery, root.Mustache);
}
}(this, function (window, $, Mustache) {
"use strict";
var MODULE_VERSION = "0.0.8";
var TEMPLATES_SUBDIR = "templates/";
var LANGUAGE_SUBDIR = "language/";
var PREVIEW_DIR = "preview/";
var DEFAULT_PAGE_TITLE = "StyleDoc showcase";
var DEFAULT_LANGUAGE = "en";
var DEFAULT_DOCTYPE = "html5";
var DEFAULT_TEMPLATE = "default";
var DEFAULT_IFRAME_DELAY = 2000;
var DEFAULT_OUTPUT_DIR = "showcase/";
var DEFAULT_PHANTOMJS_VIEWPORT = "1280x800";
var SECTION_ANCHOR_PREFIX = "section_";
var ITEM_ANCHOR_PREFIX = "item_";
var styledoc = {};
styledoc.server_mode = !window.document; // @todo revise?
styledoc.templates_dir = undefined; // defined few lines below
styledoc.item_id_trim_underscores = true; // trim leading, heading and consecutive underscores in showcase item IDs
styledoc.states_modify_unique_attrs = true; // modify "id" and "for" attr values to preserve their uniqueness when generating states
styledoc.states_html_glue = "\n"; // @todo showcaseFile option?
// Vars for npm modules (var declaration should be on top-level of the function)
var jsdom,
fs,
path,
request,
chalk,
phantom;
if (styledoc.server_mode) {
// Connect required npm modules
jsdom = require("jsdom");
fs = require("fs-extra");
path = require("path");
request = require("request");
chalk = require("chalk");
// Prepare virtual DOM for jQuery
window = jsdom.jsdom().parentWindow;
$ = $(window);
// Check if phantom package is available
try {
phantom = require("phantom");
} catch (e) {
phantom = null;
}
// Set default template path for server mode
styledoc.templates_dir = path.dirname(module.filename) + "/" + TEMPLATES_SUBDIR;
} else {
// Set default template path for browser mode
styledoc.templates_dir = "js/styledoc/" + TEMPLATES_SUBDIR;
}
// tag_name: is_multiline // @todo set is_complex here
styledoc.known_tags = {
"$title": false, // block title
"$description": true, // block description
"section": false, // (legacy?)
"base": false, // base selector (e.g. .my-element)
"modifier": false, // CSS-selector based modifier for element (e.g .my-subclass)
"state": false, // a special kind of modifier, also added to each showcase item (e.g. :disabled or .active)
"pseudo": false, // (legacy) in this version, just an alias of @state
"example": true, // HTML to use in both code snippet and live preview
"markup": true, // (legacy) alias of @example
"presentation": true, // (legacy) alias of @example
"preview": true, // (legacy) alias of @example
"author": false, // author of code block (multiple instances allowed)
"version": false, // version of code block
"since": false, // code version element exists since
"deprecated": false, // beginning code version and/or reasons for element deprecating
"see": false, // link to external resource (multiple instances allowed)
"todo": false, // some matters to be improved within the code (multiple instances allowed)
"fixme": false // some things needed to be fixed within the code (multiple instances allowed)
};
/**
* Load and parse CSS file, creating showcase page
* @param {string} url URL or relative path to root CSS file
* @param {object} options
* @param {string} [options.output_dir="showcase/"] Path to showcase page directory, relative to current location (FS mode only)
* @param {string} [options.$container=$("body")] Root container for showcase in parent document (HTTP mode only)
* @param {string} [options.template="default"] Name of showcase page template
* @param {string} [options.language="en"] Language to apply when creating page
* @param {string} [options.doctype="html5"] Target doctype
* @param {string} [options.page_title="StyleDoc showcase"] Main title of showcase page (in HTTP mode document.title has priority)
* @param {string} [options.css_url_http] HTTP(S) path to CSS file to use in preview (detected automatically by default) (FS mode only)
* @param {number} [options.iframe_delay=2000] Delay (ms) before measuring iframe height
* @param {boolean} [options.use_phantomjs=false] Use PhantomJS to pre-measure iframes height (FS mode only)
* @param {string|object} [options.phantomjs_viewport="1280x800"] Viewport size for PhantomJS instances (FS mode only)
* @param {object} [options.phantomjs_noweak=false] Disable "weak" module usage for PhantomJS instances (FS mode only)
* @param {boolean} [options.silent_mode=false] Disable console messages (FS mode only)
* @param {number|number[]} [options.preview_padding] Padding value(s) for preview container (4 or [4, 8], or [4, 0, 12, 8] etc.)
* @param {string} [options.background_color] Background color CSS value for both main showcase page and preview iframe pages
* @returns {JQueryPromise<void>}
*/
styledoc.showcaseFile = function (url, options) {
var dfd = $.Deferred();
// Preprocess common options
options = options || {};
options.page_title = options.page_title || styledoc.getDefaultPageTitle();
options.template = options.template || styledoc.getDefaultTemplate();
options.language = options.language || styledoc.getDefaultLanguage();
options.doctype = options.doctype || styledoc.getDefaultDoctype();
options.iframe_delay = options.iframe_delay || styledoc.getDefaultIframeDelay();
// Preprocess mode-specific options, display welcome message, etc.
options = styledoc.getShowcaseFileInit()(url, options);
// Load CSS file including all imports, prepare data and create showcase
styledoc.loadFileRecursive(url).done(function (files_data) {
var showcase_data = styledoc.prepareShowcaseData(styledoc.extractDocsData(files_data));
var output = styledoc.getOutput();
output(showcase_data, url, options).done(function () {
dfd.resolve();
}).fail(function (e) {
dfd.reject(e);
});
}).fail(function (e) {
dfd.reject(e);
});
return dfd.promise();
};
/**
* Extract only styledocs data from loadFileRecursive result
* @param {object} files_data
* @returns {array}
*/
styledoc.extractDocsData = function (files_data) {
var result = [];
for (var i = 0; i < files_data.length; i++) {
result = result.concat(files_data[i].docs);
}
return result;
};
/**
* Prepare data for CSS file showcase items from styledocs data
* @param {array} docs_data
* @returns {array}
*/
styledoc.prepareShowcaseData = function (docs_data) {
var result = [],
used_section_anchors = [],
used_item_ids = [];
var i,
j,
parts,
modifier,
doc,
selector,
id,
item_data,
tag_data,
tag_name,
tag_content;
for (i = 0; i < docs_data.length; i++) {
doc = docs_data[i];
id = i + 1;
item_data = {
id: id,
section: null,
anchor_name: SECTION_ANCHOR_PREFIX + id,
title: null,
description: null,
base: null,
base_description: null,
example: null,
version: null,
author: [],
since: null,
is_deprecated: false,
deprecated_info: null,
see: [],
todo: [],
fixme: [],
states: [],
subitems: []
};
// Process item own properties
for (j = 0; j < doc.tags.length; j++) {
tag_data = doc.tags[j];
tag_name = tag_data[0];
tag_content = tag_data[1];
switch (tag_name) {
case "$title":
item_data.title = tag_content;
break;
case "$description":
item_data.description = tag_content;
break;
case "section":
parts = parseComplexContent(tag_content); // @todo "is_complex" in tags config, use in parseTag
item_data.section = parts[0];
item_data.title = item_data.title || parts[1];
item_data.anchor_name = SECTION_ANCHOR_PREFIX + item_data.section;
break;
case "base":
parts = parseComplexContent(tag_content);
item_data.base = parts[0];
item_data.base_description = parts[1];
item_data.title = item_data.title || parts[1];
break;
case "example":
case "markup":
case "presentation":
case "preview":
item_data.example = item_data.example || tag_content; // @todo multiple examples
break;
case "version":
case "since":
item_data[tag_name] = tag_content;
break;
case "deprecated":
item_data.is_deprecated = true;
item_data.deprecated_info = tag_content;
break;
case "author":
case "see":
case "todo":
case "fixme":
item_data[tag_name].push(tag_content);
break;
}
}
item_data.anchor_name = getUniqueSectionAnchor(item_data.anchor_name);
// Process states
for (j = 0; j < doc.tags.length; j++) {
tag_data = doc.tags[j];
tag_name = tag_data[0];
tag_content = tag_data[1];
switch (tag_name) {
case "state":
case "pseudo":
parts = parseComplexContent(tag_content);
item_data.states.push({
state: parts[0],
description: parts[1]
});
break;
}
}
if (item_data.base) {
// Create base showcase
selector = item_data.base;
id = getUniqueItemId(selector);
item_data.subitems.push({
id: id,
anchor_name: ITEM_ANCHOR_PREFIX + id,
base: item_data.base,
modifier: null,
selector: selector,
description: item_data.base_description || "",
//example: styledoc.htmlApplyStates(item_data.example, item_data.base, item_data.states),
example: styledoc.htmlApplyModifier(item_data.example, item_data.base, "", item_data.states)
});
// Process subitems
for (j = 0; j < doc.tags.length; j++) {
tag_data = doc.tags[j];
tag_name = tag_data[0];
tag_content = tag_data[1];
switch (tag_name) {
case "modifier":
parts = parseComplexContent(tag_content);
modifier = parts[0];
selector = item_data.base + modifier;
id = getUniqueItemId(selector);
item_data.subitems.push({
id: id,
anchor_name: ITEM_ANCHOR_PREFIX + id,
base: item_data.base,
modifier: modifier,
selector: selector,
description: parts[1],
example: styledoc.htmlApplyModifier(item_data.example, item_data.base, modifier, item_data.states)
});
break;
}
}
}
result.push(item_data);
}
/**
* Converts selector to ID and assures it is unique
* @param {string} selector
* @returns {string}
* @todo dry?
*/
function getUniqueItemId(selector) {
var base_id = selectorToId(selector),
id = base_id,
numeric_suffix = 0;
while (used_item_ids.indexOf(id) !== -1) {
id = base_id + "_" + ++numeric_suffix;
}
used_item_ids.push(id);
return id;
}
/**
* Assures section anchor to be unique
* @param {string} anchor
* @returns {string}
* @todo dry?
*/
function getUniqueSectionAnchor(anchor) {
var base_anchor = anchor,
numeric_suffix = 0;
while (used_section_anchors.indexOf(anchor) !== -1) {
anchor = base_anchor + "_" + ++numeric_suffix;
}
used_section_anchors.push(anchor);
return anchor;
}
function parseComplexContent(content) {
var mask_braces = /^\{([^\{\}]+)\}(\s+(\S[\S\s]*))?$/;
var mask_no_braces = /^(\S+)(\s+(\S[\S\s]*))?$/;
var mask = mask_braces.test(content) ? mask_braces : mask_no_braces; // @todo improve
var matches = content.match(mask);
return matches ? [ matches[1], matches[3] ] : [ undefined, undefined ];
}
function sortBySection(a, b) {
if (a.section < b.section) {
return -1;
} else if (a.section > b.section) {
return 1;
} else {
return 0;
}
}
result.sort(sortBySection);
return result;
};
/**
* Append state variants after base element HTML markup
* @param {string} html Input HTML markup
* @param {string} base CSS selector for base element
* @param {array} states List containing CSS selectors for states
* @returns {string}
*/
styledoc.htmlApplyStates = function (html, base, states) {
if (isArray(states) && states.length) {
var html_base = html,
result;
for (var i = 0; i < states.length; i++) {
result = styledoc.htmlApplyModifier(html_base, base, states[i].state, undefined, styledoc.states_modify_unique_attrs);
if (result) {
html += styledoc.states_html_glue + result;
}
}
}
return html;
};
/**
* Modify base element HTML markup by CSS selector
* @param {string} html Input HTML markup
* @param {string} base CSS selector for base element
* @param {string} modifier CSS selector to modify base element
* @param {array} states List containing CSS selectors for states
* @param {boolean} modify_unique_attrs Add suffix to any "id" or "for" attr value found within the code
* @returns {string}
*/
styledoc.htmlApplyModifier = function (html, base, modifier, states, modify_unique_attrs) {
var $wrapper = $("<styledoc-wrapper>").append(html); // @todo hardcode tag name
var $elem = $(base, $wrapper);
// Basic modify
var modify_by_selector = modifier && $elem.length;
if (modify_by_selector) {
var parsed = $.find.tokenize(modifier).pop();
var item,
attr_name,
attr_value;
for (var i = 0; i < parsed.length; i++) {
item = parsed[i];
attr_name = null;
attr_value = "";
switch (item.type) {
case "ID":
attr_name = "id";
attr_value = item.matches[0];
break;
case "CLASS":
attr_name = "class";
attr_value = item.matches[0];
break;
case "ATTR":
attr_name = item.matches[0];
attr_value = item.matches[2];
break;
case "PSEUDO":
attr_name = item.matches[0];
break;
}
if (attr_name === "class") {
$elem.addClass(attr_value);
} else if (attr_name) {
$elem.attr(attr_name, attr_value);
}
}
}
// Modify "id" and "for" attribute values for any child elements (if enabled)
if (modify_unique_attrs) {
// @todo assure real uniqueness
// @todo bad luck when base/modifier contain id selector (and possibly have elems with "for")
var suffix = "_" + selectorToId(modifier);
$.each([ "id", "for" ], function (i, attr_name) {
$("[" + attr_name + "]", $wrapper).each(function (j, elem) {
var $elem = $(elem);
var attr_value = $elem.attr(attr_name);
$elem.attr(attr_name, attr_value + suffix)
});
});
}
// If input HTML has been modified, saving these modifications
if (modify_by_selector || modify_unique_attrs) {
html = $wrapper.html();
}
// Post-process with custom modifier if exists
if (typeof styledoc.htmlApplyModifierCustom === "function") {
var result = styledoc.htmlApplyModifierCustom(html, base, modifier, $wrapper, $elem);
if (typeof result === "string") {
html = result;
}
}
// Apply states
html = styledoc.htmlApplyStates(html, base, states);
return html;
};
styledoc.htmlApplyModifierCustom = null; // @todo find a better way to modify example content?
/**
* Preprocess some options and display welcome message
* @param {string} css_url URL to CSS file (relative to current location)
* @param {object} options
* @param {string} [options.output_dir="showcase/"] Path to showcase page directory (relative to current location)
* @param {boolean} [options.silent_mode=false] Disable console messages
*/
styledoc.showcaseFileInitFs = function (css_url, options) {
var silent_mode = options.silent_mode = !!options.silent_mode;
var output_dir = options.output_dir || styledoc.getDefaultOutputDir();
options.output_dir = output_dir = ensureTrailingSlash(output_dir);
if (!silent_mode) {
console.log(chalk.yellow("\nStyleDoc v" + styledoc.getModuleVersion()));
console.log("Source CSS file: " + chalk.yellow(css_url));
console.log("Target directory: " + chalk.yellow(output_dir));
console.log("\nLoading source CSS...");
}
return options;
};
/**
* In future, may preprocess some options and display welcome message
* @param {string} css_url URL to CSS file (relative to current location)
* @param {object} options
*/
styledoc.showcaseFileInitHttp = function (css_url, options) {
return options;
};
/**
* Create showcase page from data provided (HTTP/browser mode)
* @param {object} showcase_data Showcase data to be output
* @param {string} css_url URL to CSS file (relative to showcase page or absolute)
* @param {object} options Some options are already preprocessed in previous methods
* @param {string} options.template Name of showcase page template
* @param {string} options.language Language to apply when creating page
* @param {string} options.doctype Target doctype
* @param {string} [options.$container=$("body")] Root container for showcase in parent document
* @param {string} options.page_title Main title of showcase page
* @param {number} options.iframe_delay Delay (ms) before measuring iframe height
* @param {number|number[]} [options.preview_padding] Padding value(s) for preview container (4 or [4, 8], or [4, 0, 12, 8] etc.)
* @param {string} [options.background_color] Background color CSS value for both main showcase page and preview iframe pages
* @returns {JQueryPromise<void>}
*/
styledoc.outputHttp = function (showcase_data, css_url, options) {
var dfd = $.Deferred();
var $container = options.$container || $("body");
var page_title = options.page_title;
var language = options.language;
var doctype = options.doctype;
var iframe_delay = options.iframe_delay;
var template_name = options.template;
var template_dir = styledoc.templates_dir + template_name + "/";
var css_url_preview;
if (isAbsolutePath(css_url)) {
css_url_preview = css_url;
} else {
css_url_preview = "//" + document.location.host + dirPath(document.location.pathname) + css_url;
}
var preview_container_style = getPreviewContainerStyle(options);
$("head").append('<link rel="stylesheet" href="' + template_dir + 'main.css">');
if (options.background_color) {
$("body").css("background-color", options.background_color);
}
var loadFile = styledoc.getLoader().loadFile;
var load_main_template = loadFile(template_dir + "main.mustache"); // @todo doctype?
var load_lang = loadFile(template_dir + LANGUAGE_SUBDIR + language + ".json", true);
$.when(load_main_template, load_lang).done(
function (main_template_jqdata, lang_data_jqdata) {
var main_template = main_template_jqdata[0];
var lang_data = lang_data_jqdata[0];
var main_content = Mustache.render(main_template, {
page_title: page_title,
lang: lang_data,
css_url: css_url_preview,
iframe_url: template_dir + PREVIEW_DIR + doctype + ".html",
items: showcase_data,
presenter: displayPreview
});
$container.append(main_content).trigger("complete");
dfd.resolve();
}
).fail(function (e) {
dfd.reject(e);
});
/**
* Remove all after the last slash in path
* @param {string} path
* @returns {string}
*/
function dirPath(path) {
return path.replace(/\/[^\/]*$/, "/");
}
function resizeIframe($iframe) {
var iframe_body = $iframe.contents().find("body")[0];
$iframe.height(iframe_body.offsetHeight);
$iframe.removeClass("loading"); // @todo hardcode class
}
// @todo optimize (this code vs. index.mustache code)
function displayPreview() {
var data = this;
$container.on("complete", function () {
var $iframe = $("iframe#preview_" + data.id);
if ($iframe.length) {
$iframe.load(function () {
var $contents = $iframe.contents();
$contents.find("head").append('<link rel="stylesheet" href="' + css_url_preview + '">');
$contents.find("#styledoc-container") // @todo hardcode id
.append(data.example)
.attr("style", preview_container_style);
var resizer = function () {
resizeIframe($iframe);
};
setTimeout(function () {
resizer();
$(window).resize(resizer);
}, iframe_delay);
});
}
});
}
return dfd.promise();
};
/**
* Create showcase page from data provided (Filesystem/NodeJS mode)
* @param {object} showcase_data Showcase data to be output
* @param {string} css_url URL to CSS file (relative to current location)
* @param {object} options Some options are already preprocessed in previous methods
* @param {string} options.template Name of showcase page template
* @param {string} options.language Language to apply when creating page
* @param {string} options.doctype Target doctype
* @param {string} options.page_title Main title of showcase page
* @param {string} options.output_dir Path to showcase page directory (relative to current location)
* @param {string} [options.css_url_http] HTTP(S) path to CSS file to use in preview (detected automatically by default) (FS mode only)
* @param {number} options.iframe_delay Delay (ms) before measuring iframe height
* @param {boolean} [options.use_phantomjs=false] Use PhantomJS to pre-measure iframes height (FS mode only)
* @param {string|object} [options.phantomjs_viewport="1280x800"] Viewport size for PhantomJS instances (FS mode only)
* @param {object} [options.phantomjs_noweak=false] Disable "weak" module usage for PhantomJS instances (FS mode only)
* @param {boolean} options.silent_mode Disable console messages
* @param {number|number[]} [options.preview_padding] Padding value(s) for preview container (4 or [4, 8], or [4, 0, 12, 8] etc.)
* @param {string} [options.background_color] Background color CSS value for both main showcase page and preview iframe pages
* @returns {JQueryPromise<void>}
*/
styledoc.outputFs = function (showcase_data, css_url, options) {
var dfd = $.Deferred();
var silent_mode = options.silent_mode;
if (!silent_mode) {
console.log("Source CSS loaded");
}
// Counting subitems to display
var items_count = showcase_data.length,
subitems_count = 0,
previews_count = 0,
previews_dfd = $.Deferred(),
i,
j,
subitem_data,
file_name,
file_path,
file_path_relative,
preview_content;
for (i = 0; i < items_count; i++) {
subitems_count += showcase_data[i].subitems.length;
}
// If no subitems found, exiting immediately
if (!subitems_count) {
if (!silent_mode) {
console.log(chalk.red("\nNo showcase data found in CSS, exiting\n"));
}
dfd.resolve(); // or reject?
return dfd.promise();
}
var page_title = options.page_title;
var language = options.language;
var doctype = options.doctype;
var iframe_delay = options.iframe_delay;
var use_phantomjs_requested = !!options.use_phantomjs;
var use_phantomjs_available = !!phantom;
var use_phantomjs = use_phantomjs_requested && use_phantomjs_available;
var phantomjs_viewport = convertViewportValue(options.phantomjs_viewport || styledoc.getDefaultPhantomjsViewport());
var phantomjs_noweak = !!options.phantomjs_noweak;
var output_dir = options.output_dir;
var preview_dir = output_dir + PREVIEW_DIR;
var template_name = options.template;
var template_dir = styledoc.templates_dir + template_name + "/";
var realpath = ensureTrailingSlash(fs.realpathSync("./"));
var css_url_preview;
if (isString(options.css_url_http)) {
css_url_preview = options.css_url_http;
} else if (isAbsolutePath(css_url)) {
css_url_preview = css_url;
} else {
css_url_preview = path.relative(realpath + preview_dir, realpath + css_url);
css_url_preview = css_url_preview.replace(/\\/g, "/"); // avoid backslashes on Windows
}
var preview_container_style = getPreviewContainerStyle(options);
var background_color = options.background_color;
if (!silent_mode) {
console.log("\nLoading resources...");
}
var loadFile = styledoc.getLoader().loadFile;
// @todo optimize (something better than: force_fs = true)
var load_index_template = loadFile(template_dir + "index.mustache", false, true);
var load_main_template = loadFile(template_dir + "main.mustache", false, true); // @todo doctype?
var load_preview_template = loadFile(template_dir + PREVIEW_DIR + doctype + ".mustache", false, true);
var load_lang = loadFile(template_dir + LANGUAGE_SUBDIR + language + ".json", true, true);
var mkdirs = mkdirp(preview_dir);
var copy_main_css = copy(template_dir + "main.css", output_dir + "main.css");
var copy_preview_css = copy(template_dir + "preview.css", output_dir + "preview.css");
$.when(load_index_template, load_main_template, load_preview_template, load_lang, mkdirs, copy_main_css, copy_preview_css).done(
function (index_template, main_template, preview_template, lang_data) {
if (!silent_mode) {
console.log("All resources loaded");
}
var items_count = showcase_data.length,
subitems_count = 0,
previews_count = 0,
previews_dfd = $.Deferred(),
i,
j,
subitem_data,
file_name,
file_path,
file_path_relative,
preview_content;
for (i = 0; i < items_count; i++) {
subitems_count += showcase_data[i].subitems.length;
}
if (!silent_mode) {
console.log("\nCreating preview files (" + subitems_count + " total)");
}
for (i = 0; i < items_count; i++) {
for (j = 0; j < showcase_data[i].subitems.length; j++) {
subitem_data = showcase_data[i].subitems[j];
file_name = subitem_data.id + ".html";
file_path = preview_dir + file_name;
file_path_relative = PREVIEW_DIR + file_name;
preview_content = Mustache.render(preview_template, {
css_url: css_url_preview,
container_style: preview_container_style,
content: subitem_data.example
});
subitem_data.iframe_url = file_path_relative; // @todo use separate var without changing showcase_data?
(function (file_path, preview_content, subitem_data) {
fs.writeFile(
file_path,
preview_content,
function () {
if (!silent_mode) {
console.log(chalk.cyan("[CREATE] " + file_path));
}
// iframe delay mode
if (!use_phantomjs) {
countPreviewItem();
return;
}
// PhantomJS mode
phantom.create(function (ph) {
ph.createPage(function (page) {
page.set("viewportSize", phantomjs_viewport);
/**
* Only absolute paths work when opening local file in PhantomJS
* @see https://github.com/ariya/phantomjs/issues/10330
*/
page.open(fs.realpathSync(file_path), function (status) {
if (status !== "success") { // @todo also raise .fail()?
ph.exit(); // @todo is it needed?
throw new Error("Error opening " + file_path + ":\n\n" + status);
}
page.evaluate(
function () {
return document.body.offsetHeight;
},
function (body_height) {
subitem_data.iframe_height = body_height; // @todo use separate var without changing showcase_data?
if (!silent_mode) {
console.log(chalk.gray("[HEIGHT] " + file_path));
}
countPreviewItem();
ph.exit();
}
);
});
});
}, {
/** @see https://github.com/sgentle/phantomjs-node#use-it-in-windows */
dnodeOpts: {
weak: !phantomjs_noweak
}
});
}
);
})(file_path, preview_content, subitem_data);
}
}
function countPreviewItem() {
if (++previews_count === subitems_count) {
previews_dfd.resolve();
}
}
previews_dfd.done(function () {
if (!silent_mode) {
if (use_phantomjs_requested && !use_phantomjs_available) {
console.log(chalk.red('Warning: "use_phantomjs" option ignored, because "phantom" package is not installed'));
}
console.log("All preview files created");
}
var main_content = Mustache.render(main_template, {
page_title: page_title,
lang: lang_data,
css_url: css_url,
items: showcase_data,
iframe_use_onload: !use_phantomjs // @todo unify with http mode
});
if (!silent_mode) {
console.log("\nCreating index file...");
}
fs.writeFile(
output_dir + "index.html",
Mustache.render(index_template, {
page_title: page_title,
background_color: background_color,
content: main_content,
iframe_use_onload: !use_phantomjs, // @todo unify with http mode
iframe_delay: iframe_delay // @todo unify with http mode
}),
function () {
if (!silent_mode) {
console.log(chalk.cyan("[CREATE] " + output_dir + "index.html"));
console.log("Index file created");
console.log(chalk.green("\nAll done!\n"));
}
dfd.resolve();
}
);
});
}
).fail(function (e) {
dfd.reject(e);
});
/**
* Convert "WIDTHxHEIGHT" string input to { width: WIDTH, height: HEIGHT }
* Validate and normalize any object input
* Returns undefined for any bad (unconvertable) input
* @param {string|object} value
* @returns {{ width: {number}, height: {number} } | undefined}
*/
function convertViewportValue(value) {
var mask = /^(\d+)x(\d+)$/,
matches;
if (isString(value) && mask.test(value)) {
matches = value.match(mask);
return {
width: toInteger(matches[1]),
height: toInteger(matches[2])
};
} else if (isRegularObject(value) &&
value.hasOwnProperty("width") && (value.width >= 1) &&
value.hasOwnProperty("height") && (value.height >= 1)
) {
return {
width: toInteger(value.width),
height: toInteger(value.height)
};
} else {
return undefined;
}
}
function mkdirp(path) {
var dfd = $.Deferred();
fs.mkdirs(path, function (error) {
if (error) { // @todo also raise .fail()?
throw new Error("Error loading " + url + ":\n\n" + error);
}
dfd.resolve();
});
return dfd.promise();
};
function copy(src, dest) {
var dfd = $.Deferred();
fs.copy(src, dest, function (error) {
if (error) { // @todo also raise .fail()?
throw new Error("Error loading " + url + ":\n\n" + error);
}
dfd.resolve();
});
return dfd.promise();
};
return dfd.promise();
};
/**
* File loading transport interface for HTTP/browser mode
*/
styledoc.loaderHttp = {
/**
* @param {string} url
* @param {boolean} [is_json=false]
* @returns {JQueryPromise<string|object>}
*/
loadFile: function(url, is_json) {
return $.ajax({
url: url,
dataType: is_json ? "json" : "text",
error: function(jqXHR, textStatus, errorThrown) { // @todo catch
throw new Error("Error loading " + url + ":\n\n" + errorThrown);
}
});
}
};
/**
* File loading transport interface for Filesystem/NodeJS mode
*/
styledoc.loaderFs = {
/**
* @param {string} url
* @param {boolean} [is_json=false]
* @param {boolean} [force_fs=false]
* @returns {JQueryPromise<string|object>}
*/