-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathSandpackWithHTMLOutput.tsx
More file actions
92 lines (84 loc) · 2.41 KB
/
SandpackWithHTMLOutput.tsx
File metadata and controls
92 lines (84 loc) · 2.41 KB
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Children, memo} from 'react';
import InlineCode from './InlineCode';
import Sandpack from './Sandpack';
const ShowRenderedHTML = `
import { renderToStaticMarkup } from 'react-dom/server';
import formatHTML from './formatHTML.js';
export default function ShowRenderedHTML({children}) {
const markup = renderToStaticMarkup(
<html>
<head />
<body>{children}</body>
</html>
);
return (
<>
<h1>Rendered HTML:</h1>
<pre>
{formatHTML(markup)}
</pre>
</>
);
}`;
const formatHTML = `
import format from 'html-format';
export default function formatHTML(markup) {
// Cheap tricks to format the HTML readably -- haven't been able to
// find a package that runs in browser and prettifies the HTML if it
// lacks line-breaks.
return format(markup
.replace('<html>', '<html>\\n')
.replace('<head>', '<head>\\n')
.replaceAll(/<\\/script>/g, '<\\/script>\\n')
.replaceAll(/<style([^>]*)\\/>/g, '<style $1/>\\n\\n')
.replaceAll(/<\\/style>/g, '\\n <\\/style>\\n')
.replaceAll(/<link([^>]*)\\/>/g, '<link $1/>\\n')
.replaceAll(/<meta([^/]*)\\/>/g, '<meta $1/>\\n')
.replace('</head>', '</head>\\n')
.replace('<body>', '<body>\\n')
.replace('</body>', '\\n</body>\\n')
.replace('</h1>', '</h1>\\n')
);
}
`;
const packageJSON = `
{
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-scripts": "^5.0.0",
"html-format": "^1.1.2"
},
"main": "/index.js",
"devDependencies": {}
}
`;
// Intentionally not a React component because <Sandpack> will read
// through its childrens' props. This imitates the output of ```
// codeblocks in MDX.
function createFile(meta: string, source: string) {
return (
<pre key={meta}>
<InlineCode meta={meta} className="language-js">
{source}
</InlineCode>
</pre>
);
}
export default memo(function SandpackWithHTMLOutput(
props: React.ComponentProps<typeof Sandpack>
) {
const children = [
...Children.toArray(props.children),
createFile('src/ShowRenderedHTML.js', ShowRenderedHTML),
createFile('src/formatHTML.js hidden', formatHTML),
createFile('package.json hidden', packageJSON),
];
return <Sandpack {...props}>{children}</Sandpack>;
});