Skip to content

Commit

Permalink
feat(hiccup): emmet class & class attrib merging in normalize()
Browse files Browse the repository at this point in the history
- now same behavior as hdom's normalizeElement()
- update tests
  • Loading branch information
postspectacular committed Sep 23, 2018
1 parent ff5e555 commit 1d8eeb4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
21 changes: 11 additions & 10 deletions packages/hiccup/src/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,10 @@ const _serializeIter = (iter: Iterable<any>, ctx: any, esc: boolean, span: boole
}

const normalize = (tag: any[]) => {
let el = tag[0], match, id, clazz;
const attribs: any = {};
let el = tag[0];
let match, id, clazz;
const hasAttribs = isPlainObject(tag[1]);
const attribs: any = hasAttribs ? { ...tag[1] } : {};
if (!isString(el) || !(match = TAG_REGEXP.exec(el))) {
illegalArgs(`"${el}" is not a valid tag name`);
}
Expand All @@ -234,19 +236,18 @@ const normalize = (tag: any[]) => {
attribs.id = id;
}
if (clazz) {
attribs.class = clazz.replace(/\./g, " ");
clazz = clazz.replace(/\./g, " ");
if (attribs.class) {
attribs.class += " " + clazz;
} else {
attribs.class = clazz;
}
}
if (tag.length > 1) {
let i = 1;
const att = tag[1];
if (isPlainObject(att)) {
Object.assign(attribs, att);
i++;
}
if (isPlainObject(attribs.style)) {
attribs.style = css(attribs.style);
}
tag = tag.slice(i).filter((x) => x != null);
tag = tag.slice(hasAttribs ? 2 : 1).filter((x) => x != null);
if (tag.length > 0) {
return [el, attribs, tag];
}
Expand Down
8 changes: 7 additions & 1 deletion packages/hiccup/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ describe("serialize", () => {
check(
"div w/ id, class & attrib",
["div#foo.bar.baz", { extra: 23 }, "foo"],
`<div id="foo" class="bar baz" extra="23">foo</div>`
`<div extra="23" id="foo" class="bar baz">foo</div>`
);

check(
"div w/ class merging",
["div.foo", { class: "bar baz" }, "foo"],
`<div class="bar baz foo">foo</div>`
);

check(
Expand Down

0 comments on commit 1d8eeb4

Please sign in to comment.