Skip to content

Commit

Permalink
feat(hiccup): support array attrib values, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jun 24, 2020
1 parent 687a49b commit 1c4ef8a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions packages/hiccup/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,8 @@ export const SVG_TAGS = tagMap(
export const VOID_TAGS = tagMap(
"area base br circle col command ellipse embed hr img input keygen line link meta param path polygon polyline rect source stop track use wbr ?xml"
);

export const ATTRIB_JOIN_DELIMS: Record<string, string> = {
sizes: ",",
srcset: ",",
};
13 changes: 11 additions & 2 deletions packages/hiccup/src/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ import {
isFunction,
isNotStringAndIterable,
isString,
isArray,
} from "@thi.ng/checks";
import { illegalArgs } from "@thi.ng/errors";
import { COMMENT, NO_SPANS, PROC_TAGS, VOID_TAGS } from "./api";
import {
COMMENT,
NO_SPANS,
PROC_TAGS,
VOID_TAGS,
ATTRIB_JOIN_DELIMS,
} from "./api";
import { escape } from "./escape";
import { normalize } from "./normalize";

Expand Down Expand Up @@ -250,7 +257,9 @@ const serializeAttribs = (attribs: any, esc: boolean) => {
if (v === true) {
res += " " + a;
} else if (v !== false) {
v = v.toString();
v = isArray(v)
? v.join(ATTRIB_JOIN_DELIMS[a] || " ")
: v.toString();
v.length && (res += ` ${a}="${esc ? escape(v) : v}"`);
}
}
Expand Down
12 changes: 12 additions & 0 deletions packages/hiccup/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ describe("serialize", () => {
`<div foo="[object Object]"></div>`
);

check(
"array attr join (fallback)",
["a", { ping: ["google.com", "fb.com"] }],
`<a ping="google.com fb.com"></a>`
);

check(
"array attr join (delim)",
["img", { srcset: ["a.jpg", "b.jpg"] }],
`<img srcset="a.jpg,b.jpg"/>`
);

check("attr fn", ["div", { foo: () => 23 }], `<div foo="23"></div>`);

check(
Expand Down

0 comments on commit 1c4ef8a

Please sign in to comment.