From 07b93340a0a02dbed28349e13c3d1b33476205bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Luba=C5=84ski?= Date: Tue, 16 Apr 2024 14:42:47 +0200 Subject: [PATCH] fix(define): value reflects attribute in observe callback --- src/value.js | 68 +++++++++++++++------------------------------ test/spec/define.js | 2 +- 2 files changed, 23 insertions(+), 47 deletions(-) diff --git a/src/value.js b/src/value.js index 1ae90fed..445f28be 100644 --- a/src/value.js +++ b/src/value.js @@ -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) { @@ -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, }; } diff --git a/test/spec/define.js b/test/spec/define.js index 4b0a337c..72ab48df 100644 --- a/test/spec/define.js +++ b/test/spec/define.js @@ -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); }); });