Skip to content

Commit

Permalink
fix(html): add support for multiple class names as string
Browse files Browse the repository at this point in the history
  • Loading branch information
smalluban committed Nov 28, 2023
1 parent d519175 commit a6f52ba
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
22 changes: 16 additions & 6 deletions src/template/resolvers/class.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
function normalizeValue(value, set = new Set()) {
if (Array.isArray(value)) {
for (const className of value) {
function addClassNames(set, value) {
if (value) {
for (const className of String(value).split(/\s+/)) {
if (className) set.add(className);
}
}
}

function normalizeValue(value) {
const set = new Set();

if (Array.isArray(value)) {
for (const v of value) {
addClassNames(set, v);
}
} else if (value !== null && typeof value === "object") {
for (const [className, condition] of Object.entries(value)) {
if (className && condition) set.add(className);
for (const [v, condition] of Object.entries(value)) {
if (v && condition) addClassNames(set, v);
}
} else {
if (value) set.add(value);
addClassNames(set, value);
}

return set;
Expand Down
9 changes: 7 additions & 2 deletions test/spec/html.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,14 +226,19 @@ describe("html:", () => {
render("class-one")(fragment);
expect(hasClass("class-one")).toBe(true);

render("class-one class-two ")(fragment);
expect(hasClass("class-one")).toBe(true);
expect(hasClass("class-two")).toBe(true);

render("")(fragment);
expect(fragment.children[0].classList.length).toBe(0);
});

it("sets array value", () => {
render(["class-one", "class-two", ""])(fragment);
render(["class-one", "class-two class-three", ""])(fragment);
expect(hasClass("class-one")).toBe(true);
expect(hasClass("class-two")).toBe(true);
expect(hasClass("class-three")).toBe(true);
});

it("sets object value", () => {
Expand All @@ -250,7 +255,7 @@ describe("html:", () => {
});

it("updates values", () => {
render(["one", "two", "three"])(fragment);
render(["one", "two three"])(fragment);
render(["one", "four"])(fragment);

expect(hasClass("one")).toBe(true);
Expand Down

0 comments on commit a6f52ba

Please sign in to comment.