@exadel/esl
Version:
Exadel Smart Library (ESL) is the lightweight custom elements library that provide a set of super-flexible components
30 lines (29 loc) • 1.46 kB
JavaScript
import { hasAttr, setAttr } from '../dom/attr';
import { toKebabCase } from '../misc/format';
function buildConditionalDescriptor(attrName, readOnly) {
function get() {
return hasAttr(this, attrName);
}
function set(value) {
setAttr(this, attrName, !!value);
}
return readOnly ? { get } : { get, set };
}
const buildAttrName = (propName, dataAttr) => dataAttr ? `data-${toKebabCase(propName)}` : toKebabCase(propName);
/**
* Decorator to map current property to element boolean (marker) attribute state.
* - Presence mapping: attribute present means true, attribute absent means false (no third state)
* - No `defaultValue` option; cannot implicitly default to true without attribute (use `@attr` tri‑state pattern for that)
* - Setting property: truthy value ensures attribute presence (empty string); falsy value removes the attribute
* - `readonly` option exposes getter only (writes ignored at JS level)
* - Supports `data-*` via `dataAttr`
* - Works with wrapper objects exposing `$host` (resolved internally by underlying DOM helpers)
* @param config - mapping configuration. See {@link BoolAttrDescriptor}
*/
export const boolAttr = (config = {}) => {
return (target, propName) => {
const attrName = buildAttrName(config.name || propName, !!config.dataAttr);
Object.defineProperty(target, propName, buildConditionalDescriptor(attrName, !!config.readonly));
return {};
};
};