package file→ .shtukbase/packages/keer-ui/library/lib/define.ts
library/lib/define.ts
189 lines, 6.6 KB.
- // The component contract: meta and states. They are written by the file `<name>.states.tsx` next to the component:
- //
- // export const meta = defineComponent({
- // name: "TaskCompose",
- // level: "block",
- // surface: "prt-task-compose",
- // actions: ["act-task-start"],
- // });
- // export const states = defineStates<TaskComposeProps>(meta, {
- // default: { … },
- // loading: { … },
- // empty: { … },
- // error: { … },
- // notApplicable: { … }, // a state that cannot occur: { empty: "why" }
- // });
- //
- // From these files `bun run ui:registry` builds the registry (src/registry.gen.ts and registry.json),
- // and the common registry test draws every state. So meta and the state keys are written
- // as literals, with no computations and no top-level `...spread`: the registry reads them from the source.
- import type { ComponentType } from "react";
- /** Component levels from bottom to top. Imports go only downward through the levels. */
- export const LEVELS = ["primitive", "composite", "block", "screen"] as const;
- export type ComponentLevel = (typeof LEVELS)[number];
- /** A part of a screen (a block) or a screen: an entry of the product surface. */
- /** A part of a screen `prt-…` or a settings section `set-…` (a part of the “Settings” screen). */
- export type PartSurface = `prt-${string}` | `set-${string}`;
- export type ScreenSurface = `scr-${string}`;
- export type Surface = PartSurface | ScreenSurface;
- /** A product action started by the button of the component (`data-action`). */
- export type ActionId = `act-${string}`;
- /** A primitive and a composite know no product: they have no surface and no actions. */
- type GenericMeta = {
- name: string;
- level: "primitive" | "composite";
- surface?: never;
- actions?: never;
- };
- type BlockMeta = {
- name: string;
- level: "block";
- surface: PartSurface;
- actions?: readonly ActionId[];
- };
- type ScreenMeta = {
- name: string;
- level: "screen";
- surface: ScreenSurface;
- actions?: readonly ActionId[];
- };
- export type ComponentMetaInput = GenericMeta | BlockMeta | ScreenMeta;
- /** meta after defineComponent. */
- export type ComponentMeta = Readonly<ComponentMetaInput>;
- /** The required states by level (section 3 of the standard). */
- export const REQUIRED_STATES: Record<ComponentLevel, readonly string[]> = {
- primitive: ["default"],
- composite: ["default"],
- block: ["default", "loading", "empty", "error"],
- screen: ["default", "loading", "empty", "error"],
- };
- const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/;
- const KEBAB_CASE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
- const SURFACE_PREFIX: Partial<Record<ComponentLevel, readonly string[]>> = {
- block: ["prt-", "set-"],
- screen: ["scr-"],
- };
- /** The description of a component for the registry. A mistake in the description is an exception when the file is imported. */
- export function defineComponent<const M extends ComponentMetaInput>(
- meta: M,
- ): Readonly<M> {
- const where = `defineComponent(${JSON.stringify(meta.name)})`;
- if (!PASCAL_CASE.test(meta.name)) {
- throw new Error(`${where}: the component name is PascalCase`);
- }
- if (!LEVELS.includes(meta.level)) {
- throw new Error(`${where}: unknown level ${String(meta.level)}`);
- }
- const prefixes = SURFACE_PREFIX[meta.level];
- if (prefixes) {
- const surface = meta.surface;
- if (
- typeof surface !== "string" ||
- !prefixes.some((prefix) => surface.startsWith(prefix))
- ) {
- throw new Error(
- `${where}: the surface of level ${meta.level} is ${prefixes.map((p) => `"${p}…"`).join(" or ")}`,
- );
- }
- } else if (meta.surface !== undefined || meta.actions !== undefined) {
- throw new Error(
- `${where}: ${meta.level} knows no product: no surface and no actions`,
- );
- }
- for (const action of meta.actions ?? []) {
- if (!action.startsWith("act-")) {
- throw new Error(`${where}: the action ${action} must be "act-…"`);
- }
- }
- return Object.freeze(meta);
- }
- /**
- * The states of a component on demo data. The key is the state name in kebab-case, the value is the props.
- * `notApplicable` are the states a component cannot have, with the reason.
- */
- export type StatesInput<P> = {
- default: P;
- loading?: P;
- empty?: P;
- error?: P;
- notApplicable?: NotApplicable;
- /** The function's own states by surface: `waiting-file`, `partial`, `refused`… */
- [state: string]: P | NotApplicable | undefined;
- };
- /** State → why the component cannot have it. */
- export type NotApplicable = Readonly<Record<string, string>>;
- export type StatesDefinition<P> = {
- readonly meta: ComponentMeta;
- /** State names in the order of declaration. */
- readonly names: readonly string[];
- /** The props of each state. */
- readonly props: Readonly<Record<string, P>>;
- /** State → why it is absent. */
- readonly notApplicable: NotApplicable;
- };
- export function defineStates<P>(
- meta: ComponentMeta,
- input: StatesInput<P>,
- ): StatesDefinition<P> {
- const where = `defineStates(${JSON.stringify(meta.name)})`;
- const { notApplicable = {}, ...rest } = input;
- const props = rest as Record<string, P>;
- const names = Object.keys(props);
- for (const name of [...names, ...Object.keys(notApplicable)]) {
- if (!KEBAB_CASE.test(name)) {
- throw new Error(`${where}: the state name ${name} must be kebab-case`);
- }
- }
- for (const [name, reason] of Object.entries(notApplicable)) {
- if (name in props) {
- throw new Error(
- `${where}: ${name} is both in the states and in notApplicable`,
- );
- }
- if (typeof reason !== "string" || reason.trim() === "") {
- throw new Error(`${where}: notApplicable.${name} has no reason`);
- }
- }
- const missing = REQUIRED_STATES[meta.level].filter(
- (name) => !(name in props) && !(name in notApplicable),
- );
- if (missing.length > 0) {
- throw new Error(
- `${where}: no states ${missing.join(", ")}: add them or explain in notApplicable`,
- );
- }
- return Object.freeze({
- meta,
- names: Object.freeze(names),
- props: Object.freeze(props),
- notApplicable: Object.freeze({ ...notApplicable }),
- });
- }
- /** A registry entry (src/registry.gen.ts): the component, its meta and states. */
- export type RegistryEntry = {
- // biome-ignore lint/suspicious/noExplicitAny: components in the registry have different props
- readonly component: ComponentType<any>;
- readonly meta: ComponentMeta;
- // biome-ignore lint/suspicious/noExplicitAny: the same: the props of the states differ
- readonly states: StatesDefinition<any>;
- /** The path to `<name>.tsx` from the repository root. */
- readonly file: string;
- /** The names of the components that `<name>.tsx` imports. */
- readonly uses: readonly string[];
- };