-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathless.js
10832 lines (9599 loc) · 372 KB
/
less.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
/*!
* Less - Leaner CSS v2.7.2
* http://lesscss.org
*
* Copyright (c) 2009-2017, Alexis Sellier <[email protected]>
* Licensed under the Apache-2.0 License.
*
*/
/** * @license Apache-2.0
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.less = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var addDataAttr = require("./utils").addDataAttr,
browser = require("./browser");
module.exports = function(window, options) {
// use options from the current script tag data attribues
addDataAttr(options, browser.currentScript(window));
if (options.isFileProtocol === undefined) {
options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
}
// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
// doesn't start loading before the stylesheets are parsed.
// Setting this to `true` can result in flickering.
//
options.async = options.async || false;
options.fileAsync = options.fileAsync || false;
// Interval between watch polls
options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
options.env = options.env || (window.location.hostname == '127.0.0.1' ||
window.location.hostname == '0.0.0.0' ||
window.location.hostname == 'localhost' ||
(window.location.port &&
window.location.port.length > 0) ||
options.isFileProtocol ? 'development'
: 'production');
var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
if (dumpLineNumbers) {
options.dumpLineNumbers = dumpLineNumbers[1];
}
if (options.useFileCache === undefined) {
options.useFileCache = true;
}
if (options.onReady === undefined) {
options.onReady = true;
}
};
},{"./browser":3,"./utils":10}],2:[function(require,module,exports){
/**
* Kicks off less and compiles any stylesheets
* used in the browser distributed version of less
* to kick-start less using the browser api
*/
/*global window, document */
// shim Promise if required
require('promise/polyfill.js');
var options = window.less || {};
require("./add-default-options")(window, options);
var less = module.exports = require("./index")(window, options);
window.less = less;
var css, head, style;
// Always restore page visibility
function resolveOrReject(data) {
if (data.filename) {
console.warn(data);
}
if (!options.async) {
head.removeChild(style);
}
}
if (options.onReady) {
if (/!watch/.test(window.location.hash)) {
less.watch();
}
// Simulate synchronous stylesheet loading by blocking page rendering
if (!options.async) {
css = 'body { display: none !important }';
head = document.head || document.getElementsByTagName('head')[0];
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
less.registerStylesheetsImmediately();
less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
}
},{"./add-default-options":1,"./index":8,"promise/polyfill.js":97}],3:[function(require,module,exports){
var utils = require("./utils");
module.exports = {
createCSS: function (document, styles, sheet) {
// Strip the query-string
var href = sheet.href || '';
// If there is no title set, use the filename, minus the extension
var id = 'less:' + (sheet.title || utils.extractId(href));
// If this has already been inserted into the DOM, we may need to replace it
var oldStyleNode = document.getElementById(id);
var keepOldStyleNode = false;
// Create a new stylesheet node for insertion or (if necessary) replacement
var styleNode = document.createElement('style');
styleNode.setAttribute('type', 'text/css');
if (sheet.media) {
styleNode.setAttribute('media', sheet.media);
}
styleNode.id = id;
if (!styleNode.styleSheet) {
styleNode.appendChild(document.createTextNode(styles));
// If new contents match contents of oldStyleNode, don't replace oldStyleNode
keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
}
var head = document.getElementsByTagName('head')[0];
// If there is no oldStyleNode, just append; otherwise, only append if we need
// to replace oldStyleNode with an updated stylesheet
if (oldStyleNode === null || keepOldStyleNode === false) {
var nextEl = sheet && sheet.nextSibling || null;
if (nextEl) {
nextEl.parentNode.insertBefore(styleNode, nextEl);
} else {
head.appendChild(styleNode);
}
}
if (oldStyleNode && keepOldStyleNode === false) {
oldStyleNode.parentNode.removeChild(oldStyleNode);
}
// For IE.
// This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
// See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
if (styleNode.styleSheet) {
try {
styleNode.styleSheet.cssText = styles;
} catch (e) {
throw new Error("Couldn't reassign styleSheet.cssText.");
}
}
},
currentScript: function(window) {
var document = window.document;
return document.currentScript || (function() {
var scripts = document.getElementsByTagName("script");
return scripts[scripts.length - 1];
})();
}
};
},{"./utils":10}],4:[function(require,module,exports){
// Cache system is a bit outdated and could do with work
module.exports = function(window, options, logger) {
var cache = null;
if (options.env !== 'development') {
try {
cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
return {
setCSS: function(path, lastModified, modifyVars, styles) {
if (cache) {
logger.info('saving ' + path + ' to cache.');
try {
cache.setItem(path, styles);
cache.setItem(path + ':timestamp', lastModified);
if (modifyVars) {
cache.setItem(path + ':vars', JSON.stringify(modifyVars));
}
} catch(e) {
//TODO - could do with adding more robust error handling
logger.error('failed to save "' + path + '" to local storage for caching.');
}
}
},
getCSS: function(path, webInfo, modifyVars) {
var css = cache && cache.getItem(path),
timestamp = cache && cache.getItem(path + ':timestamp'),
vars = cache && cache.getItem(path + ':vars');
modifyVars = modifyVars || {};
if (timestamp && webInfo.lastModified &&
(new Date(webInfo.lastModified).valueOf() ===
new Date(timestamp).valueOf()) &&
(!modifyVars && !vars || JSON.stringify(modifyVars) === vars)) {
// Use local copy
return css;
}
}
};
};
},{}],5:[function(require,module,exports){
var utils = require("./utils"),
browser = require("./browser");
module.exports = function(window, less, options) {
function errorHTML(e, rootHref) {
var id = 'less-error-message:' + utils.extractId(rootHref || "");
var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
var elem = window.document.createElement('div'), timer, content, errors = [];
var filename = e.filename || rootHref;
var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
elem.id = id;
elem.className = "less-error-message";
content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
'</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> ";
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.extract) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
'<ul>' + errors.join('') + '</ul>';
}
if (e.stack && (e.extract || options.logLevel >= 4)) {
content += '<br/>Stack Trace</br />' + e.stack.split('\n').slice(1).join('<br/>');
}
elem.innerHTML = content;
// CSS for error messages
browser.createCSS(window.document, [
'.less-error-message ul, .less-error-message li {',
'list-style-type: none;',
'margin-right: 15px;',
'padding: 4px 0;',
'margin: 0;',
'}',
'.less-error-message label {',
'font-size: 12px;',
'margin-right: 15px;',
'padding: 4px 0;',
'color: #cc7777;',
'}',
'.less-error-message pre {',
'color: #dd6666;',
'padding: 4px 0;',
'margin: 0;',
'display: inline-block;',
'}',
'.less-error-message pre.line {',
'color: #ff0000;',
'}',
'.less-error-message h3 {',
'font-size: 20px;',
'font-weight: bold;',
'padding: 15px 0 5px 0;',
'margin: 0;',
'}',
'.less-error-message a {',
'color: #10a',
'}',
'.less-error-message .error {',
'color: red;',
'font-weight: bold;',
'padding-bottom: 2px;',
'border-bottom: 1px dashed red;',
'}'
].join('\n'), { title: 'error-message' });
elem.style.cssText = [
"font-family: Arial, sans-serif",
"border: 1px solid #e00",
"background-color: #eee",
"border-radius: 5px",
"-webkit-border-radius: 5px",
"-moz-border-radius: 5px",
"color: #e00",
"padding: 15px",
"margin-bottom: 15px"
].join(';');
if (options.env === 'development') {
timer = setInterval(function () {
var document = window.document,
body = document.body;
if (body) {
if (document.getElementById(id)) {
body.replaceChild(elem, document.getElementById(id));
} else {
body.insertBefore(elem, body.firstChild);
}
clearInterval(timer);
}
}, 10);
}
}
function removeErrorHTML(path) {
var node = window.document.getElementById('less-error-message:' + utils.extractId(path));
if (node) {
node.parentNode.removeChild(node);
}
}
function removeErrorConsole(path) {
//no action
}
function removeError(path) {
if (!options.errorReporting || options.errorReporting === "html") {
removeErrorHTML(path);
} else if (options.errorReporting === "console") {
removeErrorConsole(path);
} else if (typeof options.errorReporting === 'function') {
options.errorReporting("remove", path);
}
}
function errorConsole(e, rootHref) {
var template = '{line} {content}';
var filename = e.filename || rootHref;
var errors = [];
var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
" in " + filename + " ";
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.extract) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' +
errors.join('\n');
}
if (e.stack && (e.extract || options.logLevel >= 4)) {
content += '\nStack Trace\n' + e.stack;
}
less.logger.error(content);
}
function error(e, rootHref) {
if (!options.errorReporting || options.errorReporting === "html") {
errorHTML(e, rootHref);
} else if (options.errorReporting === "console") {
errorConsole(e, rootHref);
} else if (typeof options.errorReporting === 'function') {
options.errorReporting("add", e, rootHref);
}
}
return {
add: error,
remove: removeError
};
};
},{"./browser":3,"./utils":10}],6:[function(require,module,exports){
/*global window, XMLHttpRequest */
module.exports = function(options, logger) {
var AbstractFileManager = require("../less/environment/abstract-file-manager.js");
var fileCache = {};
//TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
function getXMLHttpRequest() {
if (window.XMLHttpRequest && (window.location.protocol !== "file:" || !("ActiveXObject" in window))) {
return new XMLHttpRequest();
} else {
try {
/*global ActiveXObject */
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
logger.error("browser doesn't support AJAX.");
return null;
}
}
}
var FileManager = function() {
};
FileManager.prototype = new AbstractFileManager();
FileManager.prototype.alwaysMakePathsAbsolute = function alwaysMakePathsAbsolute() {
return true;
};
FileManager.prototype.join = function join(basePath, laterPath) {
if (!basePath) {
return laterPath;
}
return this.extractUrlParts(laterPath, basePath).path;
};
FileManager.prototype.doXHR = function doXHR(url, type, callback, errback) {
var xhr = getXMLHttpRequest();
var async = options.isFileProtocol ? options.fileAsync : true;
if (typeof xhr.overrideMimeType === 'function') {
xhr.overrideMimeType('text/css');
}
logger.debug("XHR: Getting '" + url + "'");
xhr.open('GET', url, async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText,
xhr.getResponseHeader("Last-Modified"));
} else if (typeof errback === 'function') {
errback(xhr.status, url);
}
}
if (options.isFileProtocol && !options.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
} else {
errback(xhr.status, url);
}
} else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
} else {
handleResponse(xhr, callback, errback);
}
};
FileManager.prototype.supports = function(filename, currentDirectory, options, environment) {
return true;
};
FileManager.prototype.clearFileCache = function() {
fileCache = {};
};
FileManager.prototype.loadFile = function loadFile(filename, currentDirectory, options, environment, callback) {
if (currentDirectory && !this.isPathAbsolute(filename)) {
filename = currentDirectory + filename;
}
options = options || {};
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some context variables for imports
var hrefParts = this.extractUrlParts(filename, window.location.href);
var href = hrefParts.url;
if (options.useFileCache && fileCache[href]) {
try {
var lessText = fileCache[href];
callback(null, { contents: lessText, filename: href, webInfo: { lastModified: new Date() }});
} catch (e) {
callback({filename: href, message: "Error loading file " + href + " error was " + e.message});
}
return;
}
this.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
// per file cache
fileCache[href] = data;
// Use remote copy (re-parse)
callback(null, { contents: data, filename: href, webInfo: { lastModified: lastModified }});
}, function doXHRError(status, url) {
callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
});
};
return FileManager;
};
},{"../less/environment/abstract-file-manager.js":15}],7:[function(require,module,exports){
module.exports = function() {
var functionRegistry = require("./../less/functions/function-registry");
function imageSize() {
throw {
type: "Runtime",
message: "Image size functions are not supported in browser version of less"
};
}
var imageFunctions = {
"image-size": function(filePathNode) {
imageSize(this, filePathNode);
return -1;
},
"image-width": function(filePathNode) {
imageSize(this, filePathNode);
return -1;
},
"image-height": function(filePathNode) {
imageSize(this, filePathNode);
return -1;
}
};
functionRegistry.addMultiple(imageFunctions);
};
},{"./../less/functions/function-registry":22}],8:[function(require,module,exports){
//
// index.js
// Should expose the additional browser functions on to the less object
//
var addDataAttr = require("./utils").addDataAttr,
browser = require("./browser");
module.exports = function(window, options) {
var document = window.document;
var less = require('../less')();
//module.exports = less;
less.options = options;
var environment = less.environment,
FileManager = require("./file-manager")(options, less.logger),
fileManager = new FileManager();
environment.addFileManager(fileManager);
less.FileManager = FileManager;
require("./log-listener")(less, options);
var errors = require("./error-reporting")(window, less, options);
var cache = less.cache = options.cache || require("./cache")(window, options, less.logger);
require('./image-size')(less.environment);
//Setup user functions
if (options.functions) {
less.functions.functionRegistry.addMultiple(options.functions);
}
var typePattern = /^text\/(x-)?less$/;
function postProcessCSS(styles) { // deprecated, use a plugin for postprocesstasks
if (options.postProcessor && typeof options.postProcessor === 'function') {
styles = options.postProcessor.call(styles, styles) || styles;
}
return styles;
}
function clone(obj) {
var cloned = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
cloned[prop] = obj[prop];
}
}
return cloned;
}
// only really needed for phantom
function bind(func, thisArg) {
var curryArgs = Array.prototype.slice.call(arguments, 2);
return function() {
var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
return func.apply(thisArg, args);
};
}
function loadStyles(modifyVars) {
var styles = document.getElementsByTagName('style'),
style;
for (var i = 0; i < styles.length; i++) {
style = styles[i];
if (style.type.match(typePattern)) {
var instanceOptions = clone(options);
instanceOptions.modifyVars = modifyVars;
var lessText = style.innerHTML || '';
instanceOptions.filename = document.location.href.replace(/#.*$/, '');
/*jshint loopfunc:true */
// use closure to store current style
less.render(lessText, instanceOptions,
bind(function(style, e, result) {
if (e) {
errors.add(e, "inline");
} else {
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = result.css;
} else {
style.innerHTML = result.css;
}
}
}, null, style));
}
}
}
function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
var instanceOptions = clone(options);
addDataAttr(instanceOptions, sheet);
instanceOptions.mime = sheet.type;
if (modifyVars) {
instanceOptions.modifyVars = modifyVars;
}
function loadInitialFileCallback(loadedFile) {
var data = loadedFile.contents,
path = loadedFile.filename,
webInfo = loadedFile.webInfo;
var newFileInfo = {
currentDirectory: fileManager.getPath(path),
filename: path,
rootFilename: path,
relativeUrls: instanceOptions.relativeUrls};
newFileInfo.entryPath = newFileInfo.currentDirectory;
newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
if (webInfo) {
webInfo.remaining = remaining;
var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
if (!reload && css) {
webInfo.local = true;
callback(null, css, data, sheet, webInfo, path);
return;
}
}
//TODO add tests around how this behaves when reloading
errors.remove(path);
instanceOptions.rootFileInfo = newFileInfo;
less.render(data, instanceOptions, function(e, result) {
if (e) {
e.href = path;
callback(e);
} else {
result.css = postProcessCSS(result.css);
cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
callback(null, result.css, data, sheet, webInfo, path);
}
});
}
fileManager.loadFile(sheet.href, null, instanceOptions, environment, function(e, loadedFile) {
if (e) {
callback(e);
return;
}
loadInitialFileCallback(loadedFile);
});
}
function loadStyleSheets(callback, reload, modifyVars) {
for (var i = 0; i < less.sheets.length; i++) {
loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
}
}
function initRunningMode() {
if (less.env === 'development') {
less.watchTimer = setInterval(function () {
if (less.watchMode) {
fileManager.clearFileCache();
loadStyleSheets(function (e, css, _, sheet, webInfo) {
if (e) {
errors.add(e, e.href || sheet.href);
} else if (css) {
browser.createCSS(window.document, css, sheet);
}
});
}
}, options.poll);
}
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode ) {
less.env = 'development';
initRunningMode();
}
this.watchMode = true;
return true;
};
less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; };
//
// Synchronously get all <link> tags with the 'rel' attribute set to
// "stylesheet/less".
//
less.registerStylesheetsImmediately = function() {
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
};
//
// Asynchronously get all <link> tags with the 'rel' attribute set to
// "stylesheet/less", returning a Promise.
//
less.registerStylesheets = function() {
return new Promise(function(resolve, reject) {
less.registerStylesheetsImmediately();
resolve();
});
};
//
// With this function, it's possible to alter variables and re-render
// CSS without reloading less-files
//
less.modifyVars = function(record) {
return less.refresh(true, record, false);
};
less.refresh = function (reload, modifyVars, clearFileCache) {
if ((reload || clearFileCache) && clearFileCache !== false) {
fileManager.clearFileCache();
}
return new Promise(function (resolve, reject) {
var startTime, endTime, totalMilliseconds, remainingSheets;
startTime = endTime = new Date();
// Set counter for remaining unprocessed sheets
remainingSheets = less.sheets.length;
if (remainingSheets === 0) {
endTime = new Date();
totalMilliseconds = endTime - startTime;
less.logger.info("Less has finished and no sheets were loaded.");
resolve({
startTime: startTime,
endTime: endTime,
totalMilliseconds: totalMilliseconds,
sheets: less.sheets.length
});
} else {
// Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
loadStyleSheets(function (e, css, _, sheet, webInfo) {
if (e) {
errors.add(e, e.href || sheet.href);
reject(e);
return;
}
if (webInfo.local) {
less.logger.info("Loading " + sheet.href + " from cache.");
} else {
less.logger.info("Rendered " + sheet.href + " successfully.");
}
browser.createCSS(window.document, css, sheet);
less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms');
// Count completed sheet
remainingSheets--;
// Check if the last remaining sheet was processed and then call the promise
if (remainingSheets === 0) {
totalMilliseconds = new Date() - startTime;
less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + 'ms');
resolve({
startTime: startTime,
endTime: endTime,
totalMilliseconds: totalMilliseconds,
sheets: less.sheets.length
});
}
endTime = new Date();
}, reload, modifyVars);
}
loadStyles(modifyVars);
});
};
less.refreshStyles = loadStyles;
return less;
};
},{"../less":31,"./browser":3,"./cache":4,"./error-reporting":5,"./file-manager":6,"./image-size":7,"./log-listener":9,"./utils":10}],9:[function(require,module,exports){
module.exports = function(less, options) {
var logLevel_debug = 4,
logLevel_info = 3,
logLevel_warn = 2,
logLevel_error = 1;
// The amount of logging in the javascript console.
// 3 - Debug, information and errors
// 2 - Information and errors
// 1 - Errors
// 0 - None
// Defaults to 2
options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
if (!options.loggers) {
options.loggers = [{
debug: function(msg) {
if (options.logLevel >= logLevel_debug) {
console.log(msg);
}
},
info: function(msg) {
if (options.logLevel >= logLevel_info) {
console.log(msg);
}
},
warn: function(msg) {
if (options.logLevel >= logLevel_warn) {
console.warn(msg);
}
},
error: function(msg) {
if (options.logLevel >= logLevel_error) {
console.error(msg);
}
}
}];
}
for (var i = 0; i < options.loggers.length; i++) {
less.logger.addListener(options.loggers[i]);
}
};
},{}],10:[function(require,module,exports){
module.exports = {
extractId: function(href) {
return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
.replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
.replace(/^\//, '') // Remove root /
.replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
},
addDataAttr: function(options, tag) {
for (var opt in tag.dataset) {
if (tag.dataset.hasOwnProperty(opt)) {
if (opt === "env" || opt === "dumpLineNumbers" || opt === "rootpath" || opt === "errorReporting") {
options[opt] = tag.dataset[opt];
} else {
try {
options[opt] = JSON.parse(tag.dataset[opt]);
}
catch(_) {}
}
}
}
}
};
},{}],11:[function(require,module,exports){
var contexts = {};
module.exports = contexts;
var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
if (!original) { return; }
for (var i = 0; i < propertiesToCopy.length; i++) {
if (original.hasOwnProperty(propertiesToCopy[i])) {
destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
}
}
};
/*
parse is used whilst parsing
*/
var parseCopyProperties = [
// options
'paths', // option - unmodified - paths to search for imports on
'relativeUrls', // option - whether to adjust URL's to be relative
'rootpath', // option - rootpath to append to URL's
'strictImports', // option -
'insecure', // option - whether to allow imports from insecure ssl hosts
'dumpLineNumbers', // option - whether to dump line numbers
'compress', // option - whether to compress
'syncImport', // option - whether to import synchronously
'chunkInput', // option - whether to chunk input. more performant but causes parse issues.
'mime', // browser only - mime type for sheet import
'useFileCache', // browser only - whether to use the per file session cache
// context
'processImports', // option & context - whether to process imports. if false then imports will not be imported.
// Used by the import manager to stop multiple import visitors being created.
'pluginManager' // Used as the plugin manager for the session
];
contexts.Parse = function(options) {
copyFromOriginal(options, this, parseCopyProperties);
if (typeof this.paths === "string") { this.paths = [this.paths]; }
};
var evalCopyProperties = [
'paths', // additional include paths
'compress', // whether to compress
'ieCompat', // whether to enforce IE compatibility (IE8 data-uri)
'strictMath', // whether math has to be within parenthesis
'strictUnits', // whether units need to evaluate correctly
'sourceMap', // whether to output a source map
'importMultiple', // whether we are currently importing multiple copies
'urlArgs', // whether to add args into url tokens
'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true
'pluginManager', // Used as the plugin manager for the session
'importantScope' // used to bubble up !important statements
];
contexts.Eval = function(options, frames) {
copyFromOriginal(options, this, evalCopyProperties);
if (typeof this.paths === "string") { this.paths = [this.paths]; }
this.frames = frames || [];
this.importantScope = this.importantScope || [];
};
contexts.Eval.prototype.inParenthesis = function () {
if (!this.parensStack) {
this.parensStack = [];
}
this.parensStack.push(true);
};
contexts.Eval.prototype.outOfParenthesis = function () {
this.parensStack.pop();
};
contexts.Eval.prototype.isMathOn = function () {
return this.strictMath ? (this.parensStack && this.parensStack.length) : true;
};
contexts.Eval.prototype.isPathRelative = function (path) {
return !/^(?:[a-z-]+:|\/|#)/i.test(path);
};
contexts.Eval.prototype.normalizePath = function( path ) {
var
segments = path.split("/").reverse(),
segment;
path = [];
while (segments.length !== 0 ) {
segment = segments.pop();
switch( segment ) {
case ".":
break;