From f607e88c3fefde84fe61efbe1f5432c9b2df9bd4 Mon Sep 17 00:00:00 2001 From: Markus Hesper Date: Mon, 24 Jun 2024 11:04:31 +0200 Subject: [PATCH] feat(attrs): adds ability to toggle boolean attributes --- src/dom-parts/directives.js | 4 ++++ test/unit/directive-optional-attribute.test.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/dom-parts/directives.js b/src/dom-parts/directives.js index d9f1fd4..6618eea 100644 --- a/src/dom-parts/directives.js +++ b/src/dom-parts/directives.js @@ -130,6 +130,10 @@ export class OptionalAttributeDirective extends Directive { */ stringify(condition, attributeName, attributeValue = '') { if (condition) { + if (attributeValue === '') { + // empty string toggles boolean attributes + return `${camelToDash(attributeName)}`; + } return `${camelToDash(attributeName)}='${encodeAttribute( typeof attributeValue !== 'string' ? JSON.stringify(attributeValue) : attributeValue, )}'`; diff --git a/test/unit/directive-optional-attribute.test.js b/test/unit/directive-optional-attribute.test.js index 4054354..5b83fd4 100644 --- a/test/unit/directive-optional-attribute.test.js +++ b/test/unit/directive-optional-attribute.test.js @@ -29,6 +29,20 @@ describe('optionalAttribute directive', () => { assert.isFalse(el.hasAttribute('attr')); }); + it('adds a boolean attributes when condition is truthy and the value is an empty string', async () => { + // https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute#:~:text=into%20a%20string.-,Boolean,-attributes%20are%20considered + let condition = true; + + // SSR + const templateResult = html`
`; + assert.equal(stripCommentMarkers(templateResult.toString()), '
'); + // CSR + const el = document.createElement('div'); + const directive = new OptionalAttributeDirective(el); + directive.update(condition, 'attr', 'string'); + assert.isTrue(el.hasAttribute('attr')); + }); + it('does add and remove an attributes when condition is toggled', async () => { let condition = true; // SSR