Readme

Inject HTML Element Stream

Use InjectHTMLElementStream to inject an HTML element inside the <body /> or <html /> tag of a streamed HTML string.

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
const bodyRegex = /(<\/body[>\s])/;
const htmlRegex = /(<\/html[>\s])/;
const bodySplitTag = "</body";
const htmlSplitTag = "</html";
export class InjectHTMLElementStream extends TransformStream<string, string> {
elementSent = false;
buffered = "";
constructor(element: string) {
super({
transform: (chunk, controller) => {
// If something is buffered, add to this transform step
let bufferedChunk = this.buffered + chunk;
this.buffered = "";
// Check if the string contains the closing tags for body or html
if (!this.elementSent) {
if (bufferedChunk.match(bodyRegex)) {
controller.enqueue(bufferedChunk.replace(bodyRegex, `${element}$1`));
this.elementSent = true;
return;
}
if (bufferedChunk.match(htmlRegex)) {
controller.enqueue(bufferedChunk.replace(htmlRegex, `${element}$1`));
this.elementSent = true;
return;
}
// If the chunk ends with a partial match to the body or html string,
// buffer that to be used next chunk. Remove it from the current chunk
const end = bufferedChunk.slice(-7);
for (let i = 1; i <= 6; i++) {
const sliced = bufferedChunk.slice(-i);
if (sliced === bodySplitTag.slice(0, i) || sliced === htmlSplitTag.slice(0, i)) {
this.buffered = sliced;
bufferedChunk = bufferedChunk.slice(0, -i);
break;
}
}
}
// Base case
controller.enqueue(bufferedChunk);
},
flush: (controller) => {
// flush any buffered string
if (this.buffered) {
controller.enqueue(this.buffered);
this.buffered = "";
}
// enqueue element
if (!this.elementSent) {
controller.enqueue(element);
this.elementSent = true;
}
controller.terminate();
},
});
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
2
tmcw avatar

I think this is inserting $0 after each inserted bit of text, looks like that's in ${element}$0

andreterron avatar
v9
February 27, 2024