lit-css-vars
Version:
For easily creating and sharing typed CSS vars for the lit.dev ecosystem.
57 lines (56 loc) • 2.24 kB
JavaScript
import { check } from '@augment-vir/assert';
import { camelCaseToKebabCase, mapObjectValues } from '@augment-vir/common';
import { css, unsafeCSS } from 'lit';
/**
* Creates an easy-to-use-in-lit mapping of the given CSS Var names and defaults. The input
* determines the CSS var names and their default values. The output is a mapping of the CSS var
* names to name and value objects that can be easily interpolated into lit's css keyed template
* strings.
*
* @category Main
* @example
*
* ```ts
* import {defineCssVars} from 'lit-css-vars';
*
* // creates a CSS var with name 'my-var' and default value of 50px.
* const myVars = defineCssVars({'my-var': '50px'});
* // using the CSS var name: this will be '--my-var'
* myVars['my-var'].name;
* // accessing the CSS var value for CSS; this will be: 'var(--my-var, 50px)'
* myVars['my-var'].value;
* ```
*/
export function defineCssVars(
/**
* The CSS var setup input. Keys of this input object become the CSS var names. Values of this
* input become the default value of the CSS vars.
*/
setup) {
if (check.isObject(setup)) {
const cssVarDefinitions = mapObjectValues(setup, (key, rawInputValue) => {
if (!check.isString(key)) {
throw new TypeError(`Invalid CSS var name '${String(key)}' given. CSS var names must be strings.`);
}
const kebabKey = camelCaseToKebabCase(key).toLowerCase();
if (kebabKey !== key) {
throw new Error(`Invalid CSS var name '${key}' given. CSS var names must be in lower kebab case.`);
}
const defaultValue = rawInputValue;
const cssVarNameCssResult = key.startsWith('--')
? unsafeCSS(key)
: key.startsWith('-')
? css `-${unsafeCSS(key)}`
: css `--${unsafeCSS(key)}`;
return {
name: cssVarNameCssResult,
value: css `var(${cssVarNameCssResult}, ${unsafeCSS(defaultValue)})`,
default: String(defaultValue),
};
});
return cssVarDefinitions;
}
else {
throw new TypeError(`Invalid setup input for '${defineCssVars.name}' function.`);
}
}