UNPKG

1.96 kBJavaScriptView Raw
1import './polyfills';
2import renderToString from './index';
3import { indent, encodeEntities, assign } from './util';
4import prettyFormat from 'pretty-format';
5
6
7// we have to patch in Array support, Possible issue in npm.im/pretty-format
8let preactPlugin = {
9 test(object) {
10 return object && typeof object==='object' && 'type' in object && 'props' in object && 'key' in object;
11 },
12 print(val, print, indent) {
13 return renderToString(val, preactPlugin.context, preactPlugin.opts, true);
14 }
15};
16
17
18let prettyFormatOpts = {
19 plugins: [preactPlugin]
20};
21
22
23function attributeHook(name, value, context, opts, isComponent) {
24 let type = typeof value;
25
26 // Use render-to-string's built-in handling for these properties
27 if (name==='dangerouslySetInnerHTML') return false;
28
29 // always skip null & undefined values, skip false DOM attributes, skip functions if told to
30 if (value==null || (type==='function' && !opts.functions)) return '';
31
32 if (opts.skipFalseAttributes && !isComponent && (value===false || ((name==='class' || name==='style') && value===''))) return '';
33
34 let indentChar = typeof opts.pretty==='string' ? opts.pretty : '\t';
35 if (type!=='string') {
36 if (type==='function' && !opts.functionNames) {
37 value = 'Function';
38 }
39 else {
40 preactPlugin.context = context;
41 preactPlugin.opts = opts;
42 value = prettyFormat(value, prettyFormatOpts);
43 if (~value.indexOf('\n')) {
44 value = `${indent('\n'+value, indentChar)}\n`;
45 }
46 }
47 return indent(`\n${name}={${value}}`, indentChar);
48 }
49 return `\n${indentChar}${name}="${encodeEntities(value)}"`;
50}
51
52
53let defaultOpts = {
54 attributeHook,
55 jsx: true,
56 xml: false,
57 functions: true,
58 functionNames: true,
59 skipFalseAttributes: true,
60 pretty: ' '
61};
62
63
64function renderToJsxString(vnode, context, opts, inner) {
65 opts = assign(assign({}, defaultOpts), opts || {});
66 return renderToString(vnode, context, opts, inner);
67}
68
69export default renderToJsxString;
70export { renderToJsxString as render };