1 | import './polyfills';
|
2 | import renderToString from './index';
|
3 | import { indent, encodeEntities, assign } from './util';
|
4 | import prettyFormat from 'pretty-format';
|
5 |
|
6 |
|
7 |
|
8 | let preactPlugin = {
|
9 | test(object) {
|
10 | return object && typeof object==='object' && 'nodeName' in object && 'attributes' in object && 'children' in object && !('nodeType' in object);
|
11 | },
|
12 | print(val, print, indent) {
|
13 | return renderToString(val, preactPlugin.context, preactPlugin.opts, true);
|
14 | }
|
15 | };
|
16 |
|
17 |
|
18 | let prettyFormatOpts = {
|
19 | plugins: [preactPlugin]
|
20 | };
|
21 |
|
22 |
|
23 | function attributeHook(name, value, context, opts, isComponent) {
|
24 | let type = typeof value;
|
25 |
|
26 |
|
27 | if (name==='dangerouslySetInnerHTML') return false;
|
28 |
|
29 |
|
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 |
|
53 | let defaultOpts = {
|
54 | attributeHook,
|
55 | jsx: true,
|
56 | xml: false,
|
57 | functions: true,
|
58 | functionNames: true,
|
59 | skipFalseAttributes: true,
|
60 | pretty: ' '
|
61 | };
|
62 |
|
63 |
|
64 | export default function renderToJsxString(vnode, context, opts, inner) {
|
65 | opts = assign(assign({}, defaultOpts), opts || {});
|
66 | return renderToString(vnode, context, opts, inner);
|
67 | }
|