ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/keer-ui/library/lib/define.ts

library/lib/define.ts

189 líneas, 6.6 KB.

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

  1. // The component contract: meta and states. They are written by the file `<name>.states.tsx` next to the component:
  2. //
  3. // export const meta = defineComponent({
  4. // name: "TaskCompose",
  5. // level: "block",
  6. // surface: "prt-task-compose",
  7. // actions: ["act-task-start"],
  8. // });
  9. // export const states = defineStates<TaskComposeProps>(meta, {
  10. // default: { … },
  11. // loading: { … },
  12. // empty: { … },
  13. // error: { … },
  14. // notApplicable: { … }, // a state that cannot occur: { empty: "why" }
  15. // });
  16. //
  17. // From these files `bun run ui:registry` builds the registry (src/registry.gen.ts and registry.json),
  18. // and the common registry test draws every state. So meta and the state keys are written
  19. // as literals, with no computations and no top-level `...spread`: the registry reads them from the source.
  20. import type { ComponentType } from "react";
  21. /** Component levels from bottom to top. Imports go only downward through the levels. */
  22. export const LEVELS = ["primitive", "composite", "block", "screen"] as const;
  23. export type ComponentLevel = (typeof LEVELS)[number];
  24. /** A part of a screen (a block) or a screen: an entry of the product surface. */
  25. /** A part of a screen `prt-…` or a settings section `set-…` (a part of the “Settings” screen). */
  26. export type PartSurface = `prt-${string}` | `set-${string}`;
  27. export type ScreenSurface = `scr-${string}`;
  28. export type Surface = PartSurface | ScreenSurface;
  29. /** A product action started by the button of the component (`data-action`). */
  30. export type ActionId = `act-${string}`;
  31. /** A primitive and a composite know no product: they have no surface and no actions. */
  32. type GenericMeta = {
  33. name: string;
  34. level: "primitive" | "composite";
  35. surface?: never;
  36. actions?: never;
  37. };
  38. type BlockMeta = {
  39. name: string;
  40. level: "block";
  41. surface: PartSurface;
  42. actions?: readonly ActionId[];
  43. };
  44. type ScreenMeta = {
  45. name: string;
  46. level: "screen";
  47. surface: ScreenSurface;
  48. actions?: readonly ActionId[];
  49. };
  50. export type ComponentMetaInput = GenericMeta | BlockMeta | ScreenMeta;
  51. /** meta after defineComponent. */
  52. export type ComponentMeta = Readonly<ComponentMetaInput>;
  53. /** The required states by level (section 3 of the standard). */
  54. export const REQUIRED_STATES: Record<ComponentLevel, readonly string[]> = {
  55. primitive: ["default"],
  56. composite: ["default"],
  57. block: ["default", "loading", "empty", "error"],
  58. screen: ["default", "loading", "empty", "error"],
  59. };
  60. const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/;
  61. const KEBAB_CASE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
  62. const SURFACE_PREFIX: Partial<Record<ComponentLevel, readonly string[]>> = {
  63. block: ["prt-", "set-"],
  64. screen: ["scr-"],
  65. };
  66. /** The description of a component for the registry. A mistake in the description is an exception when the file is imported. */
  67. export function defineComponent<const M extends ComponentMetaInput>(
  68. meta: M,
  69. ): Readonly<M> {
  70. const where = `defineComponent(${JSON.stringify(meta.name)})`;
  71. if (!PASCAL_CASE.test(meta.name)) {
  72. throw new Error(`${where}: the component name is PascalCase`);
  73. }
  74. if (!LEVELS.includes(meta.level)) {
  75. throw new Error(`${where}: unknown level ${String(meta.level)}`);
  76. }
  77. const prefixes = SURFACE_PREFIX[meta.level];
  78. if (prefixes) {
  79. const surface = meta.surface;
  80. if (
  81. typeof surface !== "string" ||
  82. !prefixes.some((prefix) => surface.startsWith(prefix))
  83. ) {
  84. throw new Error(
  85. `${where}: the surface of level ${meta.level} is ${prefixes.map((p) => `"${p}…"`).join(" or ")}`,
  86. );
  87. }
  88. } else if (meta.surface !== undefined || meta.actions !== undefined) {
  89. throw new Error(
  90. `${where}: ${meta.level} knows no product: no surface and no actions`,
  91. );
  92. }
  93. for (const action of meta.actions ?? []) {
  94. if (!action.startsWith("act-")) {
  95. throw new Error(`${where}: the action ${action} must be "act-…"`);
  96. }
  97. }
  98. return Object.freeze(meta);
  99. }
  100. /**
  101. * The states of a component on demo data. The key is the state name in kebab-case, the value is the props.
  102. * `notApplicable` are the states a component cannot have, with the reason.
  103. */
  104. export type StatesInput<P> = {
  105. default: P;
  106. loading?: P;
  107. empty?: P;
  108. error?: P;
  109. notApplicable?: NotApplicable;
  110. /** The function's own states by surface: `waiting-file`, `partial`, `refused`… */
  111. [state: string]: P | NotApplicable | undefined;
  112. };
  113. /** State → why the component cannot have it. */
  114. export type NotApplicable = Readonly<Record<string, string>>;
  115. export type StatesDefinition<P> = {
  116. readonly meta: ComponentMeta;
  117. /** State names in the order of declaration. */
  118. readonly names: readonly string[];
  119. /** The props of each state. */
  120. readonly props: Readonly<Record<string, P>>;
  121. /** State → why it is absent. */
  122. readonly notApplicable: NotApplicable;
  123. };
  124. export function defineStates<P>(
  125. meta: ComponentMeta,
  126. input: StatesInput<P>,
  127. ): StatesDefinition<P> {
  128. const where = `defineStates(${JSON.stringify(meta.name)})`;
  129. const { notApplicable = {}, ...rest } = input;
  130. const props = rest as Record<string, P>;
  131. const names = Object.keys(props);
  132. for (const name of [...names, ...Object.keys(notApplicable)]) {
  133. if (!KEBAB_CASE.test(name)) {
  134. throw new Error(`${where}: the state name ${name} must be kebab-case`);
  135. }
  136. }
  137. for (const [name, reason] of Object.entries(notApplicable)) {
  138. if (name in props) {
  139. throw new Error(
  140. `${where}: ${name} is both in the states and in notApplicable`,
  141. );
  142. }
  143. if (typeof reason !== "string" || reason.trim() === "") {
  144. throw new Error(`${where}: notApplicable.${name} has no reason`);
  145. }
  146. }
  147. const missing = REQUIRED_STATES[meta.level].filter(
  148. (name) => !(name in props) && !(name in notApplicable),
  149. );
  150. if (missing.length > 0) {
  151. throw new Error(
  152. `${where}: no states ${missing.join(", ")}: add them or explain in notApplicable`,
  153. );
  154. }
  155. return Object.freeze({
  156. meta,
  157. names: Object.freeze(names),
  158. props: Object.freeze(props),
  159. notApplicable: Object.freeze({ ...notApplicable }),
  160. });
  161. }
  162. /** A registry entry (src/registry.gen.ts): the component, its meta and states. */
  163. export type RegistryEntry = {
  164. // biome-ignore lint/suspicious/noExplicitAny: components in the registry have different props
  165. readonly component: ComponentType<any>;
  166. readonly meta: ComponentMeta;
  167. // biome-ignore lint/suspicious/noExplicitAny: the same: the props of the states differ
  168. readonly states: StatesDefinition<any>;
  169. /** The path to `<name>.tsx` from the repository root. */
  170. readonly file: string;
  171. /** The names of the components that `<name>.tsx` imports. */
  172. readonly uses: readonly string[];
  173. };