Debian Codegraph @

debian/missing-sources/livereload.js/reloader.js

raw
1 /* global CSSRule */
2 const splitUrl = function (url) {
3 let hash, index, params;
4 if ((index = url.indexOf('#')) >= 0) {
5 hash = url.slice(index);
6 url = url.slice(0, index);
7 } else {
8 hash = '';
9 }
10
11 // http://your.domain.com/path/to/combo/??file1.css,file2,css
12 const 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
27 return { url, params, hash };
28 };
29
30 const pathFromUrl = function (url) {
31 if (!url) {
32 return "";
33 }
34 let path;
35 ({ url } = splitUrl(url));
36 if (url.indexOf('file://') === 0) {
37 path = url.replace(new RegExp(`^file://(localhost)?`), '');
38 } else {
39 // http : // hostname :8080 /
40 path = url.replace(new RegExp(`^([^:]+:)?//([^:/]+)(:\\d*)?/`), '/');
41 }
42
43 // decodeURI has special handling of stuff like semicolons, so use decodeURIComponent
44 return decodeURIComponent(path);
45 };
46
47 const pickBestMatch = function (path, objects, pathFunc) {
48 let score;
49 let bestMatch = { score: 0 };
50 for (let object of objects) {
51 score = numberOfMatchingSegments(path, pathFunc(object));
52 if (score > bestMatch.score) {
53 bestMatch = { object, score };
54 }
55 }
56
57 if (bestMatch.score === 0) {
58 return null;
59 }
60
61 return bestMatch;
62 };
63
64 var numberOfMatchingSegments = function (path1, path2) {
65 // get rid of leading slashes and normalize to lower case
66 path1 = path1.replace(/^\/+/, '').toLowerCase();
67 path2 = path2.replace(/^\/+/, '').toLowerCase();
68
69 if (path1 === path2) {
70 return 10000;
71 }
72
73 const comps1 = path1.split('/').reverse();
74 const comps2 = path2.split('/').reverse();
75 const len = Math.min(comps1.length, comps2.length);
76
77 let eqCount = 0;
78 while ((eqCount < len) && (comps1[eqCount] === comps2[eqCount])) {
79 ++eqCount;
80 }
81
82 return eqCount;
83 };
84
85 const pathsMatch = (path1, path2) => numberOfMatchingSegments(path1, path2) > 0;
86
87 const IMAGE_STYLES = [
88 { selector: 'background', styleNames: ['backgroundImage'] },
89 { selector: 'border', styleNames: ['borderImage', 'webkitBorderImage', 'MozBorderImage'] }
90 ];
91
92 class Reloader {
93 constructor (window, console, Timer) {
94 this.window = window;
95 this.console = console;
96 this.Timer = Timer;
97 this.document = this.window.document;
98 this.importCacheWaitPeriod = 200;
99 this.plugins = [];
100 }
101
102 addPlugin (plugin) {
103 return this.plugins.push(plugin);
104 }
105
106 analyze (callback) {
107 }
108
109 reload (path, options) {
110 this.options = options; // avoid passing it through all the funcs
111 if (!this.options.stylesheetReloadTimeout) {
112 this.options.stylesheetReloadTimeout = 15000;
113 }
114 for (let plugin of Array.from(this.plugins)) {
115 if (plugin.reload && plugin.reload(path, options)) {
116 return;
117 }
118 }
119 if (options.liveCSS && path.match(/\.css(?:\.map)?$/i)) {
120 if (this.reloadStylesheet(path)) {
121 return;
122 }
123 }
124 if (options.liveImg && path.match(/\.(jpe?g|png|gif)$/i)) {
125 this.reloadImages(path);
126 return;
127 }
128 if (options.isChromeExtension) {
129 this.reloadChromeExtension();
130 return;
131 }
132 return this.reloadPage();
133 }
134
135 reloadPage () {
136 return this.window.document.location.reload();
137 }
138
139 reloadChromeExtension () {
140 return this.window.chrome.runtime.reload();
141 }
142
143 reloadImages (path) {
144 let img;
145 const expando = this.generateUniqueString();
146
147 for (img of Array.from(this.document.images)) {
148 if (pathsMatch(path, pathFromUrl(img.src))) {
149 img.src = this.generateCacheBustUrl(img.src, expando);
150 }
151 }
152
153 if (this.document.querySelectorAll) {
154 for (let { selector, styleNames } of IMAGE_STYLES) {
155 for (img of Array.from(this.document.querySelectorAll(`[style*=${selector}]`))) {
156 this.reloadStyleImages(img.style, styleNames, path, expando);
157 }
158 }
159 }
160
161 if (this.document.styleSheets) {
162 return Array.from(this.document.styleSheets).map(styleSheet =>
163 this.reloadStylesheetImages(styleSheet, path, expando)
164 );
165 }
166 }
167
168 reloadStylesheetImages (styleSheet, path, expando) {
169 let rules;
170 try {
171 rules = (styleSheet || {}).cssRules;
172 } catch (e) {}
173
174 if (!rules) {
175 return;
176 }
177
178 for (let rule of Array.from(rules)) {
179 switch (rule.type) {
180 case CSSRule.IMPORT_RULE:
181 this.reloadStylesheetImages(rule.styleSheet, path, expando);
182 break;
183 case CSSRule.STYLE_RULE:
184 for (let { styleNames } of IMAGE_STYLES) {
185 this.reloadStyleImages(rule.style, styleNames, path, expando);
186 }
187 break;
188 case CSSRule.MEDIA_RULE:
189 this.reloadStylesheetImages(rule, path, expando);
190 break;
191 }
192 }
193 }
194
195 reloadStyleImages (style, styleNames, path, expando) {
196 for (let styleName of styleNames) {
197 const value = style[styleName];
198 if (typeof value === 'string') {
199 const newValue = value.replace(new RegExp(`\\burl\\s*\\(([^)]*)\\)`), (match, src) => {
200 if (pathsMatch(path, pathFromUrl(src))) {
201 return `url(${this.generateCacheBustUrl(src, expando)})`;
202 } else {
203 return match;
204 }
205 });
206 if (newValue !== value) {
207 style[styleName] = newValue;
208 }
209 }
210 }
211 }
212
213 reloadStylesheet (path) {
214 // has to be a real array, because DOMNodeList will be modified
215 let style;
216 let link;
217 const links = ((() => {
218 const result = [];
219 for (link of Array.from(this.document.getElementsByTagName('link'))) {
220 if (link.rel.match(/^stylesheet$/i) && !link.__LiveReload_pendingRemoval) {
221 result.push(link);
222 }
223 }
224 return result;
225 })());
226
227 // find all imported stylesheets
228 const imported = [];
229 for (style of Array.from(this.document.getElementsByTagName('style'))) {
230 if (style.sheet) {
231 this.collectImportedStylesheets(style, style.sheet, imported);
232 }
233 }
234 for (link of Array.from(links)) {
235 this.collectImportedStylesheets(link, link.sheet, imported);
236 }
237
238 // handle prefixfree
239 if (this.window.StyleFix && this.document.querySelectorAll) {
240 for (style of Array.from(this.document.querySelectorAll('style[data-href]'))) {
241 links.push(style);
242 }
243 }
244
245 this.console.log(`LiveReload found ${links.length} LINKed stylesheets, ${imported.length} @imported stylesheets`);
246 const match = pickBestMatch(path, links.concat(imported), l => pathFromUrl(this.linkHref(l)));
247
248 if (match) {
249 if (match.object.rule) {
250 this.console.log(`LiveReload is reloading imported stylesheet: ${match.object.href}`);
251 this.reattachImportedRule(match.object);
252 } else {
253 this.console.log(`LiveReload is reloading stylesheet: ${this.linkHref(match.object)}`);
254 this.reattachStylesheetLink(match.object);
255 }
256 } else {
257 if (this.options.reloadMissingCSS) {
258 this.console.log(`LiveReload will reload all stylesheets because path '${path}' did not match any specific one. \
259 To disable this behavior, set 'options.reloadMissingCSS' to 'false'.`
260 );
261 for (link of Array.from(links)) {
262 this.reattachStylesheetLink(link);
263 }
264 } else {
265 this.console.log(`LiveReload will not reload path '${path}' because the stylesheet was not found on the page \
266 and 'options.reloadMissingCSS' was set to 'false'.`
267 );
268 }
269 }
270
271 return true;
272 }
273
274 collectImportedStylesheets (link, styleSheet, result) {
275 // in WebKit, styleSheet.cssRules is null for inaccessible stylesheets;
276 // Firefox/Opera may throw exceptions
277 let rules;
278
279 try {
280 rules = (styleSheet || {}).cssRules;
281 } catch (e) {}
282
283 if (rules && rules.length) {
284 for (let index = 0; index < rules.length; index++) {
285 const rule = rules[index];
286
287 switch (rule.type) {
288 case CSSRule.CHARSET_RULE:
289 continue; // do nothing
290 case CSSRule.IMPORT_RULE:
291 result.push({ link, rule, index, href: rule.href });
292 this.collectImportedStylesheets(link, rule.styleSheet, result);
293 break;
294 default:
295 break; // import rules can only be preceded by charset rules
296 }
297 }
298 }
299 }
300
301 waitUntilCssLoads (clone, func) {
302 let callbackExecuted = false;
303
304 const executeCallback = () => {
305 if (callbackExecuted) {
306 return;
307 }
308
309 callbackExecuted = true;
310
311 return func();
312 };
313
314 // supported by Chrome 19+, Safari 5.2+, Firefox 9+, Opera 9+, IE6+
315 // http://www.zachleat.com/web/load-css-dynamically/
316 // http://pieisgood.org/test/script-link-events/
317 clone.onload = () => {
318 this.console.log('LiveReload: the new stylesheet has finished loading');
319 this.knownToSupportCssOnLoad = true;
320
321 return executeCallback();
322 };
323
324 if (!this.knownToSupportCssOnLoad) {
325 // polling
326 let poll;
327 (poll = () => {
328 if (clone.sheet) {
329 this.console.log('LiveReload is polling until the new CSS finishes loading...');
330
331 return executeCallback();
332 } else {
333 return this.Timer.start(50, poll);
334 }
335 })();
336 }
337
338 // fail safe
339 return this.Timer.start(this.options.stylesheetReloadTimeout, executeCallback);
340 }
341
342 linkHref (link) {
343 // prefixfree uses data-href when it turns LINK into STYLE
344 return link.href || (link.getAttribute && link.getAttribute('data-href'));
345 }
346
347 reattachStylesheetLink (link) {
348 // ignore LINKs that will be removed by LR soon
349 let clone;
350 if (link.__LiveReload_pendingRemoval) { return; }
351 link.__LiveReload_pendingRemoval = true;
352
353 if (link.tagName === 'STYLE') {
354 // prefixfree
355 clone = this.document.createElement('link');
356 clone.rel = 'stylesheet';
357 clone.media = link.media;
358 clone.disabled = link.disabled;
359 } else {
360 clone = link.cloneNode(false);
361 }
362
363 clone.href = this.generateCacheBustUrl(this.linkHref(link));
364
365 // insert the new LINK before the old one
366 const parent = link.parentNode;
367 if (parent.lastChild === link) {
368 parent.appendChild(clone);
369 } else {
370 parent.insertBefore(clone, link.nextSibling);
371 }
372
373 return this.waitUntilCssLoads(clone, () => {
374 let additionalWaitingTime;
375
376 if (/AppleWebKit/.test(navigator.userAgent)) {
377 additionalWaitingTime = 5;
378 } else {
379 additionalWaitingTime = 200;
380 }
381
382 return this.Timer.start(additionalWaitingTime, () => {
383 if (!link.parentNode) {
384 return;
385 }
386
387 link.parentNode.removeChild(link);
388 clone.onreadystatechange = null;
389
390 return (this.window.StyleFix ? this.window.StyleFix.link(clone) : undefined);
391 });
392 }); // prefixfree
393 }
394
395 reattachImportedRule ({ rule, index, link }) {
396 const parent = rule.parentStyleSheet;
397 const href = this.generateCacheBustUrl(rule.href);
398 const media = rule.media.length ? [].join.call(rule.media, ', ') : '';
399 const newRule = `@import url("${href}") ${media};`;
400
401 // used to detect if reattachImportedRule has been called again on the same rule
402 rule.__LiveReload_newHref = href;
403
404 // WORKAROUND FOR WEBKIT BUG: WebKit resets all styles if we add @import'ed
405 // stylesheet that hasn't been cached yet. Workaround is to pre-cache the
406 // stylesheet by temporarily adding it as a LINK tag.
407 const tempLink = this.document.createElement('link');
408 tempLink.rel = 'stylesheet';
409 tempLink.href = href;
410 tempLink.__LiveReload_pendingRemoval = true; // exclude from path matching
411
412 if (link.parentNode) {
413 link.parentNode.insertBefore(tempLink, link);
414 }
415
416 // wait for it to load
417 return this.Timer.start(this.importCacheWaitPeriod, () => {
418 if (tempLink.parentNode) {
419 tempLink.parentNode.removeChild(tempLink);
420 }
421
422 // if another reattachImportedRule call is in progress, abandon this one
423 if (rule.__LiveReload_newHref !== href) {
424 return;
425 }
426
427 parent.insertRule(newRule, index);
428 parent.deleteRule(index + 1);
429
430 // save the new rule, so that we can detect another reattachImportedRule call
431 rule = parent.cssRules[index];
432 rule.__LiveReload_newHref = href;
433
434 // repeat again for good measure
435 return this.Timer.start(this.importCacheWaitPeriod, () => {
436 // if another reattachImportedRule call is in progress, abandon this one
437 if (rule.__LiveReload_newHref !== href) {
438 return;
439 }
440
441 parent.insertRule(newRule, index);
442
443 return parent.deleteRule(index + 1);
444 });
445 });
446 }
447
448 generateUniqueString () {
449 return `livereload=${Date.now()}`;
450 }
451
452 generateCacheBustUrl (url, expando) {
453 let hash, oldParams;
454
455 if (!expando) {
456 expando = this.generateUniqueString();
457 }
458 ({ url, hash, params: oldParams } = splitUrl(url));
459
460 if (this.options.overrideURL) {
461 if (url.indexOf(this.options.serverURL) < 0) {
462 const originalUrl = url;
463 url = this.options.serverURL + this.options.overrideURL + '?url=' + encodeURIComponent(url);
464 this.console.log(`LiveReload is overriding source URL ${originalUrl} with ${url}`);
465 }
466 }
467
468 let params = oldParams.replace(/(\?|&)livereload=(\d+)/, (match, sep) => `${sep}${expando}`);
469
470 if (params === oldParams) {
471 if (oldParams.length === 0) {
472 params = `?${expando}`;
473 } else {
474 params = `${oldParams}&${expando}`;
475 }
476 }
477
478 return url + params + hash;
479 }
480 };
481
482 exports.Reloader = Reloader;