Skip to content

Commit

Permalink
feat(hiccup): add SerializeOpts.xml, update serializeAttrib
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Apr 23, 2024
1 parent 5dd66c1 commit 8fdcab9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/hiccup/src/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ export interface SerializeOpts {
* @defaultValue false
*/
keys: boolean;
/**
* If true, some serialization behaviors will be adjusted to target XML
* output.
*
* @remarks
* Currently, the following aspects are supported:
*
* - boolean attributes are serialized as `name=""` rather than just `name`
*
* @defaultValue false
*/
xml: boolean;
}

/**
Expand Down Expand Up @@ -191,8 +203,9 @@ export const serialize = (
const $opts = {
escape: false,
escapeFn: escapeEntitiesNum,
span: false,
keys: false,
span: false,
xml: false,
...opts,
};
if (opts?.keys == null && $opts.span) $opts.keys = true;
Expand Down Expand Up @@ -274,7 +287,7 @@ const serializeAttrib = (
: isFunction(v) && (/^on\w+/.test(a) || (v = v(attribs)) == null)
? null
: v === true
? " " + a
? " " + a + (opts.xml ? `=""` : "")
: v === false
? null
: a === "data"
Expand Down
5 changes: 5 additions & 0 deletions packages/hiccup/test/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ test("<br> w/ body", () => {

check("div w/ bool attr (true)", ["div", { bool: true }], `<div bool></div>`);

test("div w/ bool attr (true, XML)", () =>
expect(serialize(["div", { bool: true }], { xml: true })).toBe(
`<div bool=""></div>`
));

check("div w/ bool attr (false)", ["div", { bool: false }], `<div></div>`);

check("empty attr", ["div", { foo: "" }], `<div></div>`);
Expand Down

0 comments on commit 8fdcab9

Please sign in to comment.