-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathwithHTML.ts
43 lines (40 loc) · 1.27 KB
/
withHTML.ts
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
import { useChannel } from "@storybook/preview-api";
import type {
Renderer,
PartialStoryFn as StoryFunction,
} from "@storybook/types";
import { EVENTS } from "./constants";
import { Parameters } from "./types";
export const withHTML = (
storyFn: StoryFunction<Renderer>,
{
parameters: { html: parameters = {} } = {},
}: { parameters?: { html?: Parameters } },
) => {
const emit = useChannel({});
setTimeout(() => {
const rootSelector = parameters.root || "#storybook-root, #root";
const root = document.querySelector(rootSelector);
let code: string = root ? root.innerHTML : `${rootSelector} not found.`;
const { removeEmptyComments, removeComments, transform } = parameters;
if (removeEmptyComments) {
code = code.replace(/<!--\s*-->/g, "");
}
if (removeComments === true) {
code = code.replace(/<!--[\S\s]*?-->/g, "");
} else if (removeComments instanceof RegExp) {
code = code.replace(/<!--([\S\s]*?)-->/g, (match, p1) =>
removeComments.test(p1) ? "" : match,
);
}
if (typeof transform === "function") {
try {
code = transform(code);
} catch (e) {
console.error(e);
}
}
emit(EVENTS.CODE_UPDATE, { code, options: parameters });
}, 0);
return storyFn();
};