@forest-js/core
Version:
A tiny, functional DOM engine with explicit update and real DOM.
51 lines • 1.69 kB
JavaScript
import { enqueue, ensureMeta } from "../dom";
/**
* @function addAttribute
* @description Adds attributes to an element.
* Supports reactive attributes when using stores.
*
* @template E - Element type.
* @template R - Object with attributes to add.
* @template S - StoreMap type when used reactively.
* @param args - Attributes or store and mapper function
* @returns Utility function for adding attributes
* @example
* ```ts
* const addTitle = addAttribute<HTMLDivElement, { title: string }>(
* { title: "Hello" }
* )(MyElement);
* ```
*/
export const addAttribute = (...args) => {
return (el) => {
if (args.length === 2 && typeof args[1] === "function") {
const [stores, mapper] = args;
const apply = () => {
const values = {};
for (const key in stores)
values[key] = stores[key].get();
const attrs = mapper(values);
for (const key in attrs) {
if (key in el) {
el[key] = attrs[key];
}
}
};
apply();
const unsubs = Object.values(stores).map((store) => store.subscribe(() => enqueue(apply)));
const meta = ensureMeta(el);
meta.storeBindings ??= new Set();
unsubs.forEach((unsub) => meta.storeBindings.add(unsub));
}
else {
const [attrs] = args;
for (const key in attrs) {
if (key in el) {
el[key] = attrs[key];
}
}
}
return el;
};
};
//# sourceMappingURL=attribute.js.map