Skip to content

Commit 827aa51

Browse files
castastrophekylebuch8
authored andcommitted
Update Storybook utils to support self-closing tag (#411)
* Pull out the utils updates for self-closing tag support * moving the duplicated selfClosing variables to a constant at the top of the file
1 parent 5ba9567 commit 827aa51

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

.storybook/utils.js

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ const loremIpsum = require("lorem-ipsum");
77
// https://www.npmjs.com/package/clean-html
88
const cleaner = require("clean-html");
99

10+
// Most common self-closing tags = br, hr, img, input, link
11+
const selfClosing = ["br", "hr", "img", "input", "link"];
12+
1013
// Escape HTML to display markup as content
1114
export function escapeHTML(html) {
1215
const div = document.createElement("div");
@@ -74,20 +77,17 @@ export function customTag(obj) {
7477
// If a tag is defined, or it has slots or attributes to apply
7578
// render an open and close tag
7679
if (obj.tag || obj.slot || obj.attributes) {
77-
start += "<";
78-
end += "</";
7980
// If a tag is defined, use that, else use a div
8081
if (obj.tag) {
81-
start += obj.tag;
82-
end += obj.tag;
82+
start += `<${obj.tag}`;
83+
end += !selfClosing.includes(obj.tag) ? `</${obj.tag}>` : "";
8384
} else {
84-
start += "div";
85-
end += "div";
85+
start += "<div";
86+
end += "</div>";
8687
}
8788
start += obj.slot ? ` slot="${obj.slot}"` : "";
8889
start += obj.attributes ? listProperties(obj.attributes || {}) : "";
89-
start += ">";
90-
end += ">";
90+
start += !selfClosing.includes(obj.tag) ? ">" : "/>";
9191
}
9292
return `${start}${obj.content}${end}`;
9393
}
@@ -108,9 +108,9 @@ const parseMarkup = string => {
108108
// If results remain in the array, get the attributes
109109
if (result.length > 1 && typeof result[2] === "string") {
110110
// Break the attributes apart using the spaces
111-
let attr = result[2].trim().split(" ");
111+
let attr = result[2].trim().match(/[\w|-]+="[^"]+"/g);
112112
// If any attributes exist, break them down further
113-
if (attr.length > 0) {
113+
if (attr !== null) {
114114
attr.forEach(set => {
115115
// Break the attributes apart using the equal sign
116116
let items = set.trim().split("=");
@@ -150,9 +150,10 @@ const renderSlots = (slots = []) =>
150150
typeof slot.attributes !== "undefined" &&
151151
Object.keys(slot.attributes).length > 0;
152152
if (!has_tag && (has_slot || has_attr)) {
153-
Object.assign(slot, parseMarkup(slot.content));
153+
let parsed = parseMarkup(slot.content);
154+
Object.assign(slot, parsed);
154155
}
155-
return slot.content
156+
return slot.content || slot.tag && selfClosing.includes(slot.tag)
156157
? customTag({
157158
tag: slot.tag,
158159
slot: slot.slot,

0 commit comments

Comments
 (0)