element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
36 lines (35 loc) • 1.47 kB
JavaScript
import { getObjectTypedKeys, getOrSet } from '@augment-vir/common';
import { nothing } from '../../lit-exports/all-lit-exports.js';
import { createMutateDirective } from './mutate.directive.js';
/**
* A directive applies multiple HTML attributes to the parent element all at once.
*
* @category Directives
*/
export const attributes = createMutateDirective('attributes', ({ element, params: [attributesToApply], directive: rawDirective }) => {
if (!attributesToApply) {
return;
}
const directive = rawDirective;
const allAttributeNames = getOrSet(directive, 'allAttributesApplied', () => new Set());
getObjectTypedKeys(attributesToApply).forEach((attributeName) => {
if (attributeName.toLowerCase() !== attributeName) {
throw new Error(`Cannot assign attribute name with uppercase letters: ${attributeName}`);
}
allAttributeNames.add(attributeName);
});
allAttributeNames.forEach((attributeName) => {
const attributeValue = attributesToApply[attributeName];
if (attributeValue == undefined ||
attributeValue === false ||
attributeValue === nothing) {
element.removeAttribute(attributeName);
}
else if (attributeValue === '' || attributeValue === true) {
element.setAttribute(attributeName, '');
}
else {
element.setAttribute(attributeName, String(attributeValue));
}
});
});