Skip to content

Commit

Permalink
feat(attrs): adds ability to toggle boolean attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
quarkus committed Jun 24, 2024
1 parent ada1926 commit f607e88
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/dom-parts/directives.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)}'`;
Expand Down
14 changes: 14 additions & 0 deletions test/unit/directive-optional-attribute.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`<div ${optionalAttribute(condition, 'attr', '')}></div>`;
assert.equal(stripCommentMarkers(templateResult.toString()), '<div attr></div>');
// 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
Expand Down

0 comments on commit f607e88

Please sign in to comment.