Skip to content

Commit

Permalink
fix(define): value reflects attribute in observe callback
Browse files Browse the repository at this point in the history
  • Loading branch information
smalluban committed Apr 16, 2024
1 parent 4bf7e86 commit 07b9334
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 47 deletions.
68 changes: 22 additions & 46 deletions src/value.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,10 @@
import { camelToDash } from "./utils.js";

const setters = {
string: (host, value, attrName) => {
const nextValue = value ? String(value) : "";
if (nextValue) {
host.setAttribute(attrName, nextValue);
} else {
host.removeAttribute(attrName);
}

return nextValue;
},
number: (host, value, attrName) => {
const nextValue = Number(value);
host.setAttribute(attrName, nextValue);
return nextValue;
},
boolean: (host, value, attrName) => {
const nextValue = Boolean(value);
if (nextValue) {
host.setAttribute(attrName, "");
} else {
host.removeAttribute(attrName);
}
return nextValue;
},
undefined: (host, value, attrName) => {
const type = typeof value;
const set = type !== "undefined" && setters[type];
if (set) {
return set(host, value, attrName);
} else if (host.hasAttribute(attrName)) {
host.removeAttribute(attrName);
}

return value;
},
string: String,
number: Number,
boolean: Boolean,
undefined: (value) => value,
};

export default function value(key, desc) {
Expand All @@ -50,19 +19,26 @@ export default function value(key, desc) {

const attrName = camelToDash(key);

function reflect(host, value) {
if (!value && value !== 0) {
host.removeAttribute(attrName);
} else {
host.setAttribute(attrName, value === true ? "" : value);
}
}

return {
get: (host, value) => (value === undefined ? desc.value : value),
set: (host, value) => set(host, value, attrName),
connect:
type !== "undefined"
? (host, key, invalidate) => {
if (!host.hasAttribute(attrName) && host[key] === desc.value) {
host[key] = set(host, desc.value, attrName);
set: (host, value) => set(value),
connect: desc.connect,
observe:
type === "undefined"
? desc.observe
: desc.observe
? (host, value, lastValue) => {
reflect(host, value);
desc.observe(host, value, lastValue);
}

return desc.connect && desc.connect(host, key, invalidate);
}
: desc.connect,
observe: desc.observe,
: reflect,
};
}
2 changes: 1 addition & 1 deletion test/spec/define.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ describe("define:", () => {
expect(el.getAttribute("prop1")).toBe("a");
expect(el.getAttribute("prop2")).toBe("1");
expect(el.getAttribute("prop3")).toBe("");
expect(el.getAttribute("not-defined")).toBe("abc");
expect(el.getAttribute("not-defined")).toBe(null);
});
});

Expand Down

0 comments on commit 07b9334

Please sign in to comment.