forked from krux/postscribe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostscribe.js
717 lines (566 loc) · 19.1 KB
/
postscribe.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
// postscribe.js 1.3.2
// (c) Copyright 2012 to the present, Krux
// postscribe is freely distributable under the MIT license.
// For all details and documentation:
// http://krux.github.io/postscribe
/*globals htmlParser:false*/
(function() {
// A function that intentionally does nothing.
function doNothing() {}
// Available options and defaults.
var OPTIONS = {
// Called when an async script has loaded.
afterAsync: doNothing,
// Called immediately before removing from the write queue.
afterDequeue: doNothing,
// Called sync after a stream's first thread release.
afterStreamStart: doNothing,
// Called after writing buffered document.write calls.
afterWrite: doNothing,
// Called immediately before adding to the write queue.
beforeEnqueue: doNothing,
// Called before writing a token.
beforeWriteToken: function(tok) { return tok; },
// Called before writing buffered document.write calls.
beforeWrite: function(str) { return str; },
// Called when evaluation is finished.
done: doNothing,
// Called when a write results in an error.
error: function(e) { throw e; },
// Whether to let scripts w/ async attribute set fall out of the queue.
releaseAsync: false
};
var global = this;
var UNDEFINED = void 0;
function existy(thing) {
return thing !== UNDEFINED && thing !== null;
}
if(global.postscribe) {
return;
}
// Turn on to debug how each chunk affected the DOM.
var DEBUG_CHUNK = false;
// # Helper Functions
var slice = Array.prototype.slice;
// Is this a function?
function isFunction(x) {
return 'function' === typeof x;
}
// Loop over each item in an array-like value.
function each(arr, fn, _this) {
var i, len = (arr && arr.length) || 0;
for(i = 0; i < len; i++) {
fn.call(_this, arr[i], i);
}
}
// Loop over each key/value pair in a hash.
function eachKey(obj, fn, _this) {
var key;
for(key in obj) {
if(obj.hasOwnProperty(key)) {
fn.call(_this, key, obj[key]);
}
}
}
// Set properties on an object.
function set(obj, props) {
eachKey(props, function(key, value) {
obj[key] = value;
});
return obj;
}
// Set default options where some option was not specified.
function defaults(options, _defaults) {
options = options || {};
eachKey(_defaults, function(key, val) {
if(!existy(options[key])) {
options[key] = val;
}
});
return options;
}
// Convert value (e.g., a NodeList) to an array.
function toArray(obj) {
try {
return slice.call(obj);
} catch(e) {
var ret = [];
each(obj, function(val) {
ret.push(val);
});
return ret;
}
}
var last = function(array) {
return array[array.length - 1];
};
// Test if token is a script tag.
function isScript(tok) {
return !tok || !('tagName' in tok) ? !1 : !!~tok.tagName.toLowerCase().indexOf('script');
}
function isStyle(tok) {
return !tok || !('tagName' in tok) ? !1 : !!~tok.tagName.toLowerCase().indexOf('style');
}
// # Class WriteStream
// Stream static html to an element, where "static html" denotes "html without scripts".
// This class maintains a *history of writes devoid of any attributes* or "proxy history".
// Injecting the proxy history into a temporary div has no side-effects,
// other than to create proxy elements for previously written elements.
// Given the `staticHtml` of a new write, a `tempDiv`'s innerHTML is set to `proxy_history + staticHtml`.
// The *structure* of `tempDiv`'s contents, (i.e., the placement of new nodes beside or inside of proxy elements),
// reflects the DOM structure that would have resulted if all writes had been squashed into a single write.
// For each descendent `node` of `tempDiv` whose parentNode is a *proxy*, `node` is appended to the corresponding *real* element within the DOM.
// Proxy elements are mapped to *actual* elements in the DOM by injecting a data-id attribute into each start tag in `staticHtml`.
var WriteStream = (function(){
// Prefix for data attributes on DOM elements.
var BASEATTR = 'data-ps-';
// get / set data attributes
function data(el, name, value) {
var attr = BASEATTR + name;
if(arguments.length === 2) {
// Get
var val = el.getAttribute(attr);
// IE 8 returns a number if it's a number
return !existy(val) ? val : String(val);
} else if(existy(value) && value !== '') {
// Set
el.setAttribute(attr, value);
} else {
// Remove
el.removeAttribute(attr);
}
}
function WriteStream(root, options) {
var doc = root.ownerDocument;
set(this, {
root: root,
options: options,
win: doc.defaultView || doc.parentWindow,
doc: doc,
parser: htmlParser('', { autoFix: true }),
// Actual elements by id.
actuals: [root],
// Embodies the "structure" of what's been written so far, devoid of attributes.
proxyHistory: '',
// Create a proxy of the root element.
proxyRoot: doc.createElement(root.nodeName),
scriptStack: [],
writeQueue: []
});
data(this.proxyRoot, 'proxyof', 0);
}
WriteStream.prototype.write = function() {
[].push.apply(this.writeQueue, arguments);
// Process writes
// When new script gets pushed or pending this will stop
// because new writeQueue gets pushed
var arg;
while(!this.deferredRemote &&
this.writeQueue.length) {
arg = this.writeQueue.shift();
if(isFunction(arg)) {
this.callFunction(arg);
} else {
this.writeImpl(arg);
}
}
};
WriteStream.prototype.callFunction = function(fn) {
var tok = { type: 'function', value: fn.name || fn.toString() };
this.onScriptStart(tok);
fn.call(this.win, this.doc);
this.onScriptDone(tok);
};
WriteStream.prototype.writeImpl = function(html) {
this.parser.append(html);
var tok, tokens = [], script, style;
// stop if we see a script token
while((tok = this.parser.readToken()) && !(script=isScript(tok)) && !(style=isStyle(tok))) {
tok = this.options.beforeWriteToken(tok);
if (tok) {
tokens.push(tok);
}
}
this.writeStaticTokens(tokens);
if(script) {
this.handleScriptToken(tok);
}
if(style){
this.handleStyleToken(tok);
}
};
// ## Contiguous non-script tokens (a chunk)
WriteStream.prototype.writeStaticTokens = function(tokens) {
var chunk = this.buildChunk(tokens);
if(!chunk.actual) {
// e.g., no tokens, or a noscript that got ignored
return;
}
chunk.html = this.proxyHistory + chunk.actual;
this.proxyHistory += chunk.proxy;
this.proxyRoot.innerHTML = chunk.html;
if(DEBUG_CHUNK) {
chunk.proxyInnerHTML = this.proxyRoot.innerHTML;
}
this.walkChunk();
if(DEBUG_CHUNK) {
chunk.actualInnerHTML = this.root.innerHTML; //root
}
return chunk;
};
WriteStream.prototype.buildChunk = function (tokens) {
var nextId = this.actuals.length,
// The raw html of this chunk.
raw = [],
// The html to create the nodes in the tokens (with id's injected).
actual = [],
// Html that can later be used to proxy the nodes in the tokens.
proxy = [];
each(tokens, function(tok) {
var tokenRaw = htmlParser.tokenToString(tok);
raw.push(tokenRaw);
if(tok.attrs) { // tok.attrs <==> startTag or atomicTag or cursor
// Ignore noscript tags. They are atomic, so we don't have to worry about children.
if(!(/^noscript$/i).test(tok.tagName)) {
var id = nextId++;
// Actual: inject id attribute: replace '>' at end of start tag with id attribute + '>'
actual.push(
tokenRaw.replace(/(\/?>)/, ' '+BASEATTR+'id='+id+' $1')
);
// Don't proxy scripts: they have no bearing on DOM structure.
if(tok.attrs.id !== 'ps-script' && tok.attrs.id !== 'ps-style') {
// Proxy: strip all attributes and inject proxyof attribute
proxy.push(
// ignore atomic tags (e.g., style): they have no "structural" effect
tok.type === 'atomicTag' ? '' :
'<'+tok.tagName+' '+BASEATTR+'proxyof='+id+(tok.unary ? ' />' : '>')
);
}
}
} else {
// Visit any other type of token
// Actual: append.
actual.push(tokenRaw);
// Proxy: append endTags. Ignore everything else.
proxy.push(tok.type === 'endTag' ? tokenRaw : '');
}
});
return {
tokens: tokens,
raw: raw.join(''),
actual: actual.join(''),
proxy: proxy.join('')
};
};
WriteStream.prototype.walkChunk = function() {
var node, stack = [this.proxyRoot];
// use shift/unshift so that children are walked in document order
while(existy(node = stack.shift())) {
var isElement = node.nodeType === 1;
var isProxy = isElement && data(node, 'proxyof');
// Ignore proxies
if(!isProxy) {
if(isElement) {
// New actual element: register it and remove the the id attr.
this.actuals[data(node, 'id')] = node;
data(node, 'id', null);
}
// Is node's parent a proxy?
var parentIsProxyOf = node.parentNode && data(node.parentNode, 'proxyof');
if(parentIsProxyOf) {
// Move node under actual parent.
this.actuals[parentIsProxyOf].appendChild(node);
}
}
// prepend childNodes to stack
stack.unshift.apply(stack, toArray(node.childNodes));
}
};
// ### Script tokens
WriteStream.prototype.handleScriptToken = function(tok) {
var remainder = this.parser.clear();
if(remainder) {
// Write remainder immediately behind this script.
this.writeQueue.unshift(remainder);
}
//noinspection JSUnresolvedVariable
tok.src = tok.attrs.src || tok.attrs.SRC;
tok = this.options.beforeWriteToken(tok);
if(!tok) {
// User has removed this token
return;
}
if(tok.src && this.scriptStack.length) {
// Defer this script until scriptStack is empty.
// Assumption 1: This script will not start executing until
// scriptStack is empty.
this.deferredRemote = tok;
} else {
this.onScriptStart(tok);
}
// Put the script node in the DOM.
var _this = this;
this.writeScriptToken(tok, function() {
_this.onScriptDone(tok);
});
};
// ### Style tokens
WriteStream.prototype.handleStyleToken = function(tok) {
var remainder = this.parser.clear();
if(remainder) {
// Write remainder immediately behind this style.
this.writeQueue.unshift(remainder);
}
tok.type = tok.attrs.type || tok.attrs.TYPE || 'text/css';
tok = this.options.beforeWriteToken(tok);
if(tok) {
// Put the style node in the DOM.
this.writeStyleToken(tok);
}
if(remainder) {
this.write();
}
};
// Build a style and insert it into the DOM.
WriteStream.prototype.writeStyleToken = function(tok) {
var el = this.buildStyle(tok);
this.insertStyle(el);
// Set content
if(tok.content) {
//noinspection JSUnresolvedVariable
if(el.styleSheet && !el.sheet) {
el.styleSheet.cssText=tok.content;
}
else {
el.appendChild(this.doc.createTextNode(tok.content));
}
}
};
// Build a style element from an atomic style token.
WriteStream.prototype.buildStyle = function(tok) {
var el = this.doc.createElement(tok.tagName);
el.setAttribute('type', tok.type);
// Set attributes
eachKey(tok.attrs, function(name, value) {
el.setAttribute(name, value);
});
return el;
};
// Insert style into DOM where it would naturally be written.
WriteStream.prototype.insertStyle = function(el) {
// Append a span to the stream. That span will act as a cursor
// (i.e. insertion point) for the style.
this.writeImpl('<span id="ps-style"/>');
// Grab that span from the DOM.
var cursor = this.doc.getElementById('ps-style');
// Replace cursor with style.
cursor.parentNode.replaceChild(el, cursor);
};
WriteStream.prototype.onScriptStart = function(tok) {
tok.outerWrites = this.writeQueue;
this.writeQueue = [];
this.scriptStack.unshift(tok);
};
WriteStream.prototype.onScriptDone = function(tok) {
// Pop script and check nesting.
if(tok !== this.scriptStack[0]) {
this.options.error({ message: 'Bad script nesting or script finished twice' });
return;
}
this.scriptStack.shift();
// Append outer writes to queue and process them.
this.write.apply(this, tok.outerWrites);
// Check for pending remote
// Assumption 2: if remote_script1 writes remote_script2 then
// the we notice remote_script1 finishes before remote_script2 starts.
// I think this is equivalent to assumption 1
if(!this.scriptStack.length && this.deferredRemote) {
this.onScriptStart(this.deferredRemote);
this.deferredRemote = null;
}
};
// Build a script and insert it into the DOM.
// Done is called once script has executed.
WriteStream.prototype.writeScriptToken = function(tok, done) {
var el = this.buildScript(tok);
var asyncRelease = this.shouldRelease(el);
var afterAsync = this.options.afterAsync;
if(tok.src) {
// Fix for attribute "SRC" (capitalized). IE does not recognize it.
el.src = tok.src;
this.scriptLoadHandler(el, !asyncRelease ? function() {
done();
afterAsync();
} : afterAsync);
}
try {
this.insertScript(el);
if(!tok.src || asyncRelease) {
done();
}
} catch(e) {
this.options.error(e);
done();
}
};
// Build a script element from an atomic script token.
WriteStream.prototype.buildScript = function(tok) {
var el = this.doc.createElement(tok.tagName);
// Set attributes
eachKey(tok.attrs, function(name, value) {
el.setAttribute(name, value);
});
// Set content
if(tok.content) {
el.text = tok.content;
}
return el;
};
// Insert script into DOM where it would naturally be written.
WriteStream.prototype.insertScript = function(el) {
// Append a span to the stream. That span will act as a cursor
// (i.e. insertion point) for the script.
this.writeImpl('<span id="ps-script"/>');
// Grab that span from the DOM.
var cursor = this.doc.getElementById('ps-script');
// Replace cursor with script.
cursor.parentNode.replaceChild(el, cursor);
};
WriteStream.prototype.scriptLoadHandler = function(el, done) {
function cleanup() {
el = el.onload = el.onreadystatechange = el.onerror = null;
}
// Error handler
var error = this.options.error;
function success() {
cleanup();
done();
}
function failure(err) {
cleanup();
error(err);
done();
}
// Set handlers
set(el, {
onload: function() {
success();
},
onreadystatechange: function() {
if(/^(loaded|complete)$/.test( el.readyState )) {
success();
}
},
onerror: function() {
failure({ message: 'remote script failed ' + el.src });
}
});
};
WriteStream.prototype.shouldRelease = function(el) {
var isScript = /^script$/i.test(el.nodeName);
return !isScript || !!(this.options.releaseAsync && el.src && el.hasAttribute('async'));
};
return WriteStream;
}());
// Public-facing interface and queuing
global.postscribe = (function() {
var nextId = 0;
var queue = [];
var active = null;
function nextStream() {
var args = queue.shift();
var options;
if(args) {
options = last(args);
options.afterDequeue();
args.stream = runStream.apply(null, args);
options.afterStreamStart();
}
}
function runStream(el, html, options) {
active = new WriteStream(el, options);
// Identify this stream.
active.id = nextId++;
active.name = options.name || active.id;
postscribe.streams[active.name] = active;
// Override document.write.
var doc = el.ownerDocument;
var stash = {
close: doc.close,
open: doc.open,
write: doc.write,
writeln: doc.writeln
};
function write(str) {
str = options.beforeWrite(str);
active.write(str);
options.afterWrite(str);
}
set(doc, {
close: doNothing,
open: doNothing,
write: function(){
return write(toArray(arguments).join(''));
},
writeln: function() {
return write(toArray(arguments).join('') + '\n');
}
});
// Override window.onerror
var oldOnError = active.win.onerror || doNothing;
// This works together with the try/catch around WriteStream::insertScript
// In modern browsers, exceptions in tag scripts go directly to top level
active.win.onerror = function(msg, url, line) {
options.error({ msg: msg + ' - ' + url + ':' + line });
oldOnError.apply(active.win, arguments);
};
// Write to the stream
active.write(html, function streamDone() {
// restore document.write
set(doc, stash);
// restore window.onerror
active.win.onerror = oldOnError;
options.done();
active = null;
nextStream();
});
return active;
}
function postscribe(el, html, options) {
if(isFunction(options)) {
options = { done: options };
}
options = defaults(options, OPTIONS);
el =
// id selector
(/^#/).test(el) ? global.document.getElementById(el.substr(1)) :
// jquery object. TODO: loop over all elements.
el.jquery ? el[0] : el;
var args = [el, html, options];
el.postscribe = {
cancel: function() {
if(args.stream) {
// TODO: implement this
args.stream.abort();
} else {
args[1] = doNothing;
}
}
};
options.beforeEnqueue(args);
queue.push(args);
if(!active) {
nextStream();
}
return el.postscribe;
}
return set(postscribe, {
// Streams by name.
streams: {},
// Queue of streams.
queue: queue,
// Expose internal classes.
WriteStream: WriteStream
});
}());
}());