Initial commit
[yaffs-website] / node_modules / livereload-js / lib / reloader.js
1 (function() {
2   var IMAGE_STYLES, Reloader, numberOfMatchingSegments, pathFromUrl, pathsMatch, pickBestMatch, splitUrl;
3
4   splitUrl = function(url) {
5     var hash, index, params;
6     if ((index = url.indexOf('#')) >= 0) {
7       hash = url.slice(index);
8       url = url.slice(0, index);
9     } else {
10       hash = '';
11     }
12     if ((index = url.indexOf('?')) >= 0) {
13       params = url.slice(index);
14       url = url.slice(0, index);
15     } else {
16       params = '';
17     }
18     return {
19       url: url,
20       params: params,
21       hash: hash
22     };
23   };
24
25   pathFromUrl = function(url) {
26     var path;
27     url = splitUrl(url).url;
28     if (url.indexOf('file://') === 0) {
29       path = url.replace(/^file:\/\/(localhost)?/, '');
30     } else {
31       path = url.replace(/^([^:]+:)?\/\/([^:\/]+)(:\d*)?\//, '/');
32     }
33     return decodeURIComponent(path);
34   };
35
36   pickBestMatch = function(path, objects, pathFunc) {
37     var bestMatch, object, score, _i, _len;
38     bestMatch = {
39       score: 0
40     };
41     for (_i = 0, _len = objects.length; _i < _len; _i++) {
42       object = objects[_i];
43       score = numberOfMatchingSegments(path, pathFunc(object));
44       if (score > bestMatch.score) {
45         bestMatch = {
46           object: object,
47           score: score
48         };
49       }
50     }
51     if (bestMatch.score > 0) {
52       return bestMatch;
53     } else {
54       return null;
55     }
56   };
57
58   numberOfMatchingSegments = function(path1, path2) {
59     var comps1, comps2, eqCount, len;
60     path1 = path1.replace(/^\/+/, '').toLowerCase();
61     path2 = path2.replace(/^\/+/, '').toLowerCase();
62     if (path1 === path2) {
63       return 10000;
64     }
65     comps1 = path1.split('/').reverse();
66     comps2 = path2.split('/').reverse();
67     len = Math.min(comps1.length, comps2.length);
68     eqCount = 0;
69     while (eqCount < len && comps1[eqCount] === comps2[eqCount]) {
70       ++eqCount;
71     }
72     return eqCount;
73   };
74
75   pathsMatch = function(path1, path2) {
76     return numberOfMatchingSegments(path1, path2) > 0;
77   };
78
79   IMAGE_STYLES = [
80     {
81       selector: 'background',
82       styleNames: ['backgroundImage']
83     }, {
84       selector: 'border',
85       styleNames: ['borderImage', 'webkitBorderImage', 'MozBorderImage']
86     }
87   ];
88
89   exports.Reloader = Reloader = (function() {
90     function Reloader(window, console, Timer) {
91       this.window = window;
92       this.console = console;
93       this.Timer = Timer;
94       this.document = this.window.document;
95       this.importCacheWaitPeriod = 200;
96       this.plugins = [];
97     }
98
99     Reloader.prototype.addPlugin = function(plugin) {
100       return this.plugins.push(plugin);
101     };
102
103     Reloader.prototype.analyze = function(callback) {
104       return results;
105     };
106
107     Reloader.prototype.reload = function(path, options) {
108       var plugin, _base, _i, _len, _ref;
109       this.options = options;
110       if ((_base = this.options).stylesheetReloadTimeout == null) {
111         _base.stylesheetReloadTimeout = 15000;
112       }
113       _ref = this.plugins;
114       for (_i = 0, _len = _ref.length; _i < _len; _i++) {
115         plugin = _ref[_i];
116         if (plugin.reload && plugin.reload(path, options)) {
117           return;
118         }
119       }
120       if (options.liveCSS) {
121         if (path.match(/\.css$/i)) {
122           if (this.reloadStylesheet(path)) {
123             return;
124           }
125         }
126       }
127       if (options.liveImg) {
128         if (path.match(/\.(jpe?g|png|gif)$/i)) {
129           this.reloadImages(path);
130           return;
131         }
132       }
133       return this.reloadPage();
134     };
135
136     Reloader.prototype.reloadPage = function() {
137       return this.window.document.location.reload();
138     };
139
140     Reloader.prototype.reloadImages = function(path) {
141       var expando, img, selector, styleNames, styleSheet, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _results;
142       expando = this.generateUniqueString();
143       _ref = this.document.images;
144       for (_i = 0, _len = _ref.length; _i < _len; _i++) {
145         img = _ref[_i];
146         if (pathsMatch(path, pathFromUrl(img.src))) {
147           img.src = this.generateCacheBustUrl(img.src, expando);
148         }
149       }
150       if (this.document.querySelectorAll) {
151         for (_j = 0, _len1 = IMAGE_STYLES.length; _j < _len1; _j++) {
152           _ref1 = IMAGE_STYLES[_j], selector = _ref1.selector, styleNames = _ref1.styleNames;
153           _ref2 = this.document.querySelectorAll("[style*=" + selector + "]");
154           for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
155             img = _ref2[_k];
156             this.reloadStyleImages(img.style, styleNames, path, expando);
157           }
158         }
159       }
160       if (this.document.styleSheets) {
161         _ref3 = this.document.styleSheets;
162         _results = [];
163         for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
164           styleSheet = _ref3[_l];
165           _results.push(this.reloadStylesheetImages(styleSheet, path, expando));
166         }
167         return _results;
168       }
169     };
170
171     Reloader.prototype.reloadStylesheetImages = function(styleSheet, path, expando) {
172       var e, rule, rules, styleNames, _i, _j, _len, _len1;
173       try {
174         rules = styleSheet != null ? styleSheet.cssRules : void 0;
175       } catch (_error) {
176         e = _error;
177       }
178       if (!rules) {
179         return;
180       }
181       for (_i = 0, _len = rules.length; _i < _len; _i++) {
182         rule = rules[_i];
183         switch (rule.type) {
184           case CSSRule.IMPORT_RULE:
185             this.reloadStylesheetImages(rule.styleSheet, path, expando);
186             break;
187           case CSSRule.STYLE_RULE:
188             for (_j = 0, _len1 = IMAGE_STYLES.length; _j < _len1; _j++) {
189               styleNames = IMAGE_STYLES[_j].styleNames;
190               this.reloadStyleImages(rule.style, styleNames, path, expando);
191             }
192             break;
193           case CSSRule.MEDIA_RULE:
194             this.reloadStylesheetImages(rule, path, expando);
195         }
196       }
197     };
198
199     Reloader.prototype.reloadStyleImages = function(style, styleNames, path, expando) {
200       var newValue, styleName, value, _i, _len;
201       for (_i = 0, _len = styleNames.length; _i < _len; _i++) {
202         styleName = styleNames[_i];
203         value = style[styleName];
204         if (typeof value === 'string') {
205           newValue = value.replace(/\burl\s*\(([^)]*)\)/, (function(_this) {
206             return function(match, src) {
207               if (pathsMatch(path, pathFromUrl(src))) {
208                 return "url(" + (_this.generateCacheBustUrl(src, expando)) + ")";
209               } else {
210                 return match;
211               }
212             };
213           })(this));
214           if (newValue !== value) {
215             style[styleName] = newValue;
216           }
217         }
218       }
219     };
220
221     Reloader.prototype.reloadStylesheet = function(path) {
222       var imported, link, links, match, style, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1;
223       links = (function() {
224         var _i, _len, _ref, _results;
225         _ref = this.document.getElementsByTagName('link');
226         _results = [];
227         for (_i = 0, _len = _ref.length; _i < _len; _i++) {
228           link = _ref[_i];
229           if (link.rel.match(/^stylesheet$/i) && !link.__LiveReload_pendingRemoval) {
230             _results.push(link);
231           }
232         }
233         return _results;
234       }).call(this);
235       imported = [];
236       _ref = this.document.getElementsByTagName('style');
237       for (_i = 0, _len = _ref.length; _i < _len; _i++) {
238         style = _ref[_i];
239         if (style.sheet) {
240           this.collectImportedStylesheets(style, style.sheet, imported);
241         }
242       }
243       for (_j = 0, _len1 = links.length; _j < _len1; _j++) {
244         link = links[_j];
245         this.collectImportedStylesheets(link, link.sheet, imported);
246       }
247       if (this.window.StyleFix && this.document.querySelectorAll) {
248         _ref1 = this.document.querySelectorAll('style[data-href]');
249         for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
250           style = _ref1[_k];
251           links.push(style);
252         }
253       }
254       this.console.log("LiveReload found " + links.length + " LINKed stylesheets, " + imported.length + " @imported stylesheets");
255       match = pickBestMatch(path, links.concat(imported), (function(_this) {
256         return function(l) {
257           return pathFromUrl(_this.linkHref(l));
258         };
259       })(this));
260       if (match) {
261         if (match.object.rule) {
262           this.console.log("LiveReload is reloading imported stylesheet: " + match.object.href);
263           this.reattachImportedRule(match.object);
264         } else {
265           this.console.log("LiveReload is reloading stylesheet: " + (this.linkHref(match.object)));
266           this.reattachStylesheetLink(match.object);
267         }
268       } else {
269         this.console.log("LiveReload will reload all stylesheets because path '" + path + "' did not match any specific one");
270         for (_l = 0, _len3 = links.length; _l < _len3; _l++) {
271           link = links[_l];
272           this.reattachStylesheetLink(link);
273         }
274       }
275       return true;
276     };
277
278     Reloader.prototype.collectImportedStylesheets = function(link, styleSheet, result) {
279       var e, index, rule, rules, _i, _len;
280       try {
281         rules = styleSheet != null ? styleSheet.cssRules : void 0;
282       } catch (_error) {
283         e = _error;
284       }
285       if (rules && rules.length) {
286         for (index = _i = 0, _len = rules.length; _i < _len; index = ++_i) {
287           rule = rules[index];
288           switch (rule.type) {
289             case CSSRule.CHARSET_RULE:
290               continue;
291             case CSSRule.IMPORT_RULE:
292               result.push({
293                 link: link,
294                 rule: rule,
295                 index: index,
296                 href: rule.href
297               });
298               this.collectImportedStylesheets(link, rule.styleSheet, result);
299               break;
300             default:
301               break;
302           }
303         }
304       }
305     };
306
307     Reloader.prototype.waitUntilCssLoads = function(clone, func) {
308       var callbackExecuted, executeCallback, poll;
309       callbackExecuted = false;
310       executeCallback = (function(_this) {
311         return function() {
312           if (callbackExecuted) {
313             return;
314           }
315           callbackExecuted = true;
316           return func();
317         };
318       })(this);
319       clone.onload = (function(_this) {
320         return function() {
321           _this.console.log("LiveReload: the new stylesheet has finished loading");
322           _this.knownToSupportCssOnLoad = true;
323           return executeCallback();
324         };
325       })(this);
326       if (!this.knownToSupportCssOnLoad) {
327         (poll = (function(_this) {
328           return function() {
329             if (clone.sheet) {
330               _this.console.log("LiveReload is polling until the new CSS finishes loading...");
331               return executeCallback();
332             } else {
333               return _this.Timer.start(50, poll);
334             }
335           };
336         })(this))();
337       }
338       return this.Timer.start(this.options.stylesheetReloadTimeout, executeCallback);
339     };
340
341     Reloader.prototype.linkHref = function(link) {
342       return link.href || link.getAttribute('data-href');
343     };
344
345     Reloader.prototype.reattachStylesheetLink = function(link) {
346       var clone, parent;
347       if (link.__LiveReload_pendingRemoval) {
348         return;
349       }
350       link.__LiveReload_pendingRemoval = true;
351       if (link.tagName === 'STYLE') {
352         clone = this.document.createElement('link');
353         clone.rel = 'stylesheet';
354         clone.media = link.media;
355         clone.disabled = link.disabled;
356       } else {
357         clone = link.cloneNode(false);
358       }
359       clone.href = this.generateCacheBustUrl(this.linkHref(link));
360       parent = link.parentNode;
361       if (parent.lastChild === link) {
362         parent.appendChild(clone);
363       } else {
364         parent.insertBefore(clone, link.nextSibling);
365       }
366       return this.waitUntilCssLoads(clone, (function(_this) {
367         return function() {
368           var additionalWaitingTime;
369           if (/AppleWebKit/.test(navigator.userAgent)) {
370             additionalWaitingTime = 5;
371           } else {
372             additionalWaitingTime = 200;
373           }
374           return _this.Timer.start(additionalWaitingTime, function() {
375             var _ref;
376             if (!link.parentNode) {
377               return;
378             }
379             link.parentNode.removeChild(link);
380             clone.onreadystatechange = null;
381             return (_ref = _this.window.StyleFix) != null ? _ref.link(clone) : void 0;
382           });
383         };
384       })(this));
385     };
386
387     Reloader.prototype.reattachImportedRule = function(_arg) {
388       var href, index, link, media, newRule, parent, rule, tempLink;
389       rule = _arg.rule, index = _arg.index, link = _arg.link;
390       parent = rule.parentStyleSheet;
391       href = this.generateCacheBustUrl(rule.href);
392       media = rule.media.length ? [].join.call(rule.media, ', ') : '';
393       newRule = "@import url(\"" + href + "\") " + media + ";";
394       rule.__LiveReload_newHref = href;
395       tempLink = this.document.createElement("link");
396       tempLink.rel = 'stylesheet';
397       tempLink.href = href;
398       tempLink.__LiveReload_pendingRemoval = true;
399       if (link.parentNode) {
400         link.parentNode.insertBefore(tempLink, link);
401       }
402       return this.Timer.start(this.importCacheWaitPeriod, (function(_this) {
403         return function() {
404           if (tempLink.parentNode) {
405             tempLink.parentNode.removeChild(tempLink);
406           }
407           if (rule.__LiveReload_newHref !== href) {
408             return;
409           }
410           parent.insertRule(newRule, index);
411           parent.deleteRule(index + 1);
412           rule = parent.cssRules[index];
413           rule.__LiveReload_newHref = href;
414           return _this.Timer.start(_this.importCacheWaitPeriod, function() {
415             if (rule.__LiveReload_newHref !== href) {
416               return;
417             }
418             parent.insertRule(newRule, index);
419             return parent.deleteRule(index + 1);
420           });
421         };
422       })(this));
423     };
424
425     Reloader.prototype.generateUniqueString = function() {
426       return 'livereload=' + Date.now();
427     };
428
429     Reloader.prototype.generateCacheBustUrl = function(url, expando) {
430       var hash, oldParams, originalUrl, params, _ref;
431       if (expando == null) {
432         expando = this.generateUniqueString();
433       }
434       _ref = splitUrl(url), url = _ref.url, hash = _ref.hash, oldParams = _ref.params;
435       if (this.options.overrideURL) {
436         if (url.indexOf(this.options.serverURL) < 0) {
437           originalUrl = url;
438           url = this.options.serverURL + this.options.overrideURL + "?url=" + encodeURIComponent(url);
439           this.console.log("LiveReload is overriding source URL " + originalUrl + " with " + url);
440         }
441       }
442       params = oldParams.replace(/(\?|&)livereload=(\d+)/, function(match, sep) {
443         return "" + sep + expando;
444       });
445       if (params === oldParams) {
446         if (oldParams.length === 0) {
447           params = "?" + expando;
448         } else {
449           params = "" + oldParams + "&" + expando;
450         }
451       }
452       return url + params + hash;
453     };
454
455     return Reloader;
456
457   })();
458
459 }).call(this);