forked from MithrilJS/mithril-node-render
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
262 lines (232 loc) · 7.46 KB
/
index.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
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
import {
Attributes,
Children,
ClassComponent,
Component,
ComponentTypes,
CVnode,
FactoryComponent,
Lifecycle,
Vnode,
} from "mithril";
export interface IOptions {
strict: boolean;
hooks: Array<() => any>;
attrs: Attributes;
}
const VOID_TAGS = [
"!doctype",
"area",
"base",
"br",
"col",
"command",
"embed",
"hr",
"img",
"input",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
];
export function isComponent(
component: any,
): component is Component<Attributes, Lifecycle<Attributes, {}>> {
return typeof component === "object" && component !== null && typeof component.view === "function";
}
export function isClassComponent(
component: any,
): component is new (vnode: CVnode<Attributes>) => ClassComponent<Attributes> {
return typeof component === "function" && isComponent(component.prototype);
}
export function isFactoryComponent(
component: any,
): component is FactoryComponent<Attributes> {
return typeof component === "function" && !isComponent(component.prototype);
}
export function isComponentType(
component: any,
): component is ComponentTypes<Attributes, Lifecycle<Attributes, {}>> {
return isComponent(component) || isClassComponent(component) || isFactoryComponent(component);
}
// tslint:disable:no-bitwise
export enum Escape {
NoQuotes = 0,
QuotesSingle = 1,
QuotesDouble = QuotesSingle << 1,
Quotes = QuotesSingle | QuotesDouble,
}
const escapeHtml = (
str: string,
flag: Escape = Escape.Quotes,
map: { [_: string]: string | void | false } = {
"\"": flag & Escape.QuotesDouble ? `"` : false,
"\&": `&`,
"\'": flag & Escape.QuotesSingle ? `'` : false,
"\<": `<`,
"\>": `>`,
},
): string => str.replace(
new RegExp(
`[${Object.keys(map).map(
// use only 1-char keys and escape them
(key) => key.length === 1 && map[key] !== false ? `\\${key}` : undefined,
).join("")}]`,
`gi`,
),
(key) => typeof map[key] === "string" ? map[key] as string : `&#${key.charCodeAt(0)};`,
);
// tslint:enable:no-bitwise
const getLifecycle = (
{
attrs = {},
state = {},
}: Vnode<Attributes, Lifecycle<Attributes, {}>>,
): Lifecycle<Attributes, {}> => {
return {
onbeforeremove: attrs.onbeforeremove || state.onbeforeremove,
onbeforeupdate: attrs.onbeforeupdate || state.onbeforeupdate,
oncreate: attrs.oncreate || state.oncreate,
oninit: attrs.oninit || state.oninit,
onremove: attrs.onremove || state.onremove,
onupdate: attrs.onupdate || state.onupdate,
};
};
const camelToDash = (str: string) => str.replace(/\W+/g, "-").replace(/([a-z\d])([A-Z])/g, "$1-$2");
const removeEmpties = (n: any) => n !== "" && typeof n !== "undefined" && n !== null;
function createAttrString(view: Vnode<Attributes, Lifecycle<Attributes, {}>>) {
const attrs = view.attrs;
if (!attrs || !Object.keys(attrs).length) {
return "";
}
return Object.keys(attrs).map((name) => {
const value = attrs[name];
if (typeof value === "undefined" || value === null || typeof value === "function") {
return undefined;
}
if (typeof value === "boolean") {
return value ? `${name}` : undefined;
}
if (name === "style") {
if (!value) {
return undefined;
}
let styles = attrs.style;
if (typeof styles === "object") {
styles = Object.keys(styles).map((property) => styles[property] !== "" ?
[camelToDash(property).toLowerCase(), styles[property]].join(":") :
"",
).filter(removeEmpties).join(";");
}
return styles !== "" ? `style="${escapeHtml(styles)}"` : undefined;
}
// Handle SVG <use> tags specially
if (name === "href" && view.tag === "use") {
return `xlink:href="${escapeHtml(value)}"`;
}
return `${(name === "className" ? "class" : name)}="${escapeHtml(value)}"`;
}).join(" ").trim();
}
const parseHooks = async (
vnode: Vnode<Attributes, Lifecycle<Attributes, {}>>,
hooks: Array<() => any>,
): Promise<void> => {
const {
oninit,
onremove,
} = getLifecycle(vnode);
if (typeof oninit === "function") {
await oninit.call(vnode.state, vnode);
}
if (typeof onremove === "function") {
hooks.push(async () => await onremove.call(vnode.state, vnode as any));
}
};
export async function render(
view: any,
{
attrs = {},
hooks = [],
strict = false,
}: Partial<IOptions> = {},
): Promise<string> {
const callSelf = (v: Children, opts: Partial<IOptions> = {}) => render(v, {
// attributes used by the root component
attrs,
strict,
...opts,
});
if (Array.isArray(view)) {
return (await Promise.all(view.map((child) => callSelf(child)))).join("");
}
if (typeof view === "string" || typeof view === "number" || typeof view === "boolean") {
return escapeHtml(`${view}`, Escape.NoQuotes);
}
if (!view) {
return "";
}
if (isComponentType(view)) {
view = {
attrs,
state: {},
tag: view,
} as Vnode<any, any>;
}
// view must be a Vnode
let result: string = "";
if (typeof view.tag === "string") {
await parseHooks(view, hooks);
if (view.tag === "[") {
// fragment
result = await callSelf(view.children);
} else if (view.tag === "<") {
// trusted html
result = `${Array.isArray(view.children) ? view.children.join("") : view.children}`;
} else if (view.tag === "#") {
// text
result = escapeHtml(
`${view.text ? view.text : Array.isArray(view.children) ? view.children.join("") : view.children}`,
);
} else {
// tag
const childs = await callSelf(view.text ? view.text : view.children);
const attributes = createAttrString(view);
if (!childs.length && (VOID_TAGS.indexOf(view.tag.toLowerCase()) >= 0 || strict)) {
result = `<${view.tag}${attributes.length > 0 ? ` ${attributes}` : ""}${strict ? "/" : ""}>`;
} else {
result = [
`<${view.tag}${attributes.length > 0 ? ` ${attributes}` : ""}>`,
childs,
`</${view.tag}>`,
].join("");
}
}
} else if (isComponentType(view.tag)) {
const tag = view.tag as ComponentTypes<any, any>;
if (isComponent(tag)) {
view.state = tag;
} else if (isClassComponent(tag)) {
view.state = new tag(view);
Object.assign(view.state, tag.prototype, view.state);
} else if (isFactoryComponent(tag)) {
view.state = tag(view);
}
await parseHooks(view, hooks);
if (isComponent(view.state)) {
// just to be sure...
result = await callSelf(view.state.view.call(view.state, view));
}
} else {
throw new Error(`unknown component: '${view}'`);
}
// tslint:disable-next-line:prefer-const
for (let hook of hooks) {
await hook();
}
return result;
}
export default render;