Skip to content

Commit

Permalink
[lit-labs/ssr-dom-shim] fix toggleAttribute clearing prior values if …
Browse files Browse the repository at this point in the history
…force is true (#4494)
  • Loading branch information
AndrewJakubowicz committed Jan 12, 2024
1 parent e901c58 commit 546d75d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
2 changes: 2 additions & 0 deletions .changeset/funny-camels-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
25 changes: 18 additions & 7 deletions packages/labs/ssr-dom-shim/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,26 @@ const ElementShim = class Element {
attributesForElement(this).delete(name);
}
toggleAttribute(name: string, force?: boolean): boolean {
if (force === undefined) {
force = !this.hasAttribute(name);
}
if (force) {
this.setAttribute(name, '');
// Steps reference https://dom.spec.whatwg.org/#dom-element-toggleattribute
if (this.hasAttribute(name)) {
// Step 5
if (force === undefined || !force) {
this.removeAttribute(name);
return false;
}
} else {
this.removeAttribute(name);
// Step 4
if (force === undefined || force) {
// Step 4.1
this.setAttribute(name, '');
return true;
} else {
// Step 4.2
return false;
}
}
return force;
// Step 6
return true;
}
hasAttribute(name: string) {
return attributesForElement(this).has(name);
Expand Down
7 changes: 7 additions & 0 deletions packages/labs/ssr-dom-shim/src/test/element-shim_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ test('toggleAttribute accepts an optional force parameter', () => {
assert.ok(shimmedEl.hasAttribute('potato'));
});

test('toggleAttribute retains a previously set value if force is true', () => {
const shimmedEl = new HTMLElement();
shimmedEl.setAttribute('foo', 'bar');
assert.ok(shimmedEl.toggleAttribute('foo', true));
assert.equal(shimmedEl.getAttribute('foo'), 'bar');
});

test('setAttribute silently casts values to a string', () => {
const shimmedEl = new HTMLElement();
// It is possible to pass any value to `setAttribute`, and we
Expand Down

0 comments on commit 546d75d

Please sign in to comment.