-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
index.js
399 lines (338 loc) · 10.1 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
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
import {
encodeEntities,
styleObjToCss,
getContext,
createComponent,
UNSAFE_NAME,
XLINK,
VOID_ELEMENTS
} from './util';
import { options, h, Fragment } from 'preact';
import { _renderToStringPretty } from './pretty';
import {
COMMIT,
COMPONENT,
DIFF,
DIFFED,
DIRTY,
NEXT_STATE,
PARENT,
RENDER,
SKIP_EFFECTS,
VNODE,
CHILDREN
} from './constants';
/** @typedef {import('preact').VNode} VNode */
const SHALLOW = { shallow: true };
/** Render Preact JSX + Components to an HTML string.
* @name render
* @function
* @param {VNode} vnode JSX VNode to render.
* @param {Object} [context={}] Optionally pass an initial context object through the render path.
* @param {Object} [options={}] Rendering options
* @param {Boolean} [options.shallow=false] If `true`, renders nested Components as HTML elements (`<Foo a="b" />`).
* @param {Boolean} [options.xml=false] If `true`, uses self-closing tags for elements without children.
* @param {Boolean} [options.pretty=false] If `true`, adds whitespace for readability
* @param {RegExp|undefined} [options.voidElements] RegeEx that matches elements that are considered void (self-closing)
*/
renderToString.render = renderToString;
/** Only render elements, leaving Components inline as `<ComponentName ... />`.
* This method is just a convenience alias for `render(vnode, context, { shallow:true })`
* @name shallow
* @function
* @param {VNode} vnode JSX VNode to render.
* @param {Object} [context={}] Optionally pass an initial context object through the render path.
*/
let shallowRender = (vnode, context) => renderToString(vnode, context, SHALLOW);
const EMPTY_ARR = [];
function renderToString(vnode, context, opts) {
context = 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;
const parent = h(Fragment, null);
parent[CHILDREN] = [vnode];
let res;
if (
opts &&
(opts.pretty ||
opts.voidElements ||
opts.sortAttributes ||
opts.shallow ||
opts.allAttributes ||
opts.xml ||
opts.attributeHook)
) {
res = _renderToStringPretty(vnode, context, opts);
} else {
res = _renderToString(vnode, context, false, undefined, parent);
}
// 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;
return res;
}
function renderFunctionComponent(vnode, context) {
let rendered,
c = createComponent(vnode, context),
cctx = getContext(vnode.type, context);
vnode[COMPONENT] = c;
// 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 renderHook = options[RENDER];
let count = 0;
while (c[DIRTY] && count++ < 25) {
c[DIRTY] = false;
if (renderHook) renderHook(vnode);
// stateless functional components
rendered = vnode.type.call(c, vnode.props, cctx);
}
return rendered;
}
function renderClassComponent(vnode, context) {
let nodeName = vnode.type,
cctx = getContext(nodeName, context);
// c = new nodeName(props, context);
let c = new nodeName(vnode.props, cctx);
vnode[COMPONENT] = c;
c[VNODE] = vnode;
// turn off stateful re-rendering:
c[DIRTY] = true;
c.props = vnode.props;
if (c.state == null) c.state = {};
if (c[NEXT_STATE] == null) {
c[NEXT_STATE] = c.state;
}
c.context = cctx;
if (nodeName.getDerivedStateFromProps) {
c.state = assign(
{},
c.state,
nodeName.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;
}
let renderHook = options[RENDER];
if (renderHook) renderHook(vnode);
return c.render(c.props, c.state, c.context);
}
function normalizePropName(name, isSvgMode) {
if (name === 'className') {
return 'class';
} else if (name === 'htmlFor') {
return 'for';
} else if (name === 'defaultValue') {
return 'value';
} else if (name === 'defaultChecked') {
return 'checked';
} else if (name === 'defaultSelected') {
return 'selected';
} else if (isSvgMode && XLINK.test(name)) {
return name.toLowerCase().replace(/^xlink:?/, 'xlink:');
}
return name;
}
function normalizePropValue(name, v) {
if (name === 'style' && v != null && typeof v === 'object') {
return styleObjToCss(v);
} else if (name[0] === 'a' && name[1] === 'r' && typeof v === 'boolean') {
// always use string values instead of booleans for aria attributes
// also see https://github.com/preactjs/preact/pull/2347/files
return String(v);
}
return v;
}
const isArray = Array.isArray;
const assign = Object.assign;
/** The default export is an alias of `render()`. */
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') {
return encodeEntities(vnode);
}
// Recurse into children / Arrays
if (isArray(vnode)) {
let rendered = '';
parent[CHILDREN] = vnode;
for (let i = 0; i < vnode.length; i++) {
rendered =
rendered +
_renderToString(vnode[i], context, isSvgMode, selectValue, parent);
}
return rendered;
}
// VNodes have {constructor:undefined} to prevent JSON injection:
if (vnode.constructor !== undefined) return '';
vnode[PARENT] = parent;
if (options[DIFF]) options[DIFF](vnode);
let type = vnode.type,
props = vnode.props;
// Invoke rendering on Components
const isComponent = typeof type === 'function';
if (isComponent) {
let rendered;
if (type === Fragment) {
rendered = props.children;
} else {
if (type.prototype && typeof type.prototype.render === 'function') {
rendered = renderClassComponent(vnode, context);
} else {
rendered = renderFunctionComponent(vnode, context);
}
let component = vnode[COMPONENT];
if (component.getChildContext) {
context = assign({}, context, component.getChildContext());
}
}
// Recurse into children before invoking the after-diff hook
const str = _renderToString(
rendered,
context,
isSvgMode,
selectValue,
vnode
);
if (options[DIFFED]) options[DIFFED](vnode);
vnode[PARENT] = undefined;
if (options.unmount) options.unmount(vnode);
return str;
}
// Serialize Element VNodes to HTML
let s = '<',
children,
html;
s = s + type;
if (props) {
children = props.children;
for (let name in props) {
let v = props[name];
if (
name === 'key' ||
name === 'ref' ||
name === '__self' ||
name === '__source' ||
name === 'children' ||
(name === 'className' && 'class' in props) ||
(name === 'htmlFor' && 'for' in props)
) {
continue;
}
if (UNSAFE_NAME.test(name)) continue;
name = normalizePropName(name, isSvgMode);
v = normalizePropValue(name, v);
if (name === 'dangerouslySetInnerHTML') {
html = v && v.__html;
} else if (type === 'textarea' && name === 'value') {
// <textarea value="a&b"> --> <textarea>a&b</textarea>
children = v;
} else if ((v || v === 0 || v === '') && typeof v !== 'function') {
if (v === true || v === '') {
v = name;
s = s + ' ' + name;
continue;
}
if (name === 'value') {
if (type === 'select') {
selectValue = v;
continue;
} else if (
// If we're looking at an <option> and it's the currently selected one
type === 'option' &&
selectValue == v &&
// and the <option> doesn't already have a selected attribute on it
!('selected' in props)
) {
s = s + ' selected';
}
}
s = s + ' ' + name + '="' + encodeEntities(v) + '"';
}
}
}
let startElement = s;
s = s + '>';
if (UNSAFE_NAME.test(type)) {
throw new Error(`${type} is not a valid HTML tag name in ${s}`);
}
let pieces = '';
let hasChildren = false;
if (html) {
pieces = pieces + html;
hasChildren = true;
} else if (typeof children === 'string') {
pieces = pieces + encodeEntities(children);
hasChildren = true;
} else if (isArray(children)) {
vnode[CHILDREN] = children;
for (let i = 0; i < children.length; i++) {
let child = children[i];
if (child != null && child !== false) {
let childSvgMode =
type === 'svg' || (type !== 'foreignObject' && isSvgMode);
let ret = _renderToString(
child,
context,
childSvgMode,
selectValue,
vnode
);
// Skip if we received an empty string
if (ret) {
pieces = pieces + ret;
hasChildren = true;
}
}
}
} else if (children != null && children !== false && children !== true) {
vnode[CHILDREN] = [children];
let childSvgMode =
type === 'svg' || (type !== 'foreignObject' && isSvgMode);
let ret = _renderToString(
children,
context,
childSvgMode,
selectValue,
vnode
);
// Skip if we received an empty string
if (ret) {
pieces = pieces + ret;
hasChildren = true;
}
}
if (options[DIFFED]) options[DIFFED](vnode);
vnode[PARENT] = undefined;
if (options.unmount) options.unmount(vnode);
if (hasChildren) {
s = s + pieces;
} else if (VOID_ELEMENTS.test(type)) {
return startElement + ' />';
}
return s + '</' + type + '>';
}
/** The default export is an alias of `render()`. */
renderToString.shallowRender = shallowRender;
export default renderToString;
export {
renderToString as render,
renderToString as renderToStaticMarkup,
renderToString,
shallowRender
};