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