add boolean value to attr

This commit is contained in:
Dmitriy Pleshevskiy 2022-05-29 02:02:55 +03:00
parent 6a03f421b3
commit 1a67959b1a
3 changed files with 38 additions and 3 deletions

View File

@ -1,7 +1,8 @@
import { Nilable } from "./utils.ts";
export type Attrs = Record<string, string>;
export type AttrEntry = [key: string, value: string];
export type Attrs = Record<string, AttrVal>;
export type AttrEntry = [key: string, value: AttrVal];
export type AttrVal = boolean | string;
export type AnyNode = Fragment | FragmentNode;
export function isTextNode(val: unknown): val is TextNode {

View File

@ -184,3 +184,33 @@ Deno.test({
);
},
});
Deno.test({
name: "should filter attr",
fn: () => {
const layout = E("input", { type: "number", disabled: false });
const ren = new StrRenderer();
const res = ren.render(layout);
assertEquals(
res,
'<input type="number">',
);
},
});
Deno.test({
name: "should render boolean attr",
fn: () => {
const layout = E("input", { type: "number", disabled: true });
const ren = new StrRenderer();
const res = ren.render(layout);
assertEquals(
res,
'<input type="number" disabled>',
);
},
});

View File

@ -2,6 +2,7 @@ import {
AnyNode,
AttrEntry,
Attrs,
AttrVal,
Elem,
Fragment,
isElem,
@ -103,7 +104,10 @@ function encodeAttrs(
);
}
function encodeAttr(key: string, value: string): string {
function encodeAttr(key: string, value: AttrVal): string {
if (typeof value === "boolean") {
return value ? key : "";
}
return `${key}="${value}"`;
}