UNPKG

@exadel/esl

Version:

Exadel Smart Library (ESL) is the lightweight custom elements library that provide a set of super-flexible components

24 lines (23 loc) 1.36 kB
import { identity, resolveProperty } from '../misc/functions'; import { parseString, toKebabCase } from '../misc/format'; import { getAttr, getClosestAttr, setAttr } from '../dom/attr'; const buildAttrName = (propName, dataAttr) => dataAttr ? `data-${toKebabCase(propName)}` : toKebabCase(propName); export function attr(config = {}) { return (target, propName) => { const attrName = buildAttrName(config.name || propName, !!config.dataAttr); const inheritAttrName = typeof config.inherit === 'string' ? config.inherit : attrName; function get() { const val = config.inherit ? getAttr(this, attrName) || getClosestAttr(this, inheritAttrName) : getAttr(this, attrName); if (val === null && 'defaultValue' in config) return resolveProperty(config.defaultValue, this); // Note: if defaultValue is set, null is already handled above, so parser receives a non-null string; // otherwise parser is AttrParser<T> which accepts null. TS can't narrow the union here, so we cast. return (config.parser || parseString)(val); } function set(value) { setAttr(this, attrName, (config.serializer || identity)(value)); } Object.defineProperty(target, propName, config.readonly ? { get } : { get, set }); return {}; }; }