包文件→ .shtukbase/packages/shtukbase-ui-react/library/lib/controls.ts
library/lib/controls.ts
30 行, 1.7 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Controls as props (build contract, section 4): the same controls as the HTML library, where a control value is the
- // attribute `data-<control>="<value>"` on the root, a `bool` is the attribute present or absent, and a `range` is the inline
- // custom property `--<id>-<control>: <value><unit>`. A prop is the control name in camelCase (`glow-strength` → `glowStrength`).
- import type { CSSProperties } from "react";
- export type ControlValue = string | number | boolean | null | undefined;
- type DataProps = Record<`data-${string}`, string | undefined>;
- const kebab = (name: string) => name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
- /** `select`, `segment`, `swatch` and `text` controls: the value as `data-<control>`; no value, no attribute. */
- export function dataProps(values: Record<string, ControlValue>): DataProps {
- const out: DataProps = {};
- for (const [name, value] of Object.entries(values)) {
- if (value === undefined || value === null || value === false) continue;
- out[`data-${kebab(name)}`] = value === true ? "" : String(value);
- }
- return out;
- }
- /** `range` controls: the inline custom properties `--<id>-<control>`, merged into the style the caller gave. */
- export function rangeStyle(id: string, ranges: Record<string, { value: number | string | undefined; unit?: string }>, style?: CSSProperties): CSSProperties | undefined {
- const own: Record<string, string> = {};
- for (const [name, { value, unit = "" }] of Object.entries(ranges)) {
- if (value === undefined || value === null || value === "") continue;
- own[`--${id}-${kebab(name)}`] = `${value}${unit}`;
- }
- if (!Object.keys(own).length) return style;
- return { ...own, ...style } as CSSProperties;
- }