@krizaka/ui 4.4.0 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/dist/account-menu.d.ts +1 -1
  2. package/dist/account-menu.js +1 -1
  3. package/dist/account-menu.js.map +1 -1
  4. package/dist/account-settings.d.ts +1 -1
  5. package/dist/account-settings.js +13 -6
  6. package/dist/account-settings.js.map +1 -1
  7. package/dist/agenda.d.ts +1 -1
  8. package/dist/agenda.js +2 -1
  9. package/dist/agenda.js.map +1 -1
  10. package/dist/analysis-report.js +19 -11
  11. package/dist/analysis-report.js.map +1 -1
  12. package/dist/app-frame.d.ts +1 -1
  13. package/dist/app-frame.js.map +1 -1
  14. package/dist/app-header/search.js +2 -2
  15. package/dist/app-header/search.js.map +1 -1
  16. package/dist/avatar/defaults.js +3 -1
  17. package/dist/avatar/defaults.js.map +1 -1
  18. package/dist/avatar.js +3 -1
  19. package/dist/avatar.js.map +1 -1
  20. package/dist/bird-plate.js +8 -2
  21. package/dist/bird-plate.js.map +1 -1
  22. package/dist/chapter.js +7 -4
  23. package/dist/chapter.js.map +1 -1
  24. package/dist/chat.js +1 -1
  25. package/dist/chip.d.ts +1 -1
  26. package/dist/chip.js +1 -1
  27. package/dist/{chunk-SNSQLGGS.js → chunk-5VZ37TY3.js} +1 -1
  28. package/dist/{chunk-XWJDBQU7.js.map → chunk-5VZ37TY3.js.map} +1 -1
  29. package/dist/{chunk-MTVX4RRF.js → chunk-HP7BDMVK.js} +11 -3
  30. package/dist/chunk-HP7BDMVK.js.map +1 -0
  31. package/dist/{chunk-PK3L6WQT.js → chunk-LNAAWT4Y.js} +4 -2
  32. package/dist/{chunk-PK3L6WQT.js.map → chunk-LNAAWT4Y.js.map} +1 -1
  33. package/dist/{chunk-UIP3WX5O.js → chunk-MDSP7DJR.js} +2 -2
  34. package/dist/chunk-MDSP7DJR.js.map +1 -0
  35. package/dist/{chunk-IEGTRCDI.js → chunk-NQENOT6L.js} +2 -2
  36. package/dist/{chunk-IEGTRCDI.js.map → chunk-NQENOT6L.js.map} +1 -1
  37. package/dist/{chunk-FM42KOAU.js → chunk-P7AFIKWG.js} +5 -3
  38. package/dist/chunk-P7AFIKWG.js.map +1 -0
  39. package/dist/{chunk-BCD2CRFG.js → chunk-PJNR4NTS.js} +2 -2
  40. package/dist/chunk-PJNR4NTS.js.map +1 -0
  41. package/dist/{chunk-ZFR6ZNXD.js → chunk-PVQ2KKPZ.js} +1 -1
  42. package/dist/chunk-PVQ2KKPZ.js.map +1 -0
  43. package/dist/{chunk-U4XTZMB7.js → chunk-QA3WETWT.js} +1 -1
  44. package/dist/{chunk-U4XTZMB7.js.map → chunk-QA3WETWT.js.map} +1 -1
  45. package/dist/{chunk-YXETEQQJ.js → chunk-SG2RKUVJ.js} +2 -2
  46. package/dist/{chunk-EOWV6BNQ.js → chunk-TXFX4PMN.js} +4 -2
  47. package/dist/{chunk-EOWV6BNQ.js.map → chunk-TXFX4PMN.js.map} +1 -1
  48. package/dist/{chunk-XWJDBQU7.js → chunk-V5RO6JYI.js} +1 -1
  49. package/dist/{chunk-SNSQLGGS.js.map → chunk-V5RO6JYI.js.map} +1 -1
  50. package/dist/{chunk-VUD4IEVJ.js → chunk-VZ6ZALIJ.js} +1 -1
  51. package/dist/chunk-VZ6ZALIJ.js.map +1 -0
  52. package/dist/{chunk-2DHL7NJW.js → chunk-XVRKKYWU.js} +5 -3
  53. package/dist/{chunk-2DHL7NJW.js.map → chunk-XVRKKYWU.js.map} +1 -1
  54. package/dist/{chunk-CDNOT2KR.js → chunk-YTYNKMNS.js} +1 -1
  55. package/dist/chunk-YTYNKMNS.js.map +1 -0
  56. package/dist/code-block.js.map +1 -1
  57. package/dist/combobox.js +2 -2
  58. package/dist/copy-button.js +2 -2
  59. package/dist/copy-button.js.map +1 -1
  60. package/dist/data-table.js +3 -3
  61. package/dist/desktop-window.d.ts +1 -1
  62. package/dist/desktop-window.js +3 -1
  63. package/dist/desktop-window.js.map +1 -1
  64. package/dist/drop-overlay.js +8 -8
  65. package/dist/drop-overlay.js.map +1 -1
  66. package/dist/elephant.d.ts +1 -1
  67. package/dist/elephant.js.map +1 -1
  68. package/dist/embed-facade.d.ts +1 -1
  69. package/dist/embed-facade.js +3 -1
  70. package/dist/embed-facade.js.map +1 -1
  71. package/dist/engine-flow.js +7 -2
  72. package/dist/engine-flow.js.map +1 -1
  73. package/dist/entity-header.js +9 -3
  74. package/dist/entity-header.js.map +1 -1
  75. package/dist/file-upload.d.ts +1 -1
  76. package/dist/file-upload.js.map +1 -1
  77. package/dist/filter-bar.d.ts +4 -4
  78. package/dist/filter-bar.js +2 -2
  79. package/dist/flock.js +9 -6
  80. package/dist/flock.js.map +1 -1
  81. package/dist/form.d.ts +3 -3
  82. package/dist/form.js.map +1 -1
  83. package/dist/genui.js +3 -3
  84. package/dist/glossary-term.d.ts +1 -1
  85. package/dist/glossary-term.js.map +1 -1
  86. package/dist/glossary.d.ts +1 -1
  87. package/dist/glossary.js.map +1 -1
  88. package/dist/identity-card.js +1 -1
  89. package/dist/index.js +1 -1
  90. package/dist/kind-config-editor.d.ts +2 -2
  91. package/dist/kind-config-editor.js +1 -1
  92. package/dist/kind-config-editor.js.map +1 -1
  93. package/dist/kpi-explained.d.ts +1 -1
  94. package/dist/kpi-explained.js +4 -4
  95. package/dist/kpi-explained.js.map +1 -1
  96. package/dist/landing-page.js +1 -1
  97. package/dist/{lightbox-Q45BZ3HW.js → lightbox-MRB2YZEP.js} +1 -1
  98. package/dist/lightbox-MRB2YZEP.js.map +1 -0
  99. package/dist/map/cards.js +4 -2
  100. package/dist/map/cards.js.map +1 -1
  101. package/dist/map/pin.js +2 -1
  102. package/dist/map/pin.js.map +1 -1
  103. package/dist/map.d.ts +1 -1
  104. package/dist/map.js.map +1 -1
  105. package/dist/mascot-quote.js +1 -1
  106. package/dist/mascot-state.js +1 -1
  107. package/dist/mascots.js +1 -1
  108. package/dist/match-dialog.js +1 -1
  109. package/dist/motion.d.ts +1 -1
  110. package/dist/motion.js.map +1 -1
  111. package/dist/native/form.d.ts +3 -3
  112. package/dist/native/form.js.map +1 -1
  113. package/dist/native/markdown.d.ts +1 -1
  114. package/dist/native/markdown.js.map +1 -1
  115. package/dist/native/vertical-video.js.map +1 -1
  116. package/dist/native.d.ts +12 -12
  117. package/dist/native.js +12 -7
  118. package/dist/native.js.map +1 -1
  119. package/dist/nav-bar.d.ts +2 -2
  120. package/dist/nav-bar.js +1 -1
  121. package/dist/nav-bar.js.map +1 -1
  122. package/dist/next-actions.d.ts +1 -1
  123. package/dist/next-actions.js.map +1 -1
  124. package/dist/notification-preferences.d.ts +1 -1
  125. package/dist/notification-preferences.js +5 -2
  126. package/dist/notification-preferences.js.map +1 -1
  127. package/dist/page-index.js +2 -2
  128. package/dist/page-index.js.map +1 -1
  129. package/dist/product-page.js +1 -1
  130. package/dist/promo-code-field.d.ts +1 -1
  131. package/dist/promo-code-field.js.map +1 -1
  132. package/dist/qr-code.d.ts +1 -1
  133. package/dist/qr-code.js +1 -1
  134. package/dist/rail-nav.js +3 -3
  135. package/dist/rail-nav.js.map +1 -1
  136. package/dist/retro-tv.d.ts +1 -1
  137. package/dist/retro-tv.js.map +1 -1
  138. package/dist/reviews.d.ts +2 -2
  139. package/dist/reviews.js.map +1 -1
  140. package/dist/router.d.ts +1 -1
  141. package/dist/router.js +8 -8
  142. package/dist/router.js.map +1 -1
  143. package/dist/{schema-CL7t7xqb.d.ts → schema-Dd05m48Q.d.ts} +9 -9
  144. package/dist/service-card.js +22 -13
  145. package/dist/service-card.js.map +1 -1
  146. package/dist/settings-layout.js +1 -1
  147. package/dist/shop/booking.js.map +1 -1
  148. package/dist/shop/gallery.js +7 -6
  149. package/dist/shop/gallery.js.map +1 -1
  150. package/dist/shop/hero.js.map +1 -1
  151. package/dist/shop/look.d.ts +2 -2
  152. package/dist/shop/look.js +1 -1
  153. package/dist/shop/look.js.map +1 -1
  154. package/dist/shop/map-gate.d.ts +1 -1
  155. package/dist/shop/map-gate.js +2 -2
  156. package/dist/shop/map-gate.js.map +1 -1
  157. package/dist/shop/services.js.map +1 -1
  158. package/dist/shop-composer.d.ts +12 -12
  159. package/dist/shop-composer.js +27 -14
  160. package/dist/shop-composer.js.map +1 -1
  161. package/dist/shop-gallery.js +1 -1
  162. package/dist/shop.d.ts +2 -2
  163. package/dist/shop.js +2 -2
  164. package/dist/shop.js.map +1 -1
  165. package/dist/signature.js +2 -1
  166. package/dist/signature.js.map +1 -1
  167. package/dist/site-cahier.js +7 -3
  168. package/dist/site-cahier.js.map +1 -1
  169. package/dist/site-footer.js +6 -2
  170. package/dist/site-footer.js.map +1 -1
  171. package/dist/slot-picker.js +5 -2
  172. package/dist/slot-picker.js.map +1 -1
  173. package/dist/stat.js +1 -1
  174. package/dist/status-chip.d.ts +1 -1
  175. package/dist/status-chip.js.map +1 -1
  176. package/dist/tabs.js.map +1 -1
  177. package/dist/tag-input.js +2 -2
  178. package/dist/tag-selector.js +1 -1
  179. package/dist/text-style.js +4 -3
  180. package/dist/text-style.js.map +1 -1
  181. package/dist/usage.js +8 -3
  182. package/dist/usage.js.map +1 -1
  183. package/dist/versus-card.js +1 -1
  184. package/dist/versus-card.js.map +1 -1
  185. package/dist/vertical-video.js +1 -1
  186. package/dist/vertical-video.js.map +1 -1
  187. package/dist/wall.d.ts +4 -4
  188. package/dist/wall.js +1 -1
  189. package/dist/wall.js.map +1 -1
  190. package/package.json +5 -5
  191. package/registry/account-menu.json +1 -1
  192. package/registry/account-settings.json +2 -2
  193. package/registry/agenda.json +1 -1
  194. package/registry/analysis-report.json +2 -2
  195. package/registry/app-frame.json +3 -3
  196. package/registry/app-header.json +1 -1
  197. package/registry/avatar.json +1 -1
  198. package/registry/badge.json +2 -2
  199. package/registry/bird-plate.json +1 -1
  200. package/registry/chapter.json +1 -1
  201. package/registry/chip.json +1 -1
  202. package/registry/copy-button.json +1 -1
  203. package/registry/data-table.json +1 -1
  204. package/registry/desktop-window.json +1 -1
  205. package/registry/drop-overlay.json +1 -1
  206. package/registry/elephant.json +1 -1
  207. package/registry/embed-facade.json +2 -2
  208. package/registry/engine-flow.json +2 -2
  209. package/registry/entity-header.json +1 -1
  210. package/registry/file-upload.json +1 -1
  211. package/registry/filter-bar.json +1 -1
  212. package/registry/flock.json +2 -2
  213. package/registry/form.json +7 -7
  214. package/registry/glossary-term.json +1 -1
  215. package/registry/glossary.json +1 -1
  216. package/registry/index.json +7 -7
  217. package/registry/kind-config-editor.json +1 -1
  218. package/registry/kpi-explained.json +1 -1
  219. package/registry/map.json +4 -4
  220. package/registry/mascot-state.json +1 -1
  221. package/registry/mascots.json +2 -2
  222. package/registry/nav-bar.json +4 -4
  223. package/registry/next-actions.json +1 -1
  224. package/registry/notification-preferences.json +1 -1
  225. package/registry/page-index.json +1 -1
  226. package/registry/page.json +1 -1
  227. package/registry/promo-code-field.json +1 -1
  228. package/registry/qr-code.json +2 -2
  229. package/registry/rail-nav.json +3 -3
  230. package/registry/retro-tv.json +1 -1
  231. package/registry/reviews.json +1 -1
  232. package/registry/router.json +1 -1
  233. package/registry/service-card.json +1 -1
  234. package/registry/settings-layout.json +1 -1
  235. package/registry/shop-composer.json +7 -7
  236. package/registry/shop-gallery.json +1 -1
  237. package/registry/shop.json +11 -11
  238. package/registry/signature.json +1 -1
  239. package/registry/site-cahier.json +1 -1
  240. package/registry/site-footer.json +3 -3
  241. package/registry/slot-picker.json +1 -1
  242. package/registry/stat.json +1 -1
  243. package/registry/status-chip.json +1 -1
  244. package/registry/tabs.json +1 -1
  245. package/registry/text-style.json +1 -1
  246. package/registry/usage.json +2 -2
  247. package/registry/versus-card.json +1 -1
  248. package/registry/vertical-video.json +1 -1
  249. package/registry/wall.json +5 -5
  250. package/registry/waveform.json +2 -2
  251. package/dist/chunk-BCD2CRFG.js.map +0 -1
  252. package/dist/chunk-CDNOT2KR.js.map +0 -1
  253. package/dist/chunk-FM42KOAU.js.map +0 -1
  254. package/dist/chunk-MTVX4RRF.js.map +0 -1
  255. package/dist/chunk-UIP3WX5O.js.map +0 -1
  256. package/dist/chunk-VUD4IEVJ.js.map +0 -1
  257. package/dist/chunk-ZFR6ZNXD.js.map +0 -1
  258. package/dist/lightbox-Q45BZ3HW.js.map +0 -1
  259. /package/dist/{chunk-YXETEQQJ.js.map → chunk-SG2RKUVJ.js.map} +0 -0
@@ -1045,7 +1045,7 @@
1045
1045
  },
1046
1046
  {
1047
1047
  "name": "inputMode",
1048
- "type": "\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"",
1048
+ "type": "\"email\" | \"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"numeric\" | \"decimal\"",
1049
1049
  "default": null,
1050
1050
  "description": "The keyboard on a phone (`numeric`, `decimal`).",
1051
1051
  "required": false
@@ -1080,7 +1080,7 @@
1080
1080
  },
1081
1081
  {
1082
1082
  "name": "type",
1083
- "type": "\"search\" | \"text\" | \"tel\" | \"url\" | \"email\" | \"password\"",
1083
+ "type": "\"email\" | \"search\" | \"text\" | \"tel\" | \"url\" | \"password\"",
1084
1084
  "default": "text",
1085
1085
  "description": "`text` (default), `email`, `password`, `url`, `tel`, `search`: the right keyboard on a phone.",
1086
1086
  "required": false
@@ -1212,7 +1212,7 @@
1212
1212
  },
1213
1213
  {
1214
1214
  "name": "variant",
1215
- "type": "\"danger\" | \"primary\" | \"gradient\" | \"secondary\" | \"outline\" | \"ghost\"",
1215
+ "type": "\"primary\" | \"danger\" | \"gradient\" | \"secondary\" | \"outline\" | \"ghost\"",
1216
1216
  "default": "primary",
1217
1217
  "description": "The look. Default `primary`.",
1218
1218
  "required": false
@@ -2072,7 +2072,7 @@
2072
2072
  "files": [
2073
2073
  {
2074
2074
  "path": "form/core.tsx",
2075
- "content": "// Platform-neutral React (web and React Native): the engine of a Krizaka form, TanStack Form v1 behind the facade\n// (ADR-001: a product never imports @tanstack/*). A form = a Standard Schema (zod 4) + its default values; the schema\n// validates every change, an error shows once the person leaves the field or tries to send (and goes as soon as it is\n// fixed), a field may check a value on the server (debounced, aborted when the value changes), and a refusal of the\n// server (Problem Details `fields`) lands under its fields. The fields themselves are the platform's (web.tsx, native).\nimport { type AnyFieldApi, type AnyFormApi, type DeepKeys, type StandardSchemaV1, useField, useForm, useStore } from \"@tanstack/react-form\";\nimport * as React from \"react\";\n\nimport { type FormFieldError, type FormI18n, formMessage, type FormProblem, isFormProblem, issuesToFields, problemToErrors, type SchemaIssue } from \"./errors\";\n\n/** A schema the form validates with: any Standard Schema — zod 4 (`z.object`), valibot, arktype. */\nexport type FormSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output>;\n/** The values a form holds: the schema's input. */\nexport type FormValues<S> = S extends { readonly \"~standard\": { readonly types?: { readonly input: infer I } } } ? I : never;\n/** The values a form sends: the schema's output (zod transforms applied). */\nexport type FormOutput<S> = S extends { readonly \"~standard\": { readonly types?: { readonly output: infer O } } } ? O : never;\n/** A field's name: `email`, `address.city`, `links[0].url`. */\nexport type FieldName<V> = DeepKeys<V> & string;\n\n/** What a Server Action (or any submit) answers: done, or a refusal the form shows. */\nexport type FormActionResult<T = unknown> = { ok: true; data?: T } | { ok: false; problem: FormProblem };\n\n/** A value checked on the server as it is typed: an error (or its key), or nothing when the value is fine. */\nexport type FieldCheck<T = unknown> = (value: T, signal: AbortSignal) => Promise<FormFieldError | string | null | undefined> | FormFieldError | string | null | undefined;\n\nexport interface KrizakaFormDefinition<S extends FormSchema> {\n /** The schema of the values (zod 4): the same one the server parses with. */\n schema: S;\n /** The values at first: every field of the schema. */\n defaultValues: FormValues<S>;\n /** The words: the app's translate function, the key prefixes, the locale. */\n i18n?: FormI18n;\n}\n\nexport interface UseKrizakaFormOptions<S extends FormSchema, R = unknown> {\n /** Sends the values (the schema's output): a mutation of @krizaka/query, a Server Action. Throw a `KrizakaApiError` or\n * return `{ ok: false, problem }` to refuse: its `fields` go under their fields, the rest above the button. */\n onSubmit?: (values: FormOutput<S>) => R | Promise<R>;\n /** Called after a successful submit with what `onSubmit` returned (`data` of a `{ ok: true, data }`). */\n onSuccess?: (result: R extends FormActionResult<infer T> ? T | undefined : R) => void;\n /** Values that replace the definition's (a profile loaded from the server). */\n defaultValues?: FormValues<S>;\n /** Overrides the definition's words (the translate function of a hook). */\n i18n?: FormI18n;\n /** The server's codes that belong to a field (`{ UNDERAGE: \"dateOfBirth\", USERNAME_RESERVED: \"username\" }`): a refusal\n * with that code shows under the field, as `form.errors.<CODE>`, instead of above the button. */\n codeFields?: Readonly<Record<string, string>>;\n}\n\n/** The state of a form, for its fields and its button. */\nexport interface FormContextValue {\n /** TanStack's form, through the facade: never import @tanstack/* in a product. */\n readonly api: AnyFormApi;\n readonly i18n: FormI18n;\n /** The whole form's error (a refusal without a field), or null. */\n readonly error: FormFieldError | null;\n /** Sends the form: validates, focuses (web) or announces (native) the first error, else calls `onSubmit`. */\n readonly submit: () => Promise<boolean>;\n}\n\nexport const FormContext = React.createContext<FormContextValue | null>(null);\n\n/** The form around a field: inside `form.Form`. */\nexport function useFormContext(): FormContextValue {\n const ctx = React.useContext(FormContext);\n if (!ctx) throw new Error(\"A Krizaka form field must be inside its form's `form.Form`.\");\n return ctx;\n}\n\ntype StandardResult = { readonly value?: unknown; readonly issues?: readonly SchemaIssue[] };\n\nconst run = (schema: FormSchema, value: unknown) => schema[\"~standard\"].validate(value) as StandardResult | Promise<StandardResult>;\n\n/** The engine of a form: TanStack's form wired to the schema, the server's refusals and the submit. */\nexport function useKrizakaFormCore<S extends FormSchema, R>(definition: KrizakaFormDefinition<S>, options: UseKrizakaFormOptions<S, R> = {}): FormContextValue {\n const i18n = { ...definition.i18n, ...options.i18n };\n const latest = React.useRef({ options, i18n });\n // The latest options for the engine's callbacks (a submit, a change), which outlive the render that made them.\n React.useLayoutEffect(() => {\n latest.current = { options, i18n };\n });\n const [error, setError] = React.useState<FormFieldError | null>(null);\n const refused = React.useRef(false);\n\n const api = useForm({\n defaultValues: options.defaultValues ?? definition.defaultValues,\n validators: {\n // Every change: the schema, synchronously (an async refinement waits for the submit). Errors are computed for\n // every field; each field shows its own once the person left it or tried to send.\n onChange: ({ value }: { value: unknown }) => {\n const result = run(definition.schema, value);\n if (result instanceof Promise || !result.issues?.length) return undefined;\n const fields = issuesToFields(result.issues, latest.current.i18n.prefix);\n delete fields[\"\"];\n return { fields };\n },\n },\n onSubmit: async ({ value }: { value: unknown }) => {\n const parsed = await run(definition.schema, value);\n if (parsed.issues?.length) {\n apply({ fields: issuesToFields(parsed.issues, latest.current.i18n.prefix) as FormProblem[\"fields\"] });\n return;\n }\n let result: unknown;\n try {\n result = await latest.current.options.onSubmit?.(parsed.value as FormOutput<S>);\n } catch (thrown) {\n apply(isFormProblem(thrown) ? thrown : { code: \"server\" });\n return;\n }\n if (result && typeof result === \"object\" && \"ok\" in result && (result as FormActionResult).ok === false) {\n apply((result as unknown as { problem: FormProblem }).problem);\n return;\n }\n const data = result && typeof result === \"object\" && \"ok\" in result ? (result as { data?: unknown }).data : result;\n latest.current.options.onSuccess?.(data as never);\n },\n });\n\n const known = (name: string) => name in api.fieldInfo;\n function apply(problem: FormProblem) {\n refused.current = true;\n const { fields, form } = problemToErrors(problem, latest.current.i18n, known, latest.current.options.codeFields);\n for (const [name, fieldError] of Object.entries(fields)) {\n api.setFieldMeta(name as never, (meta) => ({ ...meta, isBlurred: true, errorMap: { ...meta.errorMap, onServer: fieldError } }));\n }\n setError(form);\n }\n\n const submit = React.useCallback(async () => {\n setError(null);\n refused.current = false;\n for (const name of Object.keys(api.fieldInfo)) {\n if ((api.getFieldMeta(name as never) as { errorMap?: Record<string, unknown> } | undefined)?.errorMap?.onServer) api.setFieldMeta(name as never, (meta) => ({ ...meta, errorMap: { ...meta.errorMap, onServer: undefined } }));\n }\n await api.handleSubmit();\n const state = api.state;\n return !refused.current && state.isSubmitSuccessful && state.isValid && !(Object.values(state.fieldMeta) as { errorMap?: Record<string, unknown> }[]).some((meta) => meta?.errorMap?.onServer);\n }, [api]);\n\n return React.useMemo(() => ({ api, i18n, error, submit }), [api, error, submit, i18n.t, i18n.prefix, i18n.apiPrefix, i18n.locale]); // eslint-disable-line react-hooks/exhaustive-deps\n}\n\nconst UNCHECKED = Symbol(\"unchecked\");\n\nexport interface FieldOptions<T> {\n /** Checks the value on the server as it is typed (a username's availability): debounced, aborted when it changes. */\n validateAsync?: FieldCheck<T>;\n /** The wait, in ms, between the last change and `validateAsync`. Default 350. */\n asyncDebounceMs?: number;\n}\n\n/** A field as its component draws it: the value, its setter, its error in words, its state. */\nexport interface KrizakaField<T = unknown> {\n /** The id of the control (`htmlFor` of its label). */\n readonly id: string;\n readonly name: string;\n readonly value: T;\n /** Sets the value (clears a refusal of the server on it). */\n setValue(value: T): void;\n /** Call when the control loses focus: from then on, its errors show. */\n readonly onBlur: () => void;\n /** The error to show, in words — only once it should show. */\n readonly error: string | undefined;\n /** The error itself, with its suggestion. */\n readonly errorDetail: FormFieldError | undefined;\n /** A check (`validateAsync`) is running. */\n readonly validating: boolean;\n /** The check passed for the current value. */\n readonly available: boolean;\n /** The ids of the hint and the error (`aria-describedby`). */\n readonly hintId: string;\n readonly errorId: string;\n /** The form's locale (numbers, money, dates). */\n readonly locale: string;\n /** TanStack's field, through the facade. */\n readonly api: AnyFieldApi;\n}\n\n/** Binds a field of the form around it (inside `form.Form`): what the platform's field components are made of. */\nexport function useKrizakaField<T = unknown>(name: string, options: FieldOptions<T> = {}): KrizakaField<T> {\n const ctx = useFormContext();\n const id = React.useId();\n const [checked, setChecked] = React.useState<unknown>(UNCHECKED);\n const check = options.validateAsync;\n const field = useField({\n form: ctx.api,\n name: name as never,\n ...(check\n ? {\n asyncDebounceMs: options.asyncDebounceMs ?? 350,\n validators: {\n onChangeAsyncDebounceMs: options.asyncDebounceMs ?? 350,\n onChangeAsync: async ({ value, signal }: { value: T; signal: AbortSignal }) => {\n const answer = await check(value, signal);\n if (signal.aborted) return undefined;\n if (!answer) {\n setChecked(value);\n return undefined;\n }\n setChecked(UNCHECKED);\n const error = typeof answer === \"string\" ? { key: answer } : answer;\n return { ...error, immediate: true, source: \"check\" } satisfies FormFieldError;\n },\n },\n }\n : {}),\n } as never) as unknown as AnyFieldApi;\n const attempts = useStore(ctx.api.store, (state: { submissionAttempts: number }) => state.submissionAttempts);\n const meta = field.state.meta;\n const map = meta.errorMap as Record<string, unknown>;\n const all = [map.onServer, map.onChange, map.onBlur, map.onSubmit, map.onMount].filter(Boolean) as (FormFieldError | string)[];\n const first = all[0];\n const detail = typeof first === \"string\" ? { key: first } : first;\n const visible = detail && (detail.immediate || detail.source === \"server\" || meta.isBlurred || attempts > 0) ? detail : undefined;\n const value = field.state.value as T;\n\n return {\n id,\n name,\n value,\n setValue: (next: T) => {\n if (map.onServer) ctx.api.setFieldMeta(name as never, (m: { errorMap: Record<string, unknown> }) => ({ ...m, errorMap: { ...m.errorMap, onServer: undefined } }) as never);\n field.handleChange(next as never);\n },\n onBlur: () => field.handleBlur(),\n error: visible ? formMessage(visible, ctx.i18n) : undefined,\n errorDetail: visible,\n validating: Boolean(meta.isValidating),\n available: Boolean(check) && checked !== UNCHECKED && Object.is(checked, value) && !meta.isValidating && all.length === 0,\n hintId: `${id}-hint`,\n errorId: `${id}-error`,\n locale: ctx.i18n.locale ?? \"en\",\n api: field,\n };\n}\n\n/** The array of a field array, with its operations (`form.FieldArray`). */\nexport interface KrizakaFieldArray<T = unknown> {\n readonly name: string;\n readonly items: readonly T[];\n /** Adds an item at the end. */\n readonly push: (item: T) => void;\n /** Removes the item at `index`. */\n readonly remove: (index: number) => void;\n /** Moves an item. */\n readonly move: (from: number, to: number) => void;\n /** The name of a sub-field of an item: `name(0, \"url\")` → `links[0].url`. */\n readonly fieldName: (index: number, key?: string) => string;\n /** The error of the array itself (too few, too many), in words, once it should show. */\n readonly error: string | undefined;\n}\n\n/** Binds an array of the form (a list of links, of tiers): its items and their operations. */\nexport function useKrizakaFieldArray<T = unknown>(name: string): KrizakaFieldArray<T> {\n const ctx = useFormContext();\n const field = useField({ form: ctx.api, name: name as never, mode: \"array\" } as never) as unknown as AnyFieldApi;\n const attempts = useStore(ctx.api.store, (state: { submissionAttempts: number }) => state.submissionAttempts);\n const map = field.state.meta.errorMap as Record<string, FormFieldError | undefined>;\n const first = map.onServer ?? map.onChange ?? map.onSubmit;\n return {\n name,\n items: (field.state.value as T[] | undefined) ?? [],\n push: (item) => field.pushValue(item as never),\n remove: (index) => void field.removeValue(index),\n move: (from, to) => field.moveValue(from, to),\n fieldName: (index, key) => `${name}[${index}]${key ? `.${key}` : \"\"}`,\n error: first && (attempts > 0 || first.source === \"server\" || field.state.meta.isDirty) ? formMessage(first, ctx.i18n) : undefined,\n };\n}\n\n/** The value of a field, kept up to date (`form.Watch`): show a part of the form only when a box is ticked. */\nexport function useFormValue<T = unknown>(name: string): T {\n const ctx = useFormContext();\n return useStore(ctx.api.store, (state: { values: unknown }) => getPath(state.values, name)) as T;\n}\n\nexport type FormFieldProps<T = unknown> = {\n /** The field's name in the schema (typed by the form). */\n name: string;\n /** Checks the value on the server as it changes. */\n validateAsync?: FieldCheck<T>;\n /** The wait, in ms, before `validateAsync`. */\n asyncDebounceMs?: number;\n /** Draws the field: its value, setter, error (and the ids, on the web) (`useKrizakaField`). */\n children: (field: KrizakaField<T>) => React.ReactNode;\n};\n\n/** A field drawn by the app (a control the package does not have): the form's value and errors, any markup. */\nexport function FormField({ name, validateAsync, asyncDebounceMs, children }: FormFieldProps) {\n return <>{children(useKrizakaField(name, { validateAsync, asyncDebounceMs }))}</>;\n}\n\nexport type FieldArrayProps<T = unknown> = {\n /** The array's name in the schema (typed by the form). */\n name: string;\n /** Draws the items: `items`, `push`, `remove`, `move`, `fieldName(i, \"url\")` for the fields of an item. */\n children: (array: KrizakaFieldArray<T>) => React.ReactNode;\n};\n\n/** A list of fields that grows and shrinks (links, tiers, guests): each item's fields named `links[0].url`. */\nexport function FieldArray({ name, children }: FieldArrayProps) {\n return <>{children(useKrizakaFieldArray(name))}</>;\n}\n\nexport type WatchProps<T = unknown> = {\n /** The field to follow (typed by the form). */\n name: string;\n /** Draws from its current value: show a part of the form only when a choice is made. */\n children: (value: T) => React.ReactNode;\n};\n\n/** Renders from a field's current value (a part shown only when a choice is made, a total). */\nexport function Watch({ name, children }: WatchProps) {\n return <>{children(useFormValue(name))}</>;\n}\n\n/** The state of the submit, for a button: sending, and whether the last try succeeded. */\nexport function useFormStatus(): { submitting: boolean; succeeded: boolean; attempts: number } {\n const ctx = useFormContext();\n const submitting = useStore(ctx.api.store, (s: { isSubmitting: boolean }) => s.isSubmitting);\n const succeeded = useStore(ctx.api.store, (s: { isSubmitSuccessful: boolean }) => s.isSubmitSuccessful);\n const attempts = useStore(ctx.api.store, (s: { submissionAttempts: number }) => s.submissionAttempts);\n return { submitting, succeeded: succeeded && !ctx.error, attempts };\n}\n\nfunction getPath(source: unknown, path: string): unknown {\n let current = source;\n for (const part of path.replace(/\\[(\\d+)\\]/g, \".$1\").split(\".\")) {\n if (current === null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/** The first visible error of a form, in words (native: announced after a refused submit). */\nexport function firstVisibleError(ctx: FormContextValue): string | undefined {\n if (ctx.error) return formMessage(ctx.error, ctx.i18n);\n for (const meta of Object.values(ctx.api.state.fieldMeta) as { errorMap?: Record<string, FormFieldError | string | undefined> }[]) {\n const error = meta?.errorMap && Object.values(meta.errorMap).find(Boolean);\n if (error) return formMessage(error, ctx.i18n);\n }\n return undefined;\n}\n\n/** The platform's components, typed by the form's field names: `name` completes and is checked against the schema. */\nexport type BoundFields<C, N extends string> = {\n [K in keyof C]: C[K] extends (props: infer P) => infer R ? (P extends { name: string } ? (props: Omit<P, \"name\"> & { name: N }) => R : C[K]) : C[K];\n};\n\n/** A form in a component: its fields (typed by the schema), its submit and its state. */\nexport type KrizakaFormInstance<S extends FormSchema, C, RootProps> = BoundFields<C, FieldName<FormValues<S>>> & {\n /** The form element (web) or view (native): renders its fields and provides them the form. */\n Form: (props: RootProps) => React.ReactElement;\n /** Sends the form (what `Submit` does): `true` when it went through. */\n submit: () => Promise<boolean>;\n /** Back to the default values (or the given ones), errors cleared. */\n reset: (values?: FormValues<S>) => void;\n /** Sets a field's value from outside (a suggestion, a preset). */\n setValue: (name: FieldName<FormValues<S>>, value: unknown) => void;\n /** The values now. */\n getValues: () => FormValues<S>;\n /** The whole form's error (a refusal without a field), or null. */\n error: FormFieldError | null;\n /** TanStack's form, the escape hatch — never import @tanstack/* in a product. */\n api: AnyFormApi;\n};\n\n/** A form defined once (schema + defaults), used in components: `signUp.useForm({ onSubmit })`. */\nexport interface KrizakaFormFactory<S extends FormSchema, C, RootProps> {\n readonly schema: S;\n readonly defaultValues: FormValues<S>;\n /** The form in a component: `onSubmit` sends the values (a mutation), a thrown `KrizakaApiError` lands on the fields. */\n useForm<R = unknown>(options?: UseKrizakaFormOptions<S, R>): KrizakaFormInstance<S, C, RootProps>;\n /** The form sent by a Server Action: it receives the values and answers `{ ok: true, data }` or `{ ok: false, problem }`. */\n useFormWithAction<T = unknown>(action: (values: FormOutput<S>) => Promise<FormActionResult<T>>, options?: Omit<UseKrizakaFormOptions<S, FormActionResult<T>>, \"onSubmit\">): KrizakaFormInstance<S, C, RootProps>;\n}\n\n/** Builds a platform's `createKrizakaForm` from its field components and its root (web `<form>`, native `View`). */\nexport function makeCreateKrizakaForm<C extends object, RootProps extends object>(components: C, Root: (props: RootProps & { value: FormContextValue }) => React.ReactElement) {\n return function createKrizakaForm<S extends FormSchema>(definition: KrizakaFormDefinition<S>): KrizakaFormFactory<S, C, RootProps> {\n function useForm<R>(options?: UseKrizakaFormOptions<S, R>): KrizakaFormInstance<S, C, RootProps> {\n const ctx = useKrizakaFormCore(definition, options);\n // One `Form` for the life of the form (never remounted, so focus and fields stay): it reads the latest state from a\n // small store the hook updates.\n const [store] = React.useState(() => createStore(ctx));\n React.useLayoutEffect(() => store.set(ctx), [store, ctx]);\n const Form = React.useCallback((props: RootProps) => <Bound store={store} Root={Root} props={props} />, [store]);\n return React.useMemo(\n () =>\n ({\n ...components,\n Form,\n submit: ctx.submit,\n reset: (values?: FormValues<S>) => ctx.api.reset(values),\n setValue: (name: string, value: unknown) => ctx.api.setFieldValue(name as never, value as never),\n getValues: () => ctx.api.state.values as FormValues<S>,\n error: ctx.error,\n api: ctx.api,\n }) as unknown as KrizakaFormInstance<S, C, RootProps>,\n [ctx, Form],\n );\n }\n return {\n schema: definition.schema,\n defaultValues: definition.defaultValues,\n useForm,\n useFormWithAction: (action, options) => useForm({ ...options, onSubmit: action }),\n };\n };\n}\n\ntype Store<T> = { get: () => T; set: (value: T) => void; subscribe: (listener: () => void) => () => void };\n\nfunction createStore<T>(initial: T): Store<T> {\n let value = initial;\n const listeners = new Set<() => void>();\n return {\n get: () => value,\n set: (next) => {\n if (Object.is(next, value)) return;\n value = next;\n listeners.forEach((listener) => listener());\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\nfunction Bound<RootProps extends object>({ store, Root, props }: { store: Store<FormContextValue>; Root: (props: RootProps & { value: FormContextValue }) => React.ReactElement; props: RootProps }) {\n const value = React.useSyncExternalStore(store.subscribe, store.get, store.get);\n return <Root {...props} value={value} />;\n}\n"
2075
+ "content": "// Platform-neutral React (web and React Native): the engine of a Krizaka form, TanStack Form v1 behind the facade\n// (ADR-001: a product never imports @tanstack/*). A form = a Standard Schema (zod 4) + its default values; the schema\n// validates every change, an error shows once the person leaves the field or tries to send (and goes as soon as it is\n// fixed), a field may check a value on the server (debounced, aborted when the value changes), and a refusal of the\n// server (Problem Details `fields`) lands under its fields. The fields themselves are the platform's (web.tsx, native).\nimport { type AnyFieldApi, type AnyFormApi, type DeepKeys, type StandardSchemaV1, useField, useForm, useStore } from \"@tanstack/react-form\";\nimport * as React from \"react\";\n\nimport { type FormFieldError, type FormI18n, formMessage, type FormProblem, isFormProblem, issuesToFields, problemToErrors, type SchemaIssue } from \"./errors\";\n\n/** A schema the form validates with: any Standard Schema — zod 4 (`z.object`), valibot, arktype. */\nexport type FormSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output>;\n/** The values a form holds: the schema's input. */\nexport type FormValues<S> = S extends { readonly \"~standard\": { readonly types?: { readonly input: infer I } } } ? I : never;\n/** The values a form sends: the schema's output (zod transforms applied). */\nexport type FormOutput<S> = S extends { readonly \"~standard\": { readonly types?: { readonly output: infer O } } } ? O : never;\n/** A field's name: `email`, `address.city`, `links[0].url`. */\nexport type FieldName<V> = DeepKeys<V> & string;\n\n/** What a Server Action (or any submit) answers: done, or a refusal the form shows. */\nexport type FormActionResult<T = unknown> = { ok: true; data?: T } | { ok: false; problem: FormProblem };\n\n/** A value checked on the server as it is typed: an error (or its key), or nothing when the value is fine. */\nexport type FieldCheck<T = unknown> = (value: T, signal: AbortSignal) => Promise<FormFieldError | string | null | undefined> | FormFieldError | string | null | undefined;\n\nexport interface KrizakaFormDefinition<S extends FormSchema> {\n /** The schema of the values (zod 4): the same one the server parses with. */\n schema: S;\n /** The values at first: every field of the schema. */\n defaultValues: FormValues<S>;\n /** The words: the app's translate function, the key prefixes, the locale. */\n i18n?: FormI18n;\n}\n\nexport interface UseKrizakaFormOptions<S extends FormSchema, R = unknown> {\n /** Sends the values (the schema's output): a mutation of @krizaka/query, a Server Action. Throw a `KrizakaApiError` or\n * return `{ ok: false, problem }` to refuse: its `fields` go under their fields, the rest above the button. */\n onSubmit?: (values: FormOutput<S>) => R | Promise<R>;\n /** Called after a successful submit with what `onSubmit` returned (`data` of a `{ ok: true, data }`). */\n onSuccess?: (result: R extends FormActionResult<infer T> ? T | undefined : R) => void;\n /** Values that replace the definition's (a profile loaded from the server). */\n defaultValues?: FormValues<S>;\n /** Overrides the definition's words (the translate function of a hook). */\n i18n?: FormI18n;\n /** The server's codes that belong to a field (`{ UNDERAGE: \"dateOfBirth\", USERNAME_RESERVED: \"username\" }`): a refusal\n * with that code shows under the field, as `form.errors.<CODE>`, instead of above the button. */\n codeFields?: Readonly<Record<string, string>>;\n}\n\n/** The state of a form, for its fields and its button. */\nexport interface FormContextValue {\n /** TanStack's form, through the facade: never import @tanstack/* in a product. */\n readonly api: AnyFormApi;\n readonly i18n: FormI18n;\n /** The whole form's error (a refusal without a field), or null. */\n readonly error: FormFieldError | null;\n /** Sends the form: validates, focuses (web) or announces (native) the first error, else calls `onSubmit`. */\n readonly submit: () => Promise<boolean>;\n}\n\nexport const FormContext = React.createContext<FormContextValue | null>(null);\n\n/** The form around a field: inside `form.Form`. */\nexport function useFormContext(): FormContextValue {\n const ctx = React.useContext(FormContext);\n if (!ctx) throw new Error(\"A Krizaka form field must be inside its form's `form.Form`.\");\n return ctx;\n}\n\ntype StandardResult = { readonly value?: unknown; readonly issues?: readonly SchemaIssue[] };\n\nconst run = (schema: FormSchema, value: unknown) => schema[\"~standard\"].validate(value) as StandardResult | Promise<StandardResult>;\n\n/** The engine of a form: TanStack's form wired to the schema, the server's refusals and the submit. */\nexport function useKrizakaFormCore<S extends FormSchema, R>(definition: KrizakaFormDefinition<S>, options: UseKrizakaFormOptions<S, R> = {}): FormContextValue {\n const i18n = { ...definition.i18n, ...options.i18n };\n const latest = React.useRef({ options, i18n });\n // The latest options for the engine's callbacks (a submit, a change), which outlive the render that made them.\n React.useLayoutEffect(() => {\n latest.current = { options, i18n };\n });\n const [error, setError] = React.useState<FormFieldError | null>(null);\n const refused = React.useRef(false);\n\n const api = useForm({\n defaultValues: options.defaultValues ?? definition.defaultValues,\n validators: {\n // Every change: the schema, synchronously (an async refinement waits for the submit). Errors are computed for\n // every field; each field shows its own once the person left it or tried to send.\n onChange: ({ value }: { value: unknown }) => {\n const result = run(definition.schema, value);\n if (result instanceof Promise || !result.issues?.length) return undefined;\n const fields = issuesToFields(result.issues, latest.current.i18n.prefix);\n delete fields[\"\"];\n return { fields };\n },\n },\n onSubmit: async ({ value }: { value: unknown }) => {\n const parsed = await run(definition.schema, value);\n if (parsed.issues?.length) {\n apply({ fields: issuesToFields(parsed.issues, latest.current.i18n.prefix) as FormProblem[\"fields\"] });\n return;\n }\n let result: unknown;\n try {\n result = await latest.current.options.onSubmit?.(parsed.value as FormOutput<S>);\n } catch (thrown) {\n apply(isFormProblem(thrown) ? thrown : { code: \"server\" });\n return;\n }\n if (result && typeof result === \"object\" && \"ok\" in result && (result as FormActionResult).ok === false) {\n apply((result as unknown as { problem: FormProblem }).problem);\n return;\n }\n const data = result && typeof result === \"object\" && \"ok\" in result ? (result as { data?: unknown }).data : result;\n latest.current.options.onSuccess?.(data as never);\n },\n });\n\n const known = (name: string) => name in api.fieldInfo;\n function apply(problem: FormProblem) {\n refused.current = true;\n const { fields, form } = problemToErrors(problem, latest.current.i18n, known, latest.current.options.codeFields);\n for (const [name, fieldError] of Object.entries(fields)) {\n api.setFieldMeta(name as never, (meta) => ({ ...meta, isBlurred: true, errorMap: { ...meta.errorMap, onServer: fieldError } }));\n }\n setError(form);\n }\n\n const submit = React.useCallback(async () => {\n setError(null);\n refused.current = false;\n for (const name of Object.keys(api.fieldInfo)) {\n if ((api.getFieldMeta(name as never) as { errorMap?: Record<string, unknown> } | undefined)?.errorMap?.onServer) api.setFieldMeta(name as never, (meta) => ({ ...meta, errorMap: { ...meta.errorMap, onServer: undefined } }));\n }\n await api.handleSubmit();\n const state = api.state;\n return !refused.current && state.isSubmitSuccessful && state.isValid && !(Object.values(state.fieldMeta) as { errorMap?: Record<string, unknown> }[]).some((meta) => meta?.errorMap?.onServer);\n }, [api]);\n\n return React.useMemo(() => ({ api, i18n, error, submit }), [api, error, submit, i18n.t, i18n.prefix, i18n.apiPrefix, i18n.locale]); // eslint-disable-line react-hooks/exhaustive-deps\n}\n\nconst UNCHECKED = Symbol(\"unchecked\");\n\nexport interface FieldOptions<T> {\n /** Checks the value on the server as it is typed (a username's availability): debounced, aborted when it changes. */\n validateAsync?: FieldCheck<T>;\n /** The wait, in ms, between the last change and `validateAsync`. Default 350. */\n asyncDebounceMs?: number;\n}\n\n/** A field as its component draws it: the value, its setter, its error in words, its state. */\nexport interface KrizakaField<T = unknown> {\n /** The id of the control (`htmlFor` of its label). */\n readonly id: string;\n readonly name: string;\n readonly value: T;\n /** Sets the value (clears a refusal of the server on it). */\n setValue(value: T): void;\n /** Call when the control loses focus: from then on, its errors show. */\n readonly onBlur: () => void;\n /** The error to show, in words — only once it should show. */\n readonly error: string | undefined;\n /** The error itself, with its suggestion. */\n readonly errorDetail: FormFieldError | undefined;\n /** A check (`validateAsync`) is running. */\n readonly validating: boolean;\n /** The check passed for the current value. */\n readonly available: boolean;\n /** The ids of the hint and the error (`aria-describedby`). */\n readonly hintId: string;\n readonly errorId: string;\n /** The form's locale (numbers, money, dates). */\n readonly locale: string;\n /** TanStack's field, through the facade. */\n readonly api: AnyFieldApi;\n}\n\n/** Binds a field of the form around it (inside `form.Form`): what the platform's field components are made of. */\nexport function useKrizakaField<T = unknown>(name: string, options: FieldOptions<T> = {}): KrizakaField<T> {\n const ctx = useFormContext();\n const id = React.useId();\n const [checked, setChecked] = React.useState<unknown>(UNCHECKED);\n const check = options.validateAsync;\n const field = useField({\n form: ctx.api,\n name: name as never,\n ...(check\n ? {\n asyncDebounceMs: options.asyncDebounceMs ?? 350,\n validators: {\n onChangeAsyncDebounceMs: options.asyncDebounceMs ?? 350,\n onChangeAsync: async ({ value, signal }: { value: T; signal: AbortSignal }) => {\n const answer = await check(value, signal);\n if (signal.aborted) return undefined;\n if (!answer) {\n setChecked(value);\n return undefined;\n }\n setChecked(UNCHECKED);\n const error = typeof answer === \"string\" ? { key: answer } : answer;\n return { ...error, immediate: true, source: \"check\" } satisfies FormFieldError;\n },\n },\n }\n : {}),\n } as never) as unknown as AnyFieldApi;\n const attempts = useStore(ctx.api.store, (state: { submissionAttempts: number }) => state.submissionAttempts);\n const meta = field.state.meta;\n const map = meta.errorMap as Record<string, unknown>;\n const all = [map.onServer, map.onChange, map.onBlur, map.onSubmit, map.onMount].filter(Boolean) as (FormFieldError | string)[];\n const first = all[0];\n const detail = typeof first === \"string\" ? { key: first } : first;\n const visible = detail && (detail.immediate || detail.source === \"server\" || meta.isBlurred || attempts > 0) ? detail : undefined;\n const value = field.state.value as T;\n\n return {\n id,\n name,\n value,\n setValue: (next: T) => {\n if (map.onServer) ctx.api.setFieldMeta(name as never, (m: { errorMap: Record<string, unknown> }) => ({ ...m, errorMap: { ...m.errorMap, onServer: undefined } }) as never);\n field.handleChange(next as never);\n },\n onBlur: () => field.handleBlur(),\n error: visible ? formMessage(visible, ctx.i18n) : undefined,\n errorDetail: visible,\n validating: Boolean(meta.isValidating),\n available: Boolean(check) && checked !== UNCHECKED && Object.is(checked, value) && !meta.isValidating && all.length === 0,\n hintId: `${id}-hint`,\n errorId: `${id}-error`,\n locale: ctx.i18n.locale ?? \"en\",\n api: field,\n };\n}\n\n/** The array of a field array, with its operations (`form.FieldArray`). */\nexport interface KrizakaFieldArray<T = unknown> {\n readonly name: string;\n readonly items: readonly T[];\n /** Adds an item at the end. */\n readonly push: (item: T) => void;\n /** Removes the item at `index`. */\n readonly remove: (index: number) => void;\n /** Moves an item. */\n readonly move: (from: number, to: number) => void;\n /** The name of a sub-field of an item: `name(0, \"url\")` → `links[0].url`. */\n readonly fieldName: (index: number, key?: string) => string;\n /** The error of the array itself (too few, too many), in words, once it should show. */\n readonly error: string | undefined;\n}\n\n/** Binds an array of the form (a list of links, of tiers): its items and their operations. */\nexport function useKrizakaFieldArray<T = unknown>(name: string): KrizakaFieldArray<T> {\n const ctx = useFormContext();\n const field = useField({ form: ctx.api, name: name as never, mode: \"array\" } as never) as unknown as AnyFieldApi;\n const attempts = useStore(ctx.api.store, (state: { submissionAttempts: number }) => state.submissionAttempts);\n const map = field.state.meta.errorMap as Record<string, FormFieldError | undefined>;\n const first = map.onServer ?? map.onChange ?? map.onSubmit;\n return {\n name,\n items: (field.state.value as T[] | undefined) ?? [],\n push: (item) => field.pushValue(item as never),\n remove: (index) => void field.removeValue(index),\n move: (from, to) => field.moveValue(from, to),\n fieldName: (index, key) => `${name}[${index}]${key ? `.${key}` : \"\"}`,\n error: first && (attempts > 0 || first.source === \"server\" || field.state.meta.isDirty) ? formMessage(first, ctx.i18n) : undefined,\n };\n}\n\n/** The value of a field, kept up to date (`form.Watch`): show a part of the form only when a box is ticked. */\nexport function useFormValue<T = unknown>(name: string): T {\n const ctx = useFormContext();\n return useStore(ctx.api.store, (state: { values: unknown }) => getPath(state.values, name)) as T;\n}\n\nexport type FormFieldProps<T = unknown> = {\n /** The field's name in the schema (typed by the form). */\n name: string;\n /** Checks the value on the server as it changes. */\n validateAsync?: FieldCheck<T>;\n /** The wait, in ms, before `validateAsync`. */\n asyncDebounceMs?: number;\n /** Draws the field: its value, setter, error (and the ids, on the web) (`useKrizakaField`). */\n children: (field: KrizakaField<T>) => React.ReactNode;\n};\n\n/** A field drawn by the app (a control the package does not have): the form's value and errors, any markup. */\nexport function FormField({ name, validateAsync, asyncDebounceMs, children }: Readonly<FormFieldProps>) {\n return <>{children(useKrizakaField(name, { validateAsync, asyncDebounceMs }))}</>;\n}\n\nexport type FieldArrayProps<T = unknown> = {\n /** The array's name in the schema (typed by the form). */\n name: string;\n /** Draws the items: `items`, `push`, `remove`, `move`, `fieldName(i, \"url\")` for the fields of an item. */\n children: (array: KrizakaFieldArray<T>) => React.ReactNode;\n};\n\n/** A list of fields that grows and shrinks (links, tiers, guests): each item's fields named `links[0].url`. */\nexport function FieldArray({ name, children }: Readonly<FieldArrayProps>) {\n return <>{children(useKrizakaFieldArray(name))}</>;\n}\n\nexport type WatchProps<T = unknown> = {\n /** The field to follow (typed by the form). */\n name: string;\n /** Draws from its current value: show a part of the form only when a choice is made. */\n children: (value: T) => React.ReactNode;\n};\n\n/** Renders from a field's current value (a part shown only when a choice is made, a total). */\nexport function Watch({ name, children }: Readonly<WatchProps>) {\n return <>{children(useFormValue(name))}</>;\n}\n\n/** The state of the submit, for a button: sending, and whether the last try succeeded. */\nexport function useFormStatus(): { submitting: boolean; succeeded: boolean; attempts: number } {\n const ctx = useFormContext();\n const submitting = useStore(ctx.api.store, (s: { isSubmitting: boolean }) => s.isSubmitting);\n const succeeded = useStore(ctx.api.store, (s: { isSubmitSuccessful: boolean }) => s.isSubmitSuccessful);\n const attempts = useStore(ctx.api.store, (s: { submissionAttempts: number }) => s.submissionAttempts);\n return { submitting, succeeded: succeeded && !ctx.error, attempts };\n}\n\nfunction getPath(source: unknown, path: string): unknown {\n let current = source;\n for (const part of path.replace(/\\[(\\d+)\\]/g, \".$1\").split(\".\")) {\n if (current === null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/** The first visible error of a form, in words (native: announced after a refused submit). */\nexport function firstVisibleError(ctx: FormContextValue): string | undefined {\n if (ctx.error) return formMessage(ctx.error, ctx.i18n);\n for (const meta of Object.values(ctx.api.state.fieldMeta) as { errorMap?: Record<string, FormFieldError | string | undefined> }[]) {\n const error = meta?.errorMap && Object.values(meta.errorMap).find(Boolean);\n if (error) return formMessage(error, ctx.i18n);\n }\n return undefined;\n}\n\n/** The platform's components, typed by the form's field names: `name` completes and is checked against the schema. */\nexport type BoundFields<C, N extends string> = {\n [K in keyof C]: C[K] extends (props: infer P) => infer R ? (P extends { name: string } ? (props: Omit<P, \"name\"> & { name: N }) => R : C[K]) : C[K];\n};\n\n/** A form in a component: its fields (typed by the schema), its submit and its state. */\nexport type KrizakaFormInstance<S extends FormSchema, C, RootProps> = BoundFields<C, FieldName<FormValues<S>>> & {\n /** The form element (web) or view (native): renders its fields and provides them the form. */\n Form: (props: RootProps) => React.ReactElement;\n /** Sends the form (what `Submit` does): `true` when it went through. */\n submit: () => Promise<boolean>;\n /** Back to the default values (or the given ones), errors cleared. */\n reset: (values?: FormValues<S>) => void;\n /** Sets a field's value from outside (a suggestion, a preset). */\n setValue: (name: FieldName<FormValues<S>>, value: unknown) => void;\n /** The values now. */\n getValues: () => FormValues<S>;\n /** The whole form's error (a refusal without a field), or null. */\n error: FormFieldError | null;\n /** TanStack's form, the escape hatch — never import @tanstack/* in a product. */\n api: AnyFormApi;\n};\n\n/** A form defined once (schema + defaults), used in components: `signUp.useForm({ onSubmit })`. */\nexport interface KrizakaFormFactory<S extends FormSchema, C, RootProps> {\n readonly schema: S;\n readonly defaultValues: FormValues<S>;\n /** The form in a component: `onSubmit` sends the values (a mutation), a thrown `KrizakaApiError` lands on the fields. */\n useForm<R = unknown>(options?: UseKrizakaFormOptions<S, R>): KrizakaFormInstance<S, C, RootProps>;\n /** The form sent by a Server Action: it receives the values and answers `{ ok: true, data }` or `{ ok: false, problem }`. */\n useFormWithAction<T = unknown>(action: (values: FormOutput<S>) => Promise<FormActionResult<T>>, options?: Omit<UseKrizakaFormOptions<S, FormActionResult<T>>, \"onSubmit\">): KrizakaFormInstance<S, C, RootProps>;\n}\n\n/** Builds a platform's `createKrizakaForm` from its field components and its root (web `<form>`, native `View`). */\nexport function makeCreateKrizakaForm<C extends object, RootProps extends object>(components: C, Root: (props: RootProps & { value: FormContextValue }) => React.ReactElement) {\n return function createKrizakaForm<S extends FormSchema>(definition: KrizakaFormDefinition<S>): KrizakaFormFactory<S, C, RootProps> {\n function useForm<R>(options?: UseKrizakaFormOptions<S, R>): KrizakaFormInstance<S, C, RootProps> {\n const ctx = useKrizakaFormCore(definition, options);\n // One `Form` for the life of the form (never remounted, so focus and fields stay): it reads the latest state from a\n // small store the hook updates.\n const [store] = React.useState(() => createStore(ctx));\n React.useLayoutEffect(() => store.set(ctx), [store, ctx]);\n const Form = React.useCallback((props: RootProps) => <Bound store={store} Root={Root} props={props} />, [store]);\n return React.useMemo(\n () =>\n ({\n ...components,\n Form,\n submit: ctx.submit,\n reset: (values?: FormValues<S>) => ctx.api.reset(values),\n setValue: (name: string, value: unknown) => ctx.api.setFieldValue(name as never, value as never),\n getValues: () => ctx.api.state.values as FormValues<S>,\n error: ctx.error,\n api: ctx.api,\n }) as unknown as KrizakaFormInstance<S, C, RootProps>,\n [ctx, Form],\n );\n }\n return {\n schema: definition.schema,\n defaultValues: definition.defaultValues,\n useForm,\n useFormWithAction: (action, options) => useForm({ ...options, onSubmit: action }),\n };\n };\n}\n\ntype Store<T> = { get: () => T; set: (value: T) => void; subscribe: (listener: () => void) => () => void };\n\nfunction createStore<T>(initial: T): Store<T> {\n let value = initial;\n const listeners = new Set<() => void>();\n return {\n get: () => value,\n set: (next) => {\n if (Object.is(next, value)) return;\n value = next;\n listeners.forEach((listener) => listener());\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\nfunction Bound<RootProps extends object>({ store, Root, props }: { store: Store<FormContextValue>; Root: (props: RootProps & { value: FormContextValue }) => React.ReactElement; props: RootProps }) {\n const value = React.useSyncExternalStore(store.subscribe, store.get, store.get);\n return <Root {...props} value={value} />;\n}\n"
2076
2076
  },
2077
2077
  {
2078
2078
  "path": "form/errors.ts",
@@ -2096,7 +2096,7 @@
2096
2096
  },
2097
2097
  {
2098
2098
  "path": "form/web.tsx",
2099
- "content": "// Client. The form's fields for the web: thin adapters from a form field (useKrizakaField) to the platform's current\n// primitives — Field + Input, Checkbox, Switch, RadioGroup (dots, cards, tactile keys, segments), Combobox, the date\n// pickers (calendar, typed, wheels), TagInput, Dropzone, Slider. A new look for a primitive changes an adapter here,\n// never a form.\nimport { Alert } from \"@krizaka/ui/alert\";\nimport { Button, type ButtonProps } from \"@krizaka/ui/button\";\nimport { Checkbox as CheckboxControl } from \"@krizaka/ui/checkbox\";\nimport { Combobox as ComboboxControl, type ComboboxLabels, type ComboboxOption } from \"@krizaka/ui/combobox\";\nimport { DateField as DatePartsControl, DatePicker, type DatePickerLabels, DateWheel } from \"@krizaka/ui/date-picker\";\nimport { Field, Input, Select as SelectControl, Textarea } from \"@krizaka/ui/field\";\nimport { Dropzone, formatBytes } from \"@krizaka/ui/file-upload\";\nimport { RadioGroup as RadioGroupControl } from \"@krizaka/ui/radio-group\";\nimport { Slider as SliderControl, type SliderMark, type SliderValue } from \"@krizaka/ui/slider\";\nimport { Spinner } from \"@krizaka/ui/spinner\";\nimport { Switch as SwitchControl } from \"@krizaka/ui/switch\";\nimport { TagInput as TagInputControl, type TagInputProps } from \"@krizaka/ui/tag-input\";\nimport * as React from \"react\";\n\nimport type { DatePart } from \"../date-picker/parts\";\nimport {\n FieldArray,\n type FieldArrayProps,\n type FieldCheck,\n FormContext,\n type FormContextValue,\n FormField,\n type FormFieldProps,\n type KrizakaField,\n makeCreateKrizakaForm,\n useFormContext,\n useFormStatus,\n useKrizakaField,\n Watch,\n type WatchProps,\n} from \"./core\";\nimport { formMessage } from \"./errors\";\nimport { currencySymbol, moneyInputText, parseMoney } from \"./money\";\n\nexport { FieldArray, type FieldArrayProps, FormField, type FormFieldProps, Watch, type WatchProps };\n\ntype Base = {\n /** The field's name in the schema: `email`, `address.city`, `links[0].url` (typed by the form). */\n name: string;\n /** The visible label, passed translated (also the control's accessible name). */\n label: string;\n /** A help text under the control, read with it; the error takes its place when there is one. */\n hint?: string;\n /** Not available. */\n disabled?: boolean;\n /** Classes merged on the field's root. */\n className?: string;\n};\n\nconst ids = (f: KrizakaField, hint?: string) => [hint && !f.error ? f.hintId : null, f.error ? f.errorId : null].filter(Boolean).join(\" \") || undefined;\n\nfunction Caption({ field, hint, ok }: { field: KrizakaField; hint?: string; ok?: string }) {\n const suggestion = field.errorDetail?.suggestion;\n if (field.error)\n return (\n <Field.Error id={field.errorId}>\n <span>\n {field.error}\n {suggestion ? (\n <>\n {\" \"}\n <button type=\"button\" className=\"font-semibold text-accent-text underline underline-offset-2\" onClick={() => field.setValue(suggestion.value)}>\n {suggestion.label}\n </button>\n </>\n ) : null}\n </span>\n </Field.Error>\n );\n const text = field.available && ok ? (hint ? `${ok} · ${hint}` : ok) : hint;\n return text ? <Field.Hint id={field.hintId}>{text}</Field.Hint> : null;\n}\n\nconst Check = () => (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4 text-fg-success\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n);\n\nexport type FormProps = Omit<React.ComponentProps<\"form\">, \"onSubmit\" | \"noValidate\"> & {\n /** The fields, the error and the button. */\n children?: React.ReactNode;\n};\n\n/** The `<form>` of a form (`form.Form`): `noValidate` (the schema validates), the first error focused after a refused submit. */\nfunction FormRoot({ value, className, children, ...props }: FormProps & { value: FormContextValue }) {\n const ref = React.useRef<HTMLFormElement>(null);\n return (\n <FormContext.Provider value={value}>\n <form\n ref={ref}\n noValidate\n className={className ?? \"flex flex-col gap-4\"}\n onSubmit={async (event) => {\n event.preventDefault();\n if (!(await value.submit())) requestAnimationFrame(() => ref.current?.querySelector<HTMLElement>('[aria-invalid=\"true\"], [data-invalid] input')?.focus());\n }}\n {...props}\n >\n {children}\n </form>\n </FormContext.Provider>\n );\n}\n\nexport type SubmitProps = Omit<ButtonProps, \"type\" | \"loading\"> & {\n /** The button's words, passed translated (\"Create my account\"). */\n children: React.ReactNode;\n};\n\n/** The submit button: busy while the form is sent (not pressable twice), never disabled for an invalid form. */\nexport function Submit({ variant = \"primary\", children, ...props }: SubmitProps) {\n const { submitting } = useFormStatus();\n return (\n <Button type=\"submit\" variant={variant} loading={submitting} {...props}>\n {children}\n </Button>\n );\n}\n\nexport type FormErrorProps = {\n /** A headline above the message (\"We could not create your account\"), passed translated. */\n title?: string;\n /** Classes merged on the alert. */\n className?: string;\n};\n\n/** The whole form's error — a refusal of the server that belongs to no field (a conflict, too many tries, no network). */\nexport function FormError({ title, className }: FormErrorProps) {\n const ctx = useFormContext();\n if (!ctx.error) return null;\n return (\n <Alert tone=\"danger\" title={title} className={className}>\n {formMessage(ctx.error, ctx.i18n)}\n </Alert>\n );\n}\n\nexport type TextFieldProps = Base & {\n /** `text` (default), `email`, `password`, `url`, `tel`, `search`: the right keyboard on a phone. */\n type?: \"text\" | \"email\" | \"password\" | \"url\" | \"tel\" | \"search\";\n /** The browser's autofill (`email`, `username`, `new-password`, `name`). */\n autoComplete?: string;\n /** An example of a value, passed translated — never the label. */\n placeholder?: string;\n /** The keyboard on a phone (`numeric`, `decimal`). */\n inputMode?: React.HTMLAttributes<HTMLInputElement>[\"inputMode\"];\n /** The most characters. */\n maxLength?: number;\n /** Cleans what is typed before it is stored (`(v) => v.toLowerCase().replace(/\\s+/g, \"_\")`). */\n transform?: (raw: string) => string;\n /** Checks the value on the server as it is typed (availability): an error key, or nothing when it is fine. */\n validateAsync?: FieldCheck<string>;\n /** The wait, in ms, between the last key and `validateAsync`. Default 350. */\n asyncDebounceMs?: number;\n /** The words once `validateAsync` accepted the value (\"@eric is free\"), passed translated. */\n availableHint?: string;\n /** The name of the wait while it checks (\"Checking\"), passed translated. */\n checkingLabel?: string;\n /** Something before the text (an `@`, an icon). */\n start?: React.ReactNode;\n};\n\n/** A text field of the form: label, input, hint or error, an optional check on the server. */\nexport function TextField({ name, label, hint, disabled, className, type = \"text\", transform, validateAsync, asyncDebounceMs, availableHint, checkingLabel = \"Checking\", start, ...input }: TextFieldProps) {\n const f = useKrizakaField<string>(name, { validateAsync, asyncDebounceMs });\n const end = f.validating ? <Spinner size=\"sm\" label={checkingLabel} /> : f.available ? <Check /> : null;\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <span className=\"relative flex items-center\">\n {start ? <span className=\"pointer-events-none absolute left-3 text-fg-muted\">{start}</span> : null}\n <Input\n id={f.id}\n name={name}\n type={type}\n value={f.value ?? \"\"}\n disabled={disabled}\n invalid={Boolean(f.error)}\n aria-describedby={ids(f, hint ?? availableHint)}\n onChange={(event) => f.setValue(transform ? transform(event.target.value) : event.target.value)}\n onBlur={f.onBlur}\n className={[start ? \"pl-9\" : \"\", end ? \"pr-10\" : \"\"].join(\" \").trim() || undefined}\n {...input}\n />\n {end ? <span className=\"absolute right-3 flex\">{end}</span> : null}\n </span>\n <Caption field={f} hint={hint} ok={availableHint} />\n </Field.Root>\n );\n}\n\nexport type TextAreaProps = Base & {\n /** An example of a value, passed translated. */\n placeholder?: string;\n /** The visible lines. Default 4. */\n rows?: number;\n /** The most characters. */\n maxLength?: number;\n};\n\n/** A longer text of the form (a bio, a description, a report). */\nexport function TextArea({ name, label, hint, disabled, className, rows = 4, ...input }: TextAreaProps) {\n const f = useKrizakaField<string>(name);\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <Textarea id={f.id} name={name} rows={rows} value={f.value ?? \"\"} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onChange={(e) => f.setValue(e.target.value)} onBlur={f.onBlur} {...input} />\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type CheckboxProps = Omit<Base, \"label\"> & {\n /** The words next to the box, clickable with it — text, or a sentence with links (terms, privacy). */\n label: React.ReactNode;\n};\n\n/** A box of the form (`boolean`): terms to accept, an option. */\nexport function Checkbox({ name, label, hint, disabled, className }: CheckboxProps) {\n const f = useKrizakaField<boolean>(name);\n return (\n <div className={className ?? \"flex flex-col gap-1.5\"}>\n <CheckboxControl id={f.id} name={name} checked={f.value === true} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onCheckedChange={(c) => f.setValue(c === true)} onBlur={f.onBlur}>\n {label}\n </CheckboxControl>\n <Caption field={f} hint={hint} />\n </div>\n );\n}\n\n/** An on/off setting of the form (`boolean`): the label and its hint beside the switch. */\nexport function Switch({ name, label, hint, disabled, className }: Base) {\n const f = useKrizakaField<boolean>(name);\n return (\n <div className={className ?? \"flex items-start justify-between gap-4\"}>\n <div className=\"flex min-w-0 flex-col gap-0.5\">\n <Field.Label htmlFor={f.id} className=\"text-sm font-medium text-fg\">\n {label}\n </Field.Label>\n <Caption field={f} hint={hint} />\n </div>\n <SwitchControl id={f.id} name={name} checked={f.value === true} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onCheckedChange={(c) => f.setValue(c)} onBlur={f.onBlur} />\n </div>\n );\n}\n\n/** A choice of the form: the value stored, its words (passed translated), a line under them. */\nexport type FormOption = { value: string; label: string; description?: string; disabled?: boolean };\n\nexport type RadioGroupProps = Base & {\n /** The choices, all visible (two to five). */\n options: readonly FormOption[];\n /**\n * `list` (a dot and its words, default), `cards` (a whole card is the radio: an amount, a plan, an audience),\n * `buttons` (tactile keys that press in: a size, a tip; `description` is the key's second line) or `segmented`\n * (two to four short choices on one line).\n */\n variant?: \"list\" | \"cards\" | \"buttons\" | \"segmented\";\n /** `vertical` (default) or `horizontal`. */\n orientation?: \"vertical\" | \"horizontal\";\n};\n\n/** One choice among a few, all visible. */\nexport function RadioGroup({ name, label, hint, disabled, className, options, variant = \"list\", orientation = \"vertical\" }: RadioGroupProps) {\n const f = useKrizakaField<string>(name);\n return (\n <Field.Root className={className} role=\"group\" aria-labelledby={`${f.id}-label`}>\n <span id={`${f.id}-label`} className=\"text-xs font-semibold text-fg-secondary\">\n {label}\n </span>\n <RadioGroupControl.Root\n aria-labelledby={`${f.id}-label`}\n value={f.value ?? \"\"}\n onValueChange={(v) => f.setValue(v)}\n onBlur={f.onBlur}\n orientation={orientation}\n disabled={disabled}\n invalid={Boolean(f.error)}\n aria-describedby={ids(f, hint)}\n name={name}\n variant={variant}\n className={variant === \"segmented\" ? \"self-start\" : undefined}\n >\n {options.map((o) =>\n variant === \"cards\" ? (\n <RadioGroupControl.Card key={o.value} value={o.value} disabled={o.disabled}>\n <span className=\"font-semibold\">{o.label}</span>\n {o.description ? <span className=\"text-xs text-fg-secondary\">{o.description}</span> : null}\n </RadioGroupControl.Card>\n ) : variant === \"buttons\" ? (\n <RadioGroupControl.Button key={o.value} value={o.value} disabled={o.disabled} hint={o.description}>\n {o.label}\n </RadioGroupControl.Button>\n ) : variant === \"segmented\" ? (\n <RadioGroupControl.Segment key={o.value} value={o.value} disabled={o.disabled}>\n {o.label}\n </RadioGroupControl.Segment>\n ) : (\n <RadioGroupControl.Item key={o.value} value={o.value} disabled={o.disabled}>\n {o.label}\n {o.description ? <span className=\"block text-xs text-fg-secondary\">{o.description}</span> : null}\n </RadioGroupControl.Item>\n ),\n )}\n </RadioGroupControl.Root>\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type SelectProps = Base & {\n /** The choices, in the platform's own menu (a country, a category). */\n options: readonly FormOption[];\n /** The first line while nothing is chosen (\"Choose a category\"), passed translated. */\n placeholder?: string;\n};\n\n/** One choice among many, in the platform's menu (`<select>`: accessible and right on phones). */\nexport function Select({ name, label, hint, disabled, className, options, placeholder }: SelectProps) {\n const f = useKrizakaField<string>(name);\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <SelectControl id={f.id} name={name} value={f.value ?? \"\"} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onChange={(e) => f.setValue(e.target.value)} onBlur={f.onBlur}>\n {placeholder !== undefined ? (\n <option value=\"\" disabled>\n {placeholder}\n </option>\n ) : null}\n {options.map((o) => (\n <option key={o.value} value={o.value} disabled={o.disabled}>\n {o.label}\n </option>\n ))}\n </SelectControl>\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type ComboboxProps = Base & {\n /** The options, filtered as the person types. */\n options?: readonly ComboboxOption[];\n /** Fetches the options for a query (debounced, aborted by a newer one). */\n onSearch?: (query: string, signal: AbortSignal) => Promise<readonly ComboboxOption[]>;\n /** Several values (`string[]`), shown as chips; one (`string`) by default. */\n multiple?: boolean;\n /** Offers to create the query as a value. */\n creatable?: boolean;\n /** The input's placeholder, passed translated. */\n placeholder?: string;\n /** The words of the control, passed translated. */\n labels?: Partial<ComboboxLabels>;\n};\n\n/** A choice among many, typed to filter or fetched: one value (`string`) or several (`string[]`). */\nexport function Combobox({ name, label, hint, disabled, className, options = [], onSearch, multiple, creatable, placeholder, labels }: ComboboxProps) {\n const f = useKrizakaField<string | string[]>(name);\n // The options chosen from a search, by value: their labels once the search has moved on.\n const [seen, setSeen] = React.useState<Record<string, ComboboxOption>>({});\n const option = (value: string) => options.find((o) => o.value === value) ?? seen[value] ?? { value, label: value };\n const remember = (o: ComboboxOption) => setSeen((known) => (known[o.value] === o ? known : { ...known, [o.value]: o }));\n const shared = { id: f.id, label, hint, error: f.error, disabled, placeholder, labels, options, onSearch, creatable, name };\n return (\n <div className={className} onBlur={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur()}>\n {multiple ? (\n <ComboboxControl\n {...shared}\n multiple\n value={((f.value as string[] | undefined) ?? []).map(option)}\n onValueChange={(next) => {\n next.forEach(remember);\n f.setValue(next.map((o) => o.value));\n }}\n />\n ) : (\n <ComboboxControl\n {...shared}\n value={f.value ? option(f.value as string) : null}\n onValueChange={(next) => {\n if (next) remember(next);\n f.setValue(next?.value ?? \"\");\n }}\n />\n )}\n </div>\n );\n}\n\nexport type DateFieldProps = Base & {\n /**\n * `calendar` (default: a date near today — a publication, an appointment), `parts` (day · month · year typed: a\n * memorable date, a birth date) or `wheel` (three wheels bounded by `min` / `max`: a birth date on a phone).\n */\n entry?: \"calendar\" | \"parts\" | \"wheel\";\n /** The earliest date (ISO), for the calendar and the wheels. */\n min?: string;\n /** The latest date (ISO), for the calendar and the wheels (`latestBirthDate(18)` for an age gate). */\n max?: string;\n /** The words of the calendar, or the names of the parts (`day`, `month`, `year`), passed translated. */\n labels?: Partial<DatePickerLabels> & Partial<Record<DatePart, string>>;\n /** `bday` for a date of birth: typed boxes are autofilled; the wheels rest on 1 January 2000 until turned. */\n autoComplete?: \"bday\" | \"off\";\n};\n\n/** A date of the form (`YYYY-MM-DD`, `\"\"` for none): a calendar, day · month · year typed, or wheels. */\nexport function DateField({ name, label, hint, disabled, className, entry = \"calendar\", min, max, labels, autoComplete }: DateFieldProps) {\n const f = useKrizakaField<string>(name);\n const onBlur = (e: React.FocusEvent<HTMLElement>) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur();\n if (entry === \"calendar\")\n return (\n <div className={className} onBlur={onBlur}>\n <DatePicker label={label} hint={hint} error={f.error} disabled={disabled} name={name} locale={f.locale} min={min} max={max} labels={labels} value={f.value || null} onValueChange={(v) => f.setValue(v ?? \"\")} />\n </div>\n );\n if (entry === \"wheel\")\n return (\n <div className={className} onBlur={onBlur}>\n <DateWheel label={label} hint={hint} error={f.error} disabled={disabled} name={name} locale={f.locale} min={min} max={max} labels={labels} defaultView={autoComplete === \"bday\" ? \"2000-01-01\" : undefined} value={f.value || null} onValueChange={(v) => f.setValue(v)} />\n </div>\n );\n return <DatePartsControl label={label} hint={hint} error={f.error} disabled={disabled} name={name} locale={f.locale} labels={labels} autoComplete={autoComplete} className={className} value={f.value ?? \"\"} onValueChange={(v) => f.setValue(v)} onBlur={f.onBlur} />;\n}\n\nexport type TagsProps = Base & Pick<TagInputProps, \"suggestions\" | \"normalize\" | \"max\" | \"separators\" | \"placeholder\" | \"labels\">;\n\n/** Free words of the form as chips (`string[]`): tags, keywords. */\nexport function TagInput({ name, label, hint, disabled, className, ...props }: TagsProps) {\n const f = useKrizakaField<string[]>(name);\n return (\n <div className={className} onBlur={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur()}>\n <TagInputControl label={label} hint={hint} error={f.error} disabled={disabled} name={name} value={f.value ?? []} onValueChange={(tags) => f.setValue(tags)} {...props} />\n </div>\n );\n}\n\nexport type FileUploadProps = Omit<Base, \"hint\"> & {\n /** The title in the zone (\"Drop your video here\"), passed translated. */\n title: string;\n /** The button that opens the file picker, passed translated. */\n browseLabel: string;\n /** What is accepted, in words (\"MP4 or MOV, up to 4 GB\"). */\n hint?: string;\n /** The types accepted (`video/*`, `image/png,.pdf`). */\n accept?: string;\n /** The largest file, in bytes. */\n maxSize?: number;\n /** Several files (`File[]`, up to `maxFiles`); one by default (still a `File[]` of one). */\n multiple?: boolean;\n /** The most files. */\n maxFiles?: number;\n /** The name of a file's remove button (`(name) => \"Remove \" + name`), passed translated. */\n removeLabel: (fileName: string) => string;\n /** The words of a refused file (`(r) => r.file.name + \" is too large\"`). */\n refusalLabel?: React.ComponentProps<typeof Dropzone>[\"refusalLabel\"];\n};\n\n/** Files of the form (`File[]`): a drop zone, then the chosen files, each removable. */\nexport function FileUpload({ name, label, hint, disabled, className, title, browseLabel, accept, maxSize, multiple, maxFiles, removeLabel, refusalLabel }: FileUploadProps) {\n const f = useKrizakaField<File[]>(name);\n const files = f.value ?? [];\n return (\n <div className={className ?? \"flex flex-col gap-2\"} role=\"group\" aria-label={label} onBlur={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur()}>\n <span className=\"text-xs font-semibold text-fg-secondary\">{label}</span>\n <Dropzone\n title={title}\n browseLabel={browseLabel}\n hint={hint}\n accept={accept}\n maxSize={maxSize}\n multiple={multiple}\n maxFiles={maxFiles}\n disabled={disabled}\n refusalLabel={refusalLabel}\n onFiles={(chosen) => f.setValue(multiple ? [...files, ...chosen].slice(0, maxFiles ?? Infinity) : chosen.slice(0, 1))}\n />\n {files.length > 0 ? (\n <ul className=\"flex flex-col gap-1.5\">\n {files.map((file, i) => (\n <li key={`${file.name}-${i}`} className=\"flex items-center justify-between gap-3 rounded-lg border border-border-default bg-surface-1 px-3 py-2 text-sm\">\n <span className=\"min-w-0 truncate text-fg\">{file.name}</span>\n <span className=\"flex shrink-0 items-center gap-2\">\n <span className=\"font-mono text-xs text-fg-secondary\">{formatBytes(file.size, f.locale)}</span>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={() => f.setValue(files.filter((_, j) => j !== i))}>\n {removeLabel(file.name)}\n </Button>\n </span>\n </li>\n ))}\n </ul>\n ) : null}\n {f.error ? <Field.Error id={f.errorId}>{f.error}</Field.Error> : null}\n </div>\n );\n}\n\nexport type MoneyProps = Base & {\n /** The currency (ISO 4217: `USD`, `EUR`, `JPY`): its sign before the amount, its decimals. */\n currency: string;\n /** An example of an amount, passed translated. */\n placeholder?: string;\n};\n\n/** An amount of the form, stored as integer minor units (cents: `1250` = 12.50), typed the locale's way. */\nexport function Money({ name, label, hint, disabled, className, currency, placeholder }: MoneyProps) {\n const f = useKrizakaField<number | null>(name);\n const [text, setText] = React.useState(() => moneyInputText(f.value, currency, f.locale));\n const [editing, setEditing] = React.useState(false);\n const shown = editing ? text : moneyInputText(f.value, currency, f.locale);\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <span className=\"relative flex items-center\">\n <span className=\"pointer-events-none absolute left-3 text-sm text-fg-secondary\" aria-hidden>\n {currencySymbol(currency, f.locale)}\n </span>\n <Input\n id={f.id}\n name={name}\n inputMode=\"decimal\"\n value={shown}\n placeholder={placeholder}\n disabled={disabled}\n invalid={Boolean(f.error)}\n aria-describedby={ids(f, hint)}\n className=\"pl-9 tabular-nums\"\n onFocus={() => {\n setText(moneyInputText(f.value, currency, f.locale));\n setEditing(true);\n }}\n onChange={(e) => {\n setText(e.target.value);\n const units = parseMoney(e.target.value, currency, f.locale);\n f.setValue(units === undefined ? null : units === null ? Number.NaN : units);\n }}\n onBlur={() => {\n setEditing(false);\n f.onBlur();\n }}\n />\n </span>\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type SliderProps = Base & {\n /** The lowest value. Default 0. */\n min?: number;\n /** The highest value. Default 100. */\n max?: number;\n /** The step. Default 1. */\n step?: number;\n /** The value as words (\"15 %\", \"3 min\"), shown and read. */\n formatValue?: (value: number) => string;\n /** For a range (`[number, number]`): each thumb's name, passed translated. */\n thumbLabels?: [string, string];\n /** A graduation per step (`true`) or at the values given. */\n ticks?: boolean | readonly number[];\n /** Words under the track at some values. */\n marks?: readonly SliderMark[];\n};\n\n/** A number (or a range) of the form, chosen by feel: a share, a volume, a price range — the value floats while it is touched. */\nexport function Slider({ name, label, hint, disabled, className, min, max, step, formatValue, thumbLabels, ticks, marks }: SliderProps) {\n const f = useKrizakaField<SliderValue>(name);\n return (\n <div className={className ?? \"flex flex-col gap-1.5\"}>\n <SliderControl label={label} showLabel floatingValue value={f.value} min={min} max={max} step={step} ticks={ticks} marks={marks} disabled={disabled} formatValue={formatValue} thumbLabels={thumbLabels} aria-describedby={ids(f, hint)} onValueChange={(v) => f.setValue(v)} onValueCommit={() => f.onBlur()} />\n <Caption field={f} hint={hint} />\n </div>\n );\n}\n\nconst fields = { TextField, TextArea, Checkbox, Switch, RadioGroup, Select, Combobox, DateField, TagInput, FileUpload, Money, Slider, Field: FormField, FieldArray, Watch, Submit, FormError };\n\n/**\n * A form, defined once: its schema (zod 4) and default values — the same schema the server parses with. In a component,\n * `signUp.useForm({ onSubmit })` gives the form and its fields, typed by the schema: `<form.Form>`, `<form.TextField\n * name=\"email\" …/>`, `<form.Submit>`. Errors are i18n keys (`form.errors.tooShort`), never the engine's English.\n */\nexport const createKrizakaForm = makeCreateKrizakaForm(fields, FormRoot);\n\n/** The form sent by a Server Action: `useFormWithAction(signUp, createAccount)` — `signUp.useFormWithAction(createAccount)`. */\nexport function useFormWithAction<F extends { useFormWithAction: (...args: never[]) => unknown }>(form: F, ...args: Parameters<F[\"useFormWithAction\"]>): ReturnType<F[\"useFormWithAction\"]> {\n return form.useFormWithAction(...args) as ReturnType<F[\"useFormWithAction\"]>;\n}\n"
2099
+ "content": "// Client. The form's fields for the web: thin adapters from a form field (useKrizakaField) to the platform's current\n// primitives — Field + Input, Checkbox, Switch, RadioGroup (dots, cards, tactile keys, segments), Combobox, the date\n// pickers (calendar, typed, wheels), TagInput, Dropzone, Slider. A new look for a primitive changes an adapter here,\n// never a form.\nimport { Alert } from \"@krizaka/ui/alert\";\nimport { Button, type ButtonProps } from \"@krizaka/ui/button\";\nimport { Checkbox as CheckboxControl } from \"@krizaka/ui/checkbox\";\nimport { Combobox as ComboboxControl, type ComboboxLabels, type ComboboxOption } from \"@krizaka/ui/combobox\";\nimport { DateField as DatePartsControl, DatePicker, type DatePickerLabels, DateWheel } from \"@krizaka/ui/date-picker\";\nimport { Field, Input, Select as SelectControl, Textarea } from \"@krizaka/ui/field\";\nimport { Dropzone, formatBytes } from \"@krizaka/ui/file-upload\";\nimport { RadioGroup as RadioGroupControl } from \"@krizaka/ui/radio-group\";\nimport { Slider as SliderControl, type SliderMark, type SliderValue } from \"@krizaka/ui/slider\";\nimport { Spinner } from \"@krizaka/ui/spinner\";\nimport { Switch as SwitchControl } from \"@krizaka/ui/switch\";\nimport { TagInput as TagInputControl, type TagInputProps } from \"@krizaka/ui/tag-input\";\nimport * as React from \"react\";\n\nimport type { DatePart } from \"../date-picker/parts\";\nimport {\n FieldArray,\n type FieldCheck,\n FormContext,\n type FormContextValue,\n FormField,\n type KrizakaField,\n makeCreateKrizakaForm,\n useFormContext,\n useFormStatus,\n useKrizakaField,\n Watch,\n} from \"./core\";\nimport { formMessage } from \"./errors\";\nimport { currencySymbol, moneyInputText, parseMoney } from \"./money\";\n\nexport { FieldArray, FormField, Watch };\nexport type { FieldArrayProps, FormFieldProps, WatchProps } from \"./core\";\n\ntype Base = {\n /** The field's name in the schema: `email`, `address.city`, `links[0].url` (typed by the form). */\n name: string;\n /** The visible label, passed translated (also the control's accessible name). */\n label: string;\n /** A help text under the control, read with it; the error takes its place when there is one. */\n hint?: string;\n /** Not available. */\n disabled?: boolean;\n /** Classes merged on the field's root. */\n className?: string;\n};\n\nconst ids = (f: KrizakaField, hint?: string) => [hint && !f.error ? f.hintId : null, f.error ? f.errorId : null].filter(Boolean).join(\" \") || undefined;\n\nfunction Caption({ field, hint, ok }: { field: KrizakaField; hint?: string; ok?: string }) {\n const suggestion = field.errorDetail?.suggestion;\n if (field.error)\n return (\n <Field.Error id={field.errorId}>\n <span>\n {field.error}\n {suggestion ? (\n <>\n {\" \"}\n <button type=\"button\" className=\"font-semibold text-accent-text underline underline-offset-2\" onClick={() => field.setValue(suggestion.value)}>\n {suggestion.label}\n </button>\n </>\n ) : null}\n </span>\n </Field.Error>\n );\n const text = field.available && ok ? (hint ? `${ok} · ${hint}` : ok) : hint;\n return text ? <Field.Hint id={field.hintId}>{text}</Field.Hint> : null;\n}\n\nconst Check = () => (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4 text-fg-success\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n);\n\nexport type FormProps = Omit<React.ComponentProps<\"form\">, \"onSubmit\" | \"noValidate\"> & {\n /** The fields, the error and the button. */\n children?: React.ReactNode;\n};\n\n/** The `<form>` of a form (`form.Form`): `noValidate` (the schema validates), the first error focused after a refused submit. */\nfunction FormRoot({ value, className, children, ...props }: FormProps & { value: FormContextValue }) {\n const ref = React.useRef<HTMLFormElement>(null);\n return (\n <FormContext.Provider value={value}>\n <form\n ref={ref}\n noValidate\n className={className ?? \"flex flex-col gap-4\"}\n onSubmit={async (event) => {\n event.preventDefault();\n if (!(await value.submit())) requestAnimationFrame(() => ref.current?.querySelector<HTMLElement>('[aria-invalid=\"true\"], [data-invalid] input')?.focus());\n }}\n {...props}\n >\n {children}\n </form>\n </FormContext.Provider>\n );\n}\n\nexport type SubmitProps = Omit<ButtonProps, \"type\" | \"loading\"> & {\n /** The button's words, passed translated (\"Create my account\"). */\n children: React.ReactNode;\n};\n\n/** The submit button: busy while the form is sent (not pressable twice), never disabled for an invalid form. */\nexport function Submit({ variant = \"primary\", children, ...props }: SubmitProps) {\n const { submitting } = useFormStatus();\n return (\n <Button type=\"submit\" variant={variant} loading={submitting} {...props}>\n {children}\n </Button>\n );\n}\n\nexport type FormErrorProps = {\n /** A headline above the message (\"We could not create your account\"), passed translated. */\n title?: string;\n /** Classes merged on the alert. */\n className?: string;\n};\n\n/** The whole form's error — a refusal of the server that belongs to no field (a conflict, too many tries, no network). */\nexport function FormError({ title, className }: FormErrorProps) {\n const ctx = useFormContext();\n if (!ctx.error) return null;\n return (\n <Alert tone=\"danger\" title={title} className={className}>\n {formMessage(ctx.error, ctx.i18n)}\n </Alert>\n );\n}\n\nexport type TextFieldProps = Base & {\n /** `text` (default), `email`, `password`, `url`, `tel`, `search`: the right keyboard on a phone. */\n type?: \"text\" | \"email\" | \"password\" | \"url\" | \"tel\" | \"search\";\n /** The browser's autofill (`email`, `username`, `new-password`, `name`). */\n autoComplete?: string;\n /** An example of a value, passed translated — never the label. */\n placeholder?: string;\n /** The keyboard on a phone (`numeric`, `decimal`). */\n inputMode?: React.HTMLAttributes<HTMLInputElement>[\"inputMode\"];\n /** The most characters. */\n maxLength?: number;\n /** Cleans what is typed before it is stored (`(v) => v.toLowerCase().replace(/\\s+/g, \"_\")`). */\n transform?: (raw: string) => string;\n /** Checks the value on the server as it is typed (availability): an error key, or nothing when it is fine. */\n validateAsync?: FieldCheck<string>;\n /** The wait, in ms, between the last key and `validateAsync`. Default 350. */\n asyncDebounceMs?: number;\n /** The words once `validateAsync` accepted the value (\"@eric is free\"), passed translated. */\n availableHint?: string;\n /** The name of the wait while it checks (\"Checking\"), passed translated. */\n checkingLabel?: string;\n /** Something before the text (an `@`, an icon). */\n start?: React.ReactNode;\n};\n\n/** A text field of the form: label, input, hint or error, an optional check on the server. */\nexport function TextField({ name, label, hint, disabled, className, type = \"text\", transform, validateAsync, asyncDebounceMs, availableHint, checkingLabel = \"Checking\", start, ...input }: TextFieldProps) {\n const f = useKrizakaField<string>(name, { validateAsync, asyncDebounceMs });\n const end = f.validating ? <Spinner size=\"sm\" label={checkingLabel} /> : f.available ? <Check /> : null;\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <span className=\"relative flex items-center\">\n {start ? <span className=\"pointer-events-none absolute left-3 text-fg-muted\">{start}</span> : null}\n <Input\n id={f.id}\n name={name}\n type={type}\n value={f.value ?? \"\"}\n disabled={disabled}\n invalid={Boolean(f.error)}\n aria-describedby={ids(f, hint ?? availableHint)}\n onChange={(event) => f.setValue(transform ? transform(event.target.value) : event.target.value)}\n onBlur={f.onBlur}\n className={[start ? \"pl-9\" : \"\", end ? \"pr-10\" : \"\"].join(\" \").trim() || undefined}\n {...input}\n />\n {end ? <span className=\"absolute right-3 flex\">{end}</span> : null}\n </span>\n <Caption field={f} hint={hint} ok={availableHint} />\n </Field.Root>\n );\n}\n\nexport type TextAreaProps = Base & {\n /** An example of a value, passed translated. */\n placeholder?: string;\n /** The visible lines. Default 4. */\n rows?: number;\n /** The most characters. */\n maxLength?: number;\n};\n\n/** A longer text of the form (a bio, a description, a report). */\nexport function TextArea({ name, label, hint, disabled, className, rows = 4, ...input }: TextAreaProps) {\n const f = useKrizakaField<string>(name);\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <Textarea id={f.id} name={name} rows={rows} value={f.value ?? \"\"} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onChange={(e) => f.setValue(e.target.value)} onBlur={f.onBlur} {...input} />\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type CheckboxProps = Omit<Base, \"label\"> & {\n /** The words next to the box, clickable with it — text, or a sentence with links (terms, privacy). */\n label: React.ReactNode;\n};\n\n/** A box of the form (`boolean`): terms to accept, an option. */\nexport function Checkbox({ name, label, hint, disabled, className }: CheckboxProps) {\n const f = useKrizakaField<boolean>(name);\n return (\n <div className={className ?? \"flex flex-col gap-1.5\"}>\n <CheckboxControl id={f.id} name={name} checked={f.value === true} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onCheckedChange={(c) => f.setValue(c === true)} onBlur={f.onBlur}>\n {label}\n </CheckboxControl>\n <Caption field={f} hint={hint} />\n </div>\n );\n}\n\n/** An on/off setting of the form (`boolean`): the label and its hint beside the switch. */\nexport function Switch({ name, label, hint, disabled, className }: Base) {\n const f = useKrizakaField<boolean>(name);\n return (\n <div className={className ?? \"flex items-start justify-between gap-4\"}>\n <div className=\"flex min-w-0 flex-col gap-0.5\">\n <Field.Label htmlFor={f.id} className=\"text-sm font-medium text-fg\">\n {label}\n </Field.Label>\n <Caption field={f} hint={hint} />\n </div>\n <SwitchControl id={f.id} name={name} checked={f.value === true} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onCheckedChange={(c) => f.setValue(c)} onBlur={f.onBlur} />\n </div>\n );\n}\n\n/** A choice of the form: the value stored, its words (passed translated), a line under them. */\nexport type FormOption = { value: string; label: string; description?: string; disabled?: boolean };\n\nexport type RadioGroupProps = Base & {\n /** The choices, all visible (two to five). */\n options: readonly FormOption[];\n /**\n * `list` (a dot and its words, default), `cards` (a whole card is the radio: an amount, a plan, an audience),\n * `buttons` (tactile keys that press in: a size, a tip; `description` is the key's second line) or `segmented`\n * (two to four short choices on one line).\n */\n variant?: \"list\" | \"cards\" | \"buttons\" | \"segmented\";\n /** `vertical` (default) or `horizontal`. */\n orientation?: \"vertical\" | \"horizontal\";\n};\n\n/** One choice among a few, all visible. */\nexport function RadioGroup({ name, label, hint, disabled, className, options, variant = \"list\", orientation = \"vertical\" }: RadioGroupProps) {\n const f = useKrizakaField<string>(name);\n return (\n <Field.Root className={className} role=\"group\" aria-labelledby={`${f.id}-label`}>\n <span id={`${f.id}-label`} className=\"text-xs font-semibold text-fg-secondary\">\n {label}\n </span>\n <RadioGroupControl.Root\n aria-labelledby={`${f.id}-label`}\n value={f.value ?? \"\"}\n onValueChange={(v) => f.setValue(v)}\n onBlur={f.onBlur}\n orientation={orientation}\n disabled={disabled}\n invalid={Boolean(f.error)}\n aria-describedby={ids(f, hint)}\n name={name}\n variant={variant}\n className={variant === \"segmented\" ? \"self-start\" : undefined}\n >\n {options.map((o) =>\n variant === \"cards\" ? (\n <RadioGroupControl.Card key={o.value} value={o.value} disabled={o.disabled}>\n <span className=\"font-semibold\">{o.label}</span>\n {o.description ? <span className=\"text-xs text-fg-secondary\">{o.description}</span> : null}\n </RadioGroupControl.Card>\n ) : variant === \"buttons\" ? (\n <RadioGroupControl.Button key={o.value} value={o.value} disabled={o.disabled} hint={o.description}>\n {o.label}\n </RadioGroupControl.Button>\n ) : variant === \"segmented\" ? (\n <RadioGroupControl.Segment key={o.value} value={o.value} disabled={o.disabled}>\n {o.label}\n </RadioGroupControl.Segment>\n ) : (\n <RadioGroupControl.Item key={o.value} value={o.value} disabled={o.disabled}>\n {o.label}\n {o.description ? <span className=\"block text-xs text-fg-secondary\">{o.description}</span> : null}\n </RadioGroupControl.Item>\n ),\n )}\n </RadioGroupControl.Root>\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type SelectProps = Base & {\n /** The choices, in the platform's own menu (a country, a category). */\n options: readonly FormOption[];\n /** The first line while nothing is chosen (\"Choose a category\"), passed translated. */\n placeholder?: string;\n};\n\n/** One choice among many, in the platform's menu (`<select>`: accessible and right on phones). */\nexport function Select({ name, label, hint, disabled, className, options, placeholder }: SelectProps) {\n const f = useKrizakaField<string>(name);\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <SelectControl id={f.id} name={name} value={f.value ?? \"\"} disabled={disabled} invalid={Boolean(f.error)} aria-describedby={ids(f, hint)} onChange={(e) => f.setValue(e.target.value)} onBlur={f.onBlur}>\n {placeholder !== undefined ? (\n <option value=\"\" disabled>\n {placeholder}\n </option>\n ) : null}\n {options.map((o) => (\n <option key={o.value} value={o.value} disabled={o.disabled}>\n {o.label}\n </option>\n ))}\n </SelectControl>\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type ComboboxProps = Base & {\n /** The options, filtered as the person types. */\n options?: readonly ComboboxOption[];\n /** Fetches the options for a query (debounced, aborted by a newer one). */\n onSearch?: (query: string, signal: AbortSignal) => Promise<readonly ComboboxOption[]>;\n /** Several values (`string[]`), shown as chips; one (`string`) by default. */\n multiple?: boolean;\n /** Offers to create the query as a value. */\n creatable?: boolean;\n /** The input's placeholder, passed translated. */\n placeholder?: string;\n /** The words of the control, passed translated. */\n labels?: Partial<ComboboxLabels>;\n};\n\n/** A choice among many, typed to filter or fetched: one value (`string`) or several (`string[]`). */\nexport function Combobox({ name, label, hint, disabled, className, options = [], onSearch, multiple, creatable, placeholder, labels }: ComboboxProps) {\n const f = useKrizakaField<string | string[]>(name);\n // The options chosen from a search, by value: their labels once the search has moved on.\n const [seen, setSeen] = React.useState<Record<string, ComboboxOption>>({});\n const option = (value: string) => options.find((o) => o.value === value) ?? seen[value] ?? { value, label: value };\n const remember = (o: ComboboxOption) => setSeen((known) => (known[o.value] === o ? known : { ...known, [o.value]: o }));\n const shared = { id: f.id, label, hint, error: f.error, disabled, placeholder, labels, options, onSearch, creatable, name };\n return (\n <div className={className} onBlur={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur()}>\n {multiple ? (\n <ComboboxControl\n {...shared}\n multiple\n value={((f.value as string[] | undefined) ?? []).map(option)}\n onValueChange={(next) => {\n next.forEach(remember);\n f.setValue(next.map((o) => o.value));\n }}\n />\n ) : (\n <ComboboxControl\n {...shared}\n value={f.value ? option(f.value as string) : null}\n onValueChange={(next) => {\n if (next) remember(next);\n f.setValue(next?.value ?? \"\");\n }}\n />\n )}\n </div>\n );\n}\n\nexport type DateFieldProps = Base & {\n /**\n * `calendar` (default: a date near today — a publication, an appointment), `parts` (day · month · year typed: a\n * memorable date, a birth date) or `wheel` (three wheels bounded by `min` / `max`: a birth date on a phone).\n */\n entry?: \"calendar\" | \"parts\" | \"wheel\";\n /** The earliest date (ISO), for the calendar and the wheels. */\n min?: string;\n /** The latest date (ISO), for the calendar and the wheels (`latestBirthDate(18)` for an age gate). */\n max?: string;\n /** The words of the calendar, or the names of the parts (`day`, `month`, `year`), passed translated. */\n labels?: Partial<DatePickerLabels> & Partial<Record<DatePart, string>>;\n /** `bday` for a date of birth: typed boxes are autofilled; the wheels rest on 1 January 2000 until turned. */\n autoComplete?: \"bday\" | \"off\";\n};\n\n/** A date of the form (`YYYY-MM-DD`, `\"\"` for none): a calendar, day · month · year typed, or wheels. */\nexport function DateField({ name, label, hint, disabled, className, entry = \"calendar\", min, max, labels, autoComplete }: DateFieldProps) {\n const f = useKrizakaField<string>(name);\n const onBlur = (e: React.FocusEvent<HTMLElement>) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur();\n if (entry === \"calendar\")\n return (\n <div className={className} onBlur={onBlur}>\n <DatePicker label={label} hint={hint} error={f.error} disabled={disabled} name={name} locale={f.locale} min={min} max={max} labels={labels} value={f.value || null} onValueChange={(v) => f.setValue(v ?? \"\")} />\n </div>\n );\n if (entry === \"wheel\")\n return (\n <div className={className} onBlur={onBlur}>\n <DateWheel label={label} hint={hint} error={f.error} disabled={disabled} name={name} locale={f.locale} min={min} max={max} labels={labels} defaultView={autoComplete === \"bday\" ? \"2000-01-01\" : undefined} value={f.value || null} onValueChange={(v) => f.setValue(v)} />\n </div>\n );\n return <DatePartsControl label={label} hint={hint} error={f.error} disabled={disabled} name={name} locale={f.locale} labels={labels} autoComplete={autoComplete} className={className} value={f.value ?? \"\"} onValueChange={(v) => f.setValue(v)} onBlur={f.onBlur} />;\n}\n\nexport type TagsProps = Base & Pick<TagInputProps, \"suggestions\" | \"normalize\" | \"max\" | \"separators\" | \"placeholder\" | \"labels\">;\n\n/** Free words of the form as chips (`string[]`): tags, keywords. */\nexport function TagInput({ name, label, hint, disabled, className, ...props }: TagsProps) {\n const f = useKrizakaField<string[]>(name);\n return (\n <div className={className} onBlur={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur()}>\n <TagInputControl label={label} hint={hint} error={f.error} disabled={disabled} name={name} value={f.value ?? []} onValueChange={(tags) => f.setValue(tags)} {...props} />\n </div>\n );\n}\n\nexport type FileUploadProps = Omit<Base, \"hint\"> & {\n /** The title in the zone (\"Drop your video here\"), passed translated. */\n title: string;\n /** The button that opens the file picker, passed translated. */\n browseLabel: string;\n /** What is accepted, in words (\"MP4 or MOV, up to 4 GB\"). */\n hint?: string;\n /** The types accepted (`video/*`, `image/png,.pdf`). */\n accept?: string;\n /** The largest file, in bytes. */\n maxSize?: number;\n /** Several files (`File[]`, up to `maxFiles`); one by default (still a `File[]` of one). */\n multiple?: boolean;\n /** The most files. */\n maxFiles?: number;\n /** The name of a file's remove button (`(name) => \"Remove \" + name`), passed translated. */\n removeLabel: (fileName: string) => string;\n /** The words of a refused file (`(r) => r.file.name + \" is too large\"`). */\n refusalLabel?: React.ComponentProps<typeof Dropzone>[\"refusalLabel\"];\n};\n\n/** Files of the form (`File[]`): a drop zone, then the chosen files, each removable. */\nexport function FileUpload({ name, label, hint, disabled, className, title, browseLabel, accept, maxSize, multiple, maxFiles, removeLabel, refusalLabel }: FileUploadProps) {\n const f = useKrizakaField<File[]>(name);\n const files = f.value ?? [];\n return (\n <div className={className ?? \"flex flex-col gap-2\"} role=\"group\" aria-label={label} onBlur={(e) => !e.currentTarget.contains(e.relatedTarget as Node | null) && f.onBlur()}>\n <span className=\"text-xs font-semibold text-fg-secondary\">{label}</span>\n <Dropzone\n title={title}\n browseLabel={browseLabel}\n hint={hint}\n accept={accept}\n maxSize={maxSize}\n multiple={multiple}\n maxFiles={maxFiles}\n disabled={disabled}\n refusalLabel={refusalLabel}\n onFiles={(chosen) => f.setValue(multiple ? [...files, ...chosen].slice(0, maxFiles ?? Infinity) : chosen.slice(0, 1))}\n />\n {files.length > 0 ? (\n <ul className=\"flex flex-col gap-1.5\">\n {files.map((file, i) => (\n <li key={`${file.name}-${i}`} className=\"flex items-center justify-between gap-3 rounded-lg border border-border-default bg-surface-1 px-3 py-2 text-sm\">\n <span className=\"min-w-0 truncate text-fg\">{file.name}</span>\n <span className=\"flex shrink-0 items-center gap-2\">\n <span className=\"font-mono text-xs text-fg-secondary\">{formatBytes(file.size, f.locale)}</span>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={() => f.setValue(files.filter((_, j) => j !== i))}>\n {removeLabel(file.name)}\n </Button>\n </span>\n </li>\n ))}\n </ul>\n ) : null}\n {f.error ? <Field.Error id={f.errorId}>{f.error}</Field.Error> : null}\n </div>\n );\n}\n\nexport type MoneyProps = Base & {\n /** The currency (ISO 4217: `USD`, `EUR`, `JPY`): its sign before the amount, its decimals. */\n currency: string;\n /** An example of an amount, passed translated. */\n placeholder?: string;\n};\n\n/** An amount of the form, stored as integer minor units (cents: `1250` = 12.50), typed the locale's way. */\nexport function Money({ name, label, hint, disabled, className, currency, placeholder }: MoneyProps) {\n const f = useKrizakaField<number | null>(name);\n const [text, setText] = React.useState(() => moneyInputText(f.value, currency, f.locale));\n const [editing, setEditing] = React.useState(false);\n const shown = editing ? text : moneyInputText(f.value, currency, f.locale);\n return (\n <Field.Root className={className}>\n <Field.Label htmlFor={f.id}>{label}</Field.Label>\n <span className=\"relative flex items-center\">\n <span className=\"pointer-events-none absolute left-3 text-sm text-fg-secondary\" aria-hidden>\n {currencySymbol(currency, f.locale)}\n </span>\n <Input\n id={f.id}\n name={name}\n inputMode=\"decimal\"\n value={shown}\n placeholder={placeholder}\n disabled={disabled}\n invalid={Boolean(f.error)}\n aria-describedby={ids(f, hint)}\n className=\"pl-9 tabular-nums\"\n onFocus={() => {\n setText(moneyInputText(f.value, currency, f.locale));\n setEditing(true);\n }}\n onChange={(e) => {\n setText(e.target.value);\n const units = parseMoney(e.target.value, currency, f.locale);\n f.setValue(units === undefined ? null : units === null ? Number.NaN : units);\n }}\n onBlur={() => {\n setEditing(false);\n f.onBlur();\n }}\n />\n </span>\n <Caption field={f} hint={hint} />\n </Field.Root>\n );\n}\n\nexport type SliderProps = Base & {\n /** The lowest value. Default 0. */\n min?: number;\n /** The highest value. Default 100. */\n max?: number;\n /** The step. Default 1. */\n step?: number;\n /** The value as words (\"15 %\", \"3 min\"), shown and read. */\n formatValue?: (value: number) => string;\n /** For a range (`[number, number]`): each thumb's name, passed translated. */\n thumbLabels?: [string, string];\n /** A graduation per step (`true`) or at the values given. */\n ticks?: boolean | readonly number[];\n /** Words under the track at some values. */\n marks?: readonly SliderMark[];\n};\n\n/** A number (or a range) of the form, chosen by feel: a share, a volume, a price range — the value floats while it is touched. */\nexport function Slider({ name, label, hint, disabled, className, min, max, step, formatValue, thumbLabels, ticks, marks }: SliderProps) {\n const f = useKrizakaField<SliderValue>(name);\n return (\n <div className={className ?? \"flex flex-col gap-1.5\"}>\n <SliderControl label={label} showLabel floatingValue value={f.value} min={min} max={max} step={step} ticks={ticks} marks={marks} disabled={disabled} formatValue={formatValue} thumbLabels={thumbLabels} aria-describedby={ids(f, hint)} onValueChange={(v) => f.setValue(v)} onValueCommit={() => f.onBlur()} />\n <Caption field={f} hint={hint} />\n </div>\n );\n}\n\nconst fields = { TextField, TextArea, Checkbox, Switch, RadioGroup, Select, Combobox, DateField, TagInput, FileUpload, Money, Slider, Field: FormField, FieldArray, Watch, Submit, FormError };\n\n/**\n * A form, defined once: its schema (zod 4) and default values — the same schema the server parses with. In a component,\n * `signUp.useForm({ onSubmit })` gives the form and its fields, typed by the schema: `<form.Form>`, `<form.TextField\n * name=\"email\" …/>`, `<form.Submit>`. Errors are i18n keys (`form.errors.tooShort`), never the engine's English.\n */\nexport const createKrizakaForm = makeCreateKrizakaForm(fields, FormRoot);\n\n/** The form sent by a Server Action: `useFormWithAction(signUp, createAccount)` — `signUp.useFormWithAction(createAccount)`. */\nexport function useFormWithAction<F extends { useFormWithAction: (...args: never[]) => unknown }>(form: F, ...args: Parameters<F[\"useFormWithAction\"]>): ReturnType<F[\"useFormWithAction\"]> {\n return form.useFormWithAction(...args) as ReturnType<F[\"useFormWithAction\"]>;\n}\n"
2100
2100
  },
2101
2101
  {
2102
2102
  "path": "meta.ts",
@@ -3090,7 +3090,7 @@
3090
3090
  },
3091
3091
  {
3092
3092
  "name": "inputMode",
3093
- "type": "\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"",
3093
+ "type": "\"email\" | \"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"numeric\" | \"decimal\"",
3094
3094
  "default": null,
3095
3095
  "description": "The keyboard on a phone (`numeric`, `decimal`).",
3096
3096
  "required": false
@@ -3125,7 +3125,7 @@
3125
3125
  },
3126
3126
  {
3127
3127
  "name": "type",
3128
- "type": "\"search\" | \"text\" | \"tel\" | \"url\" | \"email\" | \"password\"",
3128
+ "type": "\"email\" | \"search\" | \"text\" | \"tel\" | \"url\" | \"password\"",
3129
3129
  "default": "text",
3130
3130
  "description": "`text` (default), `email`, `password`, `url`, `tel`, `search`: the right keyboard on a phone.",
3131
3131
  "required": false
@@ -98,7 +98,7 @@
98
98
  "files": [
99
99
  {
100
100
  "path": "glossary-term/glossary-term.tsx",
101
- "content": "// Client (Radix Tooltip): an inline term whose definition is available on keyboard focus as well as hover.\nimport type * as React from \"react\";\n\nimport { Tooltip } from \"../tooltip\";\n\nexport interface GlossaryTermProps {\n /** The word in the host's glossary. */\n term: string;\n /** The host's definition. */\n definition: React.ReactNode;\n}\n\n/** An underlined glossary word with a keyboard- and screen-reader-accessible definition tooltip. */\nexport function GlossaryTerm({ term, definition }: GlossaryTermProps) {\n return (\n <Tooltip content={definition}>\n <dfn tabIndex={0} className=\"kz-glossary-term\">{term}</dfn>\n </Tooltip>\n );\n}\n"
101
+ "content": "// Client (Radix Tooltip): an inline term whose definition is available on keyboard focus as well as hover.\nimport type * as React from \"react\";\n\nimport { Tooltip } from \"../tooltip\";\n\nexport interface GlossaryTermProps {\n /** The word in the host's glossary. */\n term: string;\n /** The host's definition. */\n definition: React.ReactNode;\n}\n\n/** An underlined glossary word with a keyboard- and screen-reader-accessible definition tooltip. */\nexport function GlossaryTerm({ term, definition }: Readonly<GlossaryTermProps>) {\n return (\n <Tooltip content={definition}>\n <dfn tabIndex={0} className=\"kz-glossary-term\">{term}</dfn>\n </Tooltip>\n );\n}\n"
102
102
  },
103
103
  {
104
104
  "path": "glossary-term/index.ts",
@@ -93,7 +93,7 @@
93
93
  "files": [
94
94
  {
95
95
  "path": "glossary/glossary.tsx",
96
- "content": "// Server-safe. The full list from the host's glossary catalogue.\nimport * as React from \"react\";\n\nexport interface GlossaryEntry {\n /** A stable key supplied by the host. */\n id: string;\n /** The term in the host's glossary. */\n term: React.ReactNode;\n /** The host's definition. */\n definition: React.ReactNode;\n}\n\nexport interface GlossaryProps extends Omit<React.ComponentProps<\"section\">, \"children\" | \"title\"> {\n /** The section's visible heading. */\n title: React.ReactNode;\n /** The terms and definitions from the host's catalogue, in the desired reading order. */\n terms: readonly GlossaryEntry[];\n}\n\n/** A page or panel listing the terms and definitions from the host's glossary catalogue. */\nexport function Glossary({ title, terms, className, ...props }: GlossaryProps) {\n const id = React.useId();\n return (\n <section aria-labelledby={`${id}-title`} className={[\"kz-glossary\", className].filter(Boolean).join(\" \")} {...props}>\n <h2 id={`${id}-title`} className=\"kz-glossary-title\">{title}</h2>\n <dl className=\"kz-glossary-list\">\n {terms.map(({ id: termId, term, definition }) => (\n <div className=\"kz-glossary-entry\" key={termId}>\n <dt>{term}</dt>\n <dd>{definition}</dd>\n </div>\n ))}\n </dl>\n </section>\n );\n}\n"
96
+ "content": "// Server-safe. The full list from the host's glossary catalogue.\nimport * as React from \"react\";\n\nexport interface GlossaryEntry {\n /** A stable key supplied by the host. */\n id: string;\n /** The term in the host's glossary. */\n term: React.ReactNode;\n /** The host's definition. */\n definition: React.ReactNode;\n}\n\nexport interface GlossaryProps extends Omit<React.ComponentProps<\"section\">, \"children\" | \"title\"> {\n /** The section's visible heading. */\n title: React.ReactNode;\n /** The terms and definitions from the host's catalogue, in the desired reading order. */\n terms: readonly GlossaryEntry[];\n}\n\n/** A page or panel listing the terms and definitions from the host's glossary catalogue. */\nexport function Glossary({ title, terms, className, ...props }: Readonly<GlossaryProps>) {\n const id = React.useId();\n return (\n <section aria-labelledby={`${id}-title`} className={[\"kz-glossary\", className].filter(Boolean).join(\" \")} {...props}>\n <h2 id={`${id}-title`} className=\"kz-glossary-title\">{title}</h2>\n <dl className=\"kz-glossary-list\">\n {terms.map(({ id: termId, term, definition }) => (\n <div className=\"kz-glossary-entry\" key={termId}>\n <dt>{term}</dt>\n <dd>{definition}</dd>\n </div>\n ))}\n </dl>\n </section>\n );\n}\n"
97
97
  },
98
98
  {
99
99
  "path": "glossary/index.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/ui",
3
- "version": "4.4.0",
3
+ "version": "4.4.1",
4
4
  "templatePurposes": {
5
5
  "convince": {
6
6
  "title": "Convince",
@@ -1013,7 +1013,7 @@
1013
1013
  "native": 0
1014
1014
  },
1015
1015
  "dependencies": [
1016
- "@krizaka/tokens@^4.4.0"
1016
+ "@krizaka/tokens@^4.4.1"
1017
1017
  ],
1018
1018
  "registryDependencies": [
1019
1019
  "account-menu",
@@ -4017,7 +4017,7 @@
4017
4017
  "native": 2
4018
4018
  },
4019
4019
  "dependencies": [
4020
- "@krizaka/tokens@^4.4.0",
4020
+ "@krizaka/tokens@^4.4.1",
4021
4021
  "@protomaps/basemaps@5.7.2",
4022
4022
  "tailwind-variants@^3.3.1"
4023
4023
  ],
@@ -4430,7 +4430,7 @@
4430
4430
  "native": 0
4431
4431
  },
4432
4432
  "dependencies": [
4433
- "@krizaka/tokens@^4.4.0",
4433
+ "@krizaka/tokens@^4.4.1",
4434
4434
  "radix-ui@^1.8.1",
4435
4435
  "tailwind-variants@^3.3.1"
4436
4436
  ],
@@ -5298,7 +5298,7 @@
5298
5298
  "native": 0
5299
5299
  },
5300
5300
  "dependencies": [
5301
- "@krizaka/tokens@^4.4.0",
5301
+ "@krizaka/tokens@^4.4.1",
5302
5302
  "radix-ui@^1.8.1",
5303
5303
  "tailwind-variants@^3.3.1"
5304
5304
  ],
@@ -5745,7 +5745,7 @@
5745
5745
  "native": 0
5746
5746
  },
5747
5747
  "dependencies": [
5748
- "@krizaka/tokens@^4.4.0",
5748
+ "@krizaka/tokens@^4.4.1",
5749
5749
  "zod@^4.6.7"
5750
5750
  ],
5751
5751
  "registryDependencies": [
@@ -5966,7 +5966,7 @@
5966
5966
  },
5967
5967
  "dependencies": [
5968
5968
  "@krizaka/icons@^0.10.0",
5969
- "@krizaka/tokens@^4.4.0",
5969
+ "@krizaka/tokens@^4.4.1",
5970
5970
  "radix-ui@^1.8.1",
5971
5971
  "tailwind-variants@^3.3.1"
5972
5972
  ],
@@ -404,7 +404,7 @@
404
404
  },
405
405
  {
406
406
  "path": "kind-config-editor/kind-config-editor.tsx",
407
- "content": "// Client (state, drag). The admin's editors of a kind's vocabulary (krizaka-ts#89, ADR-003 of krizaka-ts: « admin configures\n// everything »): the tag set (the presets of a variant, who writes, may people add their own, the most) and the status set\n// (the states in their order, each in French and English, its tone, final; the initial state; the moves from × to with the\n// roles, a confirmation and the reasons). Each takes the descriptor and gives it back (`value` / `onChange`) and never holds the\n// save logic: the product posts it, with the `version` it read. `problems` (from `kindConfigProblems`, the server's own rules)\n// are shown in place. What the contract forbids is kept by construction (model.ts): a final state has no way out, the initial\n// state is never final, a move goes to another state. Reorder: drag the handle, or the buttons, or Alt + ↑ ↓ in a name.\nimport type { Marker, StatusSet, StatusTone } from \"@krizaka/organize/contract\";\nimport * as React from \"react\";\n\nimport { Button } from \"../button\";\nimport { Chip, MarkerPicker, TagMarker } from \"../chip\";\nimport { cn } from \"../cn\";\nimport { Input, Select } from \"../field\";\nimport { SettingsRow } from \"../settings-layout\";\nimport { Switch } from \"../switch\";\nimport { type EditorRole, STATUS_TONES, type StatusSetEditorLabels, statusSetEditorLabels, type TagSetEditorLabels, tagSetEditorLabels } from \"./labels\";\nimport {\n addPreset,\n addReason,\n addState,\n clampMax,\n duplicatePresetNames,\n type Lang,\n movePreset,\n moveState,\n recolorPreset,\n removePreset,\n removeState,\n renamePreset,\n setFinal,\n setInitial,\n setStateLabel,\n setStateTone,\n setTransitionConfirm,\n setTransitionReasons,\n setTransitionRoles,\n type TagSetValue,\n transitionOf,\n} from \"./model\";\n\nexport type { EditorRole, Lang, StatusSetEditorLabels, TagSetEditorLabels, TagSetValue };\nexport { statusSetEditorLabels, tagSetEditorLabels };\n\n\n// --- shared ----------------------------------------------------------------------------------------------------------------\n\n/** The problems the server's rules found, shown where the admin is working: a polite alert above the list. */\nfunction Problems({ title, problems }: { title: string; problems: readonly string[] | undefined }) {\n if (!problems || problems.length === 0) return null;\n return (\n <div role=\"alert\" className=\"flex flex-col gap-1 rounded-lg border border-danger/40 bg-danger/10 px-3 py-2.5\">\n <p className=\"m-0 text-xs font-semibold text-fg-danger\">{title}</p>\n <ul className=\"m-0 flex list-disc flex-col gap-0.5 pl-5 text-xs text-fg\">\n {problems.map((problem) => (\n <li key={problem}>{problem}</li>\n ))}\n </ul>\n </div>\n );\n}\n\n/** Drag a row by its handle, or move it with Alt + ↑ ↓ from a field: one pair of helpers for both lists. */\nfunction useReorder(onMove: (from: number, to: number) => void) {\n const dragging = React.useRef<number | null>(null);\n return {\n row: (index: number) => ({\n onDragOver: (event: React.DragEvent) => {\n if (dragging.current !== null) event.preventDefault();\n },\n onDrop: (event: React.DragEvent) => {\n event.preventDefault();\n if (dragging.current !== null) onMove(dragging.current, index);\n dragging.current = null;\n },\n }),\n handle: (index: number) => ({\n draggable: true,\n onDragStart: (event: React.DragEvent) => {\n dragging.current = index;\n event.dataTransfer.effectAllowed = \"move\";\n event.dataTransfer.setData(\"text/plain\", String(index));\n },\n onDragEnd: () => {\n dragging.current = null;\n },\n }),\n keys: (index: number, last: number) => (event: React.KeyboardEvent) => {\n if (!event.altKey || (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\")) return;\n event.preventDefault();\n const to = event.key === \"ArrowUp\" ? index - 1 : index + 1;\n if (to < 0 || to > last) return;\n onMove(index, to);\n // The row has moved: its field is a new element, keep the focus on it for the next press.\n const field = event.currentTarget as HTMLElement;\n requestAnimationFrame(() => field.closest(\"ol\")?.querySelectorAll<HTMLElement>(`[data-reorder-field=\"${field.dataset.reorderField}\"]`)[to]?.focus());\n },\n };\n}\n\nconst grip = (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"currentColor\" aria-hidden>\n {[7, 12, 17].flatMap((y) => [9, 15].map((x) => <circle key={`${x}-${y}`} cx={x} cy={y} r=\"1.4\" />))}\n </svg>\n);\nconst arrow = (up: boolean) => (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={up ? \"m6 15 6-6 6 6\" : \"m6 9 6 6 6-6\"} />\n </svg>\n);\nconst IconButton = ({ label, className, ...props }: React.ComponentProps<\"button\"> & { label: string }) => (\n <button\n type=\"button\"\n aria-label={label}\n title={label}\n className={cn(\n \"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-fg-secondary transition-colors hover:bg-surface-3 hover:text-fg\",\n \"focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-30\",\n className,\n )}\n {...props}\n />\n);\nconst Cross = () => (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" aria-hidden>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n);\n\n// --- the tag set -----------------------------------------------------------------------------------------------------------\n\nexport type TagSetEditorProps = {\n /** The `tags` of the kind's configuration (`KindConfig.tags`). */\n value: TagSetValue;\n /** Called with the whole set after every change. */\n onChange: (value: TagSetValue) => void;\n /** The variant whose presets are edited (a trade, or `default`). */\n variant: string;\n /** The roles of the product that can write tags. */\n roles: readonly EditorRole[];\n /** What `kindConfigProblems` found (the server's own rules), shown above the list. */\n problems?: readonly string[];\n /** The words, passed translated (English by default). */\n labels?: Partial<TagSetEditorLabels>;\n /** Not available. */\n disabled?: boolean;\n /** Classes merged on the root. */\n className?: string;\n};\n\n/** The admin's tag set: the presets of a variant (name, colour, order), who writes, whether people add their own, the most. */\nexport function TagSetEditor({ value, onChange, variant, roles, problems, labels: given, disabled, className }: TagSetEditorProps) {\n const labels: TagSetEditorLabels = { ...tagSetEditorLabels, ...given, markerNames: { ...tagSetEditorLabels.markerNames, ...given?.markerNames } };\n const presets = value.presets[variant] ?? [];\n const twins = duplicatePresetNames(presets);\n const [draft, setDraft] = React.useState(\"\");\n const [draftMarker, setDraftMarker] = React.useState<Marker>(\"blue\");\n const reorder = useReorder((from, to) => onChange(movePreset(value, variant, from, to)));\n const id = React.useId();\n const add = () => {\n const next = addPreset(value, variant, draft, draftMarker);\n if (next === value) return;\n onChange(next);\n setDraft(\"\");\n };\n return (\n <div className={cn(\"flex flex-col gap-4\", className)}>\n <Problems title={labels.problems} problems={problems} />\n <section aria-labelledby={`${id}-presets`} className=\"flex flex-col gap-2\">\n <h3 id={`${id}-presets`} className=\"m-0 text-sm font-semibold text-fg\">\n {labels.presets}\n </h3>\n {presets.length === 0 ? (\n <p className=\"m-0 text-sm text-fg-secondary\">{labels.empty}</p>\n ) : (\n <ol className=\"m-0 flex list-none flex-col gap-2 p-0\">\n {presets.map((preset, index) => {\n const shown = preset.name || String(index + 1);\n const twin = twins.has(index);\n return (\n <li key={index} {...reorder.row(index)} className=\"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-border-default bg-surface-1 px-2 py-1.5\">\n <span {...reorder.handle(index)} aria-hidden title={labels.drag(shown)} className=\"inline-flex h-9 w-6 cursor-grab items-center justify-center text-fg-muted active:cursor-grabbing max-md:hidden\">\n {grip}\n </span>\n <TagMarker marker={preset.marker} />\n <div className=\"flex min-w-40 flex-1 flex-col gap-1\">\n <Input\n aria-label={labels.name(index + 1)}\n data-reorder-field=\"name\"\n value={preset.name}\n disabled={disabled}\n invalid={twin || !preset.name.trim()}\n aria-describedby={twin ? `${id}-dup-${index}` : undefined}\n onChange={(event) => onChange(renamePreset(value, variant, index, event.target.value))}\n onBlur={(event) => event.target.value !== event.target.value.replace(/\\s+/g, \" \").trim() && onChange(renamePreset(value, variant, index, event.target.value.replace(/\\s+/g, \" \").trim()))}\n onKeyDown={reorder.keys(index, presets.length - 1)}\n className=\"h-9\"\n />\n {twin ? (\n <span id={`${id}-dup-${index}`} className=\"text-xs text-fg-danger\">\n {labels.duplicate}\n </span>\n ) : null}\n </div>\n <MarkerPicker label={labels.marker(shown)} names={labels.markerNames} value={preset.marker} disabled={disabled} onValueChange={(marker) => onChange(recolorPreset(value, variant, index, marker))} />\n <IconButton label={labels.moveUp(shown)} disabled={disabled || index === 0} onClick={() => onChange(movePreset(value, variant, index, index - 1))}>\n {arrow(true)}\n </IconButton>\n <IconButton label={labels.moveDown(shown)} disabled={disabled || index === presets.length - 1} onClick={() => onChange(movePreset(value, variant, index, index + 1))}>\n {arrow(false)}\n </IconButton>\n <IconButton label={labels.remove(shown)} disabled={disabled} onClick={() => onChange(removePreset(value, variant, index))}>\n <Cross />\n </IconButton>\n </li>\n );\n })}\n </ol>\n )}\n <div className=\"flex flex-wrap items-center gap-2\">\n <Input\n aria-label={labels.add}\n value={draft}\n maxLength={80}\n disabled={disabled}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n add();\n }\n }}\n placeholder={labels.add}\n className=\"h-9 min-w-40 flex-1\"\n />\n <MarkerPicker label={labels.marker(draft.trim() || labels.add)} names={labels.markerNames} value={draftMarker} disabled={disabled} onValueChange={setDraftMarker} />\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={disabled || !draft.trim()} onClick={add}>\n {labels.addButton}\n </Button>\n </div>\n </section>\n <div className=\"flex flex-col\">\n <SettingsRow label={labels.writers} description={labels.writersHint}>\n <Chip.Group type=\"multiple\" size=\"sm\" label={labels.writers} value={value.writers} disabled={disabled} onValueChange={(writers) => onChange({ ...value, writers })}>\n {roles.map((role) => (\n <Chip key={role.key} value={role.key}>\n {role.label}\n </Chip>\n ))}\n </Chip.Group>\n </SettingsRow>\n <SettingsRow label={labels.userTags} description={labels.userTagsHint}>\n <Switch label={labels.userTags} checked={value.userTags} disabled={disabled} onCheckedChange={(userTags) => onChange({ ...value, userTags })} />\n </SettingsRow>\n <SettingsRow label={labels.max} description={labels.maxHint} htmlFor={`${id}-max`}>\n <Input\n id={`${id}-max`}\n type=\"number\"\n inputMode=\"numeric\"\n min={1}\n max={200}\n value={value.max}\n disabled={disabled}\n invalid={!Number.isInteger(value.max) || value.max < 1 || value.max > 200}\n onChange={(event) => onChange({ ...value, max: event.target.value === \"\" ? 0 : Number(event.target.value) })}\n onBlur={() => onChange({ ...value, max: clampMax(value.max) })}\n className=\"h-9 w-24\"\n />\n </SettingsRow>\n </div>\n </div>\n );\n}\n\n// --- the status set --------------------------------------------------------------------------------------------------------\n\nexport type StatusSetEditorProps = {\n /** The kind's status set (`KindConfig.status`). */\n value: StatusSet;\n /** Called with the whole set after every change. */\n onChange: (value: StatusSet) => void;\n /** The roles of the product that can make a move. */\n roles: readonly EditorRole[];\n /** The language the states are named in elsewhere in the editor (the moves' names). */\n locale?: Lang;\n /** What `kindConfigProblems` found (the server's own rules), shown above the list. */\n problems?: readonly string[];\n /** The words, passed translated (English by default). */\n labels?: Partial<StatusSetEditorLabels>;\n /** Not available. */\n disabled?: boolean;\n /** Classes merged on the root. */\n className?: string;\n};\n\n/** The admin's status set: the states in their order (FR and EN, tone, final), the initial state, and the moves from × to. */\nexport function StatusSetEditor({ value, onChange, roles, locale = \"en\", problems, labels: given, disabled, className }: StatusSetEditorProps) {\n const labels: StatusSetEditorLabels = { ...statusSetEditorLabels, ...given };\n const [chosen, setChosen] = React.useState<{ from: string; to: string } | null>(null);\n const reorder = useReorder((from, to) => onChange(moveState(value, from, to)));\n const id = React.useId();\n const nameOf = (key: string) => value.states.find((s) => s.key === key)?.label[locale] || key;\n const roleLabel = (key: string) => roles.find((r) => r.key === key)?.label ?? key;\n const open = chosen && value.states.some((x) => x.key === chosen.from) && value.states.some((x) => x.key === chosen.to) ? chosen : null;\n const detail = open ? transitionOf(value, open.from, open.to) : undefined;\n\n if (value.mode === \"derived\") {\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n <Problems title={labels.problems} problems={problems} />\n <p className=\"m-0 text-sm text-fg-secondary\">{labels.derived}</p>\n <ol aria-label={labels.states} className=\"m-0 flex list-none flex-wrap gap-2 p-0\">\n {value.states.map((state) => (\n <li key={state.key} className=\"inline-flex items-center gap-1.5 rounded-sm bg-surface-3 px-2 py-0.5 text-[11px] font-semibold text-fg-secondary\" data-tone={state.tone}>\n <span aria-hidden className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n {state.label[locale]}\n </li>\n ))}\n </ol>\n </div>\n );\n }\n\n return (\n <div className={cn(\"flex flex-col gap-5\", className)}>\n <Problems title={labels.problems} problems={problems} />\n <section aria-labelledby={`${id}-states`} className=\"flex flex-col gap-2\">\n <h3 id={`${id}-states`} className=\"m-0 text-sm font-semibold text-fg\">\n {labels.states}\n </h3>\n <ol className=\"m-0 flex list-none flex-col gap-2 p-0\">\n {value.states.map((state, index) => {\n const n = index + 1;\n const isInitial = value.initial === state.key;\n const name = state.label[locale] || String(n);\n return (\n <li key={state.key} {...reorder.row(index)} data-state-key={state.key} className=\"flex flex-wrap items-start gap-x-3 gap-y-2 rounded-lg border border-border-default bg-surface-1 p-2.5\">\n <span {...reorder.handle(index)} aria-hidden title={labels.drag(name)} className=\"mt-1.5 inline-flex h-9 w-6 cursor-grab items-center justify-center text-fg-muted active:cursor-grabbing max-md:hidden\">\n {grip}\n </span>\n {([\"fr\", \"en\"] as const).map((lang) => (\n <Input\n key={lang}\n aria-label={labels.stateLabel(labels.languages[lang], n)}\n data-reorder-field={lang}\n lang={lang}\n value={state.label[lang]}\n maxLength={40}\n disabled={disabled}\n invalid={!state.label[lang].trim()}\n onChange={(event) => onChange(setStateLabel(value, state.key, lang, event.target.value))}\n onKeyDown={reorder.keys(index, value.states.length - 1)}\n className=\"h-9 min-w-36 flex-1\"\n />\n ))}\n <Select aria-label={labels.tone(n)} value={state.tone} disabled={disabled} onChange={(event) => onChange(setStateTone(value, state.key, event.target.value as StatusTone))} className=\"h-9 w-36\">\n {STATUS_TONES.map((tone) => (\n <option key={tone} value={tone}>\n {labels.tones[tone]}\n </option>\n ))}\n </Select>\n <div className=\"flex items-center gap-1.5 text-xs text-fg-secondary\">\n <Switch size=\"sm\" label={labels.final(n)} checked={Boolean(state.final)} disabled={disabled || isInitial} onCheckedChange={(final) => onChange(setFinal(value, state.key, final))} />\n <span aria-hidden>{isInitial ? labels.initialNotFinal : labels.finalHint}</span>\n </div>\n <label className=\"flex items-center gap-1.5 text-xs text-fg-secondary\">\n <input type=\"radio\" name={`${id}-initial`} aria-label={labels.initial(n)} checked={isInitial} disabled={disabled || Boolean(state.final)} onChange={() => onChange(setInitial(value, state.key))} className=\"h-4 w-4 accent-(--kz-accent)\" />\n <span aria-hidden>{labels.initial(n)}</span>\n </label>\n <code className=\"text-[11px] text-fg-muted\">{state.key}</code>\n <div className=\"ml-auto flex\">\n <IconButton label={labels.moveUp(name)} disabled={disabled || index === 0} onClick={() => onChange(moveState(value, index, index - 1))}>\n {arrow(true)}\n </IconButton>\n <IconButton label={labels.moveDown(name)} disabled={disabled || index === value.states.length - 1} onClick={() => onChange(moveState(value, index, index + 1))}>\n {arrow(false)}\n </IconButton>\n <IconButton label={labels.remove(name)} disabled={disabled || value.states.length <= 2} onClick={() => onChange(removeState(value, state.key))}>\n <Cross />\n </IconButton>\n </div>\n </li>\n );\n })}\n </ol>\n <div>\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={disabled || value.states.length >= 12} onClick={() => onChange(addState(value, labels.newState))}>\n {labels.addState}\n </Button>\n </div>\n </section>\n\n <section aria-labelledby={`${id}-moves`} className=\"flex flex-col gap-3\">\n <div className=\"flex flex-col gap-0.5\">\n <h3 id={`${id}-moves`} className=\"m-0 text-sm font-semibold text-fg\">\n {labels.moves}\n </h3>\n <p className=\"m-0 text-xs text-fg-secondary\">{labels.movesHint}</p>\n </div>\n {value.states.map((from) => (\n <div key={from.key} role=\"group\" aria-label={labels.from(nameOf(from.key))} className=\"flex flex-wrap items-center gap-2\">\n <span className=\"min-w-28 text-xs font-semibold text-fg\">{nameOf(from.key)}</span>\n {from.final ? (\n <span className=\"text-xs text-fg-secondary\">{labels.noWayOut}</span>\n ) : (\n value.states\n .filter((to) => to.key !== from.key)\n .map((to) => {\n const move = transitionOf(value, from.key, to.key);\n const summary = move ? move.roles.map(roleLabel).join(\", \") : labels.none;\n const on = open?.from === from.key && open.to === to.key;\n return (\n <button\n key={to.key}\n type=\"button\"\n aria-pressed={on}\n data-on={move ? \"\" : undefined}\n disabled={disabled}\n onClick={() => setChosen(on ? null : { from: from.key, to: to.key })}\n className={cn(\n \"inline-flex min-h-9 items-center gap-1.5 rounded-sm border px-2.5 py-1 text-xs transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40\",\n move ? \"border-accent bg-accent-soft text-fg\" : \"border-dashed border-border-control text-fg-secondary hover:border-border-strong\",\n on && \"ring-2 ring-ring\",\n )}\n >\n {/* The name is the sentence for a screen reader; the arrow and the short words are what the eye reads. */}\n <span className=\"sr-only\">{labels.move(nameOf(from.key), nameOf(to.key), summary)}</span>\n <span aria-hidden>→ {nameOf(to.key)}</span>\n <span aria-hidden className=\"text-fg\">\n {summary}\n </span>\n </button>\n );\n })\n )}\n </div>\n ))}\n\n {open && chosen ? (\n <div role=\"region\" aria-label={labels.moveDetail(nameOf(open.from), nameOf(open.to))} className=\"flex flex-col gap-3 rounded-lg border border-border-default bg-surface-1 p-3\">\n <h4 className=\"m-0 text-sm font-semibold text-fg\">{labels.moveDetail(nameOf(open.from), nameOf(open.to))}</h4>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-semibold text-fg-secondary\">{labels.roles}</span>\n <Chip.Group\n type=\"multiple\"\n size=\"sm\"\n label={labels.roles}\n value={detail?.roles ? [...detail.roles] : []}\n disabled={disabled}\n onValueChange={(next) => {\n onChange(setTransitionRoles(value, open.from, open.to, next));\n }}\n >\n {roles.map((role) => (\n <Chip key={role.key} value={role.key}>\n {role.label}\n </Chip>\n ))}\n </Chip.Group>\n </div>\n {detail ? (\n <>\n <div className=\"flex items-center gap-2 text-xs text-fg-secondary\">\n <Switch size=\"sm\" label={labels.confirm} checked={Boolean(detail?.confirm)} disabled={disabled} onCheckedChange={(on) => onChange(setTransitionConfirm(value, open.from, open.to, on))} />\n <span aria-hidden>{labels.confirm}</span>\n </div>\n <div className=\"flex flex-col gap-2\">\n <span className=\"text-xs font-semibold text-fg-secondary\">{labels.reasons}</span>\n {(detail?.reasons ?? []).map((reason, at) => (\n <div key={reason.key} className=\"flex flex-wrap items-center gap-2\">\n {([\"fr\", \"en\"] as const).map((lang) => (\n <Input\n key={lang}\n lang={lang}\n aria-label={labels.reasonLabel(labels.languages[lang], at + 1)}\n value={reason.label[lang]}\n maxLength={40}\n disabled={disabled}\n invalid={!reason.label[lang].trim()}\n onChange={(event) =>\n onChange(setTransitionReasons(value, open.from, open.to, (detail?.reasons ?? []).map((r) => (r.key === reason.key ? { ...r, label: { ...r.label, [lang]: event.target.value } } : r))))\n }\n className=\"h-9 min-w-36 flex-1\"\n />\n ))}\n <IconButton label={labels.removeReason(at + 1)} disabled={disabled} onClick={() => onChange(setTransitionReasons(value, open.from, open.to, (detail?.reasons ?? []).filter((r) => r.key !== reason.key)))}>\n <Cross />\n </IconButton>\n </div>\n ))}\n <div>\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={disabled || (detail?.reasons?.length ?? 0) >= 12} onClick={() => onChange(addReason(value, open.from, open.to, { fr: \"\", en: \"\" }))}>\n {labels.addReason}\n </Button>\n </div>\n </div>\n </>\n ) : null}\n </div>\n ) : null}\n </section>\n </div>\n );\n}\n"
407
+ "content": "// Client (state, drag). The admin's editors of a kind's vocabulary (krizaka-ts#89, ADR-003 of krizaka-ts: « admin configures\n// everything »): the tag set (the presets of a variant, who writes, may people add their own, the most) and the status set\n// (the states in their order, each in French and English, its tone, final; the initial state; the moves from × to with the\n// roles, a confirmation and the reasons). Each takes the descriptor and gives it back (`value` / `onChange`) and never holds the\n// save logic: the product posts it, with the `version` it read. `problems` (from `kindConfigProblems`, the server's own rules)\n// are shown in place. What the contract forbids is kept by construction (model.ts): a final state has no way out, the initial\n// state is never final, a move goes to another state. Reorder: drag the handle, or the buttons, or Alt + ↑ ↓ in a name.\nimport type { Marker, StatusSet, StatusTone } from \"@krizaka/organize/contract\";\nimport * as React from \"react\";\n\nimport { Button } from \"../button\";\nimport { Chip, MarkerPicker, TagMarker } from \"../chip\";\nimport { cn } from \"../cn\";\nimport { Input, Select } from \"../field\";\nimport { SettingsRow } from \"../settings-layout\";\nimport { Switch } from \"../switch\";\nimport { type EditorRole, STATUS_TONES, type StatusSetEditorLabels, statusSetEditorLabels, type TagSetEditorLabels, tagSetEditorLabels } from \"./labels\";\nimport {\n addPreset,\n addReason,\n addState,\n clampMax,\n duplicatePresetNames,\n type Lang,\n movePreset,\n moveState,\n recolorPreset,\n removePreset,\n removeState,\n renamePreset,\n setFinal,\n setInitial,\n setStateLabel,\n setStateTone,\n setTransitionConfirm,\n setTransitionReasons,\n setTransitionRoles,\n type TagSetValue,\n transitionOf,\n} from \"./model\";\n\nexport type { EditorRole, Lang, StatusSetEditorLabels, TagSetEditorLabels, TagSetValue };\nexport { statusSetEditorLabels, tagSetEditorLabels };\n\n\n// --- shared ----------------------------------------------------------------------------------------------------------------\n\n/** The problems the server's rules found, shown where the admin is working: a polite alert above the list. */\nfunction Problems({ title, problems }: Readonly<{ title: string; problems: readonly string[] | undefined }>) {\n if (!problems || problems.length === 0) return null;\n return (\n <div role=\"alert\" className=\"flex flex-col gap-1 rounded-lg border border-danger/40 bg-danger/10 px-3 py-2.5\">\n <p className=\"m-0 text-xs font-semibold text-fg-danger\">{title}</p>\n <ul className=\"m-0 flex list-disc flex-col gap-0.5 pl-5 text-xs text-fg\">\n {problems.map((problem) => (\n <li key={problem}>{problem}</li>\n ))}\n </ul>\n </div>\n );\n}\n\n/** Drag a row by its handle, or move it with Alt + ↑ ↓ from a field: one pair of helpers for both lists. */\nfunction useReorder(onMove: (from: number, to: number) => void) {\n const dragging = React.useRef<number | null>(null);\n return {\n row: (index: number) => ({\n onDragOver: (event: React.DragEvent) => {\n if (dragging.current !== null) event.preventDefault();\n },\n onDrop: (event: React.DragEvent) => {\n event.preventDefault();\n if (dragging.current !== null) onMove(dragging.current, index);\n dragging.current = null;\n },\n }),\n handle: (index: number) => ({\n draggable: true,\n onDragStart: (event: React.DragEvent) => {\n dragging.current = index;\n event.dataTransfer.effectAllowed = \"move\";\n event.dataTransfer.setData(\"text/plain\", String(index));\n },\n onDragEnd: () => {\n dragging.current = null;\n },\n }),\n keys: (index: number, last: number) => (event: React.KeyboardEvent) => {\n if (!event.altKey || (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\")) return;\n event.preventDefault();\n const to = event.key === \"ArrowUp\" ? index - 1 : index + 1;\n if (to < 0 || to > last) return;\n onMove(index, to);\n // The row has moved: its field is a new element, keep the focus on it for the next press.\n const field = event.currentTarget as HTMLElement;\n requestAnimationFrame(() => field.closest(\"ol\")?.querySelectorAll<HTMLElement>(`[data-reorder-field=\"${field.dataset.reorderField}\"]`)[to]?.focus());\n },\n };\n}\n\nconst grip = (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"currentColor\" aria-hidden>\n {[7, 12, 17].flatMap((y) => [9, 15].map((x) => <circle key={`${x}-${y}`} cx={x} cy={y} r=\"1.4\" />))}\n </svg>\n);\nconst arrow = (up: boolean) => (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={up ? \"m6 15 6-6 6 6\" : \"m6 9 6 6 6-6\"} />\n </svg>\n);\nconst IconButton = ({ label, className, ...props }: React.ComponentProps<\"button\"> & { label: string }) => (\n <button\n type=\"button\"\n aria-label={label}\n title={label}\n className={cn(\n \"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-fg-secondary transition-colors hover:bg-surface-3 hover:text-fg\",\n \"focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-30\",\n className,\n )}\n {...props}\n />\n);\nconst Cross = () => (\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" aria-hidden>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n);\n\n// --- the tag set -----------------------------------------------------------------------------------------------------------\n\nexport type TagSetEditorProps = {\n /** The `tags` of the kind's configuration (`KindConfig.tags`). */\n value: TagSetValue;\n /** Called with the whole set after every change. */\n onChange: (value: TagSetValue) => void;\n /** The variant whose presets are edited (a trade, or `default`). */\n variant: string;\n /** The roles of the product that can write tags. */\n roles: readonly EditorRole[];\n /** What `kindConfigProblems` found (the server's own rules), shown above the list. */\n problems?: readonly string[];\n /** The words, passed translated (English by default). */\n labels?: Partial<TagSetEditorLabels>;\n /** Not available. */\n disabled?: boolean;\n /** Classes merged on the root. */\n className?: string;\n};\n\n/** The admin's tag set: the presets of a variant (name, colour, order), who writes, whether people add their own, the most. */\nexport function TagSetEditor({ value, onChange, variant, roles, problems, labels: given, disabled, className }: Readonly<TagSetEditorProps>) {\n const labels: TagSetEditorLabels = { ...tagSetEditorLabels, ...given, markerNames: { ...tagSetEditorLabels.markerNames, ...given?.markerNames } };\n const presets = value.presets[variant] ?? [];\n const twins = duplicatePresetNames(presets);\n const [draft, setDraft] = React.useState(\"\");\n const [draftMarker, setDraftMarker] = React.useState<Marker>(\"blue\");\n const reorder = useReorder((from, to) => onChange(movePreset(value, variant, from, to)));\n const id = React.useId();\n const add = () => {\n const next = addPreset(value, variant, draft, draftMarker);\n if (next === value) return;\n onChange(next);\n setDraft(\"\");\n };\n return (\n <div className={cn(\"flex flex-col gap-4\", className)}>\n <Problems title={labels.problems} problems={problems} />\n <section aria-labelledby={`${id}-presets`} className=\"flex flex-col gap-2\">\n <h3 id={`${id}-presets`} className=\"m-0 text-sm font-semibold text-fg\">\n {labels.presets}\n </h3>\n {presets.length === 0 ? (\n <p className=\"m-0 text-sm text-fg-secondary\">{labels.empty}</p>\n ) : (\n <ol className=\"m-0 flex list-none flex-col gap-2 p-0\">\n {presets.map((preset, index) => {\n const shown = preset.name || String(index + 1);\n const twin = twins.has(index);\n return (\n <li key={index} {...reorder.row(index)} className=\"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-border-default bg-surface-1 px-2 py-1.5\">\n <span {...reorder.handle(index)} aria-hidden title={labels.drag(shown)} className=\"inline-flex h-9 w-6 cursor-grab items-center justify-center text-fg-muted active:cursor-grabbing max-md:hidden\">\n {grip}\n </span>\n <TagMarker marker={preset.marker} />\n <div className=\"flex min-w-40 flex-1 flex-col gap-1\">\n <Input\n aria-label={labels.name(index + 1)}\n data-reorder-field=\"name\"\n value={preset.name}\n disabled={disabled}\n invalid={twin || !preset.name.trim()}\n aria-describedby={twin ? `${id}-dup-${index}` : undefined}\n onChange={(event) => onChange(renamePreset(value, variant, index, event.target.value))}\n onBlur={(event) => event.target.value !== event.target.value.replace(/\\s+/g, \" \").trim() && onChange(renamePreset(value, variant, index, event.target.value.replace(/\\s+/g, \" \").trim()))}\n onKeyDown={reorder.keys(index, presets.length - 1)}\n className=\"h-9\"\n />\n {twin ? (\n <span id={`${id}-dup-${index}`} className=\"text-xs text-fg-danger\">\n {labels.duplicate}\n </span>\n ) : null}\n </div>\n <MarkerPicker label={labels.marker(shown)} names={labels.markerNames} value={preset.marker} disabled={disabled} onValueChange={(marker) => onChange(recolorPreset(value, variant, index, marker))} />\n <IconButton label={labels.moveUp(shown)} disabled={disabled || index === 0} onClick={() => onChange(movePreset(value, variant, index, index - 1))}>\n {arrow(true)}\n </IconButton>\n <IconButton label={labels.moveDown(shown)} disabled={disabled || index === presets.length - 1} onClick={() => onChange(movePreset(value, variant, index, index + 1))}>\n {arrow(false)}\n </IconButton>\n <IconButton label={labels.remove(shown)} disabled={disabled} onClick={() => onChange(removePreset(value, variant, index))}>\n <Cross />\n </IconButton>\n </li>\n );\n })}\n </ol>\n )}\n <div className=\"flex flex-wrap items-center gap-2\">\n <Input\n aria-label={labels.add}\n value={draft}\n maxLength={80}\n disabled={disabled}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n add();\n }\n }}\n placeholder={labels.add}\n className=\"h-9 min-w-40 flex-1\"\n />\n <MarkerPicker label={labels.marker(draft.trim() || labels.add)} names={labels.markerNames} value={draftMarker} disabled={disabled} onValueChange={setDraftMarker} />\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={disabled || !draft.trim()} onClick={add}>\n {labels.addButton}\n </Button>\n </div>\n </section>\n <div className=\"flex flex-col\">\n <SettingsRow label={labels.writers} description={labels.writersHint}>\n <Chip.Group type=\"multiple\" size=\"sm\" label={labels.writers} value={value.writers} disabled={disabled} onValueChange={(writers) => onChange({ ...value, writers })}>\n {roles.map((role) => (\n <Chip key={role.key} value={role.key}>\n {role.label}\n </Chip>\n ))}\n </Chip.Group>\n </SettingsRow>\n <SettingsRow label={labels.userTags} description={labels.userTagsHint}>\n <Switch label={labels.userTags} checked={value.userTags} disabled={disabled} onCheckedChange={(userTags) => onChange({ ...value, userTags })} />\n </SettingsRow>\n <SettingsRow label={labels.max} description={labels.maxHint} htmlFor={`${id}-max`}>\n <Input\n id={`${id}-max`}\n type=\"number\"\n inputMode=\"numeric\"\n min={1}\n max={200}\n value={value.max}\n disabled={disabled}\n invalid={!Number.isInteger(value.max) || value.max < 1 || value.max > 200}\n onChange={(event) => onChange({ ...value, max: event.target.value === \"\" ? 0 : Number(event.target.value) })}\n onBlur={() => onChange({ ...value, max: clampMax(value.max) })}\n className=\"h-9 w-24\"\n />\n </SettingsRow>\n </div>\n </div>\n );\n}\n\n// --- the status set --------------------------------------------------------------------------------------------------------\n\nexport type StatusSetEditorProps = {\n /** The kind's status set (`KindConfig.status`). */\n value: StatusSet;\n /** Called with the whole set after every change. */\n onChange: (value: StatusSet) => void;\n /** The roles of the product that can make a move. */\n roles: readonly EditorRole[];\n /** The language the states are named in elsewhere in the editor (the moves' names). */\n locale?: Lang;\n /** What `kindConfigProblems` found (the server's own rules), shown above the list. */\n problems?: readonly string[];\n /** The words, passed translated (English by default). */\n labels?: Partial<StatusSetEditorLabels>;\n /** Not available. */\n disabled?: boolean;\n /** Classes merged on the root. */\n className?: string;\n};\n\n/** The admin's status set: the states in their order (FR and EN, tone, final), the initial state, and the moves from × to. */\nexport function StatusSetEditor({ value, onChange, roles, locale = \"en\", problems, labels: given, disabled, className }: Readonly<StatusSetEditorProps>) {\n const labels: StatusSetEditorLabels = { ...statusSetEditorLabels, ...given };\n const [chosen, setChosen] = React.useState<{ from: string; to: string } | null>(null);\n const reorder = useReorder((from, to) => onChange(moveState(value, from, to)));\n const id = React.useId();\n const nameOf = (key: string) => value.states.find((s) => s.key === key)?.label[locale] || key;\n const roleLabel = (key: string) => roles.find((r) => r.key === key)?.label ?? key;\n const open = chosen && value.states.some((x) => x.key === chosen.from) && value.states.some((x) => x.key === chosen.to) ? chosen : null;\n const detail = open ? transitionOf(value, open.from, open.to) : undefined;\n\n if (value.mode === \"derived\") {\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n <Problems title={labels.problems} problems={problems} />\n <p className=\"m-0 text-sm text-fg-secondary\">{labels.derived}</p>\n <ol aria-label={labels.states} className=\"m-0 flex list-none flex-wrap gap-2 p-0\">\n {value.states.map((state) => (\n <li key={state.key} className=\"inline-flex items-center gap-1.5 rounded-sm bg-surface-3 px-2 py-0.5 text-[11px] font-semibold text-fg-secondary\" data-tone={state.tone}>\n <span aria-hidden className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n {state.label[locale]}\n </li>\n ))}\n </ol>\n </div>\n );\n }\n\n return (\n <div className={cn(\"flex flex-col gap-5\", className)}>\n <Problems title={labels.problems} problems={problems} />\n <section aria-labelledby={`${id}-states`} className=\"flex flex-col gap-2\">\n <h3 id={`${id}-states`} className=\"m-0 text-sm font-semibold text-fg\">\n {labels.states}\n </h3>\n <ol className=\"m-0 flex list-none flex-col gap-2 p-0\">\n {value.states.map((state, index) => {\n const n = index + 1;\n const isInitial = value.initial === state.key;\n const name = state.label[locale] || String(n);\n return (\n <li key={state.key} {...reorder.row(index)} data-state-key={state.key} className=\"flex flex-wrap items-start gap-x-3 gap-y-2 rounded-lg border border-border-default bg-surface-1 p-2.5\">\n <span {...reorder.handle(index)} aria-hidden title={labels.drag(name)} className=\"mt-1.5 inline-flex h-9 w-6 cursor-grab items-center justify-center text-fg-muted active:cursor-grabbing max-md:hidden\">\n {grip}\n </span>\n {([\"fr\", \"en\"] as const).map((lang) => (\n <Input\n key={lang}\n aria-label={labels.stateLabel(labels.languages[lang], n)}\n data-reorder-field={lang}\n lang={lang}\n value={state.label[lang]}\n maxLength={40}\n disabled={disabled}\n invalid={!state.label[lang].trim()}\n onChange={(event) => onChange(setStateLabel(value, state.key, lang, event.target.value))}\n onKeyDown={reorder.keys(index, value.states.length - 1)}\n className=\"h-9 min-w-36 flex-1\"\n />\n ))}\n <Select aria-label={labels.tone(n)} value={state.tone} disabled={disabled} onChange={(event) => onChange(setStateTone(value, state.key, event.target.value as StatusTone))} className=\"h-9 w-36\">\n {STATUS_TONES.map((tone) => (\n <option key={tone} value={tone}>\n {labels.tones[tone]}\n </option>\n ))}\n </Select>\n <div className=\"flex items-center gap-1.5 text-xs text-fg-secondary\">\n <Switch size=\"sm\" label={labels.final(n)} checked={Boolean(state.final)} disabled={disabled || isInitial} onCheckedChange={(final) => onChange(setFinal(value, state.key, final))} />\n <span aria-hidden>{isInitial ? labels.initialNotFinal : labels.finalHint}</span>\n </div>\n <label className=\"flex items-center gap-1.5 text-xs text-fg-secondary\">\n <input type=\"radio\" name={`${id}-initial`} aria-label={labels.initial(n)} checked={isInitial} disabled={disabled || Boolean(state.final)} onChange={() => onChange(setInitial(value, state.key))} className=\"h-4 w-4 accent-(--kz-accent)\" />\n <span aria-hidden>{labels.initial(n)}</span>\n </label>\n <code className=\"text-[11px] text-fg-muted\">{state.key}</code>\n <div className=\"ml-auto flex\">\n <IconButton label={labels.moveUp(name)} disabled={disabled || index === 0} onClick={() => onChange(moveState(value, index, index - 1))}>\n {arrow(true)}\n </IconButton>\n <IconButton label={labels.moveDown(name)} disabled={disabled || index === value.states.length - 1} onClick={() => onChange(moveState(value, index, index + 1))}>\n {arrow(false)}\n </IconButton>\n <IconButton label={labels.remove(name)} disabled={disabled || value.states.length <= 2} onClick={() => onChange(removeState(value, state.key))}>\n <Cross />\n </IconButton>\n </div>\n </li>\n );\n })}\n </ol>\n <div>\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={disabled || value.states.length >= 12} onClick={() => onChange(addState(value, labels.newState))}>\n {labels.addState}\n </Button>\n </div>\n </section>\n\n <section aria-labelledby={`${id}-moves`} className=\"flex flex-col gap-3\">\n <div className=\"flex flex-col gap-0.5\">\n <h3 id={`${id}-moves`} className=\"m-0 text-sm font-semibold text-fg\">\n {labels.moves}\n </h3>\n <p className=\"m-0 text-xs text-fg-secondary\">{labels.movesHint}</p>\n </div>\n {value.states.map((from) => (\n <div key={from.key} role=\"group\" aria-label={labels.from(nameOf(from.key))} className=\"flex flex-wrap items-center gap-2\">\n <span className=\"min-w-28 text-xs font-semibold text-fg\">{nameOf(from.key)}</span>\n {from.final ? (\n <span className=\"text-xs text-fg-secondary\">{labels.noWayOut}</span>\n ) : (\n value.states\n .filter((to) => to.key !== from.key)\n .map((to) => {\n const move = transitionOf(value, from.key, to.key);\n const summary = move ? move.roles.map(roleLabel).join(\", \") : labels.none;\n const on = open?.from === from.key && open.to === to.key;\n return (\n <button\n key={to.key}\n type=\"button\"\n aria-pressed={on}\n data-on={move ? \"\" : undefined}\n disabled={disabled}\n onClick={() => setChosen(on ? null : { from: from.key, to: to.key })}\n className={cn(\n \"inline-flex min-h-9 items-center gap-1.5 rounded-sm border px-2.5 py-1 text-xs transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40\",\n move ? \"border-accent bg-accent-soft text-fg\" : \"border-dashed border-border-control text-fg-secondary hover:border-border-strong\",\n on && \"ring-2 ring-ring\",\n )}\n >\n {/* The name is the sentence for a screen reader; the arrow and the short words are what the eye reads. */}\n <span className=\"sr-only\">{labels.move(nameOf(from.key), nameOf(to.key), summary)}</span>\n <span aria-hidden>→ {nameOf(to.key)}</span>\n <span aria-hidden className=\"text-fg\">\n {summary}\n </span>\n </button>\n );\n })\n )}\n </div>\n ))}\n\n {open && chosen ? (\n <div role=\"region\" aria-label={labels.moveDetail(nameOf(open.from), nameOf(open.to))} className=\"flex flex-col gap-3 rounded-lg border border-border-default bg-surface-1 p-3\">\n <h4 className=\"m-0 text-sm font-semibold text-fg\">{labels.moveDetail(nameOf(open.from), nameOf(open.to))}</h4>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-semibold text-fg-secondary\">{labels.roles}</span>\n <Chip.Group\n type=\"multiple\"\n size=\"sm\"\n label={labels.roles}\n value={detail?.roles ? [...detail.roles] : []}\n disabled={disabled}\n onValueChange={(next) => {\n onChange(setTransitionRoles(value, open.from, open.to, next));\n }}\n >\n {roles.map((role) => (\n <Chip key={role.key} value={role.key}>\n {role.label}\n </Chip>\n ))}\n </Chip.Group>\n </div>\n {detail ? (\n <>\n <div className=\"flex items-center gap-2 text-xs text-fg-secondary\">\n <Switch size=\"sm\" label={labels.confirm} checked={Boolean(detail?.confirm)} disabled={disabled} onCheckedChange={(on) => onChange(setTransitionConfirm(value, open.from, open.to, on))} />\n <span aria-hidden>{labels.confirm}</span>\n </div>\n <div className=\"flex flex-col gap-2\">\n <span className=\"text-xs font-semibold text-fg-secondary\">{labels.reasons}</span>\n {(detail?.reasons ?? []).map((reason, at) => (\n <div key={reason.key} className=\"flex flex-wrap items-center gap-2\">\n {([\"fr\", \"en\"] as const).map((lang) => (\n <Input\n key={lang}\n lang={lang}\n aria-label={labels.reasonLabel(labels.languages[lang], at + 1)}\n value={reason.label[lang]}\n maxLength={40}\n disabled={disabled}\n invalid={!reason.label[lang].trim()}\n onChange={(event) =>\n onChange(setTransitionReasons(value, open.from, open.to, (detail?.reasons ?? []).map((r) => (r.key === reason.key ? { ...r, label: { ...r.label, [lang]: event.target.value } } : r))))\n }\n className=\"h-9 min-w-36 flex-1\"\n />\n ))}\n <IconButton label={labels.removeReason(at + 1)} disabled={disabled} onClick={() => onChange(setTransitionReasons(value, open.from, open.to, (detail?.reasons ?? []).filter((r) => r.key !== reason.key)))}>\n <Cross />\n </IconButton>\n </div>\n ))}\n <div>\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={disabled || (detail?.reasons?.length ?? 0) >= 12} onClick={() => onChange(addReason(value, open.from, open.to, { fr: \"\", en: \"\" }))}>\n {labels.addReason}\n </Button>\n </div>\n </div>\n </>\n ) : null}\n </div>\n ) : null}\n </section>\n </div>\n );\n}\n"
408
408
  },
409
409
  {
410
410
  "path": "kind-config-editor/labels.ts",
@@ -217,7 +217,7 @@
217
217
  },
218
218
  {
219
219
  "path": "kpi-explained/kpi-explained.tsx",
220
- "content": "// Server-safe. A figure whose meaning, formula, source and freshness travel with its value.\nimport { type DateInput, formatDate, formatMoney, formatNumber, formatPercent, type Locale } from \"@krizaka/intl\";\nimport * as React from \"react\";\n\nexport type KpiNumberOptions = Omit<Intl.NumberFormatOptions, \"style\" | \"currency\" | \"currencyDisplay\">;\n\nexport type KpiFormat =\n | { type: \"money\"; currency: string; minorUnitDigits?: number }\n | { type: \"number\"; options?: KpiNumberOptions }\n | { type: \"percent\"; options?: KpiNumberOptions };\n\nexport type KpiState = \"ok\" | \"watch\" | \"act\";\n\nexport interface KpiExplainedProps extends Omit<React.ComponentProps<\"article\">, \"children\"> {\n /** The figure's name. */\n label: React.ReactNode;\n /** The raw number: money is integer minor units; percentages are ratios such as 0.125. */\n value: number;\n /** How to format the value with `@krizaka/intl`. */\n format: KpiFormat;\n /** The app's locale, e.g. `fr-CA`. */\n locale: Locale;\n /** The IANA time zone for freshness dates; defaults to UTC for deterministic rendering. */\n timeZone?: string;\n /** One plain-language sentence about what the figure means. */\n meaning: string;\n /** The localized label for the formula row. */\n formulaLabel: React.ReactNode;\n /** The calculation in words, e.g. “dépenses TTC ÷ ventes TTC”. */\n formula: string;\n /** The localized label for the source row. */\n sourceLabel: React.ReactNode;\n /** The source link or file name, supplied by the host. */\n source: React.ReactNode;\n /** A host-provided action such as “Verify”, next to the source. */\n verify?: React.ReactNode;\n /** Host-provided thresholds in the same units as `value`. */\n thresholds: {\n direction: \"above\" | \"below\";\n watchAt: number;\n actAt: number;\n };\n /** Host-provided words for the derived state. */\n stateLabels: Record<KpiState, React.ReactNode>;\n /** Reading time and the expected next reading time (the host derives it from its cadence). */\n freshness: {\n lastRead: DateInput;\n expectedAt: DateInput;\n now: DateInput;\n lastReadLabel: React.ReactNode;\n staleLabel: React.ReactNode;\n };\n /** An optional Sparkline from `@krizaka/charts`, with its own accessible summary. */\n sparkline?: React.ReactNode;\n /** Replace every non-space character in the value while preserving its formatted shape. */\n masked?: boolean;\n /** The accessible name shown instead of the value when masked. */\n maskedLabel: string;\n}\n\nfunction formatValue(value: number, format: KpiFormat, locale: Locale): string {\n switch (format.type) {\n case \"money\":\n return formatMoney(value, { currency: format.currency, locale, minorUnitDigits: format.minorUnitDigits });\n case \"percent\":\n return formatPercent(value, { locale, ...format.options });\n case \"number\":\n return formatNumber(value, { locale, ...format.options });\n }\n}\n\nfunction stateFor(value: number, thresholds: KpiExplainedProps[\"thresholds\"]): KpiState {\n if (thresholds.direction === \"above\") {\n return value >= thresholds.actAt ? \"act\" : value >= thresholds.watchAt ? \"watch\" : \"ok\";\n }\n return value <= thresholds.actAt ? \"act\" : value <= thresholds.watchAt ? \"watch\" : \"ok\";\n}\n\nfunction maskValue(value: string): string {\n return value.replace(/[^\\s]/gu, \"•\");\n}\n\n/** A key figure that explains what it means, how it is calculated and where it came from. */\nexport function KpiExplained({\n label,\n value,\n format,\n locale,\n timeZone = \"UTC\",\n meaning,\n formulaLabel,\n formula,\n sourceLabel,\n source,\n verify,\n thresholds,\n stateLabels,\n freshness,\n sparkline,\n masked = false,\n maskedLabel,\n className,\n ...props\n}: KpiExplainedProps) {\n const id = React.useId();\n const state = stateFor(value, thresholds);\n const formattedValue = formatValue(value, format, locale);\n const lastRead = new Date(freshness.lastRead);\n const stale = new Date(freshness.now) >= new Date(freshness.expectedAt);\n\n return (\n <article aria-labelledby={`${id}-label`} className={[\"kz-kpi\", className].filter(Boolean).join(\" \")} data-state={state} {...props}>\n <header className=\"kz-kpi-head\">\n <h3 id={`${id}-label`} className=\"kz-kpi-label\">{label}</h3>\n <span className=\"kz-kpi-state\" data-state={state}>{stateLabels[state]}</span>\n </header>\n <p className=\"kz-kpi-value\">\n {masked ? <span role=\"img\" aria-label={maskedLabel}>{maskValue(formattedValue)}</span> : formattedValue}\n </p>\n <p className=\"kz-kpi-meaning\">{meaning}</p>\n <dl className=\"kz-kpi-details\">\n <div><dt>{formulaLabel}</dt><dd>{formula}</dd></div>\n <div><dt>{sourceLabel}</dt><dd>{source}{verify ? <span className=\"kz-kpi-verify\">{verify}</span> : null}</dd></div>\n </dl>\n <p className=\"kz-kpi-freshness\">\n <span>{freshness.lastReadLabel}: </span>\n <time dateTime={lastRead.toISOString()}>{formatDate(lastRead, { locale, style: \"medium\", timeStyle: \"short\", timeZone })}</time>\n {stale ? <span className=\"kz-kpi-stale\" role=\"status\">{freshness.staleLabel}</span> : null}\n </p>\n {sparkline ? <div className=\"kz-kpi-sparkline\">{sparkline}</div> : null}\n </article>\n );\n}\n"
220
+ "content": "// Server-safe. A figure whose meaning, formula, source and freshness travel with its value.\nimport { type DateInput, formatDate, formatMoney, formatNumber, formatPercent, type Locale } from \"@krizaka/intl\";\nimport * as React from \"react\";\n\nexport type KpiNumberOptions = Omit<Intl.NumberFormatOptions, \"style\" | \"currency\" | \"currencyDisplay\">;\n\nexport type KpiFormat =\n | { type: \"money\"; currency: string; minorUnitDigits?: number }\n | { type: \"number\"; options?: KpiNumberOptions }\n | { type: \"percent\"; options?: KpiNumberOptions };\n\nexport type KpiState = \"ok\" | \"watch\" | \"act\";\n\nexport interface KpiExplainedProps extends Omit<React.ComponentProps<\"article\">, \"children\"> {\n /** The figure's name. */\n label: React.ReactNode;\n /** The raw number: money is integer minor units; percentages are ratios such as 0.125. */\n value: number;\n /** How to format the value with `@krizaka/intl`. */\n format: KpiFormat;\n /** The app's locale, e.g. `fr-CA`. */\n locale: Locale;\n /** The IANA time zone for freshness dates; defaults to UTC for deterministic rendering. */\n timeZone?: string;\n /** One plain-language sentence about what the figure means. */\n meaning: string;\n /** The localized label for the formula row. */\n formulaLabel: React.ReactNode;\n /** The calculation in words, e.g. “dépenses TTC ÷ ventes TTC”. */\n formula: string;\n /** The localized label for the source row. */\n sourceLabel: React.ReactNode;\n /** The source link or file name, supplied by the host. */\n source: React.ReactNode;\n /** A host-provided action such as “Verify”, next to the source. */\n verify?: React.ReactNode;\n /** Host-provided thresholds in the same units as `value`. */\n thresholds: {\n direction: \"above\" | \"below\";\n watchAt: number;\n actAt: number;\n };\n /** Host-provided words for the derived state. */\n stateLabels: Record<KpiState, React.ReactNode>;\n /** Reading time and the expected next reading time (the host derives it from its cadence). */\n freshness: {\n lastRead: DateInput;\n expectedAt: DateInput;\n now: DateInput;\n lastReadLabel: React.ReactNode;\n staleLabel: React.ReactNode;\n };\n /** An optional Sparkline from `@krizaka/charts`, with its own accessible summary. */\n sparkline?: React.ReactNode;\n /** Replace every non-space character in the value while preserving its formatted shape. */\n masked?: boolean;\n /** The accessible name shown instead of the value when masked. */\n maskedLabel: string;\n}\n\nfunction formatValue(value: number, format: KpiFormat, locale: Locale): string {\n switch (format.type) {\n case \"money\":\n return formatMoney(value, { currency: format.currency, locale, minorUnitDigits: format.minorUnitDigits });\n case \"percent\":\n return formatPercent(value, { locale, ...format.options });\n case \"number\":\n return formatNumber(value, { locale, ...format.options });\n }\n}\n\nfunction stateFor(value: number, thresholds: KpiExplainedProps[\"thresholds\"]): KpiState {\n const reaches = thresholds.direction === \"above\" ? (level: number) => value >= level : (level: number) => value <= level;\n if (reaches(thresholds.actAt)) return \"act\";\n if (reaches(thresholds.watchAt)) return \"watch\";\n return \"ok\";\n}\n\nfunction maskValue(value: string): string {\n return value.replace(/[^\\s]/gu, \"•\");\n}\n\n/** A key figure that explains what it means, how it is calculated and where it came from. */\nexport function KpiExplained({\n label,\n value,\n format,\n locale,\n timeZone = \"UTC\",\n meaning,\n formulaLabel,\n formula,\n sourceLabel,\n source,\n verify,\n thresholds,\n stateLabels,\n freshness,\n sparkline,\n masked = false,\n maskedLabel,\n className,\n ...props\n}: Readonly<KpiExplainedProps>) {\n const id = React.useId();\n const state = stateFor(value, thresholds);\n const formattedValue = formatValue(value, format, locale);\n const lastRead = new Date(freshness.lastRead);\n const stale = new Date(freshness.now) >= new Date(freshness.expectedAt);\n\n return (\n <article aria-labelledby={`${id}-label`} className={[\"kz-kpi\", className].filter(Boolean).join(\" \")} data-state={state} {...props}>\n <header className=\"kz-kpi-head\">\n <h3 id={`${id}-label`} className=\"kz-kpi-label\">{label}</h3>\n <span className=\"kz-kpi-state\" data-state={state}>{stateLabels[state]}</span>\n </header>\n <p className=\"kz-kpi-value\">\n {masked ? <span role=\"img\" aria-label={maskedLabel}>{maskValue(formattedValue)}</span> : formattedValue}\n </p>\n <p className=\"kz-kpi-meaning\">{meaning}</p>\n <dl className=\"kz-kpi-details\">\n <div><dt>{formulaLabel}</dt><dd>{formula}</dd></div>\n <div><dt>{sourceLabel}</dt><dd>{source}{verify ? <span className=\"kz-kpi-verify\">{verify}</span> : null}</dd></div>\n </dl>\n <p className=\"kz-kpi-freshness\">\n <span>{freshness.lastReadLabel}: </span>\n <time dateTime={lastRead.toISOString()}>{formatDate(lastRead, { locale, style: \"medium\", timeStyle: \"short\", timeZone })}</time>\n {stale ? <span className=\"kz-kpi-stale\" role=\"status\">{freshness.staleLabel}</span> : null}\n </p>\n {sparkline ? <div className=\"kz-kpi-sparkline\">{sparkline}</div> : null}\n </article>\n );\n}\n"
221
221
  },
222
222
  {
223
223
  "path": "kpi-explained/meta.ts",