UNPKG

@forest-js/core

Version:

A tiny, functional DOM engine with explicit update and real DOM.

54 lines 1.91 kB
import { ensureMeta } from "../dom"; /** * @function addStyle * @description Applies CSS styles to an element. * Supports reactive styles when using stores. * * @template R - Style properties to apply. * @template S - StoreMap type when used reactively. * @template E - Element type (defaults to HTMLElement). * @param args - Style properties or store and mapper function * @returns Utility function for adding styles * @example * ```ts * const setColor = addStyle<HTMLDivElement, { color: string }>( * { color: "red" } * )(MyElement); * ``` */ export const addStyle = (...args) => { return (el) => { if (args.length === 2 && typeof args[1] === "function") { // Reactive mode const [stores, mapper] = args; const apply = () => { const values = {}; for (const key in stores) values[key] = stores[key].get(); if (el instanceof HTMLElement) { Object.assign(el.style, mapper(values)); } else { console.warn("[Forest Warning: addStyle] el is not an HTMLElement, style will not be applied"); } }; apply(); const unsubs = Object.values(stores).map((store) => store.subscribe(() => apply())); const meta = ensureMeta(el); meta.storeBindings ??= new Set(); unsubs.forEach((unsub) => meta.storeBindings.add(unsub)); } else { // Static mode const [style] = args; if (el instanceof HTMLElement) { Object.assign(el.style, style); } else { console.warn("[Forest Warning: addStyle] el is not an HTMLElement, style will not be applied"); } } return el; }; }; //# sourceMappingURL=style.js.map