-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathindex.js
373 lines (319 loc) · 9.27 KB
/
index.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
import { encodeEntities, styleObjToCss, UNSAFE_NAME, XLINK } from './util';
import { options, h, Fragment } from 'preact';
import {
CHILDREN,
COMMIT,
COMPONENT,
DIFF,
DIFFED,
DIRTY,
NEXT_STATE,
PARENT,
RENDER,
SKIP_EFFECTS,
VNODE
} from './constants';
/** @typedef {import('preact').VNode} VNode */
const EMPTY_ARR = [];
const isArray = Array.isArray;
const assign = Object.assign;
// Global state for the current render pass
let beforeDiff, afterDiff, renderHook;
/**
* Render Preact JSX + Components to an HTML string.
* @param {VNode} vnode JSX Element / VNode to render
* @param {Object} [context={}] Initial root context object
* @returns {string} serialized HTML
*/
export default function renderToString(vnode, context) {
// Performance optimization: `renderToString` is synchronous and we
// therefore don't execute any effects. To do that we pass an empty
// array to `options._commit` (`__c`). But we can go one step further
// and avoid a lot of dirty checks and allocations by setting
// `options._skipEffects` (`__s`) too.
const previousSkipEffects = options[SKIP_EFFECTS];
options[SKIP_EFFECTS] = true;
// store options hooks once before each synchronous render call
beforeDiff = options[DIFF];
afterDiff = options[DIFFED];
renderHook = options[RENDER];
const parent = h(Fragment, null);
parent[CHILDREN] = [vnode];
try {
return _renderToString(vnode, context || {}, false, undefined, parent);
} finally {
// options._commit, we don't schedule any effects in this library right now,
// so we can pass an empty queue to this hook.
if (options[COMMIT]) options[COMMIT](vnode, EMPTY_ARR);
options[SKIP_EFFECTS] = previousSkipEffects;
EMPTY_ARR.length = 0;
}
}
// Installed as setState/forceUpdate for function components
function markAsDirty() {
this.__d = true;
}
/**
* @param {VNode} vnode
* @param {Record<string, unknown>} context
*/
function renderClassComponent(vnode, context) {
let type = /** @type {import("preact").ComponentClass<typeof vnode.props>} */ (vnode.type);
let c = new type(vnode.props, context);
vnode[COMPONENT] = c;
c[VNODE] = vnode;
c.props = vnode.props;
c.context = context;
// turn off stateful re-rendering:
c[DIRTY] = true;
if (c.state == null) c.state = {};
if (c[NEXT_STATE] == null) {
c[NEXT_STATE] = c.state;
}
if (type.getDerivedStateFromProps) {
c.state = assign(
{},
c.state,
type.getDerivedStateFromProps(c.props, c.state)
);
} else if (c.componentWillMount) {
c.componentWillMount();
// If the user called setState in cWM we need to flush pending,
// state updates. This is the same behaviour in React.
c.state = c[NEXT_STATE] !== c.state ? c[NEXT_STATE] : c.state;
}
if (renderHook) renderHook(vnode);
return c.render(c.props, c.state, context);
}
/**
* Recursively render VNodes to HTML.
* @param {VNode|any} vnode
* @param {any} context
* @param {boolean} isSvgMode
* @param {any} selectValue
* @param {VNode} parent
* @returns {string}
*/
function _renderToString(vnode, context, isSvgMode, selectValue, parent) {
// Ignore non-rendered VNodes/values
if (vnode == null || vnode === true || vnode === false || vnode === '') {
return '';
}
// Text VNodes: escape as HTML
if (typeof vnode !== 'object') {
if (typeof vnode === 'function') return '';
return encodeEntities(vnode + '');
}
// Recurse into children / Arrays
if (isArray(vnode)) {
let rendered = '';
parent[CHILDREN] = vnode;
for (let i = 0; i < vnode.length; i++) {
let child = vnode[i];
if (child == null || typeof child === 'boolean') continue;
rendered =
rendered +
_renderToString(child, context, isSvgMode, selectValue, parent);
if (
typeof child === 'string' ||
typeof child === 'number' ||
typeof child === 'bigint'
) {
// @ts-ignore manually constructing a Text vnode
vnode[i] = h(null, null, child);
}
}
return rendered;
}
// VNodes have {constructor:undefined} to prevent JSON injection:
if (vnode.constructor !== undefined) return '';
vnode[PARENT] = parent;
if (beforeDiff) beforeDiff(vnode);
let type = vnode.type,
props = vnode.props,
cctx = context,
contextType,
rendered,
component;
// Invoke rendering on Components
let isComponent = typeof type === 'function';
if (isComponent) {
if (type === Fragment) {
rendered = props.children;
} else {
contextType = type.contextType;
if (contextType != null) {
let provider = context[contextType.__c];
cctx = provider ? provider.props.value : contextType.__;
}
if (type.prototype && typeof type.prototype.render === 'function') {
rendered = /**#__NOINLINE__**/ renderClassComponent(vnode, cctx);
component = vnode[COMPONENT];
} else {
component = {
__v: vnode,
props,
context: cctx,
// silently drop state updates
setState: markAsDirty,
forceUpdate: markAsDirty,
__d: true,
// hooks
__h: []
};
vnode[COMPONENT] = component;
// If a hook invokes setState() to invalidate the component during rendering,
// re-render it up to 25 times to allow "settling" of memoized states.
// Note:
// This will need to be updated for Preact 11 to use internal.flags rather than component._dirty:
// https://github.com/preactjs/preact/blob/d4ca6fdb19bc715e49fd144e69f7296b2f4daa40/src/diff/component.js#L35-L44
let count = 0;
while (component[DIRTY] && count++ < 25) {
component[DIRTY] = false;
if (renderHook) renderHook(vnode);
rendered = type.call(component, props, cctx);
}
component[DIRTY] = true;
}
if (component.getChildContext != null) {
context = assign({}, context, component.getChildContext());
}
}
// When a component returns a Fragment node we flatten it in core, so we
// need to mirror that logic here too
let isTopLevelFragment =
rendered != null && rendered.type === Fragment && rendered.key == null;
rendered = isTopLevelFragment ? rendered.props.children : rendered;
// Recurse into children before invoking the after-diff hook
const str = _renderToString(
rendered,
context,
isSvgMode,
selectValue,
vnode
);
if (afterDiff) afterDiff(vnode);
vnode[PARENT] = undefined;
if (options.unmount) options.unmount(vnode);
return str;
}
// Serialize Element VNodes to HTML
let s = '<' + type,
html = '',
children;
for (let name in props) {
let v = props[name];
switch (name) {
case 'children':
children = v;
continue;
// VDOM-specific props
case 'key':
case 'ref':
case '__self':
case '__source':
continue;
// prefer for/class over htmlFor/className
case 'htmlFor':
if ('for' in props) continue;
name = 'for';
break;
case 'className':
if ('class' in props) continue;
name = 'class';
break;
// Form element reflected properties
case 'defaultChecked':
name = 'checked';
break;
case 'defaultSelected':
name = 'selected';
break;
// Special value attribute handling
case 'defaultValue':
case 'value':
name = 'value';
switch (type) {
// <textarea value="a&b"> --> <textarea>a&b</textarea>
case 'textarea':
children = v;
continue;
// <select value> is serialized as a selected attribute on the matching option child
case 'select':
selectValue = v;
continue;
// Add a selected attribute to <option> if its value matches the parent <select> value
case 'option':
if (selectValue == v && !('selected' in props)) {
s = s + ' selected';
}
break;
}
break;
case 'dangerouslySetInnerHTML':
html = v && v.__html;
continue;
// serialize object styles to a CSS string
case 'style':
if (typeof v === 'object') {
v = styleObjToCss(v);
}
break;
default:
if (isSvgMode && XLINK.test(name)) {
name = name.toLowerCase().replace(/^xlink:?/, 'xlink:');
} else if (UNSAFE_NAME.test(name)) {
continue;
} else if (name[0] === 'a' && name[1] === 'r' && v != null) {
// serialize boolean aria-xyz attribute values as strings
v += '';
}
}
// write this attribute to the buffer
if (v != null && v !== false && typeof v !== 'function') {
if (v === true || v === '') {
s = s + ' ' + name;
} else {
s = s + ' ' + name + '="' + encodeEntities(v + '') + '"';
}
}
}
if (UNSAFE_NAME.test(type)) {
throw new Error(`${type} is not a valid HTML tag name in ${s}>`);
}
if (html) {
// dangerouslySetInnerHTML defined this node's contents
} else if (typeof children === 'string') {
// single text child
html = encodeEntities(children);
} else if (children != null && children !== false && children !== true) {
// recurse into this element VNode's children
let childSvgMode =
type === 'svg' || (type !== 'foreignObject' && isSvgMode);
html = _renderToString(children, context, childSvgMode, selectValue, vnode);
}
if (afterDiff) afterDiff(vnode);
vnode[PARENT] = undefined;
if (options.unmount) options.unmount(vnode);
// Emit self-closing tag for empty void elements:
if (!html) {
switch (type) {
case 'area':
case 'base':
case 'br':
case 'col':
case 'embed':
case 'hr':
case 'img':
case 'input':
case 'link':
case 'meta':
case 'param':
case 'source':
case 'track':
case 'wbr':
return s + ' />';
}
}
return s + '>' + html + '</' + type + '>';
}