ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/shtukbase-ui-react/library/lib/controls.ts

library/lib/controls.ts

30 líneas, 1.7 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // Controls as props (build contract, section 4): the same controls as the HTML library, where a control value is the
  2. // attribute `data-<control>="<value>"` on the root, a `bool` is the attribute present or absent, and a `range` is the inline
  3. // custom property `--<id>-<control>: <value><unit>`. A prop is the control name in camelCase (`glow-strength` → `glowStrength`).
  4. import type { CSSProperties } from "react";
  5. export type ControlValue = string | number | boolean | null | undefined;
  6. type DataProps = Record<`data-${string}`, string | undefined>;
  7. const kebab = (name: string) => name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
  8. /** `select`, `segment`, `swatch` and `text` controls: the value as `data-<control>`; no value, no attribute. */
  9. export function dataProps(values: Record<string, ControlValue>): DataProps {
  10. const out: DataProps = {};
  11. for (const [name, value] of Object.entries(values)) {
  12. if (value === undefined || value === null || value === false) continue;
  13. out[`data-${kebab(name)}`] = value === true ? "" : String(value);
  14. }
  15. return out;
  16. }
  17. /** `range` controls: the inline custom properties `--<id>-<control>`, merged into the style the caller gave. */
  18. export function rangeStyle(id: string, ranges: Record<string, { value: number | string | undefined; unit?: string }>, style?: CSSProperties): CSSProperties | undefined {
  19. const own: Record<string, string> = {};
  20. for (const [name, { value, unit = "" }] of Object.entries(ranges)) {
  21. if (value === undefined || value === null || value === "") continue;
  22. own[`--${id}-${kebab(name)}`] = `${value}${unit}`;
  23. }
  24. if (!Object.keys(own).length) return style;
  25. return { ...own, ...style } as CSSProperties;
  26. }