-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
146 lines (125 loc) · 4.45 KB
/
main.ts
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
type TemplateStringKeyList = unknown[];
import { escapeHtml } from "./deps.ts";
import { TemplateString } from "./template_string.ts";
import {
type AttributeValue,
TemplateAttribute,
} from "./template_attribute.ts";
export type HTMLTemplateGenerator = AsyncGenerator;
export type HTMLTemplate =
| HTMLTemplateGenerator
| Promise<HTMLTemplateGenerator>;
export interface ResponseStream {
write(chunk: Uint8Array | string): unknown;
close?(): void;
}
const isAsyncIterator = (thing: unknown) =>
typeof (thing as AsyncGenerator<unknown>)[Symbol.asyncIterator] ===
"function";
async function* resolver(
parts: unknown[] = [],
): HTMLTemplateGenerator {
let i = 0;
for (const part of parts) {
if ((part as TemplateString).isTemplateString) { // just return the static string parts of template literals
yield part;
} else if (Array.isArray(part)) { // key is a list of more sub templates, that have to be rendered sequentially
yield* resolver(part);
} else if (part instanceof TemplateAttribute) { // key is a list of more sub templates, that have to be rendered sequentially
const nextPart = parts[i + 1];
yield (nextPart instanceof TemplateAttribute)
? part.toString()
: part.toString().trimEnd();
} else if (
typeof (part as AsyncGenerator<unknown>)[Symbol.asyncIterator] ===
"function"
) { // key is itself an iterator
yield* (part as HTMLTemplateGenerator);
} else {
// part is now a key provided to a template, that should be something like a string
// Itself might be a new `html` generator, so that we pass yield then to it.
const resolved = await part;
// sometimes an asynchronous call results also in an `html` tagged template.
// Such should not be escaped but handed to yield. (E.g. when a canceled promise results in alternative html`...` content.)
if (isAsyncIterator(resolved)) {
yield* (resolved as HTMLTemplateGenerator);
} else {
// anything else should be treated as a string and therefore be escaped for control signs
// yield escapeHtml(resolved as string);
yield escapeHtml((resolved?.toString()) || "" as string);
}
}
i++;
}
}
// tagged template literals come with an array for the static strings,
// and a second property with dynamic keys. Because we want to run over
// the given parts sequentially we mix them alternatingly to a single array.
export const mixUp = (
a1: TemplateStringsArray,
a2: TemplateStringKeyList = [],
) => {
return a1.map((el, i) => [new TemplateString(el), a2[i]]).reduce(
(res, curr) => {
return res.concat(curr);
},
[],
).filter((x) => x !== null && x !== undefined);
};
// Tagged template literal function
//
// Usage: html`<some-snippet /><other-snippet />`
export const html = (
strings: TemplateStringsArray,
...keys: TemplateStringKeyList
): HTMLTemplateGenerator => resolver(mixUp(strings, keys));
// Attribute function for dynamically added attributes,
// that can be rendered conditionally, depending on the attribute value.
//
// Usage: html`<some-snippet ${attr("foo", "bar")} />`
export const attr = (key: string, value: AttributeValue): TemplateAttribute =>
new TemplateAttribute(key, value);
// renderer to a fixed output string, resolving all async values provided to the template keys
export const renderToString = async (
template: HTMLTemplate,
options: { minify?: boolean } = {},
): Promise<string> => {
const result = [];
while (true) {
const part = await (await template).next();
result.push(part.value);
if (part.done) {
break;
}
}
return options.minify ? minify(result.join("")) : result.join("");
};
export const renderToStream = async (
stream: ResponseStream,
template: HTMLTemplate,
options: { minify?: boolean } = {},
) => {
const encoder = new TextEncoder();
while (true) {
try {
const part = await (await template).next();
const value = options.minify ? minify(part.value) : part.value;
stream.write(encoder.encode(value));
if (part.done) {
stream.close ? stream.close() : null;
break;
}
} catch (e) {
console.log("could not finish stream", e.message);
break;
}
}
};
function minify(text: string) {
return text?.toString().replace(/\s+/g, " ").replace(/\s>/, ">");
}
export {
type AttributeValue,
TemplateAttribute,
} from "./template_attribute.ts";
export { TemplateString } from "./template_string.ts";