@krizaka/ui 4.3.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 (267) 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/blocks.css +4 -0
  23. package/dist/chapter.js +7 -4
  24. package/dist/chapter.js.map +1 -1
  25. package/dist/chat.js +1 -1
  26. package/dist/chip.d.ts +1 -1
  27. package/dist/chip.js +1 -1
  28. package/dist/{chunk-SNSQLGGS.js → chunk-5VZ37TY3.js} +1 -1
  29. package/dist/{chunk-XWJDBQU7.js.map → chunk-5VZ37TY3.js.map} +1 -1
  30. package/dist/{chunk-MTVX4RRF.js → chunk-HP7BDMVK.js} +11 -3
  31. package/dist/chunk-HP7BDMVK.js.map +1 -0
  32. package/dist/{chunk-PK3L6WQT.js → chunk-LNAAWT4Y.js} +4 -2
  33. package/dist/{chunk-PK3L6WQT.js.map → chunk-LNAAWT4Y.js.map} +1 -1
  34. package/dist/{chunk-UIP3WX5O.js → chunk-MDSP7DJR.js} +2 -2
  35. package/dist/chunk-MDSP7DJR.js.map +1 -0
  36. package/dist/{chunk-IEGTRCDI.js → chunk-NQENOT6L.js} +2 -2
  37. package/dist/{chunk-IEGTRCDI.js.map → chunk-NQENOT6L.js.map} +1 -1
  38. package/dist/{chunk-FM42KOAU.js → chunk-P7AFIKWG.js} +5 -3
  39. package/dist/chunk-P7AFIKWG.js.map +1 -0
  40. package/dist/{chunk-BCD2CRFG.js → chunk-PJNR4NTS.js} +2 -2
  41. package/dist/chunk-PJNR4NTS.js.map +1 -0
  42. package/dist/{chunk-ZFR6ZNXD.js → chunk-PVQ2KKPZ.js} +1 -1
  43. package/dist/chunk-PVQ2KKPZ.js.map +1 -0
  44. package/dist/{chunk-U4XTZMB7.js → chunk-QA3WETWT.js} +1 -1
  45. package/dist/{chunk-U4XTZMB7.js.map → chunk-QA3WETWT.js.map} +1 -1
  46. package/dist/{chunk-YXETEQQJ.js → chunk-SG2RKUVJ.js} +2 -2
  47. package/dist/{chunk-EOWV6BNQ.js → chunk-TXFX4PMN.js} +4 -2
  48. package/dist/{chunk-EOWV6BNQ.js.map → chunk-TXFX4PMN.js.map} +1 -1
  49. package/dist/{chunk-XWJDBQU7.js → chunk-V5RO6JYI.js} +1 -1
  50. package/dist/{chunk-SNSQLGGS.js.map → chunk-V5RO6JYI.js.map} +1 -1
  51. package/dist/chunk-VZ6ZALIJ.js +13 -0
  52. package/dist/chunk-VZ6ZALIJ.js.map +1 -0
  53. package/dist/{chunk-2DHL7NJW.js → chunk-XVRKKYWU.js} +5 -3
  54. package/dist/{chunk-2DHL7NJW.js.map → chunk-XVRKKYWU.js.map} +1 -1
  55. package/dist/{chunk-CDNOT2KR.js → chunk-YTYNKMNS.js} +1 -1
  56. package/dist/chunk-YTYNKMNS.js.map +1 -0
  57. package/dist/code-block.js.map +1 -1
  58. package/dist/combobox.js +2 -2
  59. package/dist/copy-button.js +2 -2
  60. package/dist/copy-button.js.map +1 -1
  61. package/dist/data-table.js +3 -3
  62. package/dist/desktop-window.d.ts +1 -1
  63. package/dist/desktop-window.js +3 -1
  64. package/dist/desktop-window.js.map +1 -1
  65. package/dist/drop-overlay.js +8 -8
  66. package/dist/drop-overlay.js.map +1 -1
  67. package/dist/elephant.d.ts +1 -1
  68. package/dist/elephant.js.map +1 -1
  69. package/dist/embed-facade.d.ts +1 -1
  70. package/dist/embed-facade.js +3 -1
  71. package/dist/embed-facade.js.map +1 -1
  72. package/dist/engine-flow.js +7 -2
  73. package/dist/engine-flow.js.map +1 -1
  74. package/dist/entity-header.js +9 -3
  75. package/dist/entity-header.js.map +1 -1
  76. package/dist/file-upload.d.ts +1 -1
  77. package/dist/file-upload.js.map +1 -1
  78. package/dist/filter-bar.d.ts +4 -4
  79. package/dist/filter-bar.js +2 -2
  80. package/dist/flock.js +9 -6
  81. package/dist/flock.js.map +1 -1
  82. package/dist/form.d.ts +3 -3
  83. package/dist/form.js.map +1 -1
  84. package/dist/genui.js +3 -3
  85. package/dist/glossary-term.d.ts +1 -1
  86. package/dist/glossary-term.js.map +1 -1
  87. package/dist/glossary.d.ts +1 -1
  88. package/dist/glossary.js.map +1 -1
  89. package/dist/identity-card.js +1 -1
  90. package/dist/index.js +1 -1
  91. package/dist/kind-config-editor.d.ts +2 -2
  92. package/dist/kind-config-editor.js +1 -1
  93. package/dist/kind-config-editor.js.map +1 -1
  94. package/dist/kpi-explained.d.ts +1 -1
  95. package/dist/kpi-explained.js +4 -4
  96. package/dist/kpi-explained.js.map +1 -1
  97. package/dist/landing-page.d.ts +10 -3
  98. package/dist/landing-page.js +8 -6
  99. package/dist/landing-page.js.map +1 -1
  100. package/dist/{lightbox-Q45BZ3HW.js → lightbox-MRB2YZEP.js} +1 -1
  101. package/dist/lightbox-MRB2YZEP.js.map +1 -0
  102. package/dist/map/cards.js +4 -2
  103. package/dist/map/cards.js.map +1 -1
  104. package/dist/map/pin.js +2 -1
  105. package/dist/map/pin.js.map +1 -1
  106. package/dist/map.d.ts +1 -1
  107. package/dist/map.js.map +1 -1
  108. package/dist/mascot-quote.js +1 -1
  109. package/dist/mascot-state.js +1 -1
  110. package/dist/mascots.js +1 -1
  111. package/dist/match-dialog.js +1 -1
  112. package/dist/motion.d.ts +1 -1
  113. package/dist/motion.js.map +1 -1
  114. package/dist/native/form.d.ts +3 -3
  115. package/dist/native/form.js.map +1 -1
  116. package/dist/native/markdown.d.ts +1 -1
  117. package/dist/native/markdown.js.map +1 -1
  118. package/dist/native/vertical-video.js.map +1 -1
  119. package/dist/native.d.ts +12 -12
  120. package/dist/native.js +12 -7
  121. package/dist/native.js.map +1 -1
  122. package/dist/nav-bar.d.ts +2 -2
  123. package/dist/nav-bar.js +1 -1
  124. package/dist/nav-bar.js.map +1 -1
  125. package/dist/next-actions.d.ts +1 -1
  126. package/dist/next-actions.js.map +1 -1
  127. package/dist/notification-preferences.d.ts +1 -1
  128. package/dist/notification-preferences.js +5 -2
  129. package/dist/notification-preferences.js.map +1 -1
  130. package/dist/page-index.js +2 -2
  131. package/dist/page-index.js.map +1 -1
  132. package/dist/product-page.js +4 -4
  133. package/dist/product-page.js.map +1 -1
  134. package/dist/promo-code-field.d.ts +1 -1
  135. package/dist/promo-code-field.js.map +1 -1
  136. package/dist/qr-code.d.ts +1 -1
  137. package/dist/qr-code.js +1 -1
  138. package/dist/rail-nav.js +3 -3
  139. package/dist/rail-nav.js.map +1 -1
  140. package/dist/retro-tv.d.ts +1 -1
  141. package/dist/retro-tv.js.map +1 -1
  142. package/dist/reviews.d.ts +2 -2
  143. package/dist/reviews.js.map +1 -1
  144. package/dist/router.d.ts +1 -1
  145. package/dist/router.js +8 -8
  146. package/dist/router.js.map +1 -1
  147. package/dist/{schema-DgjBz7-8.d.ts → schema-Dd05m48Q.d.ts} +8 -8
  148. package/dist/service-card.js +22 -13
  149. package/dist/service-card.js.map +1 -1
  150. package/dist/settings-layout.js +1 -1
  151. package/dist/shop/booking.js.map +1 -1
  152. package/dist/shop/gallery.js +7 -6
  153. package/dist/shop/gallery.js.map +1 -1
  154. package/dist/shop/hero.js.map +1 -1
  155. package/dist/shop/look.d.ts +2 -2
  156. package/dist/shop/look.js +1 -1
  157. package/dist/shop/look.js.map +1 -1
  158. package/dist/shop/map-gate.d.ts +1 -1
  159. package/dist/shop/map-gate.js +2 -2
  160. package/dist/shop/map-gate.js.map +1 -1
  161. package/dist/shop/services.js.map +1 -1
  162. package/dist/shop-composer.d.ts +10 -10
  163. package/dist/shop-composer.js +27 -14
  164. package/dist/shop-composer.js.map +1 -1
  165. package/dist/shop-gallery.js +1 -1
  166. package/dist/shop.d.ts +2 -2
  167. package/dist/shop.js +2 -2
  168. package/dist/shop.js.map +1 -1
  169. package/dist/signature.js +2 -1
  170. package/dist/signature.js.map +1 -1
  171. package/dist/site-cahier.js +7 -3
  172. package/dist/site-cahier.js.map +1 -1
  173. package/dist/site-footer.js +6 -2
  174. package/dist/site-footer.js.map +1 -1
  175. package/dist/slot-picker.js +5 -2
  176. package/dist/slot-picker.js.map +1 -1
  177. package/dist/stat.js +1 -1
  178. package/dist/status-chip.d.ts +1 -1
  179. package/dist/status-chip.js.map +1 -1
  180. package/dist/tabs.js.map +1 -1
  181. package/dist/tag-input.js +2 -2
  182. package/dist/tag-selector.js +1 -1
  183. package/dist/text-style.js +4 -3
  184. package/dist/text-style.js.map +1 -1
  185. package/dist/usage.js +8 -3
  186. package/dist/usage.js.map +1 -1
  187. package/dist/versus-card.js +1 -1
  188. package/dist/versus-card.js.map +1 -1
  189. package/dist/vertical-video.js +1 -1
  190. package/dist/vertical-video.js.map +1 -1
  191. package/dist/wall.d.ts +4 -4
  192. package/dist/wall.js +1 -1
  193. package/dist/wall.js.map +1 -1
  194. package/package.json +6 -6
  195. package/registry/account-menu.json +1 -1
  196. package/registry/account-settings.json +2 -2
  197. package/registry/agenda.json +1 -1
  198. package/registry/analysis-report.json +2 -2
  199. package/registry/app-frame.json +3 -3
  200. package/registry/app-header.json +1 -1
  201. package/registry/avatar.json +1 -1
  202. package/registry/badge.json +2 -2
  203. package/registry/bird-plate.json +1 -1
  204. package/registry/chapter.json +1 -1
  205. package/registry/chip.json +1 -1
  206. package/registry/copy-button.json +1 -1
  207. package/registry/data-table.json +1 -1
  208. package/registry/desktop-window.json +1 -1
  209. package/registry/drop-overlay.json +1 -1
  210. package/registry/elephant.json +1 -1
  211. package/registry/embed-facade.json +2 -2
  212. package/registry/engine-flow.json +2 -2
  213. package/registry/entity-header.json +1 -1
  214. package/registry/examples/landing-page/showcase.d.ts +4 -0
  215. package/registry/examples/landing-page/showcase.js +45 -0
  216. package/registry/examples/landing-page/showcase.tsx +42 -0
  217. package/registry/file-upload.json +1 -1
  218. package/registry/filter-bar.json +1 -1
  219. package/registry/flock.json +2 -2
  220. package/registry/form.json +7 -7
  221. package/registry/glossary-term.json +1 -1
  222. package/registry/glossary.json +1 -1
  223. package/registry/index.json +19 -10
  224. package/registry/kind-config-editor.json +1 -1
  225. package/registry/kpi-explained.json +1 -1
  226. package/registry/landing-page.json +61 -21
  227. package/registry/map.json +4 -4
  228. package/registry/mascot-state.json +1 -1
  229. package/registry/mascots.json +2 -2
  230. package/registry/nav-bar.json +4 -4
  231. package/registry/next-actions.json +1 -1
  232. package/registry/notification-preferences.json +1 -1
  233. package/registry/page-index.json +1 -1
  234. package/registry/page.json +4 -0
  235. package/registry/product-page.json +1 -1
  236. package/registry/promo-code-field.json +1 -1
  237. package/registry/qr-code.json +2 -2
  238. package/registry/rail-nav.json +3 -3
  239. package/registry/retro-tv.json +1 -1
  240. package/registry/reviews.json +1 -1
  241. package/registry/router.json +1 -1
  242. package/registry/service-card.json +1 -1
  243. package/registry/settings-layout.json +1 -1
  244. package/registry/shop-composer.json +7 -7
  245. package/registry/shop-gallery.json +1 -1
  246. package/registry/shop.json +11 -11
  247. package/registry/signature.json +1 -1
  248. package/registry/site-cahier.json +1 -1
  249. package/registry/site-footer.json +3 -3
  250. package/registry/slot-picker.json +1 -1
  251. package/registry/stat.json +1 -1
  252. package/registry/status-chip.json +1 -1
  253. package/registry/tabs.json +1 -1
  254. package/registry/text-style.json +1 -1
  255. package/registry/usage.json +2 -2
  256. package/registry/versus-card.json +1 -1
  257. package/registry/vertical-video.json +1 -1
  258. package/registry/wall.json +5 -5
  259. package/registry/waveform.json +2 -2
  260. package/dist/chunk-BCD2CRFG.js.map +0 -1
  261. package/dist/chunk-CDNOT2KR.js.map +0 -1
  262. package/dist/chunk-FM42KOAU.js.map +0 -1
  263. package/dist/chunk-MTVX4RRF.js.map +0 -1
  264. package/dist/chunk-UIP3WX5O.js.map +0 -1
  265. package/dist/chunk-ZFR6ZNXD.js.map +0 -1
  266. package/dist/lightbox-Q45BZ3HW.js.map +0 -1
  267. /package/dist/{chunk-YXETEQQJ.js.map → chunk-SG2RKUVJ.js.map} +0 -0
@@ -236,7 +236,7 @@
236
236
  },
237
237
  {
238
238
  "path": "slot-picker/slot-picker.tsx",
239
- "content": "// Client (the chosen day). The next free times of a service as tappable chips: a strip of days, then the day's times.\n// A time is a link (`href`: the booking page with the time chosen) or a toggle the reader presses (`value`,\n// `onValueChange`). The app computes the slots (its availability is the truth) and formats the labels. With `week` the\n// picker moves through the weeks (← Today →): the host loads the days of the week it is asked for, the picker never computes.\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { BlockLink, type LinkComponent } from \"../block-link\";\n\nexport const slotPicker = tv({\n slots: {\n root: \"flex min-w-0 flex-col gap-3\",\n days: \"flex gap-2 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\",\n day:\n \"flex min-h-12 min-w-[4.5rem] shrink-0 cursor-pointer flex-col items-center justify-center rounded-xl border border-border-default bg-surface-1 px-3 py-1.5 text-center leading-tight text-fg-secondary \" +\n \"transition-colors hover:border-border-strong hover:text-fg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring \" +\n \"aria-pressed:border-accent aria-pressed:bg-accent-soft aria-pressed:text-fg\",\n dayName: \"text-xs font-bold\",\n daySub: \"text-[11px] tabular-nums text-fg-muted\",\n times: \"m-0 flex list-none flex-wrap gap-2 p-0\",\n time:\n \"inline-flex min-h-11 min-w-[4.75rem] items-center justify-center gap-1.5 rounded-sm border border-border-default bg-surface-1 px-4 text-sm font-semibold tabular-nums text-fg no-underline \" +\n \"transition-colors hover:border-accent/60 hover:bg-accent-soft focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring \" +\n \"aria-pressed:border-accent aria-pressed:bg-accent aria-pressed:text-on-accent disabled:cursor-not-allowed disabled:border-dashed disabled:bg-transparent disabled:text-fg-muted disabled:line-through disabled:hover:border-border-default disabled:hover:bg-transparent\",\n note: \"text-[11px] font-medium text-fg-secondary group-aria-pressed:text-on-accent\",\n weekBar: \"flex flex-wrap items-center justify-between gap-2\",\n weekLabel: \"m-0 min-w-0 text-sm font-semibold tabular-nums text-fg\",\n weekNav: \"flex items-center gap-1.5\",\n weekBtn:\n \"inline-flex min-h-11 min-w-11 cursor-pointer items-center justify-center rounded-sm border border-border-default bg-surface-1 px-3 text-sm font-semibold text-fg no-underline \" +\n \"transition-colors hover:border-border-strong focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring aria-disabled:cursor-not-allowed aria-disabled:opacity-50\",\n groups: \"m-0 flex list-none flex-col gap-3 p-0\",\n groupLabel: \"m-0 mb-1.5 text-xs font-bold text-fg-secondary\",\n footer: \"m-0 text-xs text-fg-secondary\",\n empty: \"m-0 rounded-xl border border-dashed border-border-default px-4 py-6 text-center text-sm text-fg-secondary\",\n },\n});\nconst s = slotPicker();\n\nexport type PickerSlot = {\n /** A stable id (the slot's start as an ISO string). */\n id: string;\n /** The time in words, formatted by the app (`9 h 30`). */\n label: string;\n /** What to know about it (`2 places left`), shown beside the time and read with it. */\n note?: string;\n /** Not offered any more (full): shown struck out and disabled, its `note` (`Full`) read with the time — never colour alone. */\n disabled?: boolean;\n /** Makes the time a link to this address (the booking page with the slot chosen). */\n href?: string;\n};\n\n/** A part of a day (`Morning`, `Afternoon`): the label comes from the host's messages. */\nexport type PickerGroup = {\n id: string;\n label: string;\n slots: readonly PickerSlot[];\n};\n\nexport type PickerDay = {\n /** A stable id (`2026-10-19`). */\n id: string;\n /** The day's name, translated (`Today`, `Mon`). */\n label: string;\n /** Under it (`19 Oct`). */\n sub?: string;\n /** Its times, in order — flat… */\n slots?: readonly PickerSlot[];\n /** …or in parts of the day (`Morning`, `Afternoon`), each under its own label. Wins over `slots`. */\n groups?: readonly PickerGroup[];\n};\n\nexport type SlotPickerProps = Omit<React.ComponentProps<\"div\">, \"onChange\" | \"defaultValue\"> & {\n /** The days that have free times, in order. */\n days: readonly PickerDay[];\n /** The name of the group (`Available times`), passed translated. */\n label: string;\n /** Said when no day has a free time. */\n emptyLabel: string;\n /** The chosen slot's id (controlled). */\n value?: string | null;\n /** Called with the chosen slot's id. */\n onValueChange?: (id: string) => void;\n /** The first day shown. Default: the first of `days`. */\n defaultDay?: string;\n /** The app's link component for the times that have an `href`, and for the week buttons when `weekHref` is set. */\n linkAs?: LinkComponent;\n /** The week shown, the ISO date of its first day (`2026-10-19`; controlled). Setting it turns on ← Today →. */\n week?: string;\n /** Called with the ISO date of the week asked for (± 7 days, or `todayWeek`). The host loads that week's days. */\n onWeekChange?: (week: string) => void;\n /** The earliest week the host offers (ISO date): ← is disabled there. */\n minWeek?: string;\n /** The latest week the host offers (ISO date): → is disabled there. */\n maxWeek?: string;\n /** The current week, where « Today » goes back to. Default: `minWeek`. */\n todayWeek?: string;\n /** The week in words, formatted by the host with `@krizaka/intl` (`19 – 25 Oct`); announced politely at every change. */\n weekLabel?: string;\n /** Names of the three week buttons, translated: `{ previous: \"Previous week\", today: \"Today\", next: \"Next week\" }`. */\n weekButtons?: { previous: string; today: string; next: string };\n /** Makes the week buttons links (the address holds the state: `?week=`), given the week they go to. */\n weekHref?: (week: string) => string;\n /** The context line under the times: time zone and duration (`Montréal (UTC−4) · 45 min`), formatted by the host. */\n footer?: React.ReactNode;\n};\n\n/** The ISO date `days` days after `iso` (UTC, so a time zone never moves it). */\nconst addDays = (iso: string, days: number) => {\n const d = new Date(`${iso}T00:00:00Z`);\n d.setUTCDate(d.getUTCDate() + days);\n return d.toISOString().slice(0, 10);\n};\n\nconst focusables = (root: Element | null) => [...(root?.querySelectorAll<HTMLElement>(\"button:not(:disabled), a[href]\") ?? [])];\n/** Arrows move focus inside one list of controls (`dir` -1/+1 on the arrows that follow the reading order). */\nfunction moveFocus(e: React.KeyboardEvent<HTMLElement>, keys: { prev: string[]; next: string[] }) {\n const dir = keys.prev.includes(e.key) ? -1 : keys.next.includes(e.key) ? 1 : 0;\n if (!dir) return;\n const items = focusables(e.currentTarget);\n const at = items.indexOf(document.activeElement as HTMLElement);\n if (at < 0) return;\n e.preventDefault();\n items[(at + dir + items.length) % items.length]?.focus();\n}\n\n/** Tappable free times by day: the day strip, then the day's chips (in parts of the day if asked) — links or toggles — and, with `week`, ← Today →. */\nexport function SlotPicker({\n days,\n label,\n emptyLabel,\n value,\n onValueChange,\n defaultDay,\n linkAs,\n week,\n onWeekChange,\n minWeek,\n maxWeek,\n todayWeek,\n weekLabel,\n weekButtons,\n weekHref,\n footer,\n className,\n ...props\n}: SlotPickerProps) {\n const [dayId, setDayId] = React.useState(defaultDay ?? days[0]?.id);\n const rootRef = React.useRef<HTMLDivElement>(null);\n const refocusDays = React.useRef(false);\n const active = days.find((d) => d.id === dayId) ?? days[0];\n // After a week change from the keyboard (Page Up / Down inside the times), focus goes to the day strip, which stays.\n React.useEffect(() => {\n if (!refocusDays.current) return;\n refocusDays.current = false;\n rootRef.current?.querySelector<HTMLElement>(\"[data-day][aria-pressed=true]\")?.focus();\n }, [week]);\n\n const weeks = week !== undefined;\n const prev = weeks ? addDays(week, -7) : undefined;\n const next = weeks ? addDays(week, 7) : undefined;\n const current = todayWeek ?? minWeek;\n const prevOff = !!prev && !!minWeek && prev < minWeek;\n const nextOff = !!next && !!maxWeek && next > maxWeek;\n const todayOff = !current || current === week;\n const go = (to: string | undefined, off: boolean) => {\n if (to && !off) onWeekChange?.(to);\n };\n\n const weekButton = (kind: \"previous\" | \"today\" | \"next\", to: string | undefined, off: boolean, text: string, shown: React.ReactNode) =>\n weekHref && to && !off ? (\n <BlockLink key={kind} href={weekHref(to)} linkAs={linkAs} aria-label={text} className={s.weekBtn()}>\n {shown}\n </BlockLink>\n ) : (\n <button key={kind} type=\"button\" aria-label={text} aria-disabled={off || undefined} onClick={() => go(to, off)} className={s.weekBtn()}>\n {shown}\n </button>\n );\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n if (!weeks || (e.key !== \"PageUp\" && e.key !== \"PageDown\")) return;\n const to = e.key === \"PageUp\" ? prev : next;\n if (!to || (e.key === \"PageUp\" ? prevOff : nextOff)) return;\n e.preventDefault();\n refocusDays.current = true;\n onWeekChange?.(to);\n };\n\n const timeList = (slots: readonly PickerSlot[], name: string) => (\n <ul className={s.times()} aria-label={name} onKeyDown={(e) => moveFocus(e, { prev: [\"ArrowLeft\", \"ArrowUp\"], next: [\"ArrowRight\", \"ArrowDown\"] })}>\n {slots.map((slot) => (\n <li key={slot.id}>\n {slot.href && !slot.disabled ? (\n <BlockLink href={slot.href} linkAs={linkAs} className={s.time()}>\n {slot.label}\n {slot.note && <span className={s.note()}>{slot.note}</span>}\n </BlockLink>\n ) : (\n <button type=\"button\" aria-pressed={value === slot.id} disabled={slot.disabled} onClick={() => onValueChange?.(slot.id)} className={s.time({ className: \"group\" })}>\n {slot.label}\n {slot.note && <span className={s.note()}>{slot.note}</span>}\n </button>\n )}\n </li>\n ))}\n </ul>\n );\n\n const dayName = active ? `${active.label}${active.sub ? ` ${active.sub}` : \"\"}` : \"\";\n return (\n <div ref={rootRef} className={s.root({ className })} onKeyDown={onKeyDown} {...props}>\n {weeks && weekButtons && (\n <div className={s.weekBar()}>\n {weekLabel && (\n <p className={s.weekLabel()} role=\"status\" aria-live=\"polite\">\n {weekLabel}\n </p>\n )}\n <div className={s.weekNav()}>\n {weekButton(\"previous\", prev, prevOff, weekButtons.previous, <span aria-hidden=\"true\">←</span>)}\n {weekButton(\"today\", current, todayOff, weekButtons.today, weekButtons.today)}\n {weekButton(\"next\", next, nextOff, weekButtons.next, <span aria-hidden=\"true\">→</span>)}\n </div>\n </div>\n )}\n {!active ? (\n <p className={s.empty()}>{emptyLabel}</p>\n ) : (\n <>\n <div className={s.days()} role=\"group\" aria-label={label} onKeyDown={(e) => moveFocus(e, { prev: [\"ArrowLeft\"], next: [\"ArrowRight\"] })}>\n {days.map((day) => (\n <button key={day.id} type=\"button\" data-day=\"\" aria-pressed={day.id === active.id} onClick={() => setDayId(day.id)} className={s.day()}>\n <span className={s.dayName()}>{day.label}</span>\n {day.sub && <span className={s.daySub()}>{day.sub}</span>}\n </button>\n ))}\n </div>\n {active.groups ? (\n <ul className={s.groups()} aria-label={dayName}>\n {active.groups.map((group) => (\n <li key={group.id}>\n <p className={s.groupLabel()}>{group.label}</p>\n {timeList(group.slots, `${dayName} · ${group.label}`)}\n </li>\n ))}\n </ul>\n ) : (\n timeList(active.slots ?? [], dayName)\n )}\n </>\n )}\n {footer && <p className={s.footer()}>{footer}</p>}\n </div>\n );\n}\n"
239
+ "content": "// Client (the chosen day). The next free times of a service as tappable chips: a strip of days, then the day's times.\n// A time is a link (`href`: the booking page with the time chosen) or a toggle the reader presses (`value`,\n// `onValueChange`). The app computes the slots (its availability is the truth) and formats the labels. With `week` the\n// picker moves through the weeks (← Today →): the host loads the days of the week it is asked for, the picker never computes.\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { BlockLink, type LinkComponent } from \"../block-link\";\n\nexport const slotPicker = tv({\n slots: {\n root: \"flex min-w-0 flex-col gap-3\",\n days: \"flex gap-2 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\",\n day:\n \"flex min-h-12 min-w-[4.5rem] shrink-0 cursor-pointer flex-col items-center justify-center rounded-xl border border-border-default bg-surface-1 px-3 py-1.5 text-center leading-tight text-fg-secondary \" +\n \"transition-colors hover:border-border-strong hover:text-fg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring \" +\n \"aria-pressed:border-accent aria-pressed:bg-accent-soft aria-pressed:text-fg\",\n dayName: \"text-xs font-bold\",\n daySub: \"text-[11px] tabular-nums text-fg-muted\",\n times: \"m-0 flex list-none flex-wrap gap-2 p-0\",\n time:\n \"inline-flex min-h-11 min-w-[4.75rem] items-center justify-center gap-1.5 rounded-sm border border-border-default bg-surface-1 px-4 text-sm font-semibold tabular-nums text-fg no-underline \" +\n \"transition-colors hover:border-accent/60 hover:bg-accent-soft focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring \" +\n \"aria-pressed:border-accent aria-pressed:bg-accent aria-pressed:text-on-accent disabled:cursor-not-allowed disabled:border-dashed disabled:bg-transparent disabled:text-fg-muted disabled:line-through disabled:hover:border-border-default disabled:hover:bg-transparent\",\n note: \"text-[11px] font-medium text-fg-secondary group-aria-pressed:text-on-accent\",\n weekBar: \"flex flex-wrap items-center justify-between gap-2\",\n weekLabel: \"m-0 min-w-0 text-sm font-semibold tabular-nums text-fg\",\n weekNav: \"flex items-center gap-1.5\",\n weekBtn:\n \"inline-flex min-h-11 min-w-11 cursor-pointer items-center justify-center rounded-sm border border-border-default bg-surface-1 px-3 text-sm font-semibold text-fg no-underline \" +\n \"transition-colors hover:border-border-strong focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring aria-disabled:cursor-not-allowed aria-disabled:opacity-50\",\n groups: \"m-0 flex list-none flex-col gap-3 p-0\",\n groupLabel: \"m-0 mb-1.5 text-xs font-bold text-fg-secondary\",\n footer: \"m-0 text-xs text-fg-secondary\",\n empty: \"m-0 rounded-xl border border-dashed border-border-default px-4 py-6 text-center text-sm text-fg-secondary\",\n },\n});\nconst s = slotPicker();\n\nexport type PickerSlot = {\n /** A stable id (the slot's start as an ISO string). */\n id: string;\n /** The time in words, formatted by the app (`9 h 30`). */\n label: string;\n /** What to know about it (`2 places left`), shown beside the time and read with it. */\n note?: string;\n /** Not offered any more (full): shown struck out and disabled, its `note` (`Full`) read with the time — never colour alone. */\n disabled?: boolean;\n /** Makes the time a link to this address (the booking page with the slot chosen). */\n href?: string;\n};\n\n/** A part of a day (`Morning`, `Afternoon`): the label comes from the host's messages. */\nexport type PickerGroup = {\n id: string;\n label: string;\n slots: readonly PickerSlot[];\n};\n\nexport type PickerDay = {\n /** A stable id (`2026-10-19`). */\n id: string;\n /** The day's name, translated (`Today`, `Mon`). */\n label: string;\n /** Under it (`19 Oct`). */\n sub?: string;\n /** Its times, in order — flat… */\n slots?: readonly PickerSlot[];\n /** …or in parts of the day (`Morning`, `Afternoon`), each under its own label. Wins over `slots`. */\n groups?: readonly PickerGroup[];\n};\n\nexport type SlotPickerProps = Omit<React.ComponentProps<\"div\">, \"onChange\" | \"defaultValue\"> & {\n /** The days that have free times, in order. */\n days: readonly PickerDay[];\n /** The name of the group (`Available times`), passed translated. */\n label: string;\n /** Said when no day has a free time. */\n emptyLabel: string;\n /** The chosen slot's id (controlled). */\n value?: string | null;\n /** Called with the chosen slot's id. */\n onValueChange?: (id: string) => void;\n /** The first day shown. Default: the first of `days`. */\n defaultDay?: string;\n /** The app's link component for the times that have an `href`, and for the week buttons when `weekHref` is set. */\n linkAs?: LinkComponent;\n /** The week shown, the ISO date of its first day (`2026-10-19`; controlled). Setting it turns on ← Today →. */\n week?: string;\n /** Called with the ISO date of the week asked for (± 7 days, or `todayWeek`). The host loads that week's days. */\n onWeekChange?: (week: string) => void;\n /** The earliest week the host offers (ISO date): ← is disabled there. */\n minWeek?: string;\n /** The latest week the host offers (ISO date): → is disabled there. */\n maxWeek?: string;\n /** The current week, where « Today » goes back to. Default: `minWeek`. */\n todayWeek?: string;\n /** The week in words, formatted by the host with `@krizaka/intl` (`19 – 25 Oct`); announced politely at every change. */\n weekLabel?: string;\n /** Names of the three week buttons, translated: `{ previous: \"Previous week\", today: \"Today\", next: \"Next week\" }`. */\n weekButtons?: { previous: string; today: string; next: string };\n /** Makes the week buttons links (the address holds the state: `?week=`), given the week they go to. */\n weekHref?: (week: string) => string;\n /** The context line under the times: time zone and duration (`Montréal (UTC−4) · 45 min`), formatted by the host. */\n footer?: React.ReactNode;\n};\n\n/** The ISO date `days` days after `iso` (UTC, so a time zone never moves it). */\nconst addDays = (iso: string, days: number) => {\n const d = new Date(`${iso}T00:00:00Z`);\n d.setUTCDate(d.getUTCDate() + days);\n return d.toISOString().slice(0, 10);\n};\n\nconst focusables = (root: Element | null) => [...(root?.querySelectorAll<HTMLElement>(\"button:not(:disabled), a[href]\") ?? [])];\n/** Arrows move focus inside one list of controls (`dir` -1/+1 on the arrows that follow the reading order). */\nfunction moveFocus(e: React.KeyboardEvent<HTMLElement>, keys: { prev: string[]; next: string[] }) {\n let dir = 0;\n if (keys.prev.includes(e.key)) dir = -1;\n else if (keys.next.includes(e.key)) dir = 1;\n if (!dir) return;\n const items = focusables(e.currentTarget);\n const at = items.indexOf(document.activeElement as HTMLElement);\n if (at < 0) return;\n e.preventDefault();\n items[(at + dir + items.length) % items.length]?.focus();\n}\n\n/** Tappable free times by day: the day strip, then the day's chips (in parts of the day if asked) — links or toggles — and, with `week`, ← Today →. */\nexport function SlotPicker({\n days,\n label,\n emptyLabel,\n value,\n onValueChange,\n defaultDay,\n linkAs,\n week,\n onWeekChange,\n minWeek,\n maxWeek,\n todayWeek,\n weekLabel,\n weekButtons,\n weekHref,\n footer,\n className,\n ...props\n}: SlotPickerProps) {\n const [dayId, setDayId] = React.useState(defaultDay ?? days[0]?.id);\n const rootRef = React.useRef<HTMLDivElement>(null);\n const refocusDays = React.useRef(false);\n const active = days.find((d) => d.id === dayId) ?? days[0];\n // After a week change from the keyboard (Page Up / Down inside the times), focus goes to the day strip, which stays.\n React.useEffect(() => {\n if (!refocusDays.current) return;\n refocusDays.current = false;\n rootRef.current?.querySelector<HTMLElement>(\"[data-day][aria-pressed=true]\")?.focus();\n }, [week]);\n\n const weeks = week !== undefined;\n const prev = weeks ? addDays(week, -7) : undefined;\n const next = weeks ? addDays(week, 7) : undefined;\n const current = todayWeek ?? minWeek;\n const prevOff = !!prev && !!minWeek && prev < minWeek;\n const nextOff = !!next && !!maxWeek && next > maxWeek;\n const todayOff = !current || current === week;\n const go = (to: string | undefined, off: boolean) => {\n if (to && !off) onWeekChange?.(to);\n };\n\n const weekButton = (kind: \"previous\" | \"today\" | \"next\", to: string | undefined, off: boolean, text: string, shown: React.ReactNode) =>\n weekHref && to && !off ? (\n <BlockLink key={kind} href={weekHref(to)} linkAs={linkAs} aria-label={text} className={s.weekBtn()}>\n {shown}\n </BlockLink>\n ) : (\n <button key={kind} type=\"button\" aria-label={text} aria-disabled={off || undefined} onClick={() => go(to, off)} className={s.weekBtn()}>\n {shown}\n </button>\n );\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n if (!weeks || (e.key !== \"PageUp\" && e.key !== \"PageDown\")) return;\n const to = e.key === \"PageUp\" ? prev : next;\n if (!to || (e.key === \"PageUp\" ? prevOff : nextOff)) return;\n e.preventDefault();\n refocusDays.current = true;\n onWeekChange?.(to);\n };\n\n const timeList = (slots: readonly PickerSlot[], name: string) => (\n <ul className={s.times()} aria-label={name} onKeyDown={(e) => moveFocus(e, { prev: [\"ArrowLeft\", \"ArrowUp\"], next: [\"ArrowRight\", \"ArrowDown\"] })}>\n {slots.map((slot) => (\n <li key={slot.id}>\n {slot.href && !slot.disabled ? (\n <BlockLink href={slot.href} linkAs={linkAs} className={s.time()}>\n {slot.label}\n {slot.note && <span className={s.note()}>{slot.note}</span>}\n </BlockLink>\n ) : (\n <button type=\"button\" aria-pressed={value === slot.id} disabled={slot.disabled} onClick={() => onValueChange?.(slot.id)} className={s.time({ className: \"group\" })}>\n {slot.label}\n {slot.note && <span className={s.note()}>{slot.note}</span>}\n </button>\n )}\n </li>\n ))}\n </ul>\n );\n\n const subText = active?.sub ? ` ${active.sub}` : \"\";\n const dayName = active ? `${active.label}${subText}` : \"\";\n return (\n <div ref={rootRef} className={s.root({ className })} onKeyDown={onKeyDown} {...props}>\n {weeks && weekButtons && (\n <div className={s.weekBar()}>\n {weekLabel && (\n <p className={s.weekLabel()} role=\"status\" aria-live=\"polite\">\n {weekLabel}\n </p>\n )}\n <div className={s.weekNav()}>\n {weekButton(\"previous\", prev, prevOff, weekButtons.previous, <span aria-hidden=\"true\">←</span>)}\n {weekButton(\"today\", current, todayOff, weekButtons.today, weekButtons.today)}\n {weekButton(\"next\", next, nextOff, weekButtons.next, <span aria-hidden=\"true\">→</span>)}\n </div>\n </div>\n )}\n {!active ? (\n <p className={s.empty()}>{emptyLabel}</p>\n ) : (\n <>\n <div className={s.days()} role=\"group\" aria-label={label} onKeyDown={(e) => moveFocus(e, { prev: [\"ArrowLeft\"], next: [\"ArrowRight\"] })}>\n {days.map((day) => (\n <button key={day.id} type=\"button\" data-day=\"\" aria-pressed={day.id === active.id} onClick={() => setDayId(day.id)} className={s.day()}>\n <span className={s.dayName()}>{day.label}</span>\n {day.sub && <span className={s.daySub()}>{day.sub}</span>}\n </button>\n ))}\n </div>\n {active.groups ? (\n <ul className={s.groups()} aria-label={dayName}>\n {active.groups.map((group) => (\n <li key={group.id}>\n <p className={s.groupLabel()}>{group.label}</p>\n {timeList(group.slots, `${dayName} · ${group.label}`)}\n </li>\n ))}\n </ul>\n ) : (\n timeList(active.slots ?? [], dayName)\n )}\n </>\n )}\n {footer && <p className={s.footer()}>{footer}</p>}\n </div>\n );\n}\n"
240
240
  }
241
241
  ],
242
242
  "dependencies": [
@@ -229,7 +229,7 @@
229
229
  },
230
230
  {
231
231
  "path": "stat/stat.tsx",
232
- "content": "// Server-safe. A key figure: a label, the value in tabular digits, a hint, a trend. Every word is a prop.\nimport type * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nexport const stat = tv({\n slots: {\n root: \"flex min-w-0 flex-col gap-1\",\n label: \"text-xs font-semibold text-fg-secondary\",\n value: \"kz-stat-value font-display text-2xl font-black tabular-nums text-fg\",\n meta: \"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs\",\n // The status tokens are too light for small text on a light surface: the words stay a text role, the arrow carries\n // the direction's colour.\n trend: \"inline-flex items-center gap-1 font-semibold text-fg [&>svg]:h-3.5 [&>svg]:w-3.5 [&>svg]:shrink-0\",\n hint: \"text-fg-secondary\",\n chart: \"mt-2 h-10 w-full min-w-0\",\n },\n variants: {\n trend: {\n up: { trend: \"[&>svg]:text-success\" },\n down: { trend: \"[&>svg]:text-danger\" },\n flat: { trend: \"[&>svg]:text-fg-secondary\" },\n },\n },\n});\n\nexport type StatTrend = \"up\" | \"down\" | \"flat\";\n\nconst ARROW: Record<StatTrend, string> = { up: \"M7 17 17 7M8 7h9v9\", down: \"M7 7l10 10M17 8v9H8\", flat: \"M5 12h14M13 6l6 6-6 6\" };\n\nexport type StatProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n /** What the figure is (\"Revenue\"), above it. */\n label: React.ReactNode;\n /** The figure, formatted by the app, in tabular digits. */\n value: React.ReactNode;\n /** A line under the value: the period, the comparison. */\n hint?: React.ReactNode;\n /** The direction of the change; its arrow is decorative. */\n trend?: StatTrend;\n /** The change, in words, as read and shown (e.g. \"+12 % vs last week\") — the arrow alone says nothing. */\n trendLabel?: React.ReactNode;\n /** Under the figure: a `Sparkline` of @krizaka/charts (its own accessible summary), a `Meter`. */\n chart?: React.ReactNode;\n};\n\nexport function Stat({ label, value, hint, trend, trendLabel, chart, className, ...props }: StatProps) {\n const s = stat({ trend });\n return (\n <div data-trend={trend} className={s.root({ className })} {...props}>\n <p className={s.label()}>{label}</p>\n <p className={s.value()}>{value}</p>\n {(trendLabel || hint) && (\n <p className={s.meta()}>\n {trend && trendLabel && (\n <span className={s.trend()}>\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={ARROW[trend]} />\n </svg>\n {trendLabel}\n </span>\n )}\n {hint && <span className={s.hint()}>{hint}</span>}\n </p>\n )}\n {chart ? <div className={s.chart()}>{chart}</div> : null}\n </div>\n );\n}\n\nexport const statGrid = tv({\n base: \"grid w-full grid-cols-[repeat(auto-fit,minmax(var(--kz-stat-min,11rem),1fr))] overflow-hidden rounded-xl border border-border-default bg-surface-1\",\n variants: {\n divided: {\n true: \"gap-px bg-border-subtle [&>*]:bg-surface-1 [&>*]:p-5\",\n false: \"gap-6 p-5\",\n },\n },\n defaultVariants: { divided: true },\n});\n\nexport type StatGridCommonProps = Omit<React.ComponentProps<\"div\">, \"children\">;\n\nexport type StatGridDefaultProps = React.ComponentProps<\"div\"> & {\n /** `grid` (default): figures that wrap, hairlines between them. */\n variant?: \"grid\";\n /** Hairlines between the stats (default) or space only. */\n divided?: boolean;\n /** The narrowest a stat may be before the row wraps, in rem. Default 11. */\n minWidth?: number;\n};\n\n/** One figure of the strip. */\nexport type StatStripItem = {\n id: string;\n /** What the figure is; truncated in the strip, its full text stays the item's `title`. */\n label: string;\n value: React.ReactNode;\n trend?: StatTrend;\n /** The change in words (\"+12 % vs the previous 30 d\"). */\n trendLabel?: React.ReactNode;\n /** A `Sparkline` of @krizaka/charts (64 × 18). */\n chart?: React.ReactNode;\n};\n\nexport type StatStripProps = StatGridCommonProps & {\n /** `strip`: the discreet row, 2 to 4 figures with their sparkline, as a description list. */\n variant: \"strip\";\n /** 2 to 4 figures, in one row from 320 px. */\n items: readonly StatStripItem[];\n /** The period switch (7 · 30 · 90 d), above the row. */\n period?: React.ReactNode;\n};\n\nexport type StatGridProps = StatGridDefaultProps | StatStripProps;\n\nexport const statStrip = tv({\n slots: {\n root: \"flex w-full min-w-0 flex-col gap-2\",\n list: \"m-0 flex w-full min-w-0 divide-x divide-border-default overflow-hidden rounded-xl border border-border-default bg-surface-1\",\n item: \"flex min-w-0 flex-1 flex-col gap-0.5 px-3 py-2.5\",\n label: \"m-0 truncate text-xs font-semibold text-fg-secondary\",\n value: \"m-0 font-display text-lg font-bold tabular-nums text-fg\",\n trend: \"m-0 flex min-w-0 items-center gap-1 text-[0.6875rem] text-fg-secondary [&>svg]:h-3 [&>svg]:w-3 [&>svg]:shrink-0\",\n chart: \"m-0 h-[18px] w-16 max-w-full\",\n },\n variants: {\n trend: {\n up: { trend: \"[&>svg]:text-success\" },\n down: { trend: \"[&>svg]:text-danger\" },\n flat: {},\n },\n },\n});\n\nfunction StatStripFigure({ item }: { item: StatStripItem }) {\n const s = statStrip({ trend: item.trend });\n return (\n <div className={s.item()} data-trend={item.trend}>\n <dt className={s.label()} title={item.label}>\n {item.label}\n </dt>\n <dd className={s.value()}>{item.value}</dd>\n {item.trendLabel ? (\n <dd className={s.trend()}>\n {item.trend ? (\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={ARROW[item.trend]} />\n </svg>\n ) : null}\n <span className=\"truncate\">{item.trendLabel}</span>\n </dd>\n ) : null}\n {item.chart ? <dd className={s.chart()}>{item.chart}</dd> : null}\n </div>\n );\n}\n\nfunction StatStrip({ items, period, className, ...props }: Omit<StatStripProps, \"variant\">) {\n const s = statStrip();\n return (\n <div className={s.root({ className })} {...props}>\n {period}\n <dl className={s.list()}>\n {items.map((item) => (\n <StatStripFigure key={item.id} item={item} />\n ))}\n </dl>\n </div>\n );\n}\n\n/**\n * A row of key figures. The default grid wraps with the width (a dashboard's head, the stats are its children);\n * `variant=\"strip\"` is the discreet one: 2 to 4 figures in one row, as a `dl`, each with its sparkline and its trend in words.\n */\nexport function StatGrid(props: StatGridProps) {\n if (props.variant === \"strip\") {\n const { variant: _variant, ...rest } = props;\n return <StatStrip {...rest} />;\n }\n const { variant: _variant, divided, minWidth = 11, className, style, ...rest } = props;\n return <div className={statGrid({ divided, className })} style={{ ...style, [\"--kz-stat-min\" as string]: `${minWidth}rem` }} {...rest} />;\n}\n"
232
+ "content": "// Server-safe. A key figure: a label, the value in tabular digits, a hint, a trend. Every word is a prop.\nimport type * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nexport const stat = tv({\n slots: {\n root: \"flex min-w-0 flex-col gap-1\",\n label: \"text-xs font-semibold text-fg-secondary\",\n value: \"kz-stat-value font-display text-2xl font-black tabular-nums text-fg\",\n meta: \"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs\",\n // The status tokens are too light for small text on a light surface: the words stay a text role, the arrow carries\n // the direction's colour.\n trend: \"inline-flex items-center gap-1 font-semibold text-fg [&>svg]:h-3.5 [&>svg]:w-3.5 [&>svg]:shrink-0\",\n hint: \"text-fg-secondary\",\n chart: \"mt-2 h-10 w-full min-w-0\",\n },\n variants: {\n trend: {\n up: { trend: \"[&>svg]:text-success\" },\n down: { trend: \"[&>svg]:text-danger\" },\n flat: { trend: \"[&>svg]:text-fg-secondary\" },\n },\n },\n});\n\nexport type StatTrend = \"up\" | \"down\" | \"flat\";\n\nconst ARROW: Record<StatTrend, string> = { up: \"M7 17 17 7M8 7h9v9\", down: \"M7 7l10 10M17 8v9H8\", flat: \"M5 12h14M13 6l6 6-6 6\" };\n\nexport type StatProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n /** What the figure is (\"Revenue\"), above it. */\n label: React.ReactNode;\n /** The figure, formatted by the app, in tabular digits. */\n value: React.ReactNode;\n /** A line under the value: the period, the comparison. */\n hint?: React.ReactNode;\n /** The direction of the change; its arrow is decorative. */\n trend?: StatTrend;\n /** The change, in words, as read and shown (e.g. \"+12 % vs last week\") — the arrow alone says nothing. */\n trendLabel?: React.ReactNode;\n /** Under the figure: a `Sparkline` of @krizaka/charts (its own accessible summary), a `Meter`. */\n chart?: React.ReactNode;\n};\n\nexport function Stat({ label, value, hint, trend, trendLabel, chart, className, ...props }: StatProps) {\n const s = stat({ trend });\n return (\n <div data-trend={trend} className={s.root({ className })} {...props}>\n <p className={s.label()}>{label}</p>\n <p className={s.value()}>{value}</p>\n {(trendLabel || hint) && (\n <p className={s.meta()}>\n {trend && trendLabel && (\n <span className={s.trend()}>\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={ARROW[trend]} />\n </svg>\n {trendLabel}\n </span>\n )}\n {hint && <span className={s.hint()}>{hint}</span>}\n </p>\n )}\n {chart ? <div className={s.chart()}>{chart}</div> : null}\n </div>\n );\n}\n\nexport const statGrid = tv({\n base: \"grid w-full grid-cols-[repeat(auto-fit,minmax(var(--kz-stat-min,11rem),1fr))] overflow-hidden rounded-xl border border-border-default bg-surface-1\",\n variants: {\n divided: {\n true: \"gap-px bg-border-subtle [&>*]:bg-surface-1 [&>*]:p-5\",\n false: \"gap-6 p-5\",\n },\n },\n defaultVariants: { divided: true },\n});\n\nexport type StatGridCommonProps = Omit<React.ComponentProps<\"div\">, \"children\">;\n\nexport type StatGridDefaultProps = React.ComponentProps<\"div\"> & {\n /** `grid` (default): figures that wrap, hairlines between them. */\n variant?: \"grid\";\n /** Hairlines between the stats (default) or space only. */\n divided?: boolean;\n /** The narrowest a stat may be before the row wraps, in rem. Default 11. */\n minWidth?: number;\n};\n\n/** One figure of the strip. */\nexport type StatStripItem = {\n id: string;\n /** What the figure is; truncated in the strip, its full text stays the item's `title`. */\n label: string;\n value: React.ReactNode;\n trend?: StatTrend;\n /** The change in words (\"+12 % vs the previous 30 d\"). */\n trendLabel?: React.ReactNode;\n /** A `Sparkline` of @krizaka/charts (64 × 18). */\n chart?: React.ReactNode;\n};\n\nexport type StatStripProps = StatGridCommonProps & {\n /** `strip`: the discreet row, 2 to 4 figures with their sparkline, as a description list. */\n variant: \"strip\";\n /** 2 to 4 figures, in one row from 320 px. */\n items: readonly StatStripItem[];\n /** The period switch (7 · 30 · 90 d), above the row. */\n period?: React.ReactNode;\n};\n\nexport type StatGridProps = StatGridDefaultProps | StatStripProps;\n\nexport const statStrip = tv({\n slots: {\n root: \"flex w-full min-w-0 flex-col gap-2\",\n list: \"m-0 flex w-full min-w-0 divide-x divide-border-default overflow-hidden rounded-xl border border-border-default bg-surface-1\",\n item: \"flex min-w-0 flex-1 flex-col gap-0.5 px-3 py-2.5\",\n label: \"m-0 truncate text-xs font-semibold text-fg-secondary\",\n value: \"m-0 font-display text-lg font-bold tabular-nums text-fg\",\n trend: \"m-0 flex min-w-0 items-center gap-1 text-[0.6875rem] text-fg-secondary [&>svg]:h-3 [&>svg]:w-3 [&>svg]:shrink-0\",\n chart: \"m-0 h-[18px] w-16 max-w-full\",\n },\n variants: {\n trend: {\n up: { trend: \"[&>svg]:text-success\" },\n down: { trend: \"[&>svg]:text-danger\" },\n flat: {},\n },\n },\n});\n\nfunction StatStripFigure({ item }: Readonly<{ item: StatStripItem }>) {\n const s = statStrip({ trend: item.trend });\n return (\n <div className={s.item()} data-trend={item.trend}>\n <dt className={s.label()} title={item.label}>\n {item.label}\n </dt>\n <dd className={s.value()}>{item.value}</dd>\n {item.trendLabel ? (\n <dd className={s.trend()}>\n {item.trend ? (\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={ARROW[item.trend]} />\n </svg>\n ) : null}\n <span className=\"truncate\">{item.trendLabel}</span>\n </dd>\n ) : null}\n {item.chart ? <dd className={s.chart()}>{item.chart}</dd> : null}\n </div>\n );\n}\n\nfunction StatStrip({ items, period, className, ...props }: Omit<StatStripProps, \"variant\">) {\n const s = statStrip();\n return (\n <div className={s.root({ className })} {...props}>\n {period}\n <dl className={s.list()}>\n {items.map((item) => (\n <StatStripFigure key={item.id} item={item} />\n ))}\n </dl>\n </div>\n );\n}\n\n/**\n * A row of key figures. The default grid wraps with the width (a dashboard's head, the stats are its children);\n * `variant=\"strip\"` is the discreet one: 2 to 4 figures in one row, as a `dl`, each with its sparkline and its trend in words.\n */\nexport function StatGrid(props: StatGridProps) {\n if (props.variant === \"strip\") {\n const { variant: _variant, ...rest } = props;\n return <StatStrip {...rest} />;\n }\n const { variant: _variant, divided, minWidth = 11, className, style, ...rest } = props;\n return <div className={statGrid({ divided, className })} style={{ ...style, [\"--kz-stat-min\" as string]: `${minWidth}rem` }} {...rest} />;\n}\n"
233
233
  }
234
234
  ],
235
235
  "dependencies": [
@@ -269,7 +269,7 @@
269
269
  },
270
270
  {
271
271
  "path": "status-chip/status-chip.tsx",
272
- "content": "// Client (a Radix menu). A state of a status set (krizaka-ts#89, `@krizaka/organize`): the set says the states (label in\n// both languages, tone, final) and the transitions (who may move, whether a second press confirms, which reasons may be\n// picked). Read-only when the set is derived (an invoice's « paid » comes from the ledger), when no move is allowed to\n// the role, or when nobody listens (`onMove`); otherwise a menu of the moves the role may make, in the set's order. A\n// reason is picked from a list, never typed. The tone is a tint and a dot: the label always says the state.\nimport { movesFrom, stateOf,type StatusSet, type StatusTone, type StatusTransition } from \"@krizaka/organize/contract\";\nimport { DropdownMenu as MenuPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\n\nimport { badgeVariants } from \"../badge\";\nimport { cn } from \"../cn\";\nimport { DropdownMenu } from \"../dropdown-menu\";\nimport { ChevronGlyph } from \"../glyphs\";\n\nexport type { StatusSet, StatusTone, StatusTransition };\n\nexport type StatusMove = {\n /** The transition the person chose. */\n transition: StatusTransition;\n /** The key of the reason picked from the transition's list, or null when it has none. */\n reason: string | null;\n};\n\nexport type StatusChipLabels = {\n /** The menu's accessible name: `(state) => \"Change the status, now \" + state`. */\n menu: (state: string) => string;\n /** The item that waits for a second press: `(target) => \"Confirm: \" + target`. */\n confirm: (target: string) => string;\n /** The submenu that asks for a reason: `(target) => target + \" — pick a reason\"`. */\n reason: (target: string) => string;\n};\n\nconst defaultLabels: StatusChipLabels = {\n menu: (state) => `Change the status, now ${state}`,\n confirm: (target) => `Confirm: ${target}`,\n reason: (target) => `${target} — pick a reason`,\n};\n\nexport type StatusChipProps = {\n /** The kind's status set (`KindConfig.status`). */\n set: StatusSet;\n /** The key of the entity's state. */\n state: string;\n /** The role of the person: the moves are the ones this role may make. */\n role: string;\n /** The language the labels are read in. */\n locale: \"fr\" | \"en\";\n /** Called when a move is chosen (confirmed, with its reason when it asks for one). Without it the chip is read-only. */\n onMove?: (move: StatusMove) => void;\n /** The words of the menu, passed translated. */\n labels?: Partial<StatusChipLabels>;\n /**\n * sm · md.\n * @default \"sm\"\n */\n size?: \"sm\" | \"md\";\n /** Classes merged on the badge. */\n className?: string;\n};\n\n/** The state of a status set as a badge; a menu of the allowed moves when the set, the role and `onMove` allow it. */\nexport function StatusChip({ set, state, role, locale, onMove, labels: given, size = \"sm\", className }: StatusChipProps) {\n const labels = { ...defaultLabels, ...given };\n const current = stateOf(set, state);\n const text = current ? current.label[locale] : state;\n const tone = current?.tone ?? \"neutral\";\n const moves = onMove && set.mode === \"editable\" ? movesFrom(set, state, role) : [];\n const [armed, setArmed] = React.useState<string | null>(null);\n const [open, setOpen] = React.useState(false);\n const label = (key: string) => stateOf(set, key)?.label[locale] ?? key;\n\n if (moves.length === 0) {\n return (\n <span data-status={state} data-tone={tone} className={badgeVariants({ tone, size, className })}>\n <span data-dot=\"\" aria-hidden className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n {text}\n </span>\n );\n }\n\n const choose = (move: StatusTransition, reason: string | null) => {\n setArmed(null);\n setOpen(false);\n onMove?.({ transition: move, reason });\n };\n\n return (\n <MenuPrimitive.Root\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) setArmed(null);\n }}\n modal={false}\n >\n <MenuPrimitive.Trigger\n aria-label={labels.menu(text)}\n data-status={state}\n data-tone={tone}\n className={cn(\n badgeVariants({ tone, size }),\n \"cursor-pointer transition-colors hover:brightness-110 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\",\n className,\n )}\n >\n <span data-dot=\"\" aria-hidden className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n {text}\n <ChevronGlyph className=\"-mr-0.5 h-3.5 w-3.5\" />\n </MenuPrimitive.Trigger>\n <DropdownMenu.Content align=\"start\" aria-label={labels.menu(text)}>\n {moves.map((move) => {\n const target = label(move.to);\n const reasons = move.reasons ?? [];\n if (reasons.length > 0) {\n return (\n <DropdownMenu.Sub key={move.to}>\n <DropdownMenu.SubTrigger aria-label={labels.reason(target)}>{target}</DropdownMenu.SubTrigger>\n <DropdownMenu.SubContent>\n {reasons.map((reason) => (\n <DropdownMenu.Item key={reason.key} onSelect={() => choose(move, reason.key)}>\n {reason.label[locale]}\n </DropdownMenu.Item>\n ))}\n </DropdownMenu.SubContent>\n </DropdownMenu.Sub>\n );\n }\n const waiting = move.confirm && armed === move.to;\n return (\n <DropdownMenu.Item\n key={move.to}\n data-armed={waiting ? \"\" : undefined}\n className={waiting ? \"font-semibold text-fg-accent\" : undefined}\n onSelect={(event) => {\n if (move.confirm && !waiting) {\n // The first press asks, the second one moves: the menu stays open and says so.\n event.preventDefault();\n setArmed(move.to);\n return;\n }\n choose(move, null);\n }}\n >\n <span aria-live=\"polite\">{waiting ? labels.confirm(target) : target}</span>\n </DropdownMenu.Item>\n );\n })}\n </DropdownMenu.Content>\n </MenuPrimitive.Root>\n );\n}\n"
272
+ "content": "// Client (a Radix menu). A state of a status set (krizaka-ts#89, `@krizaka/organize`): the set says the states (label in\n// both languages, tone, final) and the transitions (who may move, whether a second press confirms, which reasons may be\n// picked). Read-only when the set is derived (an invoice's « paid » comes from the ledger), when no move is allowed to\n// the role, or when nobody listens (`onMove`); otherwise a menu of the moves the role may make, in the set's order. A\n// reason is picked from a list, never typed. The tone is a tint and a dot: the label always says the state.\nimport { movesFrom, stateOf, type StatusSet, type StatusTransition } from \"@krizaka/organize/contract\";\nimport { DropdownMenu as MenuPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\n\nimport { badgeVariants } from \"../badge\";\nimport { cn } from \"../cn\";\nimport { DropdownMenu } from \"../dropdown-menu\";\nimport { ChevronGlyph } from \"../glyphs\";\n\nexport type { StatusSet, StatusTransition };\nexport type { StatusTone } from \"@krizaka/organize/contract\";\n\nexport type StatusMove = {\n /** The transition the person chose. */\n transition: StatusTransition;\n /** The key of the reason picked from the transition's list, or null when it has none. */\n reason: string | null;\n};\n\nexport type StatusChipLabels = {\n /** The menu's accessible name: `(state) => \"Change the status, now \" + state`. */\n menu: (state: string) => string;\n /** The item that waits for a second press: `(target) => \"Confirm: \" + target`. */\n confirm: (target: string) => string;\n /** The submenu that asks for a reason: `(target) => target + \" — pick a reason\"`. */\n reason: (target: string) => string;\n};\n\nconst defaultLabels: StatusChipLabels = {\n menu: (state) => `Change the status, now ${state}`,\n confirm: (target) => `Confirm: ${target}`,\n reason: (target) => `${target} — pick a reason`,\n};\n\nexport type StatusChipProps = {\n /** The kind's status set (`KindConfig.status`). */\n set: StatusSet;\n /** The key of the entity's state. */\n state: string;\n /** The role of the person: the moves are the ones this role may make. */\n role: string;\n /** The language the labels are read in. */\n locale: \"fr\" | \"en\";\n /** Called when a move is chosen (confirmed, with its reason when it asks for one). Without it the chip is read-only. */\n onMove?: (move: StatusMove) => void;\n /** The words of the menu, passed translated. */\n labels?: Partial<StatusChipLabels>;\n /**\n * sm · md.\n * @default \"sm\"\n */\n size?: \"sm\" | \"md\";\n /** Classes merged on the badge. */\n className?: string;\n};\n\n/** The state of a status set as a badge; a menu of the allowed moves when the set, the role and `onMove` allow it. */\nexport function StatusChip({ set, state, role, locale, onMove, labels: given, size = \"sm\", className }: Readonly<StatusChipProps>) {\n const labels = { ...defaultLabels, ...given };\n const current = stateOf(set, state);\n const text = current ? current.label[locale] : state;\n const tone = current?.tone ?? \"neutral\";\n const moves = onMove && set.mode === \"editable\" ? movesFrom(set, state, role) : [];\n const [armed, setArmed] = React.useState<string | null>(null);\n const [open, setOpen] = React.useState(false);\n const label = (key: string) => stateOf(set, key)?.label[locale] ?? key;\n\n if (moves.length === 0) {\n return (\n <span data-status={state} data-tone={tone} className={badgeVariants({ tone, size, className })}>\n <span data-dot=\"\" aria-hidden className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n {text}\n </span>\n );\n }\n\n const choose = (move: StatusTransition, reason: string | null) => {\n setArmed(null);\n setOpen(false);\n onMove?.({ transition: move, reason });\n };\n\n return (\n <MenuPrimitive.Root\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) setArmed(null);\n }}\n modal={false}\n >\n <MenuPrimitive.Trigger\n aria-label={labels.menu(text)}\n data-status={state}\n data-tone={tone}\n className={cn(\n badgeVariants({ tone, size }),\n \"cursor-pointer transition-colors hover:brightness-110 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\",\n className,\n )}\n >\n <span data-dot=\"\" aria-hidden className=\"h-1.5 w-1.5 rounded-full bg-current\" />\n {text}\n <ChevronGlyph className=\"-mr-0.5 h-3.5 w-3.5\" />\n </MenuPrimitive.Trigger>\n <DropdownMenu.Content align=\"start\" aria-label={labels.menu(text)}>\n {moves.map((move) => {\n const target = label(move.to);\n const reasons = move.reasons ?? [];\n if (reasons.length > 0) {\n return (\n <DropdownMenu.Sub key={move.to}>\n <DropdownMenu.SubTrigger aria-label={labels.reason(target)}>{target}</DropdownMenu.SubTrigger>\n <DropdownMenu.SubContent>\n {reasons.map((reason) => (\n <DropdownMenu.Item key={reason.key} onSelect={() => choose(move, reason.key)}>\n {reason.label[locale]}\n </DropdownMenu.Item>\n ))}\n </DropdownMenu.SubContent>\n </DropdownMenu.Sub>\n );\n }\n const waiting = move.confirm && armed === move.to;\n return (\n <DropdownMenu.Item\n key={move.to}\n data-armed={waiting ? \"\" : undefined}\n className={waiting ? \"font-semibold text-fg-accent\" : undefined}\n onSelect={(event) => {\n if (move.confirm && !waiting) {\n // The first press asks, the second one moves: the menu stays open and says so.\n event.preventDefault();\n setArmed(move.to);\n return;\n }\n choose(move, null);\n }}\n >\n <span aria-live=\"polite\">{waiting ? labels.confirm(target) : target}</span>\n </DropdownMenu.Item>\n );\n })}\n </DropdownMenu.Content>\n </MenuPrimitive.Root>\n );\n}\n"
273
273
  }
274
274
  ],
275
275
  "dependencies": [
@@ -390,7 +390,7 @@
390
390
  },
391
391
  {
392
392
  "path": "tabs/tabs.tsx",
393
- "content": "// Client (a context). Radix Tabs does the roles (tablist, tab, tabpanel), the aria-selected / aria-controls wiring,\n// the roving focus (arrows, Home, End) and automatic activation: this file only holds the three looks.\nimport { Slot, Tabs as TabsPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\nimport { tv, type VariantProps } from \"tailwind-variants\";\n\nimport { cn } from \"../cn\";\nimport { useRouteBinding } from \"../router\";\nimport { useSlidingIndicator } from \"../sliding-indicator\";\n\nexport const tabs = tv({\n slots: {\n root: \"flex gap-4 data-[orientation=horizontal]:flex-col data-[orientation=vertical]:flex-row\",\n // One light glides from the active tab to the next (`before:`, placed by useSlidingIndicator); until it is placed\n // (server render), each trigger carries its own active style.\n list:\n \"group/tabs relative isolate flex shrink-0 data-[orientation=vertical]:flex-col \" +\n \"before:pointer-events-none before:absolute before:-z-10 before:opacity-0 before:transition-[translate,width,height,opacity] before:duration-300 \" +\n \"motion-reduce:before:transition-none data-[indicator=on]:before:opacity-100\",\n trigger:\n \"inline-flex shrink-0 select-none items-center justify-center gap-2 whitespace-nowrap font-semibold transition-colors \" +\n \"focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40\",\n content: \"kz-tabs-panel min-w-0 flex-1 rounded-lg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-[state=inactive]:hidden\",\n },\n variants: {\n variant: {\n /* The section of a page: a line under the list, the active tab underlined in the accent. */\n underline: {\n list:\n \"gap-1 border-border-default data-[orientation=horizontal]:border-b data-[orientation=vertical]:border-r before:rounded-sm before:bg-accent \" +\n \"data-[orientation=horizontal]:before:-bottom-px data-[orientation=horizontal]:before:left-0 data-[orientation=horizontal]:before:h-0.5 \" +\n \"data-[orientation=horizontal]:before:w-(--kz-ind-w) data-[orientation=horizontal]:before:translate-x-(--kz-ind-x) \" +\n \"data-[orientation=vertical]:before:-right-px data-[orientation=vertical]:before:top-0 data-[orientation=vertical]:before:w-0.5 \" +\n \"data-[orientation=vertical]:before:h-(--kz-ind-h) data-[orientation=vertical]:before:translate-y-(--kz-ind-y)\",\n trigger:\n \"relative rounded-md px-3 py-2.5 text-sm text-fg-secondary hover:text-fg data-[state=active]:text-fg \" +\n \"after:absolute after:rounded-sm after:bg-transparent data-[state=active]:after:bg-accent \" +\n \"data-[orientation=horizontal]:after:inset-x-2 data-[orientation=horizontal]:after:-bottom-px data-[orientation=horizontal]:after:h-0.5 \" +\n \"data-[orientation=vertical]:justify-start data-[orientation=vertical]:after:inset-y-1.5 data-[orientation=vertical]:after:-right-px data-[orientation=vertical]:after:w-0.5 \" +\n \"group-data-[indicator=on]/tabs:data-[state=active]:after:bg-transparent\",\n },\n /* A view switch: equal segments in a track, the active one filled. */\n segmented: {\n list:\n \"inline-grid auto-cols-fr grid-flow-col gap-1 self-start rounded-xl border border-border-default bg-surface-1 p-1 data-[orientation=vertical]:grid-flow-row \" +\n \"before:left-0 before:top-0 before:h-(--kz-ind-h) before:w-(--kz-ind-w) before:translate-x-(--kz-ind-x) before:translate-y-(--kz-ind-y) before:rounded-lg before:bg-accent before:shadow-sm\",\n trigger:\n \"min-h-8 rounded-lg px-3 py-1.5 text-xs text-fg-secondary hover:bg-surface-2 hover:text-fg \" +\n \"data-[state=active]:bg-accent data-[state=active]:text-on-accent data-[state=active]:shadow-sm data-[state=active]:hover:bg-accent \" +\n \"transition-colors group-data-[indicator=on]/tabs:data-[state=active]:bg-transparent group-data-[indicator=on]/tabs:data-[state=active]:shadow-none\",\n },\n /* Pills that scroll sideways on a phone: a feed's sections. */\n pills: {\n list:\n \"gap-1.5 overflow-x-auto overflow-y-hidden overscroll-x-contain pt-1 -mt-1 pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden \" +\n \"before:left-0 before:top-0 before:h-(--kz-ind-h) before:w-(--kz-ind-w) before:translate-x-(--kz-ind-x) before:translate-y-(--kz-ind-y) \" +\n \"before:rounded-sm before:border before:border-accent before:bg-accent-soft\",\n trigger:\n \"h-9 rounded-sm border border-border-default bg-surface-1 px-4 text-xs text-fg-secondary hover:border-border-strong hover:text-fg \" +\n \"data-[state=active]:border-accent data-[state=active]:bg-accent-soft data-[state=active]:text-fg \" +\n \"group-data-[indicator=on]/tabs:data-[state=active]:border-transparent group-data-[indicator=on]/tabs:data-[state=active]:bg-transparent\",\n },\n /*\n * Binder dividers (intercalaires, #648): organise collections, tags and statuses. Each tab is a divider with a\n * coloured top edge (`hue`), its words and a count; the active one is the page's colour and joins the content\n * under the list's line. Too many dividers scroll sideways, the edges fading. No paper texture: organisation only.\n */\n binder: {\n list:\n \"items-end gap-1 overflow-x-auto overflow-y-hidden overscroll-x-contain border-b border-border-default px-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden \" +\n \"[mask-image:linear-gradient(to_right,transparent,black_12px,black_calc(100%-12px),transparent)]\",\n trigger:\n \"relative -mb-px min-h-10 rounded-t-lg border border-b-0 border-border-default bg-surface-2 px-3.5 pb-2 pt-2.5 text-sm text-fg-secondary \" +\n \"before:absolute before:inset-x-0 before:-top-px before:h-1 before:rounded-t-lg before:bg-(--kz-hue,var(--kz-accent)) \" +\n \"hover:bg-surface-3 hover:text-fg data-[state=active]:z-[1] data-[state=active]:bg-surface-1 data-[state=active]:pb-2.5 data-[state=active]:text-fg \" +\n \"data-[state=active]:shadow-[0_1px_0_0_var(--kz-surface-1)] motion-reduce:transition-none\",\n },\n },\n },\n defaultVariants: { variant: \"underline\" },\n});\n\n/**\n * A divider's colour (`variant=\"binder\"`): the brand's accent by default, or a role of the theme — every one reads at 3:1 or\n * more on both themes. The colour is never the only signal: the words and the count say it.\n */\nexport type TabsHue = \"accent\" | \"success\" | \"warning\" | \"danger\" | \"neutral\";\n// The text roles where the fill role is too light on a light page (success, warning: 2:1): every edge reaches 3:1, tested.\nconst HUE: Record<TabsHue, string> = {\n accent: \"var(--kz-accent)\",\n success: \"var(--kz-success-text)\",\n warning: \"var(--kz-warning-text)\",\n danger: \"var(--kz-danger-text)\",\n neutral: \"var(--kz-text-muted)\",\n};\n/** The style that paints a divider's edge (`--kz-hue`), merged with the host's. */\nconst hueStyle = (hue: TabsHue | undefined, style: React.CSSProperties | undefined) =>\n hue ? { ...style, [\"--kz-hue\" as string]: HUE[hue] } : style;\n\n/** The count after a tab's words: part of its name (« Clients 12 »), muted, tabular. */\nfunction TabCount({ count }: { count: number | undefined }) {\n if (count === undefined) return null;\n return <span data-tab-count=\"\" className=\"font-mono text-xs font-medium tabular-nums text-fg-secondary\">{count}</span>;\n}\n\n/** « + Intercalaire »: a button after the dividers (outside the tab list: a tablist holds only tabs). */\nfunction AddButton({ add }: { add: TabsAdd }) {\n return (\n <button\n type=\"button\"\n onClick={add.onAdd}\n className=\"mb-1 ml-1 inline-flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-2.5 text-sm font-medium text-fg-secondary hover:bg-surface-2 hover:text-fg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden focusable=\"false\">\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n {add.label}\n </button>\n );\n}\n\nexport type TabsAdd = {\n /** Its words (« Intercalaire », « New tag ») — passed translated. */\n label: string;\n /** Adds a divider (opens the host's form). */\n onAdd: () => void;\n};\n\nexport type TabsVariants = VariantProps<typeof tabs>;\ntype Variant = NonNullable<TabsVariants[\"variant\"]>;\n\nconst VariantContext = React.createContext<Variant>(\"underline\");\n\nexport type TabsRootProps = React.ComponentProps<typeof TabsPrimitive.Root> & {\n /** underline (the sections of a page) · segmented (a view switch) · pills (a feed's sections) · binder (dividers that organise collections, tags, statuses). */\n variant?: TabsVariants[\"variant\"];\n /** Binds the active tab to this search parameter of the URL (`?tab=…`): the URL is the state. Without it the state is local — only for an ephemeral choice. */\n routeKey?: string;\n /** The values the parameter may hold (the tabs' `value`s); the first is the default unless `defaultValue` says otherwise. */\n routeValues?: readonly string[];\n};\n\n/** `value`/`defaultValue` + `onValueChange`, `orientation` (horizontal by default), `variant` for the list. */\nexport function TabsRoot({ variant = \"underline\", className, routeKey, routeValues, ...rest }: TabsRootProps) {\n const props = useRouteBinding(routeKey, routeValues, rest);\n return (\n <VariantContext.Provider value={variant}>\n <TabsPrimitive.Root data-variant={variant} className={tabs({ variant }).root({ className })} {...props} />\n </VariantContext.Provider>\n );\n}\n\nexport type TabsListProps = React.ComponentProps<typeof TabsPrimitive.List> & {\n /** A « + » button after the tabs (`variant=\"binder\"`: « + Intercalaire »): its words and what it does. */\n add?: TabsAdd;\n};\n\n/** The tabs. Name it (`aria-label`) when no heading says what it switches. One light glides to the active tab. */\nexport function TabsList({ className, add, ...props }: TabsListProps) {\n const variant = React.useContext(VariantContext);\n const { ref } = useSlidingIndicator<HTMLDivElement>({ item: \"[role=tab]\", active: \"[role=tab][data-state=active]\" });\n const list = <TabsPrimitive.List ref={ref} data-variant={variant} className={tabs({ variant }).list({ className: cn(add && \"min-w-0 flex-1 border-b-0\", className) })} {...props} />;\n if (!add) return list;\n return (\n <div data-tabs-row=\"\" className={cn(\"flex min-w-0 items-end\", variant === \"binder\" && \"border-b border-border-default\")}>\n {list}\n <AddButton add={add} />\n </div>\n );\n}\n\nexport type TabsTriggerProps = React.ComponentProps<typeof TabsPrimitive.Trigger> & {\n /** A count after the words (clients in a collection, unread): part of the tab's name. */\n count?: number;\n /** `variant=\"binder\"`: the divider's colour (the accent by default). */\n hue?: TabsHue;\n};\n\nexport function TabsTrigger({ className, count, hue, style, children, ...props }: TabsTriggerProps) {\n const variant = React.useContext(VariantContext);\n return (\n <TabsPrimitive.Trigger className={tabs({ variant }).trigger({ className })} style={hueStyle(hue, style)} data-hue={hue} {...props}>\n {children}\n <TabCount count={count} />\n </TabsPrimitive.Trigger>\n );\n}\n\nexport function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return <TabsPrimitive.Content className={tabs().content({ className })} {...props} />;\n}\n\n// ── Route mode: tabs that are links; the URL is the state (Oussama, 2026-10-22) ──────────────────────────────────────\n\n/**\n * Is the link `href` the tab of the route `current` (a path, with its search: `/docs/api?tab=x`)? The path must equal the\n * link's (a trailing slash, a locale-free comparison and the hash do not count); with `exact` false (the default) a deeper\n * path of the same section counts too (`/docs/api/x` is in `/docs/api`); every search parameter of the link must be in\n * `current`. The hub link (`/`) is only ever active on `/` itself.\n */\nexport function isTabActive(current: string, href: string, exact = false): boolean {\n const split = (value: string) => {\n const url = new URL(value.split(\"#\")[0]!, \"https://tabs.invalid\");\n return { path: url.pathname.replace(/\\/+$/, \"\") || \"/\", search: url.searchParams };\n };\n const here = split(current);\n const target = split(href);\n const samePath = here.path === target.path;\n const deeper = !exact && target.path !== \"/\" && here.path.startsWith(`${target.path}/`);\n if (!samePath && !deeper) return false;\n for (const [key, value] of target.search) if (here.search.get(key) !== value) return false;\n return true;\n}\n\ninterface NavState {\n current: string;\n variant: Variant;\n}\nconst NavContext = React.createContext<NavState | null>(null);\n\nexport type TabsNavProps = Omit<React.ComponentProps<\"nav\">, \"children\"> & {\n /** A « + » button after the tabs (`variant=\"binder\"`: « + Intercalaire »). */\n add?: TabsAdd;\n /** The navigation's accessible name (« Sections »). */\n label: string;\n /** The current route, passed in: the path with its search (`usePathname()` + `useSearchParams()`, `/docs?tab=api`). The active tab comes from it; no local state. */\n current: string;\n /** underline (the sections of a page) · segmented (a view switch) · pills (a feed's sections) · binder (dividers). */\n variant?: TabsVariants[\"variant\"];\n /** The tabs: `Tabs.NavLink`. */\n children: React.ReactNode;\n};\n\n/**\n * Tabs as routes: a `nav` of links, the URL is the state. Per WAI-ARIA these are links, not a tablist: each tab is an\n * anchor, the active one carries `aria-current=\"page\"`, the keyboard is the page's own (Tab walks the links, Enter\n * follows one) and there is no panel — the page is the panel. The same looks and the same gliding light as `Tabs.List`.\n */\nexport function TabsNav({ label, current, variant = \"underline\", add, className, children, ...props }: TabsNavProps) {\n const { ref } = useSlidingIndicator<HTMLElement>({ item: \"[data-tabs-link]\", active: \"[data-tabs-link][data-state=active]\" });\n const value = React.useMemo(() => ({ current, variant }), [current, variant]);\n const nav = (\n <nav ref={ref} aria-label={label} data-variant={variant} data-orientation=\"horizontal\" className={tabs({ variant }).list({ className: cn(add && \"min-w-0 flex-1 border-b-0\", className) })} {...props}>\n {children}\n </nav>\n );\n return (\n <NavContext.Provider value={value}>\n {add ? (\n <div data-tabs-row=\"\" className={cn(\"flex min-w-0 items-end\", variant === \"binder\" && \"border-b border-border-default\")}>\n {nav}\n <AddButton add={add} />\n </div>\n ) : (\n nav\n )}\n </NavContext.Provider>\n );\n}\n\nexport type TabsNavLinkProps = React.ComponentProps<\"a\"> & {\n /** Where the tab goes (`/docs/api`, `/docs?tab=api`). */\n href: string;\n /** Match this path only, not the pages below it. */\n exact?: boolean;\n /** Renders your router's `<Link>` (pass it as the only child; the `href` goes on this part and on the link). */\n asChild?: boolean;\n /** A count after the words (not with `asChild`: put it in your link). */\n count?: number;\n /** `variant=\"binder\"`: the divider's colour (the accent by default). */\n hue?: TabsHue;\n};\n\n/** One tab of `Tabs.Nav`: an anchor that is active when the current route is its `href`. */\nexport function TabsNavLink({ href, exact, asChild, count, hue, style, className, children, ...props }: TabsNavLinkProps) {\n const ctx = React.useContext(NavContext);\n if (!ctx) throw new Error(\"Tabs.NavLink must be inside <Tabs.Nav>\");\n const active = isTabActive(ctx.current, href, exact);\n const Comp = asChild ? Slot.Root : \"a\";\n return (\n <Comp\n data-tabs-link=\"\"\n data-state={active ? \"active\" : \"inactive\"}\n data-orientation=\"horizontal\"\n aria-current={active ? \"page\" : undefined}\n {...(asChild ? {} : { href })}\n data-hue={hue}\n style={hueStyle(hue, style)}\n className={cn(tabs({ variant: ctx.variant }).trigger(), \"no-underline\", className)}\n {...props}\n >\n {asChild ? (\n children\n ) : (\n <>\n {children}\n <TabCount count={count} />\n </>\n )}\n </Comp>\n );\n}\n\n/** `Tabs.Root/List/Trigger/Content` — `variant` underline · segmented · pills · binder on the root. `Tabs.Nav` + `Tabs.NavLink`: the same tabs as routes. */\nexport const Tabs = { Root: TabsRoot, List: TabsList, Trigger: TabsTrigger, Content: TabsContent, Nav: TabsNav, NavLink: TabsNavLink };\n"
393
+ "content": "// Client (a context). Radix Tabs does the roles (tablist, tab, tabpanel), the aria-selected / aria-controls wiring,\n// the roving focus (arrows, Home, End) and automatic activation: this file only holds the three looks.\nimport { Slot, Tabs as TabsPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\nimport { tv, type VariantProps } from \"tailwind-variants\";\n\nimport { cn } from \"../cn\";\nimport { useRouteBinding } from \"../router\";\nimport { useSlidingIndicator } from \"../sliding-indicator\";\n\nexport const tabs = tv({\n slots: {\n root: \"flex gap-4 data-[orientation=horizontal]:flex-col data-[orientation=vertical]:flex-row\",\n // One light glides from the active tab to the next (`before:`, placed by useSlidingIndicator); until it is placed\n // (server render), each trigger carries its own active style.\n list:\n \"group/tabs relative isolate flex shrink-0 data-[orientation=vertical]:flex-col \" +\n \"before:pointer-events-none before:absolute before:-z-10 before:opacity-0 before:transition-[translate,width,height,opacity] before:duration-300 \" +\n \"motion-reduce:before:transition-none data-[indicator=on]:before:opacity-100\",\n trigger:\n \"inline-flex shrink-0 select-none items-center justify-center gap-2 whitespace-nowrap font-semibold transition-colors \" +\n \"focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40\",\n content: \"kz-tabs-panel min-w-0 flex-1 rounded-lg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-[state=inactive]:hidden\",\n },\n variants: {\n variant: {\n /* The section of a page: a line under the list, the active tab underlined in the accent. */\n underline: {\n list:\n \"gap-1 border-border-default data-[orientation=horizontal]:border-b data-[orientation=vertical]:border-r before:rounded-sm before:bg-accent \" +\n \"data-[orientation=horizontal]:before:-bottom-px data-[orientation=horizontal]:before:left-0 data-[orientation=horizontal]:before:h-0.5 \" +\n \"data-[orientation=horizontal]:before:w-(--kz-ind-w) data-[orientation=horizontal]:before:translate-x-(--kz-ind-x) \" +\n \"data-[orientation=vertical]:before:-right-px data-[orientation=vertical]:before:top-0 data-[orientation=vertical]:before:w-0.5 \" +\n \"data-[orientation=vertical]:before:h-(--kz-ind-h) data-[orientation=vertical]:before:translate-y-(--kz-ind-y)\",\n trigger:\n \"relative rounded-md px-3 py-2.5 text-sm text-fg-secondary hover:text-fg data-[state=active]:text-fg \" +\n \"after:absolute after:rounded-sm after:bg-transparent data-[state=active]:after:bg-accent \" +\n \"data-[orientation=horizontal]:after:inset-x-2 data-[orientation=horizontal]:after:-bottom-px data-[orientation=horizontal]:after:h-0.5 \" +\n \"data-[orientation=vertical]:justify-start data-[orientation=vertical]:after:inset-y-1.5 data-[orientation=vertical]:after:-right-px data-[orientation=vertical]:after:w-0.5 \" +\n \"group-data-[indicator=on]/tabs:data-[state=active]:after:bg-transparent\",\n },\n /* A view switch: equal segments in a track, the active one filled. */\n segmented: {\n list:\n \"inline-grid auto-cols-fr grid-flow-col gap-1 self-start rounded-xl border border-border-default bg-surface-1 p-1 data-[orientation=vertical]:grid-flow-row \" +\n \"before:left-0 before:top-0 before:h-(--kz-ind-h) before:w-(--kz-ind-w) before:translate-x-(--kz-ind-x) before:translate-y-(--kz-ind-y) before:rounded-lg before:bg-accent before:shadow-sm\",\n trigger:\n \"min-h-8 rounded-lg px-3 py-1.5 text-xs text-fg-secondary hover:bg-surface-2 hover:text-fg \" +\n \"data-[state=active]:bg-accent data-[state=active]:text-on-accent data-[state=active]:shadow-sm data-[state=active]:hover:bg-accent \" +\n \"transition-colors group-data-[indicator=on]/tabs:data-[state=active]:bg-transparent group-data-[indicator=on]/tabs:data-[state=active]:shadow-none\",\n },\n /* Pills that scroll sideways on a phone: a feed's sections. */\n pills: {\n list:\n \"gap-1.5 overflow-x-auto overflow-y-hidden overscroll-x-contain pt-1 -mt-1 pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden \" +\n \"before:left-0 before:top-0 before:h-(--kz-ind-h) before:w-(--kz-ind-w) before:translate-x-(--kz-ind-x) before:translate-y-(--kz-ind-y) \" +\n \"before:rounded-sm before:border before:border-accent before:bg-accent-soft\",\n trigger:\n \"h-9 rounded-sm border border-border-default bg-surface-1 px-4 text-xs text-fg-secondary hover:border-border-strong hover:text-fg \" +\n \"data-[state=active]:border-accent data-[state=active]:bg-accent-soft data-[state=active]:text-fg \" +\n \"group-data-[indicator=on]/tabs:data-[state=active]:border-transparent group-data-[indicator=on]/tabs:data-[state=active]:bg-transparent\",\n },\n /*\n * Binder dividers (intercalaires, #648): organise collections, tags and statuses. Each tab is a divider with a\n * coloured top edge (`hue`), its words and a count; the active one is the page's colour and joins the content\n * under the list's line. Too many dividers scroll sideways, the edges fading. No paper texture: organisation only.\n */\n binder: {\n list:\n \"items-end gap-1 overflow-x-auto overflow-y-hidden overscroll-x-contain border-b border-border-default px-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden \" +\n \"[mask-image:linear-gradient(to_right,transparent,black_12px,black_calc(100%-12px),transparent)]\",\n trigger:\n \"relative -mb-px min-h-10 rounded-t-lg border border-b-0 border-border-default bg-surface-2 px-3.5 pb-2 pt-2.5 text-sm text-fg-secondary \" +\n \"before:absolute before:inset-x-0 before:-top-px before:h-1 before:rounded-t-lg before:bg-(--kz-hue,var(--kz-accent)) \" +\n \"hover:bg-surface-3 hover:text-fg data-[state=active]:z-[1] data-[state=active]:bg-surface-1 data-[state=active]:pb-2.5 data-[state=active]:text-fg \" +\n \"data-[state=active]:shadow-[0_1px_0_0_var(--kz-surface-1)] motion-reduce:transition-none\",\n },\n },\n },\n defaultVariants: { variant: \"underline\" },\n});\n\n/**\n * A divider's colour (`variant=\"binder\"`): the brand's accent by default, or a role of the theme — every one reads at 3:1 or\n * more on both themes. The colour is never the only signal: the words and the count say it.\n */\nexport type TabsHue = \"accent\" | \"success\" | \"warning\" | \"danger\" | \"neutral\";\n// The text roles where the fill role is too light on a light page (success, warning: 2:1): every edge reaches 3:1, tested.\nconst HUE: Record<TabsHue, string> = {\n accent: \"var(--kz-accent)\",\n success: \"var(--kz-success-text)\",\n warning: \"var(--kz-warning-text)\",\n danger: \"var(--kz-danger-text)\",\n neutral: \"var(--kz-text-muted)\",\n};\n/** The style that paints a divider's edge (`--kz-hue`), merged with the host's. */\nconst hueStyle = (hue: TabsHue | undefined, style: React.CSSProperties | undefined) =>\n hue ? { ...style, [\"--kz-hue\" as string]: HUE[hue] } : style;\n\n/** The count after a tab's words: part of its name (« Clients 12 »), muted, tabular. */\nfunction TabCount({ count }: Readonly<{ count: number | undefined }>) {\n if (count === undefined) return null;\n return <span data-tab-count=\"\" className=\"font-mono text-xs font-medium tabular-nums text-fg-secondary\">{count}</span>;\n}\n\n/** « + Intercalaire »: a button after the dividers (outside the tab list: a tablist holds only tabs). */\nfunction AddButton({ add }: Readonly<{ add: TabsAdd }>) {\n return (\n <button\n type=\"button\"\n onClick={add.onAdd}\n className=\"mb-1 ml-1 inline-flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-2.5 text-sm font-medium text-fg-secondary hover:bg-surface-2 hover:text-fg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <svg viewBox=\"0 0 24 24\" className=\"h-4 w-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden focusable=\"false\">\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n {add.label}\n </button>\n );\n}\n\nexport type TabsAdd = {\n /** Its words (« Intercalaire », « New tag ») — passed translated. */\n label: string;\n /** Adds a divider (opens the host's form). */\n onAdd: () => void;\n};\n\nexport type TabsVariants = VariantProps<typeof tabs>;\ntype Variant = NonNullable<TabsVariants[\"variant\"]>;\n\nconst VariantContext = React.createContext<Variant>(\"underline\");\n\nexport type TabsRootProps = React.ComponentProps<typeof TabsPrimitive.Root> & {\n /** underline (the sections of a page) · segmented (a view switch) · pills (a feed's sections) · binder (dividers that organise collections, tags, statuses). */\n variant?: TabsVariants[\"variant\"];\n /** Binds the active tab to this search parameter of the URL (`?tab=…`): the URL is the state. Without it the state is local — only for an ephemeral choice. */\n routeKey?: string;\n /** The values the parameter may hold (the tabs' `value`s); the first is the default unless `defaultValue` says otherwise. */\n routeValues?: readonly string[];\n};\n\n/** `value`/`defaultValue` + `onValueChange`, `orientation` (horizontal by default), `variant` for the list. */\nexport function TabsRoot({ variant = \"underline\", className, routeKey, routeValues, ...rest }: TabsRootProps) {\n const props = useRouteBinding(routeKey, routeValues, rest);\n return (\n <VariantContext.Provider value={variant}>\n <TabsPrimitive.Root data-variant={variant} className={tabs({ variant }).root({ className })} {...props} />\n </VariantContext.Provider>\n );\n}\n\nexport type TabsListProps = React.ComponentProps<typeof TabsPrimitive.List> & {\n /** A « + » button after the tabs (`variant=\"binder\"`: « + Intercalaire »): its words and what it does. */\n add?: TabsAdd;\n};\n\n/** The tabs. Name it (`aria-label`) when no heading says what it switches. One light glides to the active tab. */\nexport function TabsList({ className, add, ...props }: TabsListProps) {\n const variant = React.useContext(VariantContext);\n const { ref } = useSlidingIndicator<HTMLDivElement>({ item: \"[role=tab]\", active: \"[role=tab][data-state=active]\" });\n const list = <TabsPrimitive.List ref={ref} data-variant={variant} className={tabs({ variant }).list({ className: cn(add && \"min-w-0 flex-1 border-b-0\", className) })} {...props} />;\n if (!add) return list;\n return (\n <div data-tabs-row=\"\" className={cn(\"flex min-w-0 items-end\", variant === \"binder\" && \"border-b border-border-default\")}>\n {list}\n <AddButton add={add} />\n </div>\n );\n}\n\nexport type TabsTriggerProps = React.ComponentProps<typeof TabsPrimitive.Trigger> & {\n /** A count after the words (clients in a collection, unread): part of the tab's name. */\n count?: number;\n /** `variant=\"binder\"`: the divider's colour (the accent by default). */\n hue?: TabsHue;\n};\n\nexport function TabsTrigger({ className, count, hue, style, children, ...props }: TabsTriggerProps) {\n const variant = React.useContext(VariantContext);\n return (\n <TabsPrimitive.Trigger className={tabs({ variant }).trigger({ className })} style={hueStyle(hue, style)} data-hue={hue} {...props}>\n {children}\n <TabCount count={count} />\n </TabsPrimitive.Trigger>\n );\n}\n\nexport function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return <TabsPrimitive.Content className={tabs().content({ className })} {...props} />;\n}\n\n// ── Route mode: tabs that are links; the URL is the state (Oussama, 2026-10-22) ──────────────────────────────────────\n\n/**\n * Is the link `href` the tab of the route `current` (a path, with its search: `/docs/api?tab=x`)? The path must equal the\n * link's (a trailing slash, a locale-free comparison and the hash do not count); with `exact` false (the default) a deeper\n * path of the same section counts too (`/docs/api/x` is in `/docs/api`); every search parameter of the link must be in\n * `current`. The hub link (`/`) is only ever active on `/` itself.\n */\nexport function isTabActive(current: string, href: string, exact = false): boolean {\n const split = (value: string) => {\n const url = new URL(value.split(\"#\")[0]!, \"https://tabs.invalid\");\n return { path: url.pathname.replace(/\\/+$/, \"\") || \"/\", search: url.searchParams };\n };\n const here = split(current);\n const target = split(href);\n const samePath = here.path === target.path;\n const deeper = !exact && target.path !== \"/\" && here.path.startsWith(`${target.path}/`);\n if (!samePath && !deeper) return false;\n for (const [key, value] of target.search) if (here.search.get(key) !== value) return false;\n return true;\n}\n\ninterface NavState {\n current: string;\n variant: Variant;\n}\nconst NavContext = React.createContext<NavState | null>(null);\n\nexport type TabsNavProps = Omit<React.ComponentProps<\"nav\">, \"children\"> & {\n /** A « + » button after the tabs (`variant=\"binder\"`: « + Intercalaire »). */\n add?: TabsAdd;\n /** The navigation's accessible name (« Sections »). */\n label: string;\n /** The current route, passed in: the path with its search (`usePathname()` + `useSearchParams()`, `/docs?tab=api`). The active tab comes from it; no local state. */\n current: string;\n /** underline (the sections of a page) · segmented (a view switch) · pills (a feed's sections) · binder (dividers). */\n variant?: TabsVariants[\"variant\"];\n /** The tabs: `Tabs.NavLink`. */\n children: React.ReactNode;\n};\n\n/**\n * Tabs as routes: a `nav` of links, the URL is the state. Per WAI-ARIA these are links, not a tablist: each tab is an\n * anchor, the active one carries `aria-current=\"page\"`, the keyboard is the page's own (Tab walks the links, Enter\n * follows one) and there is no panel — the page is the panel. The same looks and the same gliding light as `Tabs.List`.\n */\nexport function TabsNav({ label, current, variant = \"underline\", add, className, children, ...props }: TabsNavProps) {\n const { ref } = useSlidingIndicator<HTMLElement>({ item: \"[data-tabs-link]\", active: \"[data-tabs-link][data-state=active]\" });\n const value = React.useMemo(() => ({ current, variant }), [current, variant]);\n const nav = (\n <nav ref={ref} aria-label={label} data-variant={variant} data-orientation=\"horizontal\" className={tabs({ variant }).list({ className: cn(add && \"min-w-0 flex-1 border-b-0\", className) })} {...props}>\n {children}\n </nav>\n );\n return (\n <NavContext.Provider value={value}>\n {add ? (\n <div data-tabs-row=\"\" className={cn(\"flex min-w-0 items-end\", variant === \"binder\" && \"border-b border-border-default\")}>\n {nav}\n <AddButton add={add} />\n </div>\n ) : (\n nav\n )}\n </NavContext.Provider>\n );\n}\n\nexport type TabsNavLinkProps = React.ComponentProps<\"a\"> & {\n /** Where the tab goes (`/docs/api`, `/docs?tab=api`). */\n href: string;\n /** Match this path only, not the pages below it. */\n exact?: boolean;\n /** Renders your router's `<Link>` (pass it as the only child; the `href` goes on this part and on the link). */\n asChild?: boolean;\n /** A count after the words (not with `asChild`: put it in your link). */\n count?: number;\n /** `variant=\"binder\"`: the divider's colour (the accent by default). */\n hue?: TabsHue;\n};\n\n/** One tab of `Tabs.Nav`: an anchor that is active when the current route is its `href`. */\nexport function TabsNavLink({ href, exact, asChild, count, hue, style, className, children, ...props }: TabsNavLinkProps) {\n const ctx = React.useContext(NavContext);\n if (!ctx) throw new Error(\"Tabs.NavLink must be inside <Tabs.Nav>\");\n const active = isTabActive(ctx.current, href, exact);\n const Comp = asChild ? Slot.Root : \"a\";\n return (\n <Comp\n data-tabs-link=\"\"\n data-state={active ? \"active\" : \"inactive\"}\n data-orientation=\"horizontal\"\n aria-current={active ? \"page\" : undefined}\n {...(asChild ? {} : { href })}\n data-hue={hue}\n style={hueStyle(hue, style)}\n className={cn(tabs({ variant: ctx.variant }).trigger(), \"no-underline\", className)}\n {...props}\n >\n {asChild ? (\n children\n ) : (\n <>\n {children}\n <TabCount count={count} />\n </>\n )}\n </Comp>\n );\n}\n\n/** `Tabs.Root/List/Trigger/Content` — `variant` underline · segmented · pills · binder on the root. `Tabs.Nav` + `Tabs.NavLink`: the same tabs as routes. */\nexport const Tabs = { Root: TabsRoot, List: TabsList, Trigger: TabsTrigger, Content: TabsContent, Nav: TabsNav, NavLink: TabsNavLink };\n"
394
394
  }
395
395
  ],
396
396
  "dependencies": [
@@ -244,7 +244,7 @@
244
244
  },
245
245
  {
246
246
  "path": "text-style/text-style-picker.tsx",
247
- "content": "// Client (state, an observer). A control for the look of one text role — font, size, weight, spacing, alignment, case,\n// italic, tone — over the primitives: the font as a radio group whose options are drawn in their own face, the size as\n// a step slider, the choices as segmented radio groups, italic as a switch, the tone as swatches. It is controlled, shows\n// a live preview, and warns (never clamps) when the tone lacks contrast on the surface or body text is too small.\nimport { Button } from \"@krizaka/ui/button\";\nimport { RadioGroup } from \"@krizaka/ui/radio-group\";\nimport { Slider } from \"@krizaka/ui/slider\";\nimport { Switch } from \"@krizaka/ui/switch\";\nimport { RadioGroup as RadioGroupPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\n\nimport { cx } from \"../cx\";\nimport { StyledText } from \"./styled-text\";\nimport {\n type Align,\n aligns,\n type Case,\n cases,\n contrastRatio,\n type FontId,\n fontIds,\n fontVariable,\n fontWeights,\n isUnderMinimumSize,\n type Leading,\n leadings,\n parseColor,\n parseTextStyle,\n type SizeStep,\n sizeSteps,\n type TextStyle,\n type TextWeight,\n textWeights,\n type ToneId,\n toneIds,\n toneVariable,\n type Tracking,\n trackings,\n} from \"./text-style\";\n\n/** The controls of the picker, in the order they are drawn. */\nexport const textStyleFields = [\"font\", \"size\", \"weight\", \"leading\", \"tracking\", \"align\", \"case\", \"italic\", \"tone\"] as const;\nexport type TextStyleField = (typeof textStyleFields)[number];\n\nexport type TextStyleLabels = {\n /** The name of the whole control. */\n picker: string;\n font: string;\n size: string;\n weight: string;\n leading: string;\n tracking: string;\n align: string;\n case: string;\n italic: string;\n tone: string;\n presets: string;\n preview: string;\n fonts: Record<FontId, string>;\n weights: Record<TextWeight, string>;\n leadings: Record<Leading, string>;\n trackings: Record<Tracking, string>;\n aligns: Record<Align, string>;\n cases: Record<Case, string>;\n tones: Record<ToneId, string>;\n /** The contrast warning: `{ratio}` is what the tone reaches, `{min}` what it must. */\n contrastWarning: string;\n /** The small-text warning: `{size}` is the smallest step advised for body text. */\n minSizeWarning: string;\n};\n\n/** The English words. */\nexport const textStyleLabels: TextStyleLabels = {\n picker: \"Text style\",\n font: \"Font\",\n size: \"Size\",\n weight: \"Weight\",\n leading: \"Line height\",\n tracking: \"Letter spacing\",\n align: \"Alignment\",\n case: \"Case\",\n italic: \"Italic\",\n tone: \"Colour\",\n presets: \"Presets\",\n preview: \"Preview\",\n fonts: { display: \"Display\", text: \"Text\", mono: \"Typewriter\", cahier: \"Pen\" },\n weights: { 400: \"Regular\", 500: \"Medium\", 600: \"Semibold\", 700: \"Bold\" },\n leadings: { tight: \"Tight\", normal: \"Normal\", relaxed: \"Relaxed\" },\n trackings: { tight: \"Tight\", normal: \"Normal\", wide: \"Wide\" },\n aligns: { start: \"Start\", center: \"Centre\", end: \"End\" },\n cases: { none: \"Aa\", upper: \"AA\", \"small-caps\": \"Small caps\" },\n tones: { primary: \"Primary\", secondary: \"Secondary\", muted: \"Muted\", accent: \"Accent\" },\n contrastWarning: \"This colour reaches only {ratio}:1 on the background; {min}:1 is needed to read it comfortably.\",\n minSizeWarning: \"Body text under “{size}” is hard to read.\",\n};\n\n/** The French words. */\nexport const textStyleLabelsFr: TextStyleLabels = {\n picker: \"Style du texte\",\n font: \"Police\",\n size: \"Taille\",\n weight: \"Graisse\",\n leading: \"Interligne\",\n tracking: \"Espacement des lettres\",\n align: \"Alignement\",\n case: \"Casse\",\n italic: \"Italique\",\n tone: \"Couleur\",\n presets: \"Préréglages\",\n preview: \"Aperçu\",\n fonts: { display: \"Titre\", text: \"Texte\", mono: \"Machine à écrire\", cahier: \"Stylo\" },\n weights: { 400: \"Normal\", 500: \"Moyen\", 600: \"Demi-gras\", 700: \"Gras\" },\n leadings: { tight: \"Serré\", normal: \"Normal\", relaxed: \"Aéré\" },\n trackings: { tight: \"Serré\", normal: \"Normal\", wide: \"Large\" },\n aligns: { start: \"Début\", center: \"Centré\", end: \"Fin\" },\n cases: { none: \"Aa\", upper: \"AA\", \"small-caps\": \"Petites capitales\" },\n tones: { primary: \"Principale\", secondary: \"Secondaire\", muted: \"Discrète\", accent: \"Accent\" },\n contrastWarning: \"Cette couleur n’atteint que {ratio}:1 sur le fond ; {min}:1 est nécessaire pour la lire confortablement.\",\n minSizeWarning: \"Un texte courant sous « {size} » se lit mal.\",\n};\n\nexport type TextStylePreset = {\n /** A stable key. */\n id: string;\n /** The name on the button, passed translated (« Titre », « Prix »…). */\n label: string;\n /** The style it applies; what it does not say takes the default. Validated when applied. */\n value: Partial<TextStyle>;\n};\n\nexport type TextStylePickerProps = {\n /** The text style, controlled. Validated by `parseTextStyle`: anything invalid shows the default. */\n value: TextStyle;\n /** Called with the whole new text style at each change. */\n onChange: (value: TextStyle) => void;\n /** The sample the preview shows, passed translated (\"Boulangerie Martin\"). */\n previewText: string;\n /** Styles the person can start from, as data. */\n presets?: readonly TextStylePreset[];\n /** The controls to show, in the order of `textStyleFields` (just `[\"font\", \"size\"]`). A preset then changes only these. */\n fields?: readonly TextStyleField[];\n /** A denser form for a popover from a toolbar. */\n compact?: boolean;\n /** The words, passed translated: `textStyleLabels` (EN) or `textStyleLabelsFr`, or the host's own. */\n labels?: Partial<TextStyleLabels>;\n /** The colour the text will sit on, for the preview and the contrast check (a CSS colour). By default the page's own surface. */\n surface?: string;\n /**\n * What the text is for: `body` (reading text, which `minBodySize` guards) or `title` (a heading, which may be small).\n * @default \"body\"\n */\n role?: \"body\" | \"title\";\n /**\n * The smallest step advised for body text: under it, a warning shows — the size is never forced.\n * @default \"sm\"\n */\n minBodySize?: SizeStep;\n /** Merged last on the root. */\n className?: string;\n};\n\ntype Rgb = [number, number, number];\ntype Rgba = [number, number, number, number];\n\nfunction parseColorWithAlpha(text: string): Rgba | null {\n const value = text.trim().toLowerCase();\n if (value === \"transparent\") return [0, 0, 0, 0];\n const color = parseColor(value);\n if (!color) return null;\n\n const hex = /^#([0-9a-f]{4}|[0-9a-f]{8})$/.exec(value)?.[1];\n if (hex) {\n const alpha = hex.length === 4 ? Number.parseInt(hex[3]! + hex[3]!, 16) : Number.parseInt(hex.slice(6, 8), 16);\n return [...color, alpha / 255];\n }\n\n const components =\n /^rgba?\\(([^)]+)\\)$/.exec(value)?.[1] ??\n /^color\\(srgb\\s+([^)]+)\\)$/.exec(value)?.[1];\n if (!components) return [...color, 1];\n\n const [channels, slashAlpha] = components.split(\"/\");\n const parts = channels!.trim().split(/[\\s,]+/).filter(Boolean);\n const alpha = slashAlpha?.trim() ?? (parts.length === 4 ? parts[3] : undefined);\n if (alpha === undefined) return [...color, 1];\n const parsed = alpha.endsWith(\"%\") ? Number.parseFloat(alpha) / 100 : Number.parseFloat(alpha);\n return Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? [...color, parsed] : null;\n}\n\nconst over = (foreground: Rgba, background: Rgba): Rgba => {\n const alpha = foreground[3] + background[3] * (1 - foreground[3]);\n if (alpha === 0) return [0, 0, 0, 0];\n return [\n (foreground[0] * foreground[3] + background[0] * background[3] * (1 - foreground[3])) / alpha,\n (foreground[1] * foreground[3] + background[1] * background[3] * (1 - foreground[3])) / alpha,\n (foreground[2] * foreground[3] + background[2] * background[3] * (1 - foreground[3])) / alpha,\n alpha,\n ];\n};\n\n/** The composited colour behind an element, or null when a background layer cannot be read. */\nfunction surfaceOf(element: HTMLElement): Rgb | null {\n const layers: HTMLElement[] = [];\n for (let node: HTMLElement | null = element; node; node = node.parentElement) {\n layers.push(node);\n if (node === document.documentElement) break;\n }\n let background: Rgba = [0, 0, 0, 0];\n for (const node of layers.reverse()) {\n const color = window.getComputedStyle(node).backgroundColor;\n const layer: Rgba | null = color ? parseColorWithAlpha(color) : [0, 0, 0, 0];\n if (!layer) return null;\n background = over(layer, background);\n }\n return background[3] >= 1 ? [background[0], background[1], background[2]] : null;\n}\n\n/** What the tone reaches on its surface, measured on the preview as it is drawn (the theme and the product's tokens included). */\nfunction useContrast(ref: React.RefObject<HTMLElement | null>, key: string): { ratio: number; required: number } | null {\n const [measurement, setMeasurement] = React.useState<{ ratio: number; required: number } | null>(null);\n React.useEffect(() => {\n const element = ref.current;\n if (!element) return;\n const measure = () => {\n const sample = element.querySelector<HTMLElement>(\"[data-text-style-sample]\") ?? element;\n const computed = window.getComputedStyle(sample);\n const foreground = parseColor(computed.color);\n const background = surfaceOf(sample);\n const fontSize = Number.parseFloat(computed.fontSize);\n const fontWeight = Number.parseFloat(computed.fontWeight);\n const required = fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700) ? 3 : 4.5;\n setMeasurement(foreground && background && Number.isFinite(fontSize) && Number.isFinite(fontWeight) ? { ratio: contrastRatio(foreground, background), required } : null);\n };\n measure();\n if (typeof MutationObserver === \"undefined\") return;\n const observer = new MutationObserver(measure);\n for (let node: HTMLElement | null = element; node; node = node.parentElement) {\n observer.observe(node, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n if (node === document.documentElement) break;\n }\n return () => observer.disconnect();\n }, [ref, key]);\n return measurement;\n}\n\nconst nearest = (weights: readonly TextWeight[], weight: TextWeight): TextWeight =>\n weights.reduce((best, w) => (Math.abs(w - weight) < Math.abs(best - weight) ? w : best), weights[0]!);\n\n/** The control of a text style: font, size, weight, spacing, alignment, case, italic and tone, with a live preview. */\nexport function TextStylePicker({\n value,\n onChange,\n previewText,\n presets,\n fields = textStyleFields,\n compact,\n labels: given,\n surface,\n role = \"body\",\n minBodySize = \"sm\",\n className,\n}: TextStylePickerProps) {\n const labels = { ...textStyleLabels, ...given };\n const style = parseTextStyle(value);\n const shown = (field: TextStyleField) => fields.includes(field);\n const id = React.useId();\n const previewRef = React.useRef<HTMLDivElement>(null);\n const measurement = useContrast(previewRef, `${style.font}|${style.size}|${style.weight}|${style.tone}|${surface ?? \"\"}`);\n\n const set = (patch: Partial<TextStyle>) => onChange(parseTextStyle({ ...style, ...patch }));\n const setFont = (font: FontId) => set({ font, weight: nearest(fontWeights[font], style.weight) });\n const applyPreset = (preset: TextStylePreset) => {\n const next = parseTextStyle(preset.value);\n const patch = Object.fromEntries(textStyleFields.filter(shown).map((f) => [f, next[f]])) as Partial<TextStyle>;\n if (patch.font !== undefined || patch.weight !== undefined) {\n const font = patch.font ?? style.font;\n const weight = patch.weight ?? style.weight;\n set({ ...patch, weight: nearest(fontWeights[font], weight) });\n } else {\n set(patch);\n }\n };\n\n const warnings: string[] = [];\n if (measurement && measurement.ratio < measurement.required) {\n warnings.push(labels.contrastWarning.replace(\"{ratio}\", measurement.ratio.toFixed(1)).replace(\"{min}\", String(measurement.required)));\n }\n if (role === \"body\" && isUnderMinimumSize(style.size, minBodySize)) warnings.push(labels.minSizeWarning.replace(\"{size}\", minBodySize));\n\n const group = (field: TextStyleField, title: string, control: React.ReactNode, className?: string) => (\n <div key={field} className={cx(\"flex min-w-0 flex-col gap-2\", className)} data-field={field}>\n <span id={`${id}-${field}`} className=\"text-xs font-semibold text-fg-secondary\">\n {title}\n </span>\n {control}\n </div>\n );\n const segmented = <T extends string | number>(field: TextStyleField, title: string, items: readonly T[], current: T, text: (item: T) => string, choose: (item: T) => void, disabled?: (item: T) => boolean) =>\n group(\n field,\n title,\n <RadioGroup.Root variant=\"segmented\" aria-labelledby={`${id}-${field}`} value={String(current)} onValueChange={(next) => choose(items.find((item) => String(item) === next)!)} className=\"w-full max-w-full\">\n {items.map((item) => (\n <RadioGroup.Segment key={item} value={String(item)} disabled={disabled?.(item)} className=\"min-w-0 px-1 text-xs\">\n {text(item)}\n </RadioGroup.Segment>\n ))}\n </RadioGroup.Root>,\n \"sm:col-span-2\",\n );\n\n const controls: Record<TextStyleField, () => React.ReactNode> = {\n font: () =>\n group(\n \"font\",\n labels.font,\n <RadioGroup.Root variant=\"cards\" aria-labelledby={`${id}-font`} value={style.font} onValueChange={(next) => setFont(next as FontId)} className=\"grid-cols-[repeat(auto-fit,minmax(9rem,1fr))]\">\n {fontIds.map((font) => (\n <RadioGroup.Card key={font} value={font} style={{ fontFamily: fontVariable[font] }}>\n {labels.fonts[font]}\n </RadioGroup.Card>\n ))}\n </RadioGroup.Root>,\n ),\n size: () =>\n group(\n \"size\",\n labels.size,\n <Slider\n label={labels.size}\n min={0}\n max={sizeSteps.length - 1}\n step={1}\n ticks\n value={sizeSteps.indexOf(style.size)}\n onValueChange={(index) => set({ size: sizeSteps[index]! })}\n formatValue={(index) => sizeSteps[index]!}\n floatingValue\n />,\n ),\n weight: () => segmented(\"weight\", labels.weight, textWeights, style.weight, (w) => labels.weights[w], (weight) => set({ weight }), (w) => !fontWeights[style.font].includes(w)),\n leading: () => segmented(\"leading\", labels.leading, leadings, style.leading, (l) => labels.leadings[l], (leading) => set({ leading })),\n tracking: () => segmented(\"tracking\", labels.tracking, trackings, style.tracking, (t) => labels.trackings[t], (tracking) => set({ tracking })),\n align: () => segmented(\"align\", labels.align, aligns, style.align, (a) => labels.aligns[a], (align) => set({ align })),\n case: () => segmented(\"case\", labels.case, cases, style.case, (c) => labels.cases[c], (next) => set({ case: next })),\n italic: () => (\n <div key=\"italic\" className=\"flex min-w-0 items-center justify-between gap-3\" data-field=\"italic\">\n <span id={`${id}-italic`} className=\"text-xs font-semibold text-fg-secondary\">\n {labels.italic}\n </span>\n <Switch aria-labelledby={`${id}-italic`} checked={style.italic} onCheckedChange={(italic) => set({ italic })} />\n </div>\n ),\n tone: () =>\n group(\n \"tone\",\n labels.tone,\n <RadioGroupPrimitive.Root aria-labelledby={`${id}-tone`} value={style.tone} onValueChange={(next) => set({ tone: next as ToneId })} orientation=\"horizontal\" className=\"flex flex-wrap gap-3\">\n {toneIds.map((tone) => (\n <RadioGroupPrimitive.Item\n key={tone}\n value={tone}\n aria-label={labels.tones[tone]}\n title={labels.tones[tone]}\n style={{ backgroundColor: toneVariable(tone) }}\n className=\"h-8 w-8 rounded-full border border-border-strong focus-visible:outline-hidden focus-visible:focus-ring data-[state=checked]:ring-2 data-[state=checked]:ring-accent data-[state=checked]:ring-offset-2 data-[state=checked]:ring-offset-surface-0\"\n />\n ))}\n </RadioGroupPrimitive.Root>,\n ),\n };\n\n return (\n <div role=\"group\" aria-label={labels.picker} data-compact={compact ? \"\" : undefined} className={cx(\"flex min-w-0 flex-col\", compact ? \"gap-3\" : \"gap-5\", className)}>\n <div\n ref={previewRef}\n data-preview=\"\"\n aria-label={labels.preview}\n role=\"group\"\n style={surface ? { backgroundColor: surface } : undefined}\n className={cx(\"min-w-0 overflow-hidden rounded-xl border border-border-default\", surface ? \"\" : \"bg-surface-1\", compact ? \"p-3\" : \"p-5\")}\n >\n <StyledText as=\"p\" value={style} className=\"break-words\" data-text-style-sample=\"\">\n {previewText}\n </StyledText>\n </div>\n <div role=\"status\" aria-live=\"polite\" data-warnings=\"\">\n {warnings.map((warning) => (\n <p key={warning} className=\"text-xs font-medium text-fg-warning\">\n {warning}\n </p>\n ))}\n </div>\n {presets?.length ? (\n <div role=\"group\" aria-label={labels.presets} className=\"flex flex-wrap gap-2\">\n {presets.map((preset) => (\n <Button key={preset.id} type=\"button\" size=\"sm\" variant=\"outline\" onClick={() => applyPreset(preset)}>\n {preset.label}\n </Button>\n ))}\n </div>\n ) : null}\n <div className={cx(\"grid grid-cols-1 gap-x-6\", compact ? \"gap-y-3\" : \"gap-y-5 sm:grid-cols-2\")}>\n {textStyleFields.filter(shown).map((field) => (\n <React.Fragment key={field}>{controls[field]()}</React.Fragment>\n ))}\n </div>\n </div>\n );\n}\n"
247
+ "content": "// Client (state, an observer). A control for the look of one text role — font, size, weight, spacing, alignment, case,\n// italic, tone — over the primitives: the font as a radio group whose options are drawn in their own face, the size as\n// a step slider, the choices as segmented radio groups, italic as a switch, the tone as swatches. It is controlled, shows\n// a live preview, and warns (never clamps) when the tone lacks contrast on the surface or body text is too small.\nimport { Button } from \"@krizaka/ui/button\";\nimport { RadioGroup } from \"@krizaka/ui/radio-group\";\nimport { Slider } from \"@krizaka/ui/slider\";\nimport { Switch } from \"@krizaka/ui/switch\";\nimport { RadioGroup as RadioGroupPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\n\nimport { cx } from \"../cx\";\nimport { StyledText } from \"./styled-text\";\nimport {\n type Align,\n aligns,\n type Case,\n cases,\n contrastRatio,\n type FontId,\n fontIds,\n fontVariable,\n fontWeights,\n isUnderMinimumSize,\n type Leading,\n leadings,\n parseColor,\n parseTextStyle,\n type SizeStep,\n sizeSteps,\n type TextStyle,\n type TextWeight,\n textWeights,\n type ToneId,\n toneIds,\n toneVariable,\n type Tracking,\n trackings,\n} from \"./text-style\";\n\n/** The controls of the picker, in the order they are drawn. */\nexport const textStyleFields = [\"font\", \"size\", \"weight\", \"leading\", \"tracking\", \"align\", \"case\", \"italic\", \"tone\"] as const;\nexport type TextStyleField = (typeof textStyleFields)[number];\n\nexport type TextStyleLabels = {\n /** The name of the whole control. */\n picker: string;\n font: string;\n size: string;\n weight: string;\n leading: string;\n tracking: string;\n align: string;\n case: string;\n italic: string;\n tone: string;\n presets: string;\n preview: string;\n fonts: Record<FontId, string>;\n weights: Record<TextWeight, string>;\n leadings: Record<Leading, string>;\n trackings: Record<Tracking, string>;\n aligns: Record<Align, string>;\n cases: Record<Case, string>;\n tones: Record<ToneId, string>;\n /** The contrast warning: `{ratio}` is what the tone reaches, `{min}` what it must. */\n contrastWarning: string;\n /** The small-text warning: `{size}` is the smallest step advised for body text. */\n minSizeWarning: string;\n};\n\n/** The English words. */\nexport const textStyleLabels: TextStyleLabels = {\n picker: \"Text style\",\n font: \"Font\",\n size: \"Size\",\n weight: \"Weight\",\n leading: \"Line height\",\n tracking: \"Letter spacing\",\n align: \"Alignment\",\n case: \"Case\",\n italic: \"Italic\",\n tone: \"Colour\",\n presets: \"Presets\",\n preview: \"Preview\",\n fonts: { display: \"Display\", text: \"Text\", mono: \"Typewriter\", cahier: \"Pen\" },\n weights: { 400: \"Regular\", 500: \"Medium\", 600: \"Semibold\", 700: \"Bold\" },\n leadings: { tight: \"Tight\", normal: \"Normal\", relaxed: \"Relaxed\" },\n trackings: { tight: \"Tight\", normal: \"Normal\", wide: \"Wide\" },\n aligns: { start: \"Start\", center: \"Centre\", end: \"End\" },\n cases: { none: \"Aa\", upper: \"AA\", \"small-caps\": \"Small caps\" },\n tones: { primary: \"Primary\", secondary: \"Secondary\", muted: \"Muted\", accent: \"Accent\" },\n contrastWarning: \"This colour reaches only {ratio}:1 on the background; {min}:1 is needed to read it comfortably.\",\n minSizeWarning: \"Body text under “{size}” is hard to read.\",\n};\n\n/** The French words. */\nexport const textStyleLabelsFr: TextStyleLabels = {\n picker: \"Style du texte\",\n font: \"Police\",\n size: \"Taille\",\n weight: \"Graisse\",\n leading: \"Interligne\",\n tracking: \"Espacement des lettres\",\n align: \"Alignement\",\n case: \"Casse\",\n italic: \"Italique\",\n tone: \"Couleur\",\n presets: \"Préréglages\",\n preview: \"Aperçu\",\n fonts: { display: \"Titre\", text: \"Texte\", mono: \"Machine à écrire\", cahier: \"Stylo\" },\n weights: { 400: \"Normal\", 500: \"Moyen\", 600: \"Demi-gras\", 700: \"Gras\" },\n leadings: { tight: \"Serré\", normal: \"Normal\", relaxed: \"Aéré\" },\n trackings: { tight: \"Serré\", normal: \"Normal\", wide: \"Large\" },\n aligns: { start: \"Début\", center: \"Centré\", end: \"Fin\" },\n cases: { none: \"Aa\", upper: \"AA\", \"small-caps\": \"Petites capitales\" },\n tones: { primary: \"Principale\", secondary: \"Secondaire\", muted: \"Discrète\", accent: \"Accent\" },\n contrastWarning: \"Cette couleur n’atteint que {ratio}:1 sur le fond ; {min}:1 est nécessaire pour la lire confortablement.\",\n minSizeWarning: \"Un texte courant sous « {size} » se lit mal.\",\n};\n\nexport type TextStylePreset = {\n /** A stable key. */\n id: string;\n /** The name on the button, passed translated (« Titre », « Prix »…). */\n label: string;\n /** The style it applies; what it does not say takes the default. Validated when applied. */\n value: Partial<TextStyle>;\n};\n\nexport type TextStylePickerProps = {\n /** The text style, controlled. Validated by `parseTextStyle`: anything invalid shows the default. */\n value: TextStyle;\n /** Called with the whole new text style at each change. */\n onChange: (value: TextStyle) => void;\n /** The sample the preview shows, passed translated (\"Boulangerie Martin\"). */\n previewText: string;\n /** Styles the person can start from, as data. */\n presets?: readonly TextStylePreset[];\n /** The controls to show, in the order of `textStyleFields` (just `[\"font\", \"size\"]`). A preset then changes only these. */\n fields?: readonly TextStyleField[];\n /** A denser form for a popover from a toolbar. */\n compact?: boolean;\n /** The words, passed translated: `textStyleLabels` (EN) or `textStyleLabelsFr`, or the host's own. */\n labels?: Partial<TextStyleLabels>;\n /** The colour the text will sit on, for the preview and the contrast check (a CSS colour). By default the page's own surface. */\n surface?: string;\n /**\n * What the text is for: `body` (reading text, which `minBodySize` guards) or `title` (a heading, which may be small).\n * @default \"body\"\n */\n role?: \"body\" | \"title\";\n /**\n * The smallest step advised for body text: under it, a warning shows — the size is never forced.\n * @default \"sm\"\n */\n minBodySize?: SizeStep;\n /** Merged last on the root. */\n className?: string;\n};\n\ntype Rgb = [number, number, number];\ntype Rgba = [number, number, number, number];\n\nfunction parseColorWithAlpha(text: string): Rgba | null {\n const value = text.trim().toLowerCase();\n if (value === \"transparent\") return [0, 0, 0, 0];\n const color = parseColor(value);\n if (!color) return null;\n\n const hex = /^#([0-9a-f]{4}|[0-9a-f]{8})$/.exec(value)?.[1];\n if (hex) {\n const alpha = hex.length === 4 ? Number.parseInt(hex[3]! + hex[3]!, 16) : Number.parseInt(hex.slice(6, 8), 16);\n return [...color, alpha / 255];\n }\n\n const components =\n /^rgba?\\(([^)]+)\\)$/.exec(value)?.[1] ??\n /^color\\(srgb\\s+([^)]+)\\)$/.exec(value)?.[1];\n if (!components) return [...color, 1];\n\n const [channels, slashAlpha] = components.split(\"/\");\n const parts = channels!.trim().split(/[\\s,]+/).filter(Boolean);\n const alpha = slashAlpha?.trim() ?? (parts.length === 4 ? parts[3] : undefined);\n if (alpha === undefined) return [...color, 1];\n const parsed = alpha.endsWith(\"%\") ? Number.parseFloat(alpha) / 100 : Number.parseFloat(alpha);\n return Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? [...color, parsed] : null;\n}\n\nconst over = (foreground: Rgba, background: Rgba): Rgba => {\n const alpha = foreground[3] + background[3] * (1 - foreground[3]);\n if (alpha === 0) return [0, 0, 0, 0];\n return [\n (foreground[0] * foreground[3] + background[0] * background[3] * (1 - foreground[3])) / alpha,\n (foreground[1] * foreground[3] + background[1] * background[3] * (1 - foreground[3])) / alpha,\n (foreground[2] * foreground[3] + background[2] * background[3] * (1 - foreground[3])) / alpha,\n alpha,\n ];\n};\n\n/** The composited colour behind an element, or null when a background layer cannot be read. */\nfunction surfaceOf(element: HTMLElement): Rgb | null {\n const layers: HTMLElement[] = [];\n for (let node: HTMLElement | null = element; node; node = node.parentElement) {\n layers.push(node);\n if (node === document.documentElement) break;\n }\n let background: Rgba = [0, 0, 0, 0];\n for (const node of layers.reverse()) {\n const color = getComputedStyle(node).backgroundColor;\n const layer: Rgba | null = color ? parseColorWithAlpha(color) : [0, 0, 0, 0];\n if (!layer) return null;\n background = over(layer, background);\n }\n const [red, green, blue, alpha] = background;\n return alpha >= 1 ? [red, green, blue] : null;\n}\n\n/** What the tone reaches on its surface, measured on the preview as it is drawn (the theme and the product's tokens included). */\nfunction useContrast(ref: React.RefObject<HTMLElement | null>, key: string): { ratio: number; required: number } | null {\n const [measurement, setMeasurement] = React.useState<{ ratio: number; required: number } | null>(null);\n React.useEffect(() => {\n const element = ref.current;\n if (!element) return;\n const measure = () => {\n const sample = element.querySelector<HTMLElement>(\"[data-text-style-sample]\") ?? element;\n const computed = getComputedStyle(sample);\n const foreground = parseColor(computed.color);\n const background = surfaceOf(sample);\n const fontSize = Number.parseFloat(computed.fontSize);\n const fontWeight = Number.parseFloat(computed.fontWeight);\n const required = fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700) ? 3 : 4.5;\n setMeasurement(foreground && background && Number.isFinite(fontSize) && Number.isFinite(fontWeight) ? { ratio: contrastRatio(foreground, background), required } : null);\n };\n measure();\n if (typeof MutationObserver === \"undefined\") return;\n const observer = new MutationObserver(measure);\n for (let node: HTMLElement | null = element; node; node = node.parentElement) {\n observer.observe(node, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n if (node === document.documentElement) break;\n }\n return () => observer.disconnect();\n }, [ref, key]);\n return measurement;\n}\n\nconst nearest = (weights: readonly TextWeight[], weight: TextWeight): TextWeight =>\n weights.reduce((best, w) => (Math.abs(w - weight) < Math.abs(best - weight) ? w : best), weights[0]!);\n\n/** The control of a text style: font, size, weight, spacing, alignment, case, italic and tone, with a live preview. */\nexport function TextStylePicker({\n value,\n onChange,\n previewText,\n presets,\n fields = textStyleFields,\n compact,\n labels: given,\n surface,\n role = \"body\",\n minBodySize = \"sm\",\n className,\n}: TextStylePickerProps) {\n const labels = { ...textStyleLabels, ...given };\n const style = parseTextStyle(value);\n const shown = (field: TextStyleField) => fields.includes(field);\n const id = React.useId();\n const previewRef = React.useRef<HTMLDivElement>(null);\n const measurement = useContrast(previewRef, `${style.font}|${style.size}|${style.weight}|${style.tone}|${surface ?? \"\"}`);\n\n const set = (patch: Partial<TextStyle>) => onChange(parseTextStyle({ ...style, ...patch }));\n const setFont = (font: FontId) => set({ font, weight: nearest(fontWeights[font], style.weight) });\n const applyPreset = (preset: TextStylePreset) => {\n const next = parseTextStyle(preset.value);\n const patch = Object.fromEntries(textStyleFields.filter(shown).map((f) => [f, next[f]])) as Partial<TextStyle>;\n if (patch.font !== undefined || patch.weight !== undefined) {\n const font = patch.font ?? style.font;\n const weight = patch.weight ?? style.weight;\n set({ ...patch, weight: nearest(fontWeights[font], weight) });\n } else {\n set(patch);\n }\n };\n\n const warnings: string[] = [];\n if (measurement && measurement.ratio < measurement.required) {\n warnings.push(labels.contrastWarning.replace(\"{ratio}\", measurement.ratio.toFixed(1)).replace(\"{min}\", String(measurement.required)));\n }\n if (role === \"body\" && isUnderMinimumSize(style.size, minBodySize)) warnings.push(labels.minSizeWarning.replace(\"{size}\", minBodySize));\n\n const group = (field: TextStyleField, title: string, control: React.ReactNode, className?: string) => (\n <div key={field} className={cx(\"flex min-w-0 flex-col gap-2\", className)} data-field={field}>\n <span id={`${id}-${field}`} className=\"text-xs font-semibold text-fg-secondary\">\n {title}\n </span>\n {control}\n </div>\n );\n const segmented = <T extends string | number>(field: TextStyleField, title: string, items: readonly T[], current: T, text: (item: T) => string, choose: (item: T) => void, disabled?: (item: T) => boolean) =>\n group(\n field,\n title,\n <RadioGroup.Root variant=\"segmented\" aria-labelledby={`${id}-${field}`} value={String(current)} onValueChange={(next) => choose(items.find((item) => String(item) === next)!)} className=\"w-full max-w-full\">\n {items.map((item) => (\n <RadioGroup.Segment key={item} value={String(item)} disabled={disabled?.(item)} className=\"min-w-0 px-1 text-xs\">\n {text(item)}\n </RadioGroup.Segment>\n ))}\n </RadioGroup.Root>,\n \"sm:col-span-2\",\n );\n\n const controls: Record<TextStyleField, () => React.ReactNode> = {\n font: () =>\n group(\n \"font\",\n labels.font,\n <RadioGroup.Root variant=\"cards\" aria-labelledby={`${id}-font`} value={style.font} onValueChange={(next) => setFont(next as FontId)} className=\"grid-cols-[repeat(auto-fit,minmax(9rem,1fr))]\">\n {fontIds.map((font) => (\n <RadioGroup.Card key={font} value={font} style={{ fontFamily: fontVariable[font] }}>\n {labels.fonts[font]}\n </RadioGroup.Card>\n ))}\n </RadioGroup.Root>,\n ),\n size: () =>\n group(\n \"size\",\n labels.size,\n <Slider\n label={labels.size}\n min={0}\n max={sizeSteps.length - 1}\n step={1}\n ticks\n value={sizeSteps.indexOf(style.size)}\n onValueChange={(index) => set({ size: sizeSteps[index]! })}\n formatValue={(index) => sizeSteps[index]!}\n floatingValue\n />,\n ),\n weight: () => segmented(\"weight\", labels.weight, textWeights, style.weight, (w) => labels.weights[w], (weight) => set({ weight }), (w) => !fontWeights[style.font].includes(w)),\n leading: () => segmented(\"leading\", labels.leading, leadings, style.leading, (l) => labels.leadings[l], (leading) => set({ leading })),\n tracking: () => segmented(\"tracking\", labels.tracking, trackings, style.tracking, (t) => labels.trackings[t], (tracking) => set({ tracking })),\n align: () => segmented(\"align\", labels.align, aligns, style.align, (a) => labels.aligns[a], (align) => set({ align })),\n case: () => segmented(\"case\", labels.case, cases, style.case, (c) => labels.cases[c], (next) => set({ case: next })),\n italic: () => (\n <div key=\"italic\" className=\"flex min-w-0 items-center justify-between gap-3\" data-field=\"italic\">\n <span id={`${id}-italic`} className=\"text-xs font-semibold text-fg-secondary\">\n {labels.italic}\n </span>\n <Switch aria-labelledby={`${id}-italic`} checked={style.italic} onCheckedChange={(italic) => set({ italic })} />\n </div>\n ),\n tone: () =>\n group(\n \"tone\",\n labels.tone,\n <RadioGroupPrimitive.Root aria-labelledby={`${id}-tone`} value={style.tone} onValueChange={(next) => set({ tone: next as ToneId })} orientation=\"horizontal\" className=\"flex flex-wrap gap-3\">\n {toneIds.map((tone) => (\n <RadioGroupPrimitive.Item\n key={tone}\n value={tone}\n aria-label={labels.tones[tone]}\n title={labels.tones[tone]}\n style={{ backgroundColor: toneVariable(tone) }}\n className=\"h-8 w-8 rounded-full border border-border-strong focus-visible:outline-hidden focus-visible:focus-ring data-[state=checked]:ring-2 data-[state=checked]:ring-accent data-[state=checked]:ring-offset-2 data-[state=checked]:ring-offset-surface-0\"\n />\n ))}\n </RadioGroupPrimitive.Root>,\n ),\n };\n\n return (\n <div role=\"group\" aria-label={labels.picker} data-compact={compact ? \"\" : undefined} className={cx(\"flex min-w-0 flex-col\", compact ? \"gap-3\" : \"gap-5\", className)}>\n <div\n ref={previewRef}\n data-preview=\"\"\n aria-label={labels.preview}\n role=\"group\"\n style={surface ? { backgroundColor: surface } : undefined}\n className={cx(\"min-w-0 overflow-hidden rounded-xl border border-border-default\", surface ? \"\" : \"bg-surface-1\", compact ? \"p-3\" : \"p-5\")}\n >\n <StyledText as=\"p\" value={style} className=\"break-words\" data-text-style-sample=\"\">\n {previewText}\n </StyledText>\n </div>\n <div role=\"status\" aria-live=\"polite\" data-warnings=\"\">\n {warnings.map((warning) => (\n <p key={warning} className=\"text-xs font-medium text-fg-warning\">\n {warning}\n </p>\n ))}\n </div>\n {presets?.length ? (\n <div role=\"group\" aria-label={labels.presets} className=\"flex flex-wrap gap-2\">\n {presets.map((preset) => (\n <Button key={preset.id} type=\"button\" size=\"sm\" variant=\"outline\" onClick={() => applyPreset(preset)}>\n {preset.label}\n </Button>\n ))}\n </div>\n ) : null}\n <div className={cx(\"grid grid-cols-1 gap-x-6\", compact ? \"gap-y-3\" : \"gap-y-5 sm:grid-cols-2\")}>\n {textStyleFields.filter(shown).map((field) => (\n <React.Fragment key={field}>{controls[field]()}</React.Fragment>\n ))}\n </div>\n </div>\n );\n}\n"
248
248
  },
249
249
  {
250
250
  "path": "text-style/text-style.ts",
@@ -316,11 +316,11 @@
316
316
  },
317
317
  {
318
318
  "path": "usage/model.ts",
319
- "content": "// Headless: the arithmetic and the words of the usage blocks (period, tiles, chart rows), read by the web entry.\nimport { formatNumber, formatPercent } from \"@krizaka/intl\";\nimport type * as React from \"react\";\n\nimport type { StatStripItem, StatTrend } from \"../stat\";\n\n/** The periods a usage page offers, in days. */\nexport const USAGE_PERIODS = [7, 30, 90] as const;\nexport type UsagePeriod = (typeof USAGE_PERIODS)[number];\n\n/** Reads `?period=` back: anything but an offered period is the default, so the address can never break the page. */\nexport function parsePeriod(raw: string | string[] | null | undefined, allowed: readonly number[] = USAGE_PERIODS, fallback = 30): number {\n const value = Number(Array.isArray(raw) ? raw[0] : raw);\n return allowed.includes(value) ? value : fallback;\n}\n\n/** The address of a period: the same path with `period` set, every other parameter kept. */\nexport function periodHref(base: string, period: number, param = \"period\"): string {\n const [path = \"\", query = \"\"] = base.split(\"?\");\n const params = new URLSearchParams(query);\n params.set(param, String(period));\n return `${path}?${params.toString()}`;\n}\n\nconst WORDS = {\n fr: { vsPrevious: \"{change} vs période précédente\", same: \"stable\", up: \"en hausse\", down: \"en baisse\" },\n en: { vsPrevious: \"{change} vs previous period\", same: \"steady\", up: \"up\", down: \"down\" },\n} as const;\n\nexport type UsageWords = {\n /** The change against the previous period; `{change}` is replaced by the signed percentage. */\n vsPrevious: string;\n /** When the figure did not move. */\n same: string;\n};\n\nconst FLAT = 0.005;\n\nexport interface UsageTileInput {\n id: string;\n label: string;\n value: number;\n /** The same figure for the previous period: the trend is computed from it. */\n previous?: number;\n /** Which direction is good news (latency, failures: `down`). Default `up`. */\n good?: \"up\" | \"down\";\n /** The shape of the period, rendered by the app (a `Sparkline` of @krizaka/charts, 64 × 18). */\n chart?: React.ReactNode;\n /** Digits of the figure. Default 0. */\n digits?: number;\n}\n\nexport interface UsageTileOptions {\n /** Default `fr-CA`: French figures and words with no props. */\n /** The language of the figures and the words. Default `fr-CA`. */\n locale?: string;\n /** Your own words for the change: `{change}` is the percentage. */\n words?: Partial<UsageWords>;\n}\n\nconst wordsOf = (locale: string): (typeof WORDS)[keyof typeof WORDS] => (locale.toLowerCase().startsWith(\"en\") ? WORDS.en : WORDS.fr);\n\nfunction direction(change: number | null): StatTrend | undefined {\n if (change === null) return undefined;\n if (Math.abs(change) < FLAT) return \"flat\";\n return change > 0 ? \"up\" : \"down\";\n}\n\nfunction changeOf(value: number, previous: number | undefined): number | null {\n if (previous === undefined) return null;\n if (previous === 0) return value === 0 ? 0 : null;\n return value / previous - 1;\n}\n\n/** One strip figure: the value written for the locale, the change against the previous period said in words. */\nexport function usageTile(input: UsageTileInput, { locale = \"fr-CA\", words }: UsageTileOptions = {}): StatStripItem {\n const w = { ...wordsOf(locale), ...words };\n const change = changeOf(input.value, input.previous);\n const trend = direction(change);\n const text = change === null ? undefined : trend === \"flat\" ? w.same : w.vsPrevious.replace(\"{change}\", formatPercent(change, { locale, signDisplay: \"exceptZero\", maximumFractionDigits: 0 }));\n return {\n id: input.id,\n label: input.label,\n value: formatNumber(input.value, { locale, maximumFractionDigits: input.digits ?? 0 }),\n trend,\n trendLabel: text,\n chart: input.chart,\n };\n}\n\n/** One bar of the usage chart: a day, its counts by outcome. */\nexport interface UsageDay {\n /** The day, written by the app (`3 nov.`). */\n label: string;\n values: Readonly<Partial<Record<string, number>>>;\n}\n\nexport interface UsageOutcome {\n id: string;\n label: string;\n /** `accent`, `success`, `warning`, `danger` or `muted`: tones of the tokens, never a colour. */\n tone: \"accent\" | \"success\" | \"warning\" | \"danger\" | \"muted\";\n}\n\nexport interface UsageBar {\n label: string;\n total: number;\n /** Height of the whole bar, 0–1 of the tallest day. */\n height: number;\n segments: { id: string; value: number; share: number }[];\n}\n\n/** The bars of the chart: heights relative to the tallest day, segments as shares of their bar. */\nexport function usageBars(days: readonly UsageDay[], outcomes: readonly UsageOutcome[]): UsageBar[] {\n const totals = days.map((d) => outcomes.reduce((sum, o) => sum + (d.values[o.id] ?? 0), 0));\n const max = Math.max(1, ...totals);\n return days.map((d, i) => {\n const total = totals[i] ?? 0;\n return {\n label: d.label,\n total,\n height: total / max,\n segments: outcomes.map((o) => ({ id: o.id, value: d.values[o.id] ?? 0, share: total === 0 ? 0 : (d.values[o.id] ?? 0) / total })),\n };\n });\n}\n"
319
+ "content": "// Headless: the arithmetic and the words of the usage blocks (period, tiles, chart rows), read by the web entry.\nimport { formatNumber, formatPercent } from \"@krizaka/intl\";\nimport type * as React from \"react\";\n\nimport type { StatStripItem, StatTrend } from \"../stat\";\n\n/** The periods a usage page offers, in days. */\nexport const USAGE_PERIODS = [7, 30, 90] as const;\nexport type UsagePeriod = (typeof USAGE_PERIODS)[number];\n\n/** Reads `?period=` back: anything but an offered period is the default, so the address can never break the page. */\nexport function parsePeriod(raw: string | string[] | null | undefined, allowed: readonly number[] = USAGE_PERIODS, fallback = 30): number {\n const value = Number(Array.isArray(raw) ? raw[0] : raw);\n return allowed.includes(value) ? value : fallback;\n}\n\n/** The address of a period: the same path with `period` set, every other parameter kept. */\nexport function periodHref(base: string, period: number, param = \"period\"): string {\n const [path = \"\", query = \"\"] = base.split(\"?\");\n const params = new URLSearchParams(query);\n params.set(param, String(period));\n return `${path}?${params.toString()}`;\n}\n\nconst WORDS = {\n fr: { vsPrevious: \"{change} vs période précédente\", same: \"stable\", up: \"en hausse\", down: \"en baisse\" },\n en: { vsPrevious: \"{change} vs previous period\", same: \"steady\", up: \"up\", down: \"down\" },\n} as const;\n\nexport type UsageWords = {\n /** The change against the previous period; `{change}` is replaced by the signed percentage. */\n vsPrevious: string;\n /** When the figure did not move. */\n same: string;\n};\n\nconst FLAT = 0.005;\n\nexport interface UsageTileInput {\n id: string;\n label: string;\n value: number;\n /** The same figure for the previous period: the trend is computed from it. */\n previous?: number;\n /** Which direction is good news (latency, failures: `down`). Default `up`. */\n good?: \"up\" | \"down\";\n /** The shape of the period, rendered by the app (a `Sparkline` of @krizaka/charts, 64 × 18). */\n chart?: React.ReactNode;\n /** Digits of the figure. Default 0. */\n digits?: number;\n}\n\nexport interface UsageTileOptions {\n /** Default `fr-CA`: French figures and words with no props. */\n /** The language of the figures and the words. Default `fr-CA`. */\n locale?: string;\n /** Your own words for the change: `{change}` is the percentage. */\n words?: Partial<UsageWords>;\n}\n\nconst wordsOf = (locale: string): (typeof WORDS)[keyof typeof WORDS] => (locale.toLowerCase().startsWith(\"en\") ? WORDS.en : WORDS.fr);\n\nfunction direction(change: number | null): StatTrend | undefined {\n if (change === null) return undefined;\n if (Math.abs(change) < FLAT) return \"flat\";\n return change > 0 ? \"up\" : \"down\";\n}\n\nfunction changeOf(value: number, previous: number | undefined): number | null {\n if (previous === undefined) return null;\n if (previous === 0) return value === 0 ? 0 : null;\n return value / previous - 1;\n}\n\n/** One strip figure: the value written for the locale, the change against the previous period said in words. */\nexport function usageTile(input: UsageTileInput, { locale = \"fr-CA\", words }: UsageTileOptions = {}): StatStripItem {\n const w = { ...wordsOf(locale), ...words };\n const change = changeOf(input.value, input.previous);\n const trend = direction(change);\n let text: string | undefined;\n if (change !== null) {\n text = trend === \"flat\" ? w.same : w.vsPrevious.replace(\"{change}\", formatPercent(change, { locale, signDisplay: \"exceptZero\", maximumFractionDigits: 0 }));\n }\n return {\n id: input.id,\n label: input.label,\n value: formatNumber(input.value, { locale, maximumFractionDigits: input.digits ?? 0 }),\n trend,\n trendLabel: text,\n chart: input.chart,\n };\n}\n\n/** One bar of the usage chart: a day, its counts by outcome. */\nexport interface UsageDay {\n /** The day, written by the app (`3 nov.`). */\n label: string;\n values: Readonly<Partial<Record<string, number>>>;\n}\n\nexport interface UsageOutcome {\n id: string;\n label: string;\n /** `accent`, `success`, `warning`, `danger` or `muted`: tones of the tokens, never a colour. */\n tone: \"accent\" | \"success\" | \"warning\" | \"danger\" | \"muted\";\n}\n\nexport interface UsageBar {\n label: string;\n total: number;\n /** Height of the whole bar, 0–1 of the tallest day. */\n height: number;\n segments: { id: string; value: number; share: number }[];\n}\n\n/** The bars of the chart: heights relative to the tallest day, segments as shares of their bar. */\nexport function usageBars(days: readonly UsageDay[], outcomes: readonly UsageOutcome[]): UsageBar[] {\n const totals = days.map((d) => outcomes.reduce((sum, o) => sum + (d.values[o.id] ?? 0), 0));\n const max = Math.max(1, ...totals);\n return days.map((d, i) => {\n const total = totals[i] ?? 0;\n return {\n label: d.label,\n total,\n height: total / max,\n segments: outcomes.map((o) => ({ id: o.id, value: d.values[o.id] ?? 0, share: total === 0 ? 0 : (d.values[o.id] ?? 0) / total })),\n };\n });\n}\n"
320
320
  },
321
321
  {
322
322
  "path": "usage/usage.tsx",
323
- "content": "// Server-safe. The blocks of a « Credits & usage » page: the balance on a Meter, the period switch (the address holds it),\n// the figures on the strip, the activity stacked by outcome. Words are props (French by default for the few built in);\n// figures are written with @krizaka/intl. Demo data only in the examples.\nimport { formatNumber } from \"@krizaka/intl\";\nimport type * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { BlockLink, type LinkComponent } from \"../block-link\";\nimport { Meter } from \"../meter\";\nimport { StatGrid } from \"../stat\";\nimport { periodHref, USAGE_PERIODS, type UsageBar, usageBars, type UsageDay, type UsageOutcome, usageTile,type UsageTileInput, type UsageTileOptions } from \"./model\";\n\nexport const usage = tv({\n slots: {\n credits: \"flex w-full min-w-0 flex-col gap-3 rounded-xl border border-border-default bg-surface-1 p-5\",\n creditsHead: \"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1\",\n creditsTitle: \"m-0 text-sm font-semibold text-fg-secondary\",\n creditsFigure: \"m-0 font-display text-3xl font-bold tabular-nums text-fg\",\n creditsFoot: \"m-0 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-fg-secondary\",\n switchList: \"m-0 inline-flex list-none gap-1 rounded-lg border border-border-default bg-surface-1 p-1\",\n switchLink:\n \"inline-flex min-h-9 min-w-11 items-center justify-center rounded-md px-3 text-sm font-semibold tabular-nums text-fg-secondary no-underline transition-colors \" +\n \"hover:text-fg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring aria-[current=page]:bg-accent-soft aria-[current=page]:text-fg\",\n chart: \"m-0 flex w-full min-w-0 flex-col gap-3 rounded-xl border border-border-default bg-surface-1 p-5\",\n chartTitle: \"text-sm font-semibold text-fg\",\n plot: \"flex h-40 w-full items-end gap-1\",\n column: \"flex h-full min-w-0 flex-1 flex-col justify-end\",\n bar: \"flex w-full flex-col-reverse overflow-hidden rounded-sm\",\n legend: \"m-0 flex list-none flex-wrap gap-x-4 gap-y-1 p-0 text-xs text-fg-secondary\",\n swatch: \"mr-1.5 inline-block h-2 w-2 rounded-full align-baseline\",\n state: \"m-0 flex h-40 items-center justify-center rounded-lg border border-dashed border-border-default px-4 text-center text-sm text-fg-secondary\",\n skeleton: \"h-40 w-full animate-pulse rounded-lg bg-surface-3 motion-reduce:animate-none\",\n },\n variants: {\n tone: {\n accent: { swatch: \"bg-accent\" },\n success: { swatch: \"bg-success\" },\n warning: { swatch: \"bg-warning\" },\n danger: { swatch: \"bg-danger\" },\n muted: { swatch: \"bg-border-strong\" },\n },\n },\n});\n\nconst FILL: Record<UsageOutcome[\"tone\"], string> = { accent: \"bg-accent\", success: \"bg-success\", warning: \"bg-warning\", danger: \"bg-danger\", muted: \"bg-border-strong\" };\n\nconst CREDIT_WORDS = {\n fr: { of: \"sur\", left: \"restants\" },\n en: { of: \"of\", left: \"left\" },\n} as const;\n\nexport type CreditsMeterProps = Omit<React.ComponentProps<\"section\">, \"children\"> & {\n /** What the balance is (« Crédits »): the heading and the meter's name. */\n label: string;\n /** Credits left. */\n balance: number;\n /** The allowance of the period; the meter fills with what is left. */\n total: number;\n /** The renewal, written by the app (« Renouvelés le 1er novembre »). */\n renewal?: React.ReactNode;\n /** The way to buy more: a link or a button. */\n action?: React.ReactNode;\n /** Default `fr-CA`. */\n locale?: string;\n};\n\n/** The balance: the figure large, a meter that turns to warning then danger as it runs low, the renewal and the way to buy. */\nexport function CreditsMeter({ label, balance, total, renewal, action, locale = \"fr-CA\", className, ...props }: CreditsMeterProps) {\n const s = usage();\n const w = locale.toLowerCase().startsWith(\"en\") ? CREDIT_WORDS.en : CREDIT_WORDS.fr;\n const write = (n: number) => formatNumber(n, { locale });\n const words = `${write(balance)} ${w.of} ${write(total)}`;\n return (\n <section aria-label={label} className={s.credits({ className })} {...props}>\n <div className={s.creditsHead()}>\n <h3 className={s.creditsTitle()}>{label}</h3>\n <p className={s.creditsFigure()}>\n {write(balance)} <span className=\"sr-only\">{w.left}</span>\n </p>\n </div>\n <Meter label={label} value={balance} max={Math.max(1, total)} valueText={words} optimum=\"high\" thresholds={{ low: 0.2, high: 0.5 }} size=\"lg\" />\n <p className={s.creditsFoot()}>\n <span>{words}</span>\n {renewal ? <span>{renewal}</span> : null}\n {action}\n </p>\n </section>\n );\n}\n\nexport type PeriodSwitchProps = Omit<React.ComponentProps<\"nav\">, \"children\"> & {\n /** The accessible name (« Période »). */\n label: string;\n /** The period shown, from `parsePeriod(searchParams.period)`. */\n value: number;\n /** The page's path (and any other parameters); each period is a link to it with `?period=`. */\n href: string;\n /** The periods offered, in days. Default 7 · 30 · 90. */\n periods?: readonly number[];\n /** The query parameter. Default `period`. */\n param?: string;\n /** The text of a period. Default `7 j` (`7 d` for an English locale). */\n periodLabel?: (days: number) => string;\n /** Default `fr-CA`. */\n locale?: string;\n /** The app's router link (Next's `Link`); default a plain `<a>`. */\n linkAs?: LinkComponent;\n};\n\n/** 7 · 30 · 90 d: links, so the address holds the period (`?period=30`) and the server renders it. */\nexport function PeriodSwitch({ label, value, href, periods = USAGE_PERIODS, param = \"period\", periodLabel, locale = \"fr-CA\", linkAs, className, ...props }: PeriodSwitchProps) {\n const s = usage();\n const unit = locale.toLowerCase().startsWith(\"en\") ? \"d\" : \"j\";\n const text = periodLabel ?? ((days: number) => `${days} ${unit}`);\n return (\n <nav aria-label={label} className={className} {...props}>\n <ul className={s.switchList()}>\n {periods.map((days) => (\n <li key={days}>\n <BlockLink href={periodHref(href, days, param)} linkAs={linkAs} className={s.switchLink()} aria-current={days === value ? \"page\" : undefined}>\n {text(days)}\n </BlockLink>\n </li>\n ))}\n </ul>\n </nav>\n );\n}\n\nexport type UsageTilesProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n /** 2 to 4 figures. */\n tiles: readonly UsageTileInput[];\n /** The period switch, above the row. */\n period?: React.ReactNode;\n /** The data is on its way: the row keeps its height. */\n loading?: boolean;\n} & UsageTileOptions;\n\n/** The figures of the period on the strip, each compared with the previous period in words. */\nexport function UsageTiles({ tiles, period, loading, locale, words, className, ...props }: UsageTilesProps) {\n const s = usage();\n if (loading) return <div aria-busy=\"true\" className={s.skeleton({ className: [\"h-20\", className].filter(Boolean).join(\" \") })} {...props} />;\n return <StatGrid variant=\"strip\" items={tiles.map((t) => usageTile(t, { locale, words }))} period={period} className={className} {...props} />;\n}\n\nexport type UsageChartProps = Omit<React.ComponentProps<\"figure\">, \"children\"> & {\n /** What it draws (« Activité par résultat »). */\n title: string;\n /** The days, oldest first. */\n days: readonly UsageDay[];\n /** The outcomes stacked in each bar, bottom first. */\n outcomes: readonly UsageOutcome[];\n /** Said when there is nothing in the period. */\n emptyLabel: string;\n /** The text version's column headings: the day, the total. */\n columns: { day: string; total: string };\n /** The data is on its way: a skeleton keeps the height. */\n loading?: boolean;\n /** Default `fr-CA`. */\n locale?: string;\n};\n\nfunction Column({ bar, outcomes }: { bar: UsageBar; outcomes: readonly UsageOutcome[] }) {\n const s = usage();\n return (\n <div className={s.column()}>\n <div className={s.bar()} style={{ height: `${bar.height * 100}%` }}>\n {bar.segments.map((seg, i) =>\n seg.value > 0 ? <span key={seg.id} className={FILL[outcomes[i]?.tone ?? \"muted\"]} style={{ height: `${seg.share * 100}%` }} /> : null,\n )}\n </div>\n </div>\n );\n}\n\n/** The activity of the period, one bar per day stacked by outcome — with its legend and its text version (a table). */\nexport function UsageChart({ title, days, outcomes, emptyLabel, columns, loading, locale = \"fr-CA\", className, ...props }: UsageChartProps) {\n const s = usage();\n const bars = usageBars(days, outcomes);\n const sum = (id: string) => days.reduce((n, d) => n + (d.values[id] ?? 0), 0);\n const empty = bars.every((b) => b.total === 0);\n const write = (n: number) => formatNumber(n, { locale });\n return (\n <figure aria-busy={loading || undefined} className={s.chart({ className })} {...props}>\n <figcaption className={s.chartTitle()}>{title}</figcaption>\n {loading ? (\n <div className={s.skeleton()} />\n ) : empty ? (\n <p className={s.state()}>{emptyLabel}</p>\n ) : (\n <>\n <div aria-hidden className={s.plot()}>\n {bars.map((bar) => (\n <Column key={bar.label} bar={bar} outcomes={outcomes} />\n ))}\n </div>\n <ul className={s.legend()}>\n {outcomes.map((o) => (\n <li key={o.id}>\n <span aria-hidden className={s.swatch({ tone: o.tone })} />\n {o.label} <span className=\"tabular-nums text-fg\">{write(sum(o.id))}</span>\n </li>\n ))}\n </ul>\n <table className=\"sr-only\">\n <caption>{title}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{columns.day}</th>\n {outcomes.map((o) => (\n <th key={o.id} scope=\"col\">\n {o.label}\n </th>\n ))}\n <th scope=\"col\">{columns.total}</th>\n </tr>\n </thead>\n <tbody>\n {days.map((d, i) => (\n <tr key={d.label}>\n <th scope=\"row\">{d.label}</th>\n {outcomes.map((o) => (\n <td key={o.id}>{write(d.values[o.id] ?? 0)}</td>\n ))}\n <td>{write(bars[i]?.total ?? 0)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </>\n )}\n </figure>\n );\n}\n"
323
+ "content": "// Server-safe. The blocks of a « Credits & usage » page: the balance on a Meter, the period switch (the address holds it),\n// the figures on the strip, the activity stacked by outcome. Words are props (French by default for the few built in);\n// figures are written with @krizaka/intl. Demo data only in the examples.\nimport { formatNumber } from \"@krizaka/intl\";\nimport type * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { BlockLink, type LinkComponent } from \"../block-link\";\nimport { Meter } from \"../meter\";\nimport { StatGrid } from \"../stat\";\nimport { periodHref, USAGE_PERIODS, type UsageBar, usageBars, type UsageDay, type UsageOutcome, usageTile,type UsageTileInput, type UsageTileOptions } from \"./model\";\n\nexport const usage = tv({\n slots: {\n credits: \"flex w-full min-w-0 flex-col gap-3 rounded-xl border border-border-default bg-surface-1 p-5\",\n creditsHead: \"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1\",\n creditsTitle: \"m-0 text-sm font-semibold text-fg-secondary\",\n creditsFigure: \"m-0 font-display text-3xl font-bold tabular-nums text-fg\",\n creditsFoot: \"m-0 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-fg-secondary\",\n switchList: \"m-0 inline-flex list-none gap-1 rounded-lg border border-border-default bg-surface-1 p-1\",\n switchLink:\n \"inline-flex min-h-9 min-w-11 items-center justify-center rounded-md px-3 text-sm font-semibold tabular-nums text-fg-secondary no-underline transition-colors \" +\n \"hover:text-fg focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring aria-[current=page]:bg-accent-soft aria-[current=page]:text-fg\",\n chart: \"m-0 flex w-full min-w-0 flex-col gap-3 rounded-xl border border-border-default bg-surface-1 p-5\",\n chartTitle: \"text-sm font-semibold text-fg\",\n plot: \"flex h-40 w-full items-end gap-1\",\n column: \"flex h-full min-w-0 flex-1 flex-col justify-end\",\n bar: \"flex w-full flex-col-reverse overflow-hidden rounded-sm\",\n legend: \"m-0 flex list-none flex-wrap gap-x-4 gap-y-1 p-0 text-xs text-fg-secondary\",\n swatch: \"mr-1.5 inline-block h-2 w-2 rounded-full align-baseline\",\n state: \"m-0 flex h-40 items-center justify-center rounded-lg border border-dashed border-border-default px-4 text-center text-sm text-fg-secondary\",\n skeleton: \"h-40 w-full animate-pulse rounded-lg bg-surface-3 motion-reduce:animate-none\",\n },\n variants: {\n tone: {\n accent: { swatch: \"bg-accent\" },\n success: { swatch: \"bg-success\" },\n warning: { swatch: \"bg-warning\" },\n danger: { swatch: \"bg-danger\" },\n muted: { swatch: \"bg-border-strong\" },\n },\n },\n});\n\nconst FILL: Record<UsageOutcome[\"tone\"], string> = { accent: \"bg-accent\", success: \"bg-success\", warning: \"bg-warning\", danger: \"bg-danger\", muted: \"bg-border-strong\" };\n\nconst CREDIT_WORDS = {\n fr: { of: \"sur\", left: \"restants\" },\n en: { of: \"of\", left: \"left\" },\n} as const;\n\nexport type CreditsMeterProps = Omit<React.ComponentProps<\"section\">, \"children\"> & {\n /** What the balance is (« Crédits »): the heading and the meter's name. */\n label: string;\n /** Credits left. */\n balance: number;\n /** The allowance of the period; the meter fills with what is left. */\n total: number;\n /** The renewal, written by the app (« Renouvelés le 1er novembre »). */\n renewal?: React.ReactNode;\n /** The way to buy more: a link or a button. */\n action?: React.ReactNode;\n /** Default `fr-CA`. */\n locale?: string;\n};\n\n/** The balance: the figure large, a meter that turns to warning then danger as it runs low, the renewal and the way to buy. */\nexport function CreditsMeter({ label, balance, total, renewal, action, locale = \"fr-CA\", className, ...props }: CreditsMeterProps) {\n const s = usage();\n const w = locale.toLowerCase().startsWith(\"en\") ? CREDIT_WORDS.en : CREDIT_WORDS.fr;\n const write = (n: number) => formatNumber(n, { locale });\n const words = `${write(balance)} ${w.of} ${write(total)}`;\n return (\n <section aria-label={label} className={s.credits({ className })} {...props}>\n <div className={s.creditsHead()}>\n <h3 className={s.creditsTitle()}>{label}</h3>\n <p className={s.creditsFigure()}>\n {write(balance)} <span className=\"sr-only\">{w.left}</span>\n </p>\n </div>\n <Meter label={label} value={balance} max={Math.max(1, total)} valueText={words} optimum=\"high\" thresholds={{ low: 0.2, high: 0.5 }} size=\"lg\" />\n <p className={s.creditsFoot()}>\n <span>{words}</span>\n {renewal ? <span>{renewal}</span> : null}\n {action}\n </p>\n </section>\n );\n}\n\nexport type PeriodSwitchProps = Omit<React.ComponentProps<\"nav\">, \"children\"> & {\n /** The accessible name (« Période »). */\n label: string;\n /** The period shown, from `parsePeriod(searchParams.period)`. */\n value: number;\n /** The page's path (and any other parameters); each period is a link to it with `?period=`. */\n href: string;\n /** The periods offered, in days. Default 7 · 30 · 90. */\n periods?: readonly number[];\n /** The query parameter. Default `period`. */\n param?: string;\n /** The text of a period. Default `7 j` (`7 d` for an English locale). */\n periodLabel?: (days: number) => string;\n /** Default `fr-CA`. */\n locale?: string;\n /** The app's router link (Next's `Link`); default a plain `<a>`. */\n linkAs?: LinkComponent;\n};\n\n/** 7 · 30 · 90 d: links, so the address holds the period (`?period=30`) and the server renders it. */\nexport function PeriodSwitch({ label, value, href, periods = USAGE_PERIODS, param = \"period\", periodLabel, locale = \"fr-CA\", linkAs, className, ...props }: PeriodSwitchProps) {\n const s = usage();\n const unit = locale.toLowerCase().startsWith(\"en\") ? \"d\" : \"j\";\n const text = periodLabel ?? ((days: number) => `${days} ${unit}`);\n return (\n <nav aria-label={label} className={className} {...props}>\n <ul className={s.switchList()}>\n {periods.map((days) => (\n <li key={days}>\n <BlockLink href={periodHref(href, days, param)} linkAs={linkAs} className={s.switchLink()} aria-current={days === value ? \"page\" : undefined}>\n {text(days)}\n </BlockLink>\n </li>\n ))}\n </ul>\n </nav>\n );\n}\n\nexport type UsageTilesProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n /** 2 to 4 figures. */\n tiles: readonly UsageTileInput[];\n /** The period switch, above the row. */\n period?: React.ReactNode;\n /** The data is on its way: the row keeps its height. */\n loading?: boolean;\n} & UsageTileOptions;\n\n/** The figures of the period on the strip, each compared with the previous period in words. */\nexport function UsageTiles({ tiles, period, loading, locale, words, className, ...props }: UsageTilesProps) {\n const s = usage();\n if (loading) return <div aria-busy=\"true\" className={s.skeleton({ className: [\"h-20\", className].filter(Boolean).join(\" \") })} {...props} />;\n return <StatGrid variant=\"strip\" items={tiles.map((t) => usageTile(t, { locale, words }))} period={period} className={className} {...props} />;\n}\n\nexport type UsageChartProps = Omit<React.ComponentProps<\"figure\">, \"children\"> & {\n /** What it draws (« Activité par résultat »). */\n title: string;\n /** The days, oldest first. */\n days: readonly UsageDay[];\n /** The outcomes stacked in each bar, bottom first. */\n outcomes: readonly UsageOutcome[];\n /** Said when there is nothing in the period. */\n emptyLabel: string;\n /** The text version's column headings: the day, the total. */\n columns: { day: string; total: string };\n /** The data is on its way: a skeleton keeps the height. */\n loading?: boolean;\n /** Default `fr-CA`. */\n locale?: string;\n};\n\nfunction Column({ bar, outcomes }: Readonly<{ bar: UsageBar; outcomes: readonly UsageOutcome[] }>) {\n const s = usage();\n return (\n <div className={s.column()}>\n <div className={s.bar()} style={{ height: `${bar.height * 100}%` }}>\n {bar.segments.map((seg, i) =>\n seg.value > 0 ? <span key={seg.id} className={FILL[outcomes[i]?.tone ?? \"muted\"]} style={{ height: `${seg.share * 100}%` }} /> : null,\n )}\n </div>\n </div>\n );\n}\n\n/** The activity of the period, one bar per day stacked by outcome — with its legend and its text version (a table). */\nexport function UsageChart({ title, days, outcomes, emptyLabel, columns, loading, locale = \"fr-CA\", className, ...props }: UsageChartProps) {\n const s = usage();\n const bars = usageBars(days, outcomes);\n const sum = (id: string) => days.reduce((n, d) => n + (d.values[id] ?? 0), 0);\n const empty = bars.every((b) => b.total === 0);\n const write = (n: number) => formatNumber(n, { locale });\n return (\n <figure aria-busy={loading || undefined} className={s.chart({ className })} {...props}>\n <figcaption className={s.chartTitle()}>{title}</figcaption>\n {loading && <div className={s.skeleton()} />}\n {!loading && empty && <p className={s.state()}>{emptyLabel}</p>}\n {!loading && !empty && (\n <>\n <div aria-hidden className={s.plot()}>\n {bars.map((bar) => (\n <Column key={bar.label} bar={bar} outcomes={outcomes} />\n ))}\n </div>\n <ul className={s.legend()}>\n {outcomes.map((o) => (\n <li key={o.id}>\n <span aria-hidden className={s.swatch({ tone: o.tone })} />\n {o.label} <span className=\"tabular-nums text-fg\">{write(sum(o.id))}</span>\n </li>\n ))}\n </ul>\n <table className=\"sr-only\">\n <caption>{title}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{columns.day}</th>\n {outcomes.map((o) => (\n <th key={o.id} scope=\"col\">\n {o.label}\n </th>\n ))}\n <th scope=\"col\">{columns.total}</th>\n </tr>\n </thead>\n <tbody>\n {days.map((d, i) => (\n <tr key={d.label}>\n <th scope=\"row\">{d.label}</th>\n {outcomes.map((o) => (\n <td key={o.id}>{write(d.values[o.id] ?? 0)}</td>\n ))}\n <td>{write(bars[i]?.total ?? 0)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </>\n )}\n </figure>\n );\n}\n"
324
324
  }
325
325
  ],
326
326
  "dependencies": [
@@ -138,7 +138,7 @@
138
138
  },
139
139
  {
140
140
  "path": "versus-card/versus-card.tsx",
141
- "content": "// Client (the birds hold an id). The arcade « character select » card of the Krizaka style (blocks.css): two subjects face to\n// face — a component and its alternative, two releases — each a bird as the fighter, with stat bars, and a « VS » mark between\n// them. Every bar is a real figure passed in by the host (`value` of `max`, and its text), read as a definition list: the bars\n// repeat the numbers, they never replace them. No winner is computed: the reader compares.\nimport type * as React from \"react\";\n\nimport { cn } from \"../cn\";\nimport type { MascotBird } from \"../mascots/geometry\";\nimport { Mascot } from \"../mascots/mascot\";\n\nexport interface FighterStat {\n /** What is measured (`Bundle size`, `Coverage`). */\n label: string;\n /** The measured value, from 0 to `max`. Real data: a stat that is not a finite number is left out. */\n value: number;\n /** The top of the bar. @default 100 */\n max?: number;\n /** The value as the reader reads it (`4.1 kB`, `92 %`); `value` when omitted. */\n display?: React.ReactNode;\n}\n\nexport interface Fighter {\n /** The subject's name (`@krizaka/ui 2.7`, `Radix Dialog`). */\n name: React.ReactNode;\n /** The bird that fights for it. */\n bird: MascotBird;\n /** One line under the name. */\n caption?: React.ReactNode;\n /** Its stat bars, from real data. */\n stats: readonly FighterStat[];\n}\n\nexport type VersusCardProps = Omit<React.HTMLAttributes<HTMLElement>, \"title\"> & {\n /** The accessible name of the match: `Krizaka UI 2.7 versus 2.6`. */\n label: string;\n /** The subject on the left. */\n left: Fighter;\n /** The subject on the right (its bird faces left). */\n right: Fighter;\n /** The mark between them. @default \"VS\" */\n vs?: React.ReactNode;\n /** Where the figures come from, under the card. */\n source?: React.ReactNode;\n};\n\nfunction FighterPane({ fighter, side }: { fighter: Fighter; side: \"left\" | \"right\" }) {\n const stats = fighter.stats.filter((s) => Number.isFinite(s.value) && Number.isFinite(s.max ?? 100) && (s.max ?? 100) > 0);\n return (\n <div className=\"kz-versus-fighter\" data-side={side}>\n <div className=\"kz-versus-bird\" aria-hidden=\"true\">\n <Mascot bird={fighter.bird} tone=\"own\" size={104} animated={false} />\n </div>\n <p className=\"kz-versus-name\">{fighter.name}</p>\n {fighter.caption && <p className=\"kz-versus-caption\">{fighter.caption}</p>}\n <dl className=\"kz-versus-stats\">\n {stats.map((s) => {\n const fill = Math.min(100, Math.max(0, (s.value / (s.max ?? 100)) * 100));\n return (\n <div key={s.label} className=\"kz-versus-stat\">\n <dt>{s.label}</dt>\n <dd>\n <span className=\"kz-versus-value\">{s.display ?? s.value}</span>\n <span className=\"kz-versus-bar\" aria-hidden=\"true\" style={{ [\"--kz-versus-fill\" as string]: `${Math.round(fill * 10) / 10}%` }} />\n </dd>\n </div>\n );\n })}\n </dl>\n </div>\n );\n}\n\n/** An arcade versus card: two subjects face to face, a bird each, stat bars from real data, a « VS » between them. */\nexport function VersusCard({ label, left, right, vs = \"VS\", source, className, ...props }: VersusCardProps) {\n return (\n <section className={cn(\"kz-versus\", className)} aria-label={label} {...props}>\n <FighterPane fighter={left} side=\"left\" />\n <span className=\"kz-versus-mark\">{vs}</span>\n <FighterPane fighter={right} side=\"right\" />\n {source && <p className=\"kz-versus-source\">{source}</p>}\n </section>\n );\n}\n"
141
+ "content": "// Client (the birds hold an id). The arcade « character select » card of the Krizaka style (blocks.css): two subjects face to\n// face — a component and its alternative, two releases — each a bird as the fighter, with stat bars, and a « VS » mark between\n// them. Every bar is a real figure passed in by the host (`value` of `max`, and its text), read as a definition list: the bars\n// repeat the numbers, they never replace them. No winner is computed: the reader compares.\nimport type * as React from \"react\";\n\nimport { cn } from \"../cn\";\nimport type { MascotBird } from \"../mascots/geometry\";\nimport { Mascot } from \"../mascots/mascot\";\n\nexport interface FighterStat {\n /** What is measured (`Bundle size`, `Coverage`). */\n label: string;\n /** The measured value, from 0 to `max`. Real data: a stat that is not a finite number is left out. */\n value: number;\n /** The top of the bar. @default 100 */\n max?: number;\n /** The value as the reader reads it (`4.1 kB`, `92 %`); `value` when omitted. */\n display?: React.ReactNode;\n}\n\nexport interface Fighter {\n /** The subject's name (`@krizaka/ui 2.7`, `Radix Dialog`). */\n name: React.ReactNode;\n /** The bird that fights for it. */\n bird: MascotBird;\n /** One line under the name. */\n caption?: React.ReactNode;\n /** Its stat bars, from real data. */\n stats: readonly FighterStat[];\n}\n\nexport type VersusCardProps = Omit<React.HTMLAttributes<HTMLElement>, \"title\"> & {\n /** The accessible name of the match: `Krizaka UI 2.7 versus 2.6`. */\n label: string;\n /** The subject on the left. */\n left: Fighter;\n /** The subject on the right (its bird faces left). */\n right: Fighter;\n /** The mark between them. @default \"VS\" */\n vs?: React.ReactNode;\n /** Where the figures come from, under the card. */\n source?: React.ReactNode;\n};\n\nfunction FighterPane({ fighter, side }: Readonly<{ fighter: Fighter; side: \"left\" | \"right\" }>) {\n const stats = fighter.stats.filter((s) => Number.isFinite(s.value) && Number.isFinite(s.max ?? 100) && (s.max ?? 100) > 0);\n return (\n <div className=\"kz-versus-fighter\" data-side={side}>\n <div className=\"kz-versus-bird\" aria-hidden=\"true\">\n <Mascot bird={fighter.bird} tone=\"own\" size={104} animated={false} />\n </div>\n <p className=\"kz-versus-name\">{fighter.name}</p>\n {fighter.caption && <p className=\"kz-versus-caption\">{fighter.caption}</p>}\n <dl className=\"kz-versus-stats\">\n {stats.map((s) => {\n const fill = Math.min(100, Math.max(0, (s.value / (s.max ?? 100)) * 100));\n return (\n <div key={s.label} className=\"kz-versus-stat\">\n <dt>{s.label}</dt>\n <dd>\n <span className=\"kz-versus-value\">{s.display ?? s.value}</span>\n <span className=\"kz-versus-bar\" aria-hidden=\"true\" style={{ [\"--kz-versus-fill\" as string]: `${Math.round(fill * 10) / 10}%` }} />\n </dd>\n </div>\n );\n })}\n </dl>\n </div>\n );\n}\n\n/** An arcade versus card: two subjects face to face, a bird each, stat bars from real data, a « VS » between them. */\nexport function VersusCard({ label, left, right, vs = \"VS\", source, className, ...props }: VersusCardProps) {\n return (\n <section className={cn(\"kz-versus\", className)} aria-label={label} {...props}>\n <FighterPane fighter={left} side=\"left\" />\n <span className=\"kz-versus-mark\">{vs}</span>\n <FighterPane fighter={right} side=\"right\" />\n {source && <p className=\"kz-versus-source\">{source}</p>}\n </section>\n );\n}\n"
142
142
  }
143
143
  ],
144
144
  "dependencies": [],
@@ -633,7 +633,7 @@
633
633
  },
634
634
  {
635
635
  "path": "vertical-video/vertical-video.tsx",
636
- "content": "// Client (a video element, an observer, keys). A 9:16 clip filling its frame, with the action rail of a short-video feed on\n// the right (avatar + follow, like, comment, share, a slot for tip / unlock, more) and the caption block bottom-left. Every\n// word is a prop; counts are formatted with @krizaka/intl; everything over the picture reads on the invariant `scrim` /\n// `fg-on-media` tokens, so it is legible in both themes. Under reduced motion nothing autoplays: the poster and a play button.\nimport { formatCompact } from \"@krizaka/intl\";\nimport * as React from \"react\";\n\nimport { Avatar } from \"../avatar/avatar\";\nimport { IconButton } from \"../button/button\";\nimport { cn } from \"../cn\";\nimport { VerifiedBadge } from \"../verified-badge/verified-badge\";\nimport { type VerticalVideoLabels, verticalVideoLabels, type VerticalVideoShared } from \"./model\";\n\nexport { type VerticalVideoLabels, verticalVideoLabels };\n\nexport interface VerticalVideoCreator {\n name: string;\n /** Their portrait. */\n avatarSrc?: string;\n /** The seal's words (\"Verified\"): shows the seal beside the name. */\n verifiedLabel?: string;\n}\n\nexport interface VerticalVideoProps extends Omit<React.ComponentProps<\"article\">, \"title\" | \"children\">, VerticalVideoShared {\n /** The clip — absent, the poster alone shows (MP4 or WebM; an HLS address only in Safari — use the player of `@krizaka/ui/video-player` for HLS). */\n src?: string;\n /** The picture until the first frame, and under reduced motion. */\n poster?: string;\n /** The next slide's: `auto` loads it ahead, `none` waits. Default `metadata`. */\n preload?: \"none\" | \"metadata\" | \"auto\";\n /** Plays again at the end. Default `true`. */\n loop?: boolean;\n /** Starts muted (autoplay needs it). Default `true`. */\n muted?: boolean;\n /** Who made it: name, portrait, the seal's words. */\n creator: VerticalVideoCreator;\n /**\n * How it takes its space: `frame` draws its own 9:16 box from its width; `fill` fills the box it is given (a bento\n * tile, a grid cell, a phone frame) — the clip covers it, cropped at the edges, the rail and the caption over it.\n * @default \"frame\"\n */\n fit?: \"frame\" | \"fill\";\n}\n\nconst glyph = (d: string) => (\n <svg viewBox=\"0 0 24 24\" className=\"h-6 w-6\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={d} />\n </svg>\n);\nconst HEART = \"M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10z\";\nconst COMMENT = \"M4 5h16v11H9l-5 4z\";\nconst SHARE = \"M4 12v7h16v-7M12 3v12M7 8l5-5 5 5\";\nconst MORE = \"M5 12h.01M12 12h.01M19 12h.01\";\n\nconst useReducedMotion = () =>\n React.useSyncExternalStore(\n (notify) => {\n const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n query.addEventListener(\"change\", notify);\n return () => query.removeEventListener(\"change\", notify);\n },\n () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n () => false,\n );\n\n/** One short video: 9:16, the rail of actions on the right, the creator's caption bottom-left, a progress hairline. */\nexport function VerticalVideo({\n title,\n src,\n poster,\n active = true,\n preload = \"metadata\",\n loop = true,\n muted = true,\n creator,\n disclosure,\n caption,\n tags = [],\n credit,\n likes,\n comments,\n shares,\n liked = false,\n following = false,\n onLike,\n onComment,\n onShare,\n onFollow,\n onMore,\n tipSlot,\n topStart,\n aboveCaption,\n fit = \"frame\",\n locale = \"en\",\n labels: custom,\n className,\n onKeyDown,\n ...props\n}: VerticalVideoProps) {\n const labels = { ...verticalVideoLabels, ...custom };\n const reduce = useReducedMotion();\n const video = React.useRef<HTMLVideoElement>(null);\n const [playing, setPlaying] = React.useState(false);\n const [paused, setPaused] = React.useState(false); // the viewer's pause: it holds until they play again\n const [progress, setProgress] = React.useState(0);\n const [open, setOpen] = React.useState(false);\n const [heart, setHeart] = React.useState(0);\n\n const shouldPlay = active && !paused && !reduce;\n React.useEffect(() => {\n const el = video.current;\n if (!el) return;\n if (shouldPlay) void el.play().catch(() => undefined);\n else el.pause();\n }, [shouldPlay, src]);\n\n const press = () => {\n const el = video.current;\n if (!el) return;\n if (el.paused) {\n setPaused(false);\n void el.play().catch(() => undefined);\n } else {\n setPaused(true);\n el.pause();\n }\n };\n const like = () => onLike?.(!liked);\n const doubleTap = () => {\n if (!liked) like();\n setHeart((n) => n + 1); // a heart blooms over the picture (still under reduced motion: it shows and goes)\n };\n const count = (n?: number) => (n === undefined ? undefined : formatCompact(n, { locale }));\n const name = creator.name;\n\n return (\n <article\n aria-label={title}\n tabIndex={0}\n data-playing={playing ? \"\" : undefined}\n data-fit={fit}\n className={cn(\"relative isolate w-full overflow-hidden\", fit === \"fill\" ? \"h-full min-h-0\" : \"aspect-[9/16]\", \"bg-surface-0 text-fg-on-media focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\", className)}\n onKeyDown={(event) => {\n onKeyDown?.(event);\n if (event.defaultPrevented || event.target !== event.currentTarget) return;\n if (event.key === \" \" || event.key.toLowerCase() === \"k\") {\n event.preventDefault();\n press();\n } else if (event.key.toLowerCase() === \"l\") like();\n }}\n {...props}\n >\n <video\n ref={video}\n src={src}\n poster={poster}\n muted={muted}\n loop={loop}\n playsInline\n preload={preload}\n className=\"absolute inset-0 -z-10 h-full w-full object-cover\"\n onPlay={() => setPlaying(true)}\n onPause={() => setPlaying(false)}\n onTimeUpdate={(event) => {\n const el = event.currentTarget;\n setProgress(el.duration ? el.currentTime / el.duration : 0);\n }}\n />\n {/* The tap target: a tap pauses or plays, a double tap likes. It is a button, so the keyboard has it too. */}\n <button type=\"button\" aria-label={playing ? labels.pause : labels.play} onClick={press} onDoubleClick={doubleTap} className=\"absolute inset-0 cursor-pointer bg-transparent focus-visible:outline-hidden\">\n {!playing && (\n <span aria-hidden className=\"absolute left-1/2 top-1/2 grid h-16 w-16 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-scrim backdrop-blur-md\">\n <svg viewBox=\"0 0 24 24\" className=\"h-7 w-7\" fill=\"currentColor\"><path d=\"M8 5v14l11-7z\" /></svg>\n </span>\n )}\n </button>\n {heart > 0 && (\n <span key={heart} aria-hidden className=\"pointer-events-none absolute left-1/2 top-1/2 grid -translate-x-1/2 -translate-y-1/2 place-items-center text-accent motion-safe:animate-ping\">\n <svg viewBox=\"0 0 24 24\" className=\"h-20 w-20\" fill=\"currentColor\"><path d={HEART} /></svg>\n </span>\n )}\n <div aria-hidden className=\"pointer-events-none absolute inset-x-0 bottom-0 h-2/5 bg-linear-to-t from-scrim to-transparent\" />\n {topStart && <div className=\"absolute left-3 top-3\">{topStart}</div>}\n\n <div role=\"group\" aria-label={labels.actions} className=\"absolute bottom-16 right-2 flex flex-col items-center gap-3\">\n <div className=\"relative\">\n <Avatar src={creator.avatarSrc} alt={name} fallback={name.slice(0, 1)} size=\"md\" className=\"ring-2 ring-white\" />\n {onFollow && (\n <IconButton\n label={format(following ? labels.following : labels.follow, name)}\n aria-pressed={following}\n size=\"icon\"\n variant={following ? \"secondary\" : \"primary\"}\n shape=\"pill\"\n onClick={() => onFollow(!following)}\n className=\"absolute -bottom-3 left-1/2 h-6 min-h-6 w-6 min-w-6 -translate-x-1/2 p-0\"\n >\n {glyph(following ? \"M5 12l5 5 9-10\" : \"M12 5v14M5 12h14\")}\n </IconButton>\n )}\n </div>\n <Rail label={labels.like} count={count(likes)} pressed={liked} onClick={like} tone={liked ? \"text-accent\" : undefined}>\n <svg viewBox=\"0 0 24 24\" className=\"h-6 w-6\" fill={liked ? \"currentColor\" : \"none\"} stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden><path d={HEART} /></svg>\n </Rail>\n <Rail label={labels.comment} count={count(comments)} onClick={onComment}>{glyph(COMMENT)}</Rail>\n <Rail label={labels.share} count={count(shares)} onClick={onShare}>{glyph(SHARE)}</Rail>\n {tipSlot}\n {onMore && <Rail label={labels.more} onClick={onMore}>{glyph(MORE)}</Rail>}\n </div>\n\n <div className=\"absolute bottom-4 left-3 right-16 flex min-w-0 flex-col gap-1.5\">\n {aboveCaption}\n <p className=\"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-bold\">\n {name}\n {creator.verifiedLabel && <VerifiedBadge label={creator.verifiedLabel} onMedia size=\"sm\" />}\n {disclosure && <span className=\"whitespace-nowrap rounded-full bg-scrim px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-fg-on-media backdrop-blur-md\">{disclosure}</span>}\n </p>\n {caption && (\n <p className={cn(\"text-sm leading-snug\", !open && \"line-clamp-2\")}>\n {caption}\n {tags.length > 0 && <span className=\"font-semibold\"> {tags.map((tag) => `#${tag}`).join(\" \")}</span>}\n </p>\n )}\n {caption && caption.length > 90 && (\n <button type=\"button\" aria-expanded={open} onClick={() => setOpen((v) => !v)} className=\"w-fit rounded text-xs font-semibold underline focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\">\n {open ? labels.collapse : labels.expand}\n </button>\n )}\n {credit && <p className=\"text-xs opacity-90\">{credit}</p>}\n </div>\n\n <div role=\"progressbar\" aria-label={labels.progress} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(progress * 100)} className=\"absolute inset-x-0 bottom-0 h-1 bg-scrim\">\n <div className=\"h-full bg-white\" style={{ width: `${progress * 100}%` }} />\n </div>\n </article>\n );\n}\n\n/** \"Follow {name}\" → \"Follow Elena\". */\nconst format = (message: string, name: string) => message.replace(\"{name}\", name);\n\nfunction Rail({ label, count, pressed, onClick, tone, children }: { label: string; count?: string | undefined; pressed?: boolean; onClick?: (() => void) | undefined; tone?: string | undefined; children: React.ReactNode }) {\n return (\n <div className=\"flex flex-col items-center gap-0.5\">\n <IconButton label={label} aria-pressed={pressed} variant=\"ghost\" shape=\"pill\" onClick={onClick} className={cn(\"h-11 min-h-11 w-11 min-w-11 bg-scrim text-fg-on-media backdrop-blur-md hover:bg-scrim\", tone)}>\n {children}\n </IconButton>\n {count !== undefined && <span className=\"text-xs font-semibold tabular-nums\">{count}</span>}\n </div>\n );\n}\n"
636
+ "content": "// Client (a video element, an observer, keys). A 9:16 clip filling its frame, with the action rail of a short-video feed on\n// the right (avatar + follow, like, comment, share, a slot for tip / unlock, more) and the caption block bottom-left. Every\n// word is a prop; counts are formatted with @krizaka/intl; everything over the picture reads on the invariant `scrim` /\n// `fg-on-media` tokens, so it is legible in both themes. Under reduced motion nothing autoplays: the poster and a play button.\nimport { formatCompact } from \"@krizaka/intl\";\nimport * as React from \"react\";\n\nimport { Avatar } from \"../avatar/avatar\";\nimport { IconButton } from \"../button/button\";\nimport { cn } from \"../cn\";\nimport { VerifiedBadge } from \"../verified-badge/verified-badge\";\nimport { verticalVideoLabels, type VerticalVideoShared } from \"./model\";\n\nexport type { VerticalVideoLabels } from \"./model\";\nexport { verticalVideoLabels };\n\nexport interface VerticalVideoCreator {\n name: string;\n /** Their portrait. */\n avatarSrc?: string;\n /** The seal's words (\"Verified\"): shows the seal beside the name. */\n verifiedLabel?: string;\n}\n\nexport interface VerticalVideoProps extends Omit<React.ComponentProps<\"article\">, \"title\" | \"children\">, VerticalVideoShared {\n /** The clip — absent, the poster alone shows (MP4 or WebM; an HLS address only in Safari — use the player of `@krizaka/ui/video-player` for HLS). */\n src?: string;\n /** The picture until the first frame, and under reduced motion. */\n poster?: string;\n /** The next slide's: `auto` loads it ahead, `none` waits. Default `metadata`. */\n preload?: \"none\" | \"metadata\" | \"auto\";\n /** Plays again at the end. Default `true`. */\n loop?: boolean;\n /** Starts muted (autoplay needs it). Default `true`. */\n muted?: boolean;\n /** Who made it: name, portrait, the seal's words. */\n creator: VerticalVideoCreator;\n /**\n * How it takes its space: `frame` draws its own 9:16 box from its width; `fill` fills the box it is given (a bento\n * tile, a grid cell, a phone frame) — the clip covers it, cropped at the edges, the rail and the caption over it.\n * @default \"frame\"\n */\n fit?: \"frame\" | \"fill\";\n}\n\nconst glyph = (d: string) => (\n <svg viewBox=\"0 0 24 24\" className=\"h-6 w-6\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d={d} />\n </svg>\n);\nconst HEART = \"M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10z\";\nconst COMMENT = \"M4 5h16v11H9l-5 4z\";\nconst SHARE = \"M4 12v7h16v-7M12 3v12M7 8l5-5 5 5\";\nconst MORE = \"M5 12h.01M12 12h.01M19 12h.01\";\n\nconst useReducedMotion = () =>\n React.useSyncExternalStore(\n (notify) => {\n const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n query.addEventListener(\"change\", notify);\n return () => query.removeEventListener(\"change\", notify);\n },\n () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n () => false,\n );\n\n/** One short video: 9:16, the rail of actions on the right, the creator's caption bottom-left, a progress hairline. */\nexport function VerticalVideo({\n title,\n src,\n poster,\n active = true,\n preload = \"metadata\",\n loop = true,\n muted = true,\n creator,\n disclosure,\n caption,\n tags = [],\n credit,\n likes,\n comments,\n shares,\n liked = false,\n following = false,\n onLike,\n onComment,\n onShare,\n onFollow,\n onMore,\n tipSlot,\n topStart,\n aboveCaption,\n fit = \"frame\",\n locale = \"en\",\n labels: custom,\n className,\n onKeyDown,\n ...props\n}: VerticalVideoProps) {\n const labels = { ...verticalVideoLabels, ...custom };\n const reduce = useReducedMotion();\n const video = React.useRef<HTMLVideoElement>(null);\n const [playing, setPlaying] = React.useState(false);\n const [paused, setPaused] = React.useState(false); // the viewer's pause: it holds until they play again\n const [progress, setProgress] = React.useState(0);\n const [open, setOpen] = React.useState(false);\n const [heart, setHeart] = React.useState(0);\n\n const shouldPlay = active && !paused && !reduce;\n React.useEffect(() => {\n const el = video.current;\n if (!el) return;\n if (shouldPlay) void el.play().catch(() => undefined);\n else el.pause();\n }, [shouldPlay, src]);\n\n const press = () => {\n const el = video.current;\n if (!el) return;\n if (el.paused) {\n setPaused(false);\n void el.play().catch(() => undefined);\n } else {\n setPaused(true);\n el.pause();\n }\n };\n const like = () => onLike?.(!liked);\n const doubleTap = () => {\n if (!liked) like();\n setHeart((n) => n + 1); // a heart blooms over the picture (still under reduced motion: it shows and goes)\n };\n const count = (n?: number) => (n === undefined ? undefined : formatCompact(n, { locale }));\n const name = creator.name;\n\n return (\n <article\n aria-label={title}\n tabIndex={0}\n data-playing={playing ? \"\" : undefined}\n data-fit={fit}\n className={cn(\"relative isolate w-full overflow-hidden\", fit === \"fill\" ? \"h-full min-h-0\" : \"aspect-[9/16]\", \"bg-surface-0 text-fg-on-media focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\", className)}\n onKeyDown={(event) => {\n onKeyDown?.(event);\n if (event.defaultPrevented || event.target !== event.currentTarget) return;\n if (event.key === \" \" || event.key.toLowerCase() === \"k\") {\n event.preventDefault();\n press();\n } else if (event.key.toLowerCase() === \"l\") like();\n }}\n {...props}\n >\n <video\n ref={video}\n src={src}\n poster={poster}\n muted={muted}\n loop={loop}\n playsInline\n preload={preload}\n className=\"absolute inset-0 -z-10 h-full w-full object-cover\"\n onPlay={() => setPlaying(true)}\n onPause={() => setPlaying(false)}\n onTimeUpdate={(event) => {\n const el = event.currentTarget;\n setProgress(el.duration ? el.currentTime / el.duration : 0);\n }}\n />\n {/* The tap target: a tap pauses or plays, a double tap likes. It is a button, so the keyboard has it too. */}\n <button type=\"button\" aria-label={playing ? labels.pause : labels.play} onClick={press} onDoubleClick={doubleTap} className=\"absolute inset-0 cursor-pointer bg-transparent focus-visible:outline-hidden\">\n {!playing && (\n <span aria-hidden className=\"absolute left-1/2 top-1/2 grid h-16 w-16 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-scrim backdrop-blur-md\">\n <svg viewBox=\"0 0 24 24\" className=\"h-7 w-7\" fill=\"currentColor\"><path d=\"M8 5v14l11-7z\" /></svg>\n </span>\n )}\n </button>\n {heart > 0 && (\n <span key={heart} aria-hidden className=\"pointer-events-none absolute left-1/2 top-1/2 grid -translate-x-1/2 -translate-y-1/2 place-items-center text-accent motion-safe:animate-ping\">\n <svg viewBox=\"0 0 24 24\" className=\"h-20 w-20\" fill=\"currentColor\"><path d={HEART} /></svg>\n </span>\n )}\n <div aria-hidden className=\"pointer-events-none absolute inset-x-0 bottom-0 h-2/5 bg-linear-to-t from-scrim to-transparent\" />\n {topStart && <div className=\"absolute left-3 top-3\">{topStart}</div>}\n\n <div role=\"group\" aria-label={labels.actions} className=\"absolute bottom-16 right-2 flex flex-col items-center gap-3\">\n <div className=\"relative\">\n <Avatar src={creator.avatarSrc} alt={name} fallback={name.slice(0, 1)} size=\"md\" className=\"ring-2 ring-white\" />\n {onFollow && (\n <IconButton\n label={format(following ? labels.following : labels.follow, name)}\n aria-pressed={following}\n size=\"icon\"\n variant={following ? \"secondary\" : \"primary\"}\n shape=\"pill\"\n onClick={() => onFollow(!following)}\n className=\"absolute -bottom-3 left-1/2 h-6 min-h-6 w-6 min-w-6 -translate-x-1/2 p-0\"\n >\n {glyph(following ? \"M5 12l5 5 9-10\" : \"M12 5v14M5 12h14\")}\n </IconButton>\n )}\n </div>\n <Rail label={labels.like} count={count(likes)} pressed={liked} onClick={like} tone={liked ? \"text-accent\" : undefined}>\n <svg viewBox=\"0 0 24 24\" className=\"h-6 w-6\" fill={liked ? \"currentColor\" : \"none\"} stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden><path d={HEART} /></svg>\n </Rail>\n <Rail label={labels.comment} count={count(comments)} onClick={onComment}>{glyph(COMMENT)}</Rail>\n <Rail label={labels.share} count={count(shares)} onClick={onShare}>{glyph(SHARE)}</Rail>\n {tipSlot}\n {onMore && <Rail label={labels.more} onClick={onMore}>{glyph(MORE)}</Rail>}\n </div>\n\n <div className=\"absolute bottom-4 left-3 right-16 flex min-w-0 flex-col gap-1.5\">\n {aboveCaption}\n <p className=\"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-bold\">\n {name}\n {creator.verifiedLabel && <VerifiedBadge label={creator.verifiedLabel} onMedia size=\"sm\" />}\n {disclosure && <span className=\"whitespace-nowrap rounded-full bg-scrim px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-fg-on-media backdrop-blur-md\">{disclosure}</span>}\n </p>\n {caption && (\n <p className={cn(\"text-sm leading-snug\", !open && \"line-clamp-2\")}>\n {caption}\n {tags.length > 0 && <span className=\"font-semibold\"> {tags.map((tag) => `#${tag}`).join(\" \")}</span>}\n </p>\n )}\n {caption && caption.length > 90 && (\n <button type=\"button\" aria-expanded={open} onClick={() => setOpen((v) => !v)} className=\"w-fit rounded text-xs font-semibold underline focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring\">\n {open ? labels.collapse : labels.expand}\n </button>\n )}\n {credit && <p className=\"text-xs opacity-90\">{credit}</p>}\n </div>\n\n <div role=\"progressbar\" aria-label={labels.progress} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(progress * 100)} className=\"absolute inset-x-0 bottom-0 h-1 bg-scrim\">\n <div className=\"h-full bg-white\" style={{ width: `${progress * 100}%` }} />\n </div>\n </article>\n );\n}\n\n/** \"Follow {name}\" → \"Follow Elena\". */\nconst format = (message: string, name: string) => message.replace(\"{name}\", name);\n\nfunction Rail({ label, count, pressed, onClick, tone, children }: { label: string; count?: string | undefined; pressed?: boolean; onClick?: (() => void) | undefined; tone?: string | undefined; children: React.ReactNode }) {\n return (\n <div className=\"flex flex-col items-center gap-0.5\">\n <IconButton label={label} aria-pressed={pressed} variant=\"ghost\" shape=\"pill\" onClick={onClick} className={cn(\"h-11 min-h-11 w-11 min-w-11 bg-scrim text-fg-on-media backdrop-blur-md hover:bg-scrim\", tone)}>\n {children}\n </IconButton>\n {count !== undefined && <span className=\"text-xs font-semibold tabular-nums\">{count}</span>}\n </div>\n );\n}\n"
637
637
  }
638
638
  ],
639
639
  "dependencies": [