preact-render-to-string 5.2.0 → 5.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pretty.js ADDED
@@ -0,0 +1,385 @@
1
+ import {
2
+ encodeEntities,
3
+ indent,
4
+ isLargeString,
5
+ styleObjToCss,
6
+ getChildren,
7
+ createComponent,
8
+ getContext,
9
+ UNSAFE_NAME,
10
+ XLINK,
11
+ VOID_ELEMENTS
12
+ } from './util';
13
+ import { options, Fragment } from 'preact';
14
+
15
+ // components without names, kept as a hash for later comparison to return consistent UnnamedComponentXX names.
16
+ const UNNAMED = [];
17
+
18
+ export function _renderToStringPretty(
19
+ vnode,
20
+ context,
21
+ opts,
22
+ inner,
23
+ isSvgMode,
24
+ selectValue
25
+ ) {
26
+ if (vnode == null || typeof vnode === 'boolean') {
27
+ return '';
28
+ }
29
+
30
+ // #text nodes
31
+ if (typeof vnode !== 'object') {
32
+ return encodeEntities(vnode);
33
+ }
34
+
35
+ let pretty = opts.pretty,
36
+ indentChar = pretty && typeof pretty === 'string' ? pretty : '\t';
37
+
38
+ if (Array.isArray(vnode)) {
39
+ let rendered = '';
40
+ for (let i = 0; i < vnode.length; i++) {
41
+ if (pretty && i > 0) rendered = rendered + '\n';
42
+ rendered =
43
+ rendered +
44
+ _renderToStringPretty(
45
+ vnode[i],
46
+ context,
47
+ opts,
48
+ inner,
49
+ isSvgMode,
50
+ selectValue
51
+ );
52
+ }
53
+ return rendered;
54
+ }
55
+
56
+ let nodeName = vnode.type,
57
+ props = vnode.props,
58
+ isComponent = false;
59
+
60
+ // components
61
+ if (typeof nodeName === 'function') {
62
+ isComponent = true;
63
+ if (opts.shallow && (inner || opts.renderRootComponent === false)) {
64
+ nodeName = getComponentName(nodeName);
65
+ } else if (nodeName === Fragment) {
66
+ const children = [];
67
+ getChildren(children, vnode.props.children);
68
+ return _renderToStringPretty(
69
+ children,
70
+ context,
71
+ opts,
72
+ opts.shallowHighOrder !== false,
73
+ isSvgMode,
74
+ selectValue
75
+ );
76
+ } else {
77
+ let rendered;
78
+
79
+ let c = (vnode.__c = createComponent(vnode, context));
80
+
81
+ // options._diff
82
+ if (options.__b) options.__b(vnode);
83
+
84
+ // options._render
85
+ let renderHook = options.__r;
86
+
87
+ if (
88
+ !nodeName.prototype ||
89
+ typeof nodeName.prototype.render !== 'function'
90
+ ) {
91
+ let cctx = getContext(nodeName, context);
92
+
93
+ // If a hook invokes setState() to invalidate the component during rendering,
94
+ // re-render it up to 25 times to allow "settling" of memoized states.
95
+ // Note:
96
+ // This will need to be updated for Preact 11 to use internal.flags rather than component._dirty:
97
+ // https://github.com/preactjs/preact/blob/d4ca6fdb19bc715e49fd144e69f7296b2f4daa40/src/diff/component.js#L35-L44
98
+ let count = 0;
99
+ while (c.__d && count++ < 25) {
100
+ c.__d = false;
101
+
102
+ if (renderHook) renderHook(vnode);
103
+
104
+ // stateless functional components
105
+ rendered = nodeName.call(vnode.__c, props, cctx);
106
+ }
107
+ } else {
108
+ let cctx = getContext(nodeName, context);
109
+
110
+ // c = new nodeName(props, context);
111
+ c = vnode.__c = new nodeName(props, cctx);
112
+ c.__v = vnode;
113
+ // turn off stateful re-rendering:
114
+ c._dirty = c.__d = true;
115
+ c.props = props;
116
+ if (c.state == null) c.state = {};
117
+
118
+ if (c._nextState == null && c.__s == null) {
119
+ c._nextState = c.__s = c.state;
120
+ }
121
+
122
+ c.context = cctx;
123
+ if (nodeName.getDerivedStateFromProps)
124
+ c.state = Object.assign(
125
+ {},
126
+ c.state,
127
+ nodeName.getDerivedStateFromProps(c.props, c.state)
128
+ );
129
+ else if (c.componentWillMount) {
130
+ c.componentWillMount();
131
+
132
+ // If the user called setState in cWM we need to flush pending,
133
+ // state updates. This is the same behaviour in React.
134
+ c.state =
135
+ c._nextState !== c.state
136
+ ? c._nextState
137
+ : c.__s !== c.state
138
+ ? c.__s
139
+ : c.state;
140
+ }
141
+
142
+ if (renderHook) renderHook(vnode);
143
+
144
+ rendered = c.render(c.props, c.state, c.context);
145
+ }
146
+
147
+ if (c.getChildContext) {
148
+ context = Object.assign({}, context, c.getChildContext());
149
+ }
150
+
151
+ if (options.diffed) options.diffed(vnode);
152
+ return _renderToStringPretty(
153
+ rendered,
154
+ context,
155
+ opts,
156
+ opts.shallowHighOrder !== false,
157
+ isSvgMode,
158
+ selectValue
159
+ );
160
+ }
161
+ }
162
+
163
+ // render JSX to HTML
164
+ let s = '<' + nodeName,
165
+ propChildren,
166
+ html;
167
+
168
+ if (props) {
169
+ let attrs = Object.keys(props);
170
+
171
+ // allow sorting lexicographically for more determinism (useful for tests, such as via preact-jsx-chai)
172
+ if (opts && opts.sortAttributes === true) attrs.sort();
173
+
174
+ for (let i = 0; i < attrs.length; i++) {
175
+ let name = attrs[i],
176
+ v = props[name];
177
+ if (name === 'children') {
178
+ propChildren = v;
179
+ continue;
180
+ }
181
+
182
+ if (UNSAFE_NAME.test(name)) continue;
183
+
184
+ if (
185
+ !(opts && opts.allAttributes) &&
186
+ (name === 'key' ||
187
+ name === 'ref' ||
188
+ name === '__self' ||
189
+ name === '__source')
190
+ )
191
+ continue;
192
+
193
+ if (name === 'defaultValue') {
194
+ name = 'value';
195
+ } else if (name === 'defaultChecked') {
196
+ name = 'checked';
197
+ } else if (name === 'defaultSelected') {
198
+ name = 'selected';
199
+ } else if (name === 'className') {
200
+ if (typeof props.class !== 'undefined') continue;
201
+ name = 'class';
202
+ } else if (isSvgMode && XLINK.test(name)) {
203
+ name = name.toLowerCase().replace(/^xlink:?/, 'xlink:');
204
+ }
205
+
206
+ if (name === 'htmlFor') {
207
+ if (props.for) continue;
208
+ name = 'for';
209
+ }
210
+
211
+ if (name === 'style' && v && typeof v === 'object') {
212
+ v = styleObjToCss(v);
213
+ }
214
+
215
+ // always use string values instead of booleans for aria attributes
216
+ // also see https://github.com/preactjs/preact/pull/2347/files
217
+ if (name[0] === 'a' && name['1'] === 'r' && typeof v === 'boolean') {
218
+ v = String(v);
219
+ }
220
+
221
+ let hooked =
222
+ opts.attributeHook &&
223
+ opts.attributeHook(name, v, context, opts, isComponent);
224
+ if (hooked || hooked === '') {
225
+ s = s + hooked;
226
+ continue;
227
+ }
228
+
229
+ if (name === 'dangerouslySetInnerHTML') {
230
+ html = v && v.__html;
231
+ } else if (nodeName === 'textarea' && name === 'value') {
232
+ // <textarea value="a&b"> --> <textarea>a&amp;b</textarea>
233
+ propChildren = v;
234
+ } else if ((v || v === 0 || v === '') && typeof v !== 'function') {
235
+ if (v === true || v === '') {
236
+ v = name;
237
+ // in non-xml mode, allow boolean attributes
238
+ if (!opts || !opts.xml) {
239
+ s = s + ' ' + name;
240
+ continue;
241
+ }
242
+ }
243
+
244
+ if (name === 'value') {
245
+ if (nodeName === 'select') {
246
+ selectValue = v;
247
+ continue;
248
+ } else if (
249
+ // If we're looking at an <option> and it's the currently selected one
250
+ nodeName === 'option' &&
251
+ selectValue == v &&
252
+ // and the <option> doesn't already have a selected attribute on it
253
+ typeof props.selected === 'undefined'
254
+ ) {
255
+ s = s + ` selected`;
256
+ }
257
+ }
258
+ s = s + ` ${name}="${encodeEntities(v)}"`;
259
+ }
260
+ }
261
+ }
262
+
263
+ // account for >1 multiline attribute
264
+ if (pretty) {
265
+ let sub = s.replace(/\n\s*/, ' ');
266
+ if (sub !== s && !~sub.indexOf('\n')) s = sub;
267
+ else if (pretty && ~s.indexOf('\n')) s = s + '\n';
268
+ }
269
+
270
+ s = s + '>';
271
+
272
+ if (UNSAFE_NAME.test(nodeName))
273
+ throw new Error(`${nodeName} is not a valid HTML tag name in ${s}`);
274
+
275
+ let isVoid =
276
+ VOID_ELEMENTS.test(nodeName) ||
277
+ (opts.voidElements && opts.voidElements.test(nodeName));
278
+ let pieces = [];
279
+
280
+ let children;
281
+ if (html) {
282
+ // if multiline, indent.
283
+ if (pretty && isLargeString(html)) {
284
+ html = '\n' + indentChar + indent(html, indentChar);
285
+ }
286
+ s = s + html;
287
+ } else if (
288
+ propChildren != null &&
289
+ getChildren((children = []), propChildren).length
290
+ ) {
291
+ let hasLarge = pretty && ~s.indexOf('\n');
292
+ let lastWasText = false;
293
+
294
+ for (let i = 0; i < children.length; i++) {
295
+ let child = children[i];
296
+
297
+ if (child != null && child !== false) {
298
+ let childSvgMode =
299
+ nodeName === 'svg'
300
+ ? true
301
+ : nodeName === 'foreignObject'
302
+ ? false
303
+ : isSvgMode,
304
+ ret = _renderToStringPretty(
305
+ child,
306
+ context,
307
+ opts,
308
+ true,
309
+ childSvgMode,
310
+ selectValue
311
+ );
312
+
313
+ if (pretty && !hasLarge && isLargeString(ret)) hasLarge = true;
314
+
315
+ // Skip if we received an empty string
316
+ if (ret) {
317
+ if (pretty) {
318
+ let isText = ret.length > 0 && ret[0] != '<';
319
+
320
+ // We merge adjacent text nodes, otherwise each piece would be printed
321
+ // on a new line.
322
+ if (lastWasText && isText) {
323
+ pieces[pieces.length - 1] += ret;
324
+ } else {
325
+ pieces.push(ret);
326
+ }
327
+
328
+ lastWasText = isText;
329
+ } else {
330
+ pieces.push(ret);
331
+ }
332
+ }
333
+ }
334
+ }
335
+ if (pretty && hasLarge) {
336
+ for (let i = pieces.length; i--; ) {
337
+ pieces[i] = '\n' + indentChar + indent(pieces[i], indentChar);
338
+ }
339
+ }
340
+ }
341
+
342
+ if (pieces.length || html) {
343
+ s = s + pieces.join('');
344
+ } else if (opts && opts.xml) {
345
+ return s.substring(0, s.length - 1) + ' />';
346
+ }
347
+
348
+ if (isVoid && !children && !html) {
349
+ s = s.replace(/>$/, ' />');
350
+ } else {
351
+ if (pretty && ~s.indexOf('\n')) s = s + '\n';
352
+ s = s + `</${nodeName}>`;
353
+ }
354
+
355
+ return s;
356
+ }
357
+
358
+ function getComponentName(component) {
359
+ return (
360
+ component.displayName ||
361
+ (component !== Function && component.name) ||
362
+ getFallbackComponentName(component)
363
+ );
364
+ }
365
+
366
+ function getFallbackComponentName(component) {
367
+ let str = Function.prototype.toString.call(component),
368
+ name = (str.match(/^\s*function\s+([^( ]+)/) || '')[1];
369
+ if (!name) {
370
+ // search for an existing indexed name for the given component:
371
+ let index = -1;
372
+ for (let i = UNNAMED.length; i--; ) {
373
+ if (UNNAMED[i] === component) {
374
+ index = i;
375
+ break;
376
+ }
377
+ }
378
+ // not found, create a new indexed name:
379
+ if (index < 0) {
380
+ index = UNNAMED.push(component) - 1;
381
+ }
382
+ name = `UnnamedComponent${index}`;
383
+ }
384
+ return name;
385
+ }
package/src/util.js CHANGED
@@ -1,18 +1,46 @@
1
1
  // DOM properties that should NOT have "px" added when numeric
2
2
  export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i;
3
+ export const VOID_ELEMENTS = /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
4
+ export const UNSAFE_NAME = /[\s\n\\/='"\0<>]/;
5
+ export const XLINK = /^xlink:?./;
3
6
 
4
- const ENCODED_ENTITIES = /[&<>"]/;
7
+ const ENCODED_ENTITIES = /["&<]/;
5
8
 
6
- export function encodeEntities(input) {
7
- const s = String(input);
8
- if (!ENCODED_ENTITIES.test(s)) {
9
- return s;
9
+ export function encodeEntities(str) {
10
+ // Ensure we're always parsing and returning a string:
11
+ str += '';
12
+
13
+ // Skip all work for strings with no entities needing encoding:
14
+ if (ENCODED_ENTITIES.test(str) === false) return str;
15
+
16
+ let last = 0,
17
+ i = 0,
18
+ out = '',
19
+ ch = '';
20
+
21
+ // Seek forward in str until the next entity char:
22
+ for (; i < str.length; i++) {
23
+ switch (str.charCodeAt(i)) {
24
+ case 34:
25
+ ch = '&quot;';
26
+ break;
27
+ case 38:
28
+ ch = '&amp;';
29
+ break;
30
+ case 60:
31
+ ch = '&lt;';
32
+ break;
33
+ default:
34
+ continue;
35
+ }
36
+ // Append skipped/buffered characters and the encoded entity:
37
+ if (i !== last) out += str.slice(last, i);
38
+ out += ch;
39
+ // Start the next seek/buffer after the entity's offset:
40
+ last = i + 1;
10
41
  }
11
- return s
12
- .replace(/&/g, '&amp;')
13
- .replace(/</g, '&lt;')
14
- .replace(/>/g, '&gt;')
15
- .replace(/"/g, '&quot;');
42
+ if (i !== last) out += str.slice(last, i);
43
+ return out;
16
44
  }
17
45
 
18
46
  export let indent = (s, char) =>
@@ -25,6 +53,7 @@ export let isLargeString = (s, length, ignoreLines) =>
25
53
 
26
54
  const JS_TO_CSS = {};
27
55
 
56
+ const CSS_REGEX = /([A-Z])/g;
28
57
  // Convert an Object style to a CSSText string
29
58
  export function styleObjToCss(s) {
30
59
  let str = '';
@@ -37,30 +66,18 @@ export function styleObjToCss(s) {
37
66
  prop[0] == '-'
38
67
  ? prop
39
68
  : JS_TO_CSS[prop] ||
40
- (JS_TO_CSS[prop] = prop.replace(/([A-Z])/g, '-$1').toLowerCase());
41
- str += ': ';
42
- str += val;
69
+ (JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$1').toLowerCase());
70
+
43
71
  if (typeof val === 'number' && IS_NON_DIMENSIONAL.test(prop) === false) {
44
- str += 'px';
72
+ str = str + ': ' + val + 'px;';
73
+ } else {
74
+ str = str + ': ' + val + ';';
45
75
  }
46
- str += ';';
47
76
  }
48
77
  }
49
78
  return str || undefined;
50
79
  }
51
80
 
52
- /**
53
- * Copy all properties from `props` onto `obj`.
54
- * @param {object} obj Object onto which properties should be copied.
55
- * @param {object} props Object from which to copy properties.
56
- * @returns {object}
57
- * @private
58
- */
59
- export function assign(obj, props) {
60
- for (let i in props) obj[i] = props[i];
61
- return obj;
62
- }
63
-
64
81
  /**
65
82
  * Get flattened children from the children prop
66
83
  * @param {Array} accumulator
@@ -76,3 +93,33 @@ export function getChildren(accumulator, children) {
76
93
  }
77
94
  return accumulator;
78
95
  }
96
+
97
+ function markAsDirty() {
98
+ this.__d = true;
99
+ }
100
+
101
+ export function createComponent(vnode, context) {
102
+ return {
103
+ __v: vnode,
104
+ context,
105
+ props: vnode.props,
106
+ // silently drop state updates
107
+ setState: markAsDirty,
108
+ forceUpdate: markAsDirty,
109
+ __d: true,
110
+ // hooks
111
+ __h: []
112
+ };
113
+ }
114
+
115
+ // Necessary for createContext api. Setting this property will pass
116
+ // the context value as `this.context` just for this component.
117
+ export function getContext(nodeName, context) {
118
+ let cxType = nodeName.contextType;
119
+ let provider = cxType && context[cxType.__c];
120
+ return cxType != null
121
+ ? provider
122
+ ? provider.props.value
123
+ : cxType.__
124
+ : context;
125
+ }