@krizaka/ui 3.70.0 → 3.71.0

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-settings.d.ts +1 -1
  4. package/dist/account-settings.js +1 -1
  5. package/dist/avatar/defaults.d.ts +22 -2
  6. package/dist/avatar/defaults.js +20 -7
  7. package/dist/avatar/defaults.js.map +1 -1
  8. package/dist/{avatar-BdZcfkWR.d.ts → avatar-B_na7r1U.d.ts} +16 -0
  9. package/dist/avatar.d.ts +22 -2
  10. package/dist/avatar.js +20 -7
  11. package/dist/avatar.js.map +1 -1
  12. package/dist/blocks.css +11 -0
  13. package/dist/chat.js +1 -1
  14. package/dist/chunk-3PRYL2LS.js +2 -0
  15. package/dist/chunk-3PRYL2LS.js.map +1 -0
  16. package/dist/{chunk-HK525THY.js → chunk-5MPPIGCB.js} +18 -7
  17. package/dist/chunk-5MPPIGCB.js.map +1 -0
  18. package/dist/{chunk-CSRKYZ53.js → chunk-CZHPWLNW.js} +1 -1
  19. package/dist/{chunk-PZ4FJOD5.js → chunk-HLEBSAGC.js} +5 -1
  20. package/dist/{chunk-PZ4FJOD5.js.map → chunk-HLEBSAGC.js.map} +1 -1
  21. package/dist/{chunk-EUJ7337V.js → chunk-TISDOZH3.js} +18 -7
  22. package/dist/chunk-TISDOZH3.js.map +1 -0
  23. package/dist/chunk-W64RAX4N.js +79 -0
  24. package/dist/chunk-W64RAX4N.js.map +1 -0
  25. package/dist/collection-switcher.d.ts +1 -1
  26. package/dist/{default-avatar-D9kiSFNB.d.ts → default-avatar-BL0nJFti.d.ts} +16 -0
  27. package/dist/entity-header.d.ts +1 -1
  28. package/dist/index.js +7 -7
  29. package/dist/kind-config-editor.js +3 -2
  30. package/dist/kind-config-editor.js.map +1 -1
  31. package/dist/map.d.ts +6 -6
  32. package/dist/match-dialog.js +1 -1
  33. package/dist/media-grid.d.ts +16 -0
  34. package/dist/media-grid.js +1 -1
  35. package/dist/money-input.js +6 -70
  36. package/dist/money-input.js.map +1 -1
  37. package/dist/native.d.ts +16 -0
  38. package/dist/native.js +17 -6
  39. package/dist/native.js.map +1 -1
  40. package/dist/nav-bar.d.ts +13 -2
  41. package/dist/nav-bar.js +71 -54
  42. package/dist/nav-bar.js.map +1 -1
  43. package/dist/notification-preferences.js +2 -1
  44. package/dist/notification-preferences.js.map +1 -1
  45. package/dist/price-catalogue-editor.d.ts +117 -0
  46. package/dist/price-catalogue-editor.js +194 -0
  47. package/dist/price-catalogue-editor.js.map +1 -0
  48. package/dist/promo-code-field.js +1 -1
  49. package/dist/schema-form.d.ts +106 -0
  50. package/dist/schema-form.js +268 -0
  51. package/dist/schema-form.js.map +1 -0
  52. package/dist/switch.js +2 -1
  53. package/dist/vertical-video.js +1 -1
  54. package/dist/wall.d.ts +7 -1
  55. package/dist/wall.js +5 -4
  56. package/dist/wall.js.map +1 -1
  57. package/package.json +37 -6
  58. package/registry/account-menu.json +1 -1
  59. package/registry/account-settings.json +1 -1
  60. package/registry/achievement.json +1 -1
  61. package/registry/action-bar.json +1 -1
  62. package/registry/activity-feed.json +1 -1
  63. package/registry/agenda.json +1 -1
  64. package/registry/alert.json +1 -1
  65. package/registry/analysis-report.json +1 -1
  66. package/registry/anatomy-plate.json +1 -1
  67. package/registry/app-frame.json +2 -2
  68. package/registry/app-header.json +1 -1
  69. package/registry/app-shell.json +1 -1
  70. package/registry/argument-card.json +1 -1
  71. package/registry/audio-player.json +1 -1
  72. package/registry/auth-layout.json +1 -1
  73. package/registry/avatar.json +4 -4
  74. package/registry/badge.json +1 -1
  75. package/registry/bird-plate.json +1 -1
  76. package/registry/button.json +1 -1
  77. package/registry/captcha.json +1 -1
  78. package/registry/card-grid.json +1 -1
  79. package/registry/card.json +1 -1
  80. package/registry/catalogue-page.json +1 -1
  81. package/registry/changelog-page.json +1 -1
  82. package/registry/chapter.json +1 -1
  83. package/registry/chat.json +1 -1
  84. package/registry/checkbox.json +1 -1
  85. package/registry/chip-link.json +1 -1
  86. package/registry/chip-row.json +1 -1
  87. package/registry/chip.json +1 -1
  88. package/registry/choice-grid.json +1 -1
  89. package/registry/code-block.json +1 -1
  90. package/registry/collection-switcher.json +1 -1
  91. package/registry/combobox.json +1 -1
  92. package/registry/command.json +1 -1
  93. package/registry/comparison-table.json +1 -1
  94. package/registry/component-page.json +1 -1
  95. package/registry/confirm-button.json +1 -1
  96. package/registry/contact-page.json +1 -1
  97. package/registry/continue-prompt.json +1 -1
  98. package/registry/copy-button.json +1 -1
  99. package/registry/countdown.json +1 -1
  100. package/registry/cover-hero.json +1 -1
  101. package/registry/cta-panel.json +1 -1
  102. package/registry/dashboard-layout.json +1 -1
  103. package/registry/data-table.json +1 -1
  104. package/registry/date-picker.json +1 -1
  105. package/registry/decision-list.json +1 -1
  106. package/registry/description-list.json +1 -1
  107. package/registry/desktop-window.json +1 -1
  108. package/registry/detail-layout.json +1 -1
  109. package/registry/dialog.json +1 -1
  110. package/registry/docs-article-page.json +1 -1
  111. package/registry/docs-hub-page.json +1 -1
  112. package/registry/docs-layout.json +1 -1
  113. package/registry/docs-nav.json +1 -1
  114. package/registry/document-viewer.json +1 -1
  115. package/registry/doodle.json +1 -1
  116. package/registry/drop-overlay.json +1 -1
  117. package/registry/dropdown-menu.json +1 -1
  118. package/registry/elephant.json +2 -2
  119. package/registry/embed-facade.json +1 -1
  120. package/registry/empty-state.json +1 -1
  121. package/registry/engine-flow.json +1 -1
  122. package/registry/entity-header.json +1 -1
  123. package/registry/environment-notice.json +1 -1
  124. package/registry/error-page.json +1 -1
  125. package/registry/examples/price-catalogue-editor/default.d.ts +4 -0
  126. package/registry/examples/price-catalogue-editor/default.js +47 -0
  127. package/registry/examples/price-catalogue-editor/default.tsx +25 -0
  128. package/registry/examples/schema-form/default.d.ts +4 -0
  129. package/registry/examples/schema-form/default.js +29 -0
  130. package/registry/examples/schema-form/default.tsx +27 -0
  131. package/registry/examples/wall/pinned-note.js +2 -1
  132. package/registry/examples/wall/pinned-note.tsx +2 -1
  133. package/registry/field.json +1 -1
  134. package/registry/file-upload.json +1 -1
  135. package/registry/filter-bar.json +1 -1
  136. package/registry/flock.json +1 -1
  137. package/registry/footnote.json +1 -1
  138. package/registry/force-update-screen.json +1 -1
  139. package/registry/form.json +1 -1
  140. package/registry/gallery-page.json +1 -1
  141. package/registry/genui.json +1 -1
  142. package/registry/glossary-term.json +1 -1
  143. package/registry/glossary.json +1 -1
  144. package/registry/glow-card.json +1 -1
  145. package/registry/goal-gauge.json +1 -1
  146. package/registry/grade-stamp.json +1 -1
  147. package/registry/how-it-works-page.json +1 -1
  148. package/registry/image-cropper.json +1 -1
  149. package/registry/index.json +80 -8
  150. package/registry/iso.json +1 -1
  151. package/registry/kanban.json +1 -1
  152. package/registry/kbd.json +1 -1
  153. package/registry/kind-config-editor.json +1 -1
  154. package/registry/kpi-explained.json +1 -1
  155. package/registry/landing-page.json +1 -1
  156. package/registry/landscape.json +1 -1
  157. package/registry/language-switch.json +1 -1
  158. package/registry/legal-page.json +1 -1
  159. package/registry/link-card.json +1 -1
  160. package/registry/list.json +1 -1
  161. package/registry/loader.json +1 -1
  162. package/registry/longform-page.json +1 -1
  163. package/registry/maintenance-screen.json +1 -1
  164. package/registry/map.json +2 -2
  165. package/registry/margin-layout.json +1 -1
  166. package/registry/markdown.json +1 -1
  167. package/registry/marketing-layout.json +1 -1
  168. package/registry/marquee.json +1 -1
  169. package/registry/mascot-quote.json +1 -1
  170. package/registry/mascot-state.json +1 -1
  171. package/registry/mascots.json +1 -1
  172. package/registry/match-dialog.json +1 -1
  173. package/registry/media-capture.json +1 -1
  174. package/registry/media-gallery.json +1 -1
  175. package/registry/media-grid.json +1 -1
  176. package/registry/meta-row.json +1 -1
  177. package/registry/meter.json +1 -1
  178. package/registry/money-input.json +1 -1
  179. package/registry/nav-bar.json +30 -6
  180. package/registry/next-actions.json +1 -1
  181. package/registry/notification-preferences.json +1 -1
  182. package/registry/number-ticker.json +1 -1
  183. package/registry/opening-hours.json +1 -1
  184. package/registry/page-header.json +1 -1
  185. package/registry/page-hero.json +1 -1
  186. package/registry/page-index.json +1 -1
  187. package/registry/page.json +1 -1
  188. package/registry/pagination.json +1 -1
  189. package/registry/photo-grid.json +1 -1
  190. package/registry/pointer-light.json +1 -1
  191. package/registry/popover.json +1 -1
  192. package/registry/price-catalogue-editor.json +228 -0
  193. package/registry/pricing-page.json +1 -1
  194. package/registry/product-page.json +1 -1
  195. package/registry/profile-card.json +1 -1
  196. package/registry/progress.json +1 -1
  197. package/registry/promise-card.json +1 -1
  198. package/registry/promo-code-field.json +1 -1
  199. package/registry/proposal.json +1 -1
  200. package/registry/qr-code.json +1 -1
  201. package/registry/quota-meter.json +1 -1
  202. package/registry/radio-group.json +1 -1
  203. package/registry/rail-nav.json +2 -2
  204. package/registry/recipes.json +1 -1
  205. package/registry/retro-tv.json +1 -1
  206. package/registry/reviews.json +1 -1
  207. package/registry/router.json +1 -1
  208. package/registry/schema-form.json +253 -0
  209. package/registry/scroll-stage.json +1 -1
  210. package/registry/search-field.json +1 -1
  211. package/registry/section-backdrop.json +1 -1
  212. package/registry/separator.json +1 -1
  213. package/registry/service-card.json +1 -1
  214. package/registry/settings-layout.json +1 -1
  215. package/registry/shop-composer.json +1 -1
  216. package/registry/shop-gallery.json +1 -1
  217. package/registry/shop.json +2 -2
  218. package/registry/showcase.json +1 -1
  219. package/registry/signature.json +1 -1
  220. package/registry/site-cahier.json +1 -1
  221. package/registry/site-footer.json +2 -2
  222. package/registry/sites.json +1 -1
  223. package/registry/skeleton.json +1 -1
  224. package/registry/skip-link.json +1 -1
  225. package/registry/slider.json +1 -1
  226. package/registry/slot-picker.json +1 -1
  227. package/registry/slot.json +1 -1
  228. package/registry/specimen-tag.json +1 -1
  229. package/registry/speed-lines.json +1 -1
  230. package/registry/spinner.json +1 -1
  231. package/registry/split-view.json +1 -1
  232. package/registry/stage-banner.json +1 -1
  233. package/registry/stat.json +1 -1
  234. package/registry/status-chip.json +1 -1
  235. package/registry/status-page.json +1 -1
  236. package/registry/step-progress.json +1 -1
  237. package/registry/step-showcase.json +1 -1
  238. package/registry/stepper.json +1 -1
  239. package/registry/sticky-action.json +1 -1
  240. package/registry/stuck.json +1 -1
  241. package/registry/swipe-deck.json +1 -1
  242. package/registry/switch.json +1 -1
  243. package/registry/tabs.json +1 -1
  244. package/registry/tag-input.json +1 -1
  245. package/registry/tag-selector.json +1 -1
  246. package/registry/taped-photo.json +1 -1
  247. package/registry/terminal-replay.json +1 -1
  248. package/registry/text-style.json +1 -1
  249. package/registry/theme.json +1 -1
  250. package/registry/toast.json +1 -1
  251. package/registry/toc.json +1 -1
  252. package/registry/tooltip.json +1 -1
  253. package/registry/tree-view.json +1 -1
  254. package/registry/update-prompt.json +1 -1
  255. package/registry/upload-queue.json +1 -1
  256. package/registry/usage.json +1 -1
  257. package/registry/verified-badge.json +1 -1
  258. package/registry/versus-card.json +1 -1
  259. package/registry/vertical-video.json +1 -1
  260. package/registry/video-player.json +1 -1
  261. package/registry/video-trimmer.json +1 -1
  262. package/registry/virtual.json +1 -1
  263. package/registry/wall.json +47 -4
  264. package/registry/waveform.json +1 -1
  265. package/dist/chunk-EUJ7337V.js.map +0 -1
  266. package/dist/chunk-HK525THY.js.map +0 -1
  267. /package/dist/{chunk-CSRKYZ53.js.map → chunk-CZHPWLNW.js.map} +0 -0
@@ -0,0 +1,194 @@
1
+ "use client";
2
+ import {
3
+ MoneyInput
4
+ } from "./chunk-W64RAX4N.js";
5
+ import {
6
+ Field,
7
+ Input,
8
+ Select
9
+ } from "./chunk-HLEBSAGC.js";
10
+ import {
11
+ Badge
12
+ } from "./chunk-S4TLZRGZ.js";
13
+ import {
14
+ Button
15
+ } from "./chunk-V7W4RLRW.js";
16
+ import "./chunk-D3T54RSL.js";
17
+ import "./chunk-WEVYKZIF.js";
18
+ import {
19
+ cn
20
+ } from "./chunk-NSLXEDIS.js";
21
+
22
+ // src/price-catalogue-editor/price-catalogue-editor.tsx
23
+ import { currencyDigits } from "@krizaka/intl";
24
+ import * as React from "react";
25
+ import { jsx, jsxs } from "react/jsx-runtime";
26
+ var fill = (template, vars) => template.replace(/\{(\w+)\}/g, (_, name) => String(vars[name] ?? ""));
27
+ var TONES = { public: "success", "founder-limited": "accent", preparing: "warning" };
28
+ var availabilityTone = (id) => TONES[id] ?? "neutral";
29
+ function amountText(cents, currency, locale, onQuote) {
30
+ if (cents === null) return onQuote;
31
+ const digits = currencyDigits(currency);
32
+ return new Intl.NumberFormat(locale, { style: "currency", currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(cents / 10 ** digits);
33
+ }
34
+ var dateText = (iso, locale) => new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "UTC" }).format(new Date(iso));
35
+ var figuresText = (f, currency, locale, w) => f === null ? "\u2014" : `${amountText(f.amountCents, currency, locale, w.onQuote)} ${w.units[f.unit] ?? f.unit}`;
36
+ function EntryForm({ entry, prices, words, locale, today, onSchedule, onDone }) {
37
+ const id = React.useId();
38
+ const [cents, setCents] = React.useState(entry.amountCents);
39
+ const [unit, setUnit] = React.useState(entry.unit);
40
+ const [availability, setAvailability] = React.useState(entry.availability);
41
+ const [limits, setLimits] = React.useState(() => Object.fromEntries(Object.entries(entry.limits).map(([k, v]) => [k, String(v)])));
42
+ const [from, setFrom] = React.useState(today);
43
+ const [error, setError] = React.useState(null);
44
+ const [busy, setBusy] = React.useState(false);
45
+ const limitKeys = Object.keys(entry.limits);
46
+ const dateInvalid = from < today;
47
+ return /* @__PURE__ */ jsxs(
48
+ "form",
49
+ {
50
+ "aria-label": `${words.edit} \u2014 ${entry.product} \xB7 ${entry.plan}`,
51
+ className: "mt-4 grid gap-4 border-t border-border pt-4",
52
+ onSubmit: async (event) => {
53
+ event.preventDefault();
54
+ if (dateInvalid || busy) return;
55
+ setBusy(true);
56
+ const next = {};
57
+ for (const key of limitKeys) next[key] = Number.parseInt(limits[key] ?? "0", 10) || 0;
58
+ const result = await onSchedule(entry.key, { amountCents: cents, unit, availability, limits: next }, from);
59
+ setBusy(false);
60
+ if (result.ok) onDone();
61
+ else setError(result.message);
62
+ },
63
+ children: [
64
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
65
+ /* @__PURE__ */ jsxs(Field.Root, { children: [
66
+ /* @__PURE__ */ jsx(Field.Label, { htmlFor: `${id}-amount`, children: words.amount }),
67
+ /* @__PURE__ */ jsx(MoneyInput, { id: `${id}-amount`, value: cents, onValueChange: setCents, currency: entry.currency, locale, "aria-describedby": `${id}-amount-hint` }),
68
+ /* @__PURE__ */ jsx(Field.Hint, { id: `${id}-amount-hint`, children: words.emptyIsQuote })
69
+ ] }),
70
+ /* @__PURE__ */ jsxs(Field.Root, { children: [
71
+ /* @__PURE__ */ jsx(Field.Label, { htmlFor: `${id}-unit`, children: words.unit }),
72
+ /* @__PURE__ */ jsx(Select, { id: `${id}-unit`, value: unit, onChange: (e) => setUnit(e.target.value), children: prices.units.map((u) => /* @__PURE__ */ jsx("option", { value: u, children: words.units[u] ?? u }, u)) })
73
+ ] }),
74
+ /* @__PURE__ */ jsxs(Field.Root, { children: [
75
+ /* @__PURE__ */ jsx(Field.Label, { htmlFor: `${id}-availability`, children: words.availability }),
76
+ /* @__PURE__ */ jsx(Select, { id: `${id}-availability`, value: availability, onChange: (e) => setAvailability(e.target.value), children: prices.availabilities.map((a) => /* @__PURE__ */ jsx("option", { value: a, children: words.availabilities[a] ?? a }, a)) })
77
+ ] }),
78
+ /* @__PURE__ */ jsxs(Field.Root, { children: [
79
+ /* @__PURE__ */ jsx(Field.Label, { htmlFor: `${id}-from`, children: words.from }),
80
+ /* @__PURE__ */ jsx(Input, { id: `${id}-from`, type: "date", min: today, value: from, onChange: (e) => setFrom(e.target.value), invalid: dateInvalid })
81
+ ] })
82
+ ] }),
83
+ limitKeys.length > 0 && /* @__PURE__ */ jsxs("fieldset", { className: "grid gap-4 sm:grid-cols-2", children: [
84
+ /* @__PURE__ */ jsx("legend", { className: "mb-2 text-xs font-semibold text-fg-secondary", children: words.limits }),
85
+ limitKeys.map((key) => /* @__PURE__ */ jsxs(Field.Root, { children: [
86
+ /* @__PURE__ */ jsx(Field.Label, { htmlFor: `${id}-limit-${key}`, children: words.limitNames?.[key] ?? key }),
87
+ /* @__PURE__ */ jsx(Input, { id: `${id}-limit-${key}`, inputMode: "numeric", pattern: "[0-9]*", value: limits[key] ?? "", onChange: (e) => setLimits({ ...limits, [key]: e.target.value.replace(/\D/g, "") }) })
88
+ ] }, key))
89
+ ] }),
90
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-fg-secondary", children: words.keepsPrice }),
91
+ error && /* @__PURE__ */ jsx(Field.Error, { children: error }),
92
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
93
+ /* @__PURE__ */ jsx(Button, { type: "submit", size: "sm", variant: "primary", disabled: busy || dateInvalid, children: words.save }),
94
+ /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: onDone, children: words.cancel })
95
+ ] })
96
+ ]
97
+ }
98
+ );
99
+ }
100
+ function HistoryFold({ entry, words, locale, loadHistory }) {
101
+ const [lines, setLines] = React.useState(null);
102
+ const asked = React.useRef(false);
103
+ return /* @__PURE__ */ jsxs(
104
+ "details",
105
+ {
106
+ className: "group",
107
+ onToggle: (event) => {
108
+ if (!event.currentTarget.open || asked.current) return;
109
+ asked.current = true;
110
+ void loadHistory(entry.key).then(setLines);
111
+ },
112
+ children: [
113
+ /* @__PURE__ */ jsx("summary", { className: "cursor-pointer text-sm font-medium text-fg-secondary hover:text-fg", children: words.history }),
114
+ lines === null && /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-fg-secondary", children: words.loading }),
115
+ lines?.length === 0 && /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-fg-secondary", children: words.historyEmpty }),
116
+ lines && lines.length > 0 && /* @__PURE__ */ jsx("ol", { className: "mt-2 grid gap-1.5 text-sm text-fg-secondary", children: lines.map((line) => /* @__PURE__ */ jsx("li", { children: fill(words.historyLine, {
117
+ actor: line.actorLabel,
118
+ at: dateText(line.at, locale),
119
+ before: figuresText(line.before, entry.currency, locale, words),
120
+ after: figuresText(line.after, entry.currency, locale, words),
121
+ from: dateText(line.effectiveFrom, locale)
122
+ }) }, line.versionId)) })
123
+ ]
124
+ }
125
+ );
126
+ }
127
+ function PriceCatalogueEditor({ prices, words, locale, today, onSchedule, loadHistory, headingLevel = 3, className, ...props }) {
128
+ const [open, setOpen] = React.useState(null);
129
+ const [saved, setSaved] = React.useState(false);
130
+ const Heading = `h${headingLevel}`;
131
+ return /* @__PURE__ */ jsxs("section", { "data-price-catalogue": "", className: cn("grid gap-3", className), ...props, children: [
132
+ /* @__PURE__ */ jsx("ul", { className: "grid gap-3", children: prices.entries.map((entry) => /* @__PURE__ */ jsxs("li", { "data-availability": entry.availability, className: "rounded-xl border border-border bg-surface-1 p-4", children: [
133
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-between gap-x-4 gap-y-2", children: [
134
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
135
+ /* @__PURE__ */ jsxs(Heading, { className: "text-sm font-semibold text-fg", children: [
136
+ entry.product,
137
+ " \xB7 ",
138
+ entry.plan
139
+ ] }),
140
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 flex flex-wrap items-baseline gap-x-2 text-fg", children: [
141
+ /* @__PURE__ */ jsx("span", { className: "text-xl font-semibold tabular-nums", children: amountText(entry.amountCents, entry.currency, locale, words.onQuote) }),
142
+ entry.amountCents !== null && /* @__PURE__ */ jsxs("span", { className: "text-sm text-fg-secondary", children: [
143
+ words.units[entry.unit] ?? entry.unit,
144
+ " \xB7 ",
145
+ words.plusTaxes
146
+ ] })
147
+ ] })
148
+ ] }),
149
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
150
+ /* @__PURE__ */ jsx(Badge, { tone: availabilityTone(entry.availability), dot: true, children: words.availabilities[entry.availability] ?? entry.availability }),
151
+ open !== entry.key && /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "secondary", "aria-label": `${words.edit} \u2014 ${entry.product} \xB7 ${entry.plan}`, onClick: () => {
152
+ setOpen(entry.key);
153
+ setSaved(false);
154
+ }, children: words.edit })
155
+ ] })
156
+ ] }),
157
+ Object.keys(entry.limits).length > 0 && /* @__PURE__ */ jsx("dl", { className: "mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-fg-secondary", children: Object.entries(entry.limits).map(([key, value]) => /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5", children: [
158
+ /* @__PURE__ */ jsx("dt", { children: words.limitNames?.[key] ?? key }),
159
+ /* @__PURE__ */ jsx("dd", { className: "font-medium tabular-nums text-fg", children: new Intl.NumberFormat(locale).format(value) })
160
+ ] }, key)) }),
161
+ open === entry.key && /* @__PURE__ */ jsx(
162
+ EntryForm,
163
+ {
164
+ entry,
165
+ prices,
166
+ words,
167
+ locale,
168
+ today,
169
+ onSchedule,
170
+ onDone: () => {
171
+ setOpen(null);
172
+ setSaved(true);
173
+ }
174
+ }
175
+ ),
176
+ (entry.upcoming.length > 0 || loadHistory) && /* @__PURE__ */ jsxs("div", { className: "mt-3 grid gap-2", children: [
177
+ entry.upcoming.length > 0 && /* @__PURE__ */ jsxs("details", { children: [
178
+ /* @__PURE__ */ jsx("summary", { className: "cursor-pointer text-sm font-medium text-fg-secondary hover:text-fg", children: fill(words.scheduled, { count: entry.upcoming.length }) }),
179
+ /* @__PURE__ */ jsx("ul", { className: "mt-2 grid gap-1.5 text-sm text-fg-secondary", children: entry.upcoming.map((v) => /* @__PURE__ */ jsxs("li", { children: [
180
+ figuresText(v, entry.currency, locale, words),
181
+ " \xB7 ",
182
+ fill(words.scheduledLine, { from: dateText(v.effectiveFrom, locale) })
183
+ ] }, v.versionId)) })
184
+ ] }),
185
+ loadHistory && /* @__PURE__ */ jsx(HistoryFold, { entry, words, locale, loadHistory })
186
+ ] })
187
+ ] }, entry.key)) }),
188
+ /* @__PURE__ */ jsx("output", { className: "sr-only", children: saved ? words.saved : "" })
189
+ ] });
190
+ }
191
+ export {
192
+ PriceCatalogueEditor
193
+ };
194
+ //# sourceMappingURL=price-catalogue-editor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/price-catalogue-editor/price-catalogue-editor.tsx"],"sourcesContent":["\"use client\";\n// Client (the open row, the draft, the folds). An administrator edits a product's price entries: one row per entry, a\n// change that takes effect from a date (today by default, never the past) and says that current subscriptions keep their\n// price, the scheduled changes and the history folded. Fed by `describePrices()` of @krizaka/settings (JSON-safe); the\n// block never fetches, saves or reads the clock: the host passes `onSchedule`, `loadHistory` and `today`. Words are props.\nimport { currencyDigits } from \"@krizaka/intl\";\nimport * as React from \"react\";\n\nimport { Badge } from \"../badge/badge\";\nimport { Button } from \"../button/button\";\nimport { cn } from \"../cn\";\nimport { Field, Input, Select } from \"../field/field\";\nimport { MoneyInput } from \"../money-input/money-input\";\n\n/** The figures of a price: what one version of an entry holds. */\nexport interface PriceFigures {\n /** Integer cents; `null` is « on quote ». */\n amountCents: number | null;\n unit: string;\n availability: string;\n /** Named integers the product reads (`included`, `founderCap`…). */\n limits: Record<string, number>;\n}\n\n/** A change a host scheduled, still waiting for its date. */\nexport interface PriceScheduledView extends PriceFigures {\n versionId: string;\n /** ISO date-time. */\n effectiveFrom: string;\n}\n\n/** An entry as `describePrices()` returns it. */\nexport interface PriceEntryView extends PriceFigures {\n key: string;\n product: string;\n plan: string;\n currency: string;\n versionId: string;\n effectiveFrom: string;\n upcoming: PriceScheduledView[];\n}\n\n/** The catalogue as `describePrices()` returns it: the enumerations the fields offer, and the entries. */\nexport interface PricesView {\n units: string[];\n availabilities: string[];\n entries: PriceEntryView[];\n}\n\n/** One line of an entry's history: who, when, before → after, from when. */\nexport interface PriceHistoryEntry {\n versionId: string;\n /** ISO date-time the change was made. */\n at: string;\n actorLabel: string;\n effectiveFrom: string;\n before: PriceFigures | null;\n after: PriceFigures;\n}\n\n/** The result the host returns after saving. */\nexport type PriceScheduleResult = { ok: true } | { ok: false; message: string };\n\n/** The words, passed translated. `{name}` placeholders are filled by the block. */\nexport interface PriceCatalogueWords {\n /** « Change » — opens an entry's form. */\n edit: string;\n /** « Amount » */\n amount: string;\n /** « On quote » — an entry with no figure. */\n onQuote: string;\n /** « plus taxes » */\n plusTaxes: string;\n /** « Unit » */\n unit: string;\n /** « Availability » */\n availability: string;\n /** « Limits » */\n limits: string;\n /** « From » — the date the change takes effect. */\n from: string;\n /** « Current subscriptions keep their price. » */\n keepsPrice: string;\n /** « Schedule the change » */\n save: string;\n cancel: string;\n /** « Leave empty for “on quote”. » */\n emptyIsQuote: string;\n /** « Scheduled changes ({count}) » */\n scheduled: string;\n /** « History » */\n history: string;\n /** « No change yet. » */\n historyEmpty: string;\n /** « Loading… » */\n loading: string;\n /** « {actor}, {at}: {before} → {after}, from {from} » */\n historyLine: string;\n /** « from {from} » — a scheduled change. */\n scheduledLine: string;\n /** « Saved. » — announced after a change is scheduled. */\n saved: string;\n /** The unit's name by id: `{ month: \"per month\" }`. A missing id shows the id. */\n units: Record<string, string>;\n /** The availability's name by id: `{ public: \"Public\" }`. */\n availabilities: Record<string, string>;\n /** The limit's name by key: `{ founderCap: \"First customers\" }`. A missing key shows the key. */\n limitNames?: Record<string, string>;\n}\n\nexport interface PriceCatalogueEditorProps extends Omit<React.ComponentProps<\"section\">, \"children\"> {\n /** The catalogue as `describePrices()` returns it: the enumerations the fields offer, and the entries. */\n prices: PricesView;\n /** The words, passed translated (see `PriceCatalogueWords`). */\n words: PriceCatalogueWords;\n /** BCP 47 locale for the amounts and the dates: `\"fr-CA\"`. */\n locale: string;\n /** Today as `YYYY-MM-DD`: the earliest date a change may start from (the block never reads the clock). */\n today: string;\n /** Saves a change from a date (`YYYY-MM-DD`). The host validates and returns the refusal in words. */\n onSchedule: (key: string, change: PriceFigures, effectiveFrom: string) => Promise<PriceScheduleResult>;\n /** The history of an entry, asked when its fold opens. Omitted: no history fold. */\n loadHistory?: (key: string) => Promise<PriceHistoryEntry[]>;\n /** Heading level of an entry's name. @default 3 */\n headingLevel?: 2 | 3 | 4;\n}\n\nconst fill = (template: string, vars: Record<string, string | number>) => template.replace(/\\{(\\w+)\\}/g, (_, name: string) => String(vars[name] ?? \"\"));\n\nconst TONES: Record<string, \"success\" | \"accent\" | \"warning\"> = { public: \"success\", \"founder-limited\": \"accent\", preparing: \"warning\" };\nconst availabilityTone = (id: string) => TONES[id] ?? \"neutral\";\n\n/** « 9,99 $ » / « $9.99 » by locale, or the « on quote » word. Cents are bounded integers, so the division is exact for display. */\nfunction amountText(cents: number | null, currency: string, locale: string, onQuote: string): string {\n if (cents === null) return onQuote;\n const digits = currencyDigits(currency);\n return new Intl.NumberFormat(locale, { style: \"currency\", currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(cents / 10 ** digits);\n}\n\nconst dateText = (iso: string, locale: string) => new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeZone: \"UTC\" }).format(new Date(iso));\nconst figuresText = (f: PriceFigures | null, currency: string, locale: string, w: PriceCatalogueWords) =>\n f === null ? \"—\" : `${amountText(f.amountCents, currency, locale, w.onQuote)} ${w.units[f.unit] ?? f.unit}`;\n\nfunction EntryForm({ entry, prices, words, locale, today, onSchedule, onDone }: Readonly<{ entry: PriceEntryView; prices: PricesView; words: PriceCatalogueWords; locale: string; today: string; onSchedule: PriceCatalogueEditorProps[\"onSchedule\"]; onDone: () => void }>) {\n const id = React.useId();\n const [cents, setCents] = React.useState<number | null>(entry.amountCents);\n const [unit, setUnit] = React.useState(entry.unit);\n const [availability, setAvailability] = React.useState(entry.availability);\n const [limits, setLimits] = React.useState<Record<string, string>>(() => Object.fromEntries(Object.entries(entry.limits).map(([k, v]) => [k, String(v)])));\n const [from, setFrom] = React.useState(today);\n const [error, setError] = React.useState<string | null>(null);\n const [busy, setBusy] = React.useState(false);\n const limitKeys = Object.keys(entry.limits);\n const dateInvalid = from < today;\n return (\n <form\n aria-label={`${words.edit} — ${entry.product} · ${entry.plan}`}\n className=\"mt-4 grid gap-4 border-t border-border pt-4\"\n onSubmit={async (event) => {\n event.preventDefault();\n if (dateInvalid || busy) return;\n setBusy(true);\n const next: Record<string, number> = {};\n for (const key of limitKeys) next[key] = Number.parseInt(limits[key] ?? \"0\", 10) || 0;\n const result = await onSchedule(entry.key, { amountCents: cents, unit, availability, limits: next }, from);\n setBusy(false);\n if (result.ok) onDone();\n else setError(result.message);\n }}\n >\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <Field.Root>\n <Field.Label htmlFor={`${id}-amount`}>{words.amount}</Field.Label>\n <MoneyInput id={`${id}-amount`} value={cents} onValueChange={setCents} currency={entry.currency} locale={locale} aria-describedby={`${id}-amount-hint`} />\n <Field.Hint id={`${id}-amount-hint`}>{words.emptyIsQuote}</Field.Hint>\n </Field.Root>\n <Field.Root>\n <Field.Label htmlFor={`${id}-unit`}>{words.unit}</Field.Label>\n <Select id={`${id}-unit`} value={unit} onChange={(e) => setUnit(e.target.value)}>\n {prices.units.map((u) => (\n <option key={u} value={u}>\n {words.units[u] ?? u}\n </option>\n ))}\n </Select>\n </Field.Root>\n <Field.Root>\n <Field.Label htmlFor={`${id}-availability`}>{words.availability}</Field.Label>\n <Select id={`${id}-availability`} value={availability} onChange={(e) => setAvailability(e.target.value)}>\n {prices.availabilities.map((a) => (\n <option key={a} value={a}>\n {words.availabilities[a] ?? a}\n </option>\n ))}\n </Select>\n </Field.Root>\n <Field.Root>\n <Field.Label htmlFor={`${id}-from`}>{words.from}</Field.Label>\n <Input id={`${id}-from`} type=\"date\" min={today} value={from} onChange={(e) => setFrom(e.target.value)} invalid={dateInvalid} />\n </Field.Root>\n </div>\n {limitKeys.length > 0 && (\n <fieldset className=\"grid gap-4 sm:grid-cols-2\">\n <legend className=\"mb-2 text-xs font-semibold text-fg-secondary\">{words.limits}</legend>\n {limitKeys.map((key) => (\n <Field.Root key={key}>\n <Field.Label htmlFor={`${id}-limit-${key}`}>{words.limitNames?.[key] ?? key}</Field.Label>\n <Input id={`${id}-limit-${key}`} inputMode=\"numeric\" pattern=\"[0-9]*\" value={limits[key] ?? \"\"} onChange={(e) => setLimits({ ...limits, [key]: e.target.value.replace(/\\D/g, \"\") })} />\n </Field.Root>\n ))}\n </fieldset>\n )}\n <p className=\"text-sm text-fg-secondary\">{words.keepsPrice}</p>\n {error && <Field.Error>{error}</Field.Error>}\n <div className=\"flex flex-wrap gap-2\">\n <Button type=\"submit\" size=\"sm\" variant=\"primary\" disabled={busy || dateInvalid}>\n {words.save}\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={onDone}>\n {words.cancel}\n </Button>\n </div>\n </form>\n );\n}\n\nfunction HistoryFold({ entry, words, locale, loadHistory }: Readonly<{ entry: PriceEntryView; words: PriceCatalogueWords; locale: string; loadHistory: NonNullable<PriceCatalogueEditorProps[\"loadHistory\"]> }>) {\n const [lines, setLines] = React.useState<PriceHistoryEntry[] | null>(null);\n const asked = React.useRef(false);\n return (\n <details\n className=\"group\"\n onToggle={(event) => {\n if (!(event.currentTarget as HTMLDetailsElement).open || asked.current) return;\n asked.current = true;\n void loadHistory(entry.key).then(setLines);\n }}\n >\n <summary className=\"cursor-pointer text-sm font-medium text-fg-secondary hover:text-fg\">{words.history}</summary>\n {lines === null && <p className=\"mt-2 text-sm text-fg-secondary\">{words.loading}</p>}\n {lines?.length === 0 && <p className=\"mt-2 text-sm text-fg-secondary\">{words.historyEmpty}</p>}\n {lines && lines.length > 0 && (\n <ol className=\"mt-2 grid gap-1.5 text-sm text-fg-secondary\">\n {lines.map((line) => (\n <li key={line.versionId}>\n {fill(words.historyLine, {\n actor: line.actorLabel,\n at: dateText(line.at, locale),\n before: figuresText(line.before, entry.currency, locale, words),\n after: figuresText(line.after, entry.currency, locale, words),\n from: dateText(line.effectiveFrom, locale),\n })}\n </li>\n ))}\n </ol>\n )}\n </details>\n );\n}\n\n/** The price entries of a product, each editable from a date, with what is scheduled and its history folded. */\nexport function PriceCatalogueEditor({ prices, words, locale, today, onSchedule, loadHistory, headingLevel = 3, className, ...props }: Readonly<PriceCatalogueEditorProps>) {\n const [open, setOpen] = React.useState<string | null>(null);\n const [saved, setSaved] = React.useState(false);\n const Heading = `h${headingLevel}` as \"h3\";\n return (\n <section data-price-catalogue=\"\" className={cn(\"grid gap-3\", className)} {...props}>\n <ul className=\"grid gap-3\">\n {prices.entries.map((entry) => (\n <li key={entry.key} data-availability={entry.availability} className=\"rounded-xl border border-border bg-surface-1 p-4\">\n <div className=\"flex flex-wrap items-start justify-between gap-x-4 gap-y-2\">\n <div className=\"min-w-0\">\n <Heading className=\"text-sm font-semibold text-fg\">\n {entry.product} · {entry.plan}\n </Heading>\n <p className=\"mt-1 flex flex-wrap items-baseline gap-x-2 text-fg\">\n <span className=\"text-xl font-semibold tabular-nums\">{amountText(entry.amountCents, entry.currency, locale, words.onQuote)}</span>\n {entry.amountCents !== null && (\n <span className=\"text-sm text-fg-secondary\">\n {words.units[entry.unit] ?? entry.unit} · {words.plusTaxes}\n </span>\n )}\n </p>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Badge tone={availabilityTone(entry.availability)} dot>\n {words.availabilities[entry.availability] ?? entry.availability}\n </Badge>\n {open !== entry.key && (\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" aria-label={`${words.edit} — ${entry.product} · ${entry.plan}`} onClick={() => {\n setOpen(entry.key);\n setSaved(false);\n }}>\n {words.edit}\n </Button>\n )}\n </div>\n </div>\n {Object.keys(entry.limits).length > 0 && (\n <dl className=\"mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-fg-secondary\">\n {Object.entries(entry.limits).map(([key, value]) => (\n <div key={key} className=\"flex gap-1.5\">\n <dt>{words.limitNames?.[key] ?? key}</dt>\n <dd className=\"font-medium tabular-nums text-fg\">{new Intl.NumberFormat(locale).format(value)}</dd>\n </div>\n ))}\n </dl>\n )}\n {open === entry.key && (\n <EntryForm\n entry={entry}\n prices={prices}\n words={words}\n locale={locale}\n today={today}\n onSchedule={onSchedule}\n onDone={() => {\n setOpen(null);\n setSaved(true);\n }}\n />\n )}\n {(entry.upcoming.length > 0 || loadHistory) && (\n <div className=\"mt-3 grid gap-2\">\n {entry.upcoming.length > 0 && (\n <details>\n <summary className=\"cursor-pointer text-sm font-medium text-fg-secondary hover:text-fg\">{fill(words.scheduled, { count: entry.upcoming.length })}</summary>\n <ul className=\"mt-2 grid gap-1.5 text-sm text-fg-secondary\">\n {entry.upcoming.map((v) => (\n <li key={v.versionId}>\n {figuresText(v, entry.currency, locale, words)} · {fill(words.scheduledLine, { from: dateText(v.effectiveFrom, locale) })}\n </li>\n ))}\n </ul>\n </details>\n )}\n {loadHistory && <HistoryFold entry={entry} words={words} locale={locale} loadHistory={loadHistory} />}\n </div>\n )}\n </li>\n ))}\n </ul>\n <output className=\"sr-only\">{saved ? words.saved : \"\"}</output>\n </section>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,sBAAsB;AAC/B,YAAY,WAAW;AAqKf,SACE,KADF;AA5CR,IAAM,OAAO,CAAC,UAAkB,SAA0C,SAAS,QAAQ,cAAc,CAAC,GAAG,SAAiB,OAAO,KAAK,IAAI,KAAK,EAAE,CAAC;AAEtJ,IAAM,QAA0D,EAAE,QAAQ,WAAW,mBAAmB,UAAU,WAAW,UAAU;AACvI,IAAM,mBAAmB,CAAC,OAAe,MAAM,EAAE,KAAK;AAGtD,SAAS,WAAW,OAAsB,UAAkB,QAAgB,SAAyB;AACnG,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,SAAS,eAAe,QAAQ;AACtC,SAAO,IAAI,KAAK,aAAa,QAAQ,EAAE,OAAO,YAAY,UAAU,uBAAuB,QAAQ,uBAAuB,OAAO,CAAC,EAAE,OAAO,QAAQ,MAAM,MAAM;AACjK;AAEA,IAAM,WAAW,CA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QAAG,WAAU,oCAAoC,cAAI,KAAK,aAAa,MAAM,EAAE,OAAO,KAAK,GAAE;AAAA,WAFtF,GAGV,CACD,GACH;AAAA,MAED,SAAS,MAAM,OACd;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA,QAAQ,MAAM;AACZ,oBAAQ,IAAI;AACZ,qBAAS,IAAI;AAAA,UACf;AAAA;AAAA,MACF;AAAA,OAEA,MAAM,SAAS,SAAS,KAAK,gBAC7B,qBAAC,SAAI,WAAU,mBACZ;AAAA,cAAM,SAAS,SAAS,KACvB,qBAAC,aACC;AAAA,8BAAC,aAAQ,WAAU,sEAAsE,eAAK,MAAM,WAAW,EAAE,OAAO,MAAM,SAAS,OAAO,CAAC,GAAE;AAAA,UACjJ,oBAAC,QAAG,WAAU,+CACX,gBAAM,SAAS,IAAI,CAAC,MACnB,qBAAC,QACE;AAAA,wBAAY,GAAG,MAAM,UAAU,QAAQ,KAAK;AAAA,YAAE;AAAA,YAAI,KAAK,MAAM,eAAe,EAAE,MAAM,SAAS,EAAE,eAAe,MAAM,EAAE,CAAC;AAAA,eADjH,EAAE,SAEX,CACD,GACH;AAAA,WACF;AAAA,QAED,eAAe,oBAAC,eAAY,OAAc,OAAc,QAAgB,aAA0B;AAAA,SACrG;AAAA,SApEK,MAAM,GAsEf,CACD,GACH;AAAA,IACA,oBAAC,YAAO,WAAU,WAAW,kBAAQ,MAAM,QAAQ,IAAG;AAAA,KACxD;AAEJ;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  Field,
4
4
  Input
5
- } from "./chunk-PZ4FJOD5.js";
5
+ } from "./chunk-HLEBSAGC.js";
6
6
  import {
7
7
  Button
8
8
  } from "./chunk-V7W4RLRW.js";
@@ -0,0 +1,106 @@
1
+ import * as React from 'react';
2
+
3
+ /** What a field is drawn as. */
4
+ type SchemaFieldKind = "text" | "textarea" | "number" | "integer" | "boolean" | "select" | "date" | "money" | "list";
5
+ /** One field of the form, derived from a property of the schema. */
6
+ interface SchemaField {
7
+ key: string;
8
+ kind: SchemaFieldKind;
9
+ /** The title in the page's language (`x-i18n`), else the schema's `title`, else the key. */
10
+ title: string;
11
+ /** A line of help under the field. */
12
+ description: string | null;
13
+ /** An example of what to type. */
14
+ placeholder: string | null;
15
+ required: boolean;
16
+ /** `x-advanced`: folded under « more options ». */
17
+ advanced: boolean;
18
+ /** A closed list: `enum` or `oneOf` of `const`, with the labels of the language. */
19
+ options: {
20
+ value: string;
21
+ label: string;
22
+ }[] | null;
23
+ min: number | null;
24
+ max: number | null;
25
+ minLength: number | null;
26
+ maxLength: number | null;
27
+ maxItems: number | null;
28
+ pattern: string | null;
29
+ /** The ISO 4217 code of a `money` field (`x-money.currency`, default CAD). */
30
+ currency: string;
31
+ /** The value the form starts on, when the schema states one. */
32
+ defaultValue: unknown;
33
+ }
34
+ /** The fields of a JSON Schema object, in the schema's order. A property the form cannot draw (a nested object…) is left out. */
35
+ declare function fieldsFromSchema(schema: unknown, locale: string): SchemaField[];
36
+ /** The words of the checks, passed translated. `{min}`, `{max}` are filled. */
37
+ interface SchemaFormMessages {
38
+ required: string;
39
+ /** « At least {min} characters. » */
40
+ tooShort: string;
41
+ /** « At most {max} characters. » */
42
+ tooLong: string;
43
+ /** « Not below {min}. » */
44
+ belowMin: string;
45
+ /** « Not above {max}. » */
46
+ aboveMax: string;
47
+ /** « Not a number. » */
48
+ notANumber: string;
49
+ /** « Not in the expected form. » */
50
+ badPattern: string;
51
+ /** « At most {max} items. » */
52
+ tooMany: string;
53
+ }
54
+ /** A list typed as « a, b, c »: its items. */
55
+ declare const listItems: (text: string) => string[];
56
+ /** The raw answer of a field as the form holds it (a string, a boolean, or cents), checked against the schema's rules. Returns the message, or null. */
57
+ declare function checkField(field: SchemaField, value: unknown, m: SchemaFormMessages): string | null;
58
+ /** The messages of every field that fails; an empty object is a valid form. */
59
+ declare function checkValues(fields: readonly SchemaField[], values: Record<string, unknown>, m: SchemaFormMessages): Record<string, string>;
60
+ /** What a form holds at the start: the schema's defaults, then the given values. */
61
+ declare function initialValues(fields: readonly SchemaField[], given?: Record<string, unknown>): Record<string, unknown>;
62
+ /** The typed payload the host receives: numbers as numbers, lists as arrays, money as integer cents, empty answers left out. */
63
+ declare function payloadOf(fields: readonly SchemaField[], values: Record<string, unknown>): Record<string, unknown>;
64
+
65
+ /** What a custom field receives to draw itself. */
66
+ interface SchemaFieldContext {
67
+ /** An id to wire the label (`htmlFor`) and the description. */
68
+ id: string;
69
+ /** The raw answer: a string, a boolean, or integer cents for a money field. */
70
+ value: unknown;
71
+ setValue: (value: unknown) => void;
72
+ /** The refusal to show, or `null`. */
73
+ error: string | null;
74
+ disabled: boolean;
75
+ }
76
+ interface SchemaFormWords {
77
+ /** The submit button: « Run ». */
78
+ submit: string;
79
+ /** The fold of the `x-advanced` fields: « More options ». */
80
+ advanced: string;
81
+ }
82
+ interface SchemaFormProps extends Omit<React.ComponentProps<"form">, "onSubmit" | "children"> {
83
+ /** The JSON Schema object (or its JSON text): `properties`, `required`, `x-i18n`, `x-advanced`. */
84
+ schema: unknown;
85
+ /** BCP 47 language for the `x-i18n` words and the money: `"fr-CA"`. */
86
+ locale: string;
87
+ /** The words, passed translated. */
88
+ words: SchemaFormWords;
89
+ /** The checks' words, passed translated. */
90
+ messages: SchemaFormMessages;
91
+ /** Answers to start from, by field key (over the schema's defaults). */
92
+ values?: Record<string, unknown>;
93
+ /** Called with the typed payload once every field passes. */
94
+ onSubmit: (payload: Record<string, unknown>) => void;
95
+ /** The form is being submitted: the fields are blocked and the button shows progress (no second submit). */
96
+ submitting?: boolean;
97
+ /** Draws a field in the host's way (an upload, a picker); return `undefined` for the default. */
98
+ renderField?: (field: SchemaField, context: SchemaFieldContext) => React.ReactNode;
99
+ /** Beside the submit button: a cost line, a note. */
100
+ footer?: React.ReactNode;
101
+ }
102
+ /** A form from a JSON Schema: typed fields, the schema's rules, `x-i18n` words, `x-advanced` folded. */
103
+ declare function SchemaForm({ schema, locale, words, messages, values: given, onSubmit, submitting, renderField, footer, className, ...props }: Readonly<SchemaFormProps>): React.JSX.Element;
104
+
105
+ export { SchemaForm, checkField, checkValues, fieldsFromSchema, initialValues, listItems, payloadOf };
106
+ export type { SchemaField, SchemaFieldContext, SchemaFieldKind, SchemaFormMessages, SchemaFormProps, SchemaFormWords };
@@ -0,0 +1,268 @@
1
+ "use client";
2
+ import {
3
+ MoneyInput
4
+ } from "./chunk-W64RAX4N.js";
5
+ import {
6
+ Field,
7
+ Input,
8
+ Select,
9
+ Textarea
10
+ } from "./chunk-HLEBSAGC.js";
11
+ import {
12
+ Switch
13
+ } from "./chunk-CZHPWLNW.js";
14
+ import {
15
+ Button
16
+ } from "./chunk-V7W4RLRW.js";
17
+ import "./chunk-D3T54RSL.js";
18
+ import "./chunk-WEVYKZIF.js";
19
+ import {
20
+ cn
21
+ } from "./chunk-NSLXEDIS.js";
22
+
23
+ // src/schema-form/schema.ts
24
+ var MULTILINE_OVER = 500;
25
+ var obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : null;
26
+ var str = (v) => typeof v === "string" && v.trim() !== "" ? v : null;
27
+ var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
28
+ function wordsFor(i18n, locale) {
29
+ const by = obj(i18n);
30
+ if (!by) return null;
31
+ return obj(by[locale]) ?? obj(by[locale.split("-")[0] ?? ""]) ?? obj(by.en);
32
+ }
33
+ function optionsOf(spec, words) {
34
+ const label = (value) => {
35
+ const w = words?.options?.[value];
36
+ return typeof w === "string" ? w : w?.label ?? null;
37
+ };
38
+ if (Array.isArray(spec.enum)) return spec.enum.map(String).map((value) => ({ value, label: label(value) ?? value }));
39
+ const one = spec.oneOf;
40
+ if (Array.isArray(one) && one.length > 0 && one.every((e) => obj(e) && "const" in e)) {
41
+ return one.map((e) => ({ value: String(e.const), label: label(String(e.const)) ?? str(e.title) ?? String(e.const) }));
42
+ }
43
+ return null;
44
+ }
45
+ function kindOf(spec, options) {
46
+ const items = obj(spec.items);
47
+ if (options) return "select";
48
+ if (spec["x-money"] || spec.format === "money") return "money";
49
+ switch (spec.type) {
50
+ case "boolean":
51
+ return "boolean";
52
+ case "integer":
53
+ return "integer";
54
+ case "number":
55
+ return "number";
56
+ case "array":
57
+ return items && (items.type === void 0 || items.type === "string") ? "list" : null;
58
+ case "string":
59
+ case void 0:
60
+ if (spec.format === "date") return "date";
61
+ return (num(spec.maxLength) ?? 0) > MULTILINE_OVER ? "textarea" : "text";
62
+ default:
63
+ return null;
64
+ }
65
+ }
66
+ function fieldsFromSchema(schema, locale) {
67
+ let root = obj(schema);
68
+ if (typeof schema === "string") {
69
+ try {
70
+ root = obj(JSON.parse(schema));
71
+ } catch {
72
+ root = null;
73
+ }
74
+ }
75
+ const properties = obj(root?.properties);
76
+ if (!properties) return [];
77
+ const required = new Set(Array.isArray(root?.required) ? root.required.map(String) : []);
78
+ const fields = [];
79
+ for (const [key, raw] of Object.entries(properties)) {
80
+ const spec = obj(raw);
81
+ if (!spec) continue;
82
+ const words = wordsFor(spec["x-i18n"], locale);
83
+ const options = optionsOf(spec, words);
84
+ const kind = kindOf(spec, options);
85
+ if (!kind) continue;
86
+ fields.push({
87
+ key,
88
+ kind,
89
+ title: words?.title ?? str(spec.title) ?? key,
90
+ description: words?.description ?? str(spec.description),
91
+ placeholder: words?.placeholder ?? null,
92
+ required: required.has(key),
93
+ advanced: spec["x-advanced"] === true,
94
+ options,
95
+ min: num(spec.minimum),
96
+ max: num(spec.maximum),
97
+ minLength: num(spec.minLength),
98
+ maxLength: num(spec.maxLength),
99
+ maxItems: num(spec.maxItems),
100
+ pattern: str(spec.pattern),
101
+ currency: str(obj(spec["x-money"])?.currency) ?? "CAD",
102
+ defaultValue: spec.default ?? null
103
+ });
104
+ }
105
+ return fields;
106
+ }
107
+ var fill = (template, vars) => template.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? ""));
108
+ var listItems = (text) => text.split(",").map((s) => s.trim()).filter(Boolean);
109
+ var asNumber = (text) => Number(text.replace(",", "."));
110
+ function checkNumber(field, text, m) {
111
+ const n = asNumber(text);
112
+ if (!Number.isFinite(n) || field.kind === "integer" && !Number.isInteger(n)) return m.notANumber;
113
+ if (field.min !== null && n < field.min) return fill(m.belowMin, { min: field.min });
114
+ if (field.max !== null && n > field.max) return fill(m.aboveMax, { max: field.max });
115
+ return null;
116
+ }
117
+ function checkText(field, text, m) {
118
+ if (field.minLength !== null && text.length < field.minLength) return fill(m.tooShort, { min: field.minLength });
119
+ if (field.maxLength !== null && text.length > field.maxLength) return fill(m.tooLong, { max: field.maxLength });
120
+ if (field.pattern !== null && !new RegExp(field.pattern, "u").test(text)) return m.badPattern;
121
+ return null;
122
+ }
123
+ function checkField(field, value, m) {
124
+ if (field.kind === "boolean") return null;
125
+ const empty = field.kind === "money" ? value === null || value === void 0 : textOf(value) === "";
126
+ if (empty) return field.required ? m.required : null;
127
+ if (field.kind === "money") return null;
128
+ const text = textOf(value);
129
+ if (field.kind === "number" || field.kind === "integer") return checkNumber(field, text, m);
130
+ if (field.kind === "list") return field.maxItems !== null && listItems(text).length > field.maxItems ? fill(m.tooMany, { max: field.maxItems }) : null;
131
+ return checkText(field, text, m);
132
+ }
133
+ function checkValues(fields, values, m) {
134
+ const errors = {};
135
+ for (const field of fields) {
136
+ const message = checkField(field, values[field.key], m);
137
+ if (message) errors[field.key] = message;
138
+ }
139
+ return errors;
140
+ }
141
+ var textOf = (v) => typeof v === "string" ? v.trim() : "";
142
+ function startOf(f, v) {
143
+ if (f.kind === "boolean") return v === true;
144
+ if (f.kind === "money") return typeof v === "number" ? v : null;
145
+ if (f.kind === "list" && Array.isArray(v)) return v.join(", ");
146
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return String(v);
147
+ return "";
148
+ }
149
+ function initialValues(fields, given = {}) {
150
+ return Object.fromEntries(fields.map((f) => [f.key, startOf(f, given[f.key] ?? f.defaultValue)]));
151
+ }
152
+ function typed(f, text) {
153
+ if (f.kind === "number" || f.kind === "integer") return asNumber(text);
154
+ return f.kind === "list" ? listItems(text) : text;
155
+ }
156
+ function payloadOf(fields, values) {
157
+ const out = {};
158
+ for (const f of fields) {
159
+ const v = values[f.key];
160
+ if (f.kind === "boolean") out[f.key] = v === true;
161
+ else if (f.kind === "money") {
162
+ if (typeof v === "number") out[f.key] = v;
163
+ } else if (textOf(v) !== "") out[f.key] = typed(f, textOf(v));
164
+ }
165
+ return out;
166
+ }
167
+
168
+ // src/schema-form/schema-form.tsx
169
+ import * as React from "react";
170
+ import { jsx, jsxs } from "react/jsx-runtime";
171
+ function FieldControl({ field, ctx, locale }) {
172
+ const { id, value, setValue, error, disabled } = ctx;
173
+ const describedBy = [field.description ? `${id}-help` : null, error ? `${id}-error` : null].filter(Boolean).join(" ") || void 0;
174
+ const common = { id, disabled, "aria-describedby": describedBy, "aria-required": field.required || void 0 };
175
+ const text = typeof value === "string" ? value : "";
176
+ switch (field.kind) {
177
+ case "boolean":
178
+ return /* @__PURE__ */ jsx(Switch, { id, disabled, "aria-describedby": describedBy, checked: value === true, onCheckedChange: setValue });
179
+ case "select":
180
+ return /* @__PURE__ */ jsxs(Select, { ...common, invalid: !!error, value: text, onChange: (e) => setValue(e.target.value), children: [
181
+ !field.required && /* @__PURE__ */ jsx("option", { value: "" }),
182
+ field.options?.map((o) => /* @__PURE__ */ jsx("option", { value: o.value, children: o.label }, o.value))
183
+ ] });
184
+ case "textarea":
185
+ return /* @__PURE__ */ jsx(Textarea, { ...common, invalid: !!error, value: text, maxLength: field.maxLength ?? void 0, placeholder: field.placeholder ?? void 0, onChange: (e) => setValue(e.target.value) });
186
+ case "money":
187
+ return /* @__PURE__ */ jsx(MoneyInput, { ...common, invalid: !!error, value: typeof value === "number" ? value : null, onValueChange: setValue, currency: field.currency, locale });
188
+ case "number":
189
+ case "integer":
190
+ return /* @__PURE__ */ jsx(Input, { ...common, invalid: !!error, type: "text", inputMode: field.kind === "integer" ? "numeric" : "decimal", value: text, placeholder: field.placeholder ?? void 0, onChange: (e) => setValue(e.target.value) });
191
+ case "date":
192
+ return /* @__PURE__ */ jsx(Input, { ...common, invalid: !!error, type: "date", value: text, onChange: (e) => setValue(e.target.value) });
193
+ default:
194
+ return /* @__PURE__ */ jsx(Input, { ...common, invalid: !!error, type: "text", value: text, maxLength: field.maxLength ?? void 0, placeholder: field.placeholder ?? void 0, onChange: (e) => setValue(e.target.value) });
195
+ }
196
+ }
197
+ function SchemaForm({ schema, locale, words, messages, values: given, onSubmit, submitting = false, renderField, footer, className, ...props }) {
198
+ const base = React.useId();
199
+ const fields = React.useMemo(() => fieldsFromSchema(schema, locale), [schema, locale]);
200
+ const [answers, setAnswers] = React.useState(() => initialValues(fields, given));
201
+ const [shown, setShown] = React.useState(() => /* @__PURE__ */ new Set());
202
+ const errors = React.useMemo(() => checkValues(fields, answers, messages), [fields, answers, messages]);
203
+ const formRef = React.useRef(null);
204
+ const draw = (field) => {
205
+ const id = `${base}-${field.key}`;
206
+ const error = shown.has(field.key) ? errors[field.key] ?? null : null;
207
+ const ctx = { id, value: answers[field.key], setValue: (v) => setAnswers((a) => ({ ...a, [field.key]: v })), error, disabled: submitting };
208
+ const custom = renderField?.(field, ctx);
209
+ const inline = field.kind === "boolean";
210
+ return /* @__PURE__ */ jsxs(Field.Root, { "data-field": field.key, "data-kind": field.kind, onBlur: () => setShown((s) => s.has(field.key) ? s : new Set(s).add(field.key)), children: [
211
+ /* @__PURE__ */ jsxs("div", { className: cn(inline && "flex items-center justify-between gap-3"), children: [
212
+ /* @__PURE__ */ jsxs(Field.Label, { htmlFor: id, children: [
213
+ field.title,
214
+ field.required && /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: " *" })
215
+ ] }),
216
+ inline && (custom ?? /* @__PURE__ */ jsx(FieldControl, { field, ctx, locale }))
217
+ ] }),
218
+ !inline && (custom ?? /* @__PURE__ */ jsx(FieldControl, { field, ctx, locale })),
219
+ field.description && /* @__PURE__ */ jsx(Field.Hint, { id: `${id}-help`, children: field.description }),
220
+ error && /* @__PURE__ */ jsx(Field.Error, { id: `${id}-error`, children: error })
221
+ ] }, field.key);
222
+ };
223
+ const main = fields.filter((f) => !f.advanced);
224
+ const more = fields.filter((f) => f.advanced);
225
+ return /* @__PURE__ */ jsxs(
226
+ "form",
227
+ {
228
+ ref: formRef,
229
+ noValidate: true,
230
+ "data-schema-form": "",
231
+ className: cn("flex flex-col gap-4", className),
232
+ onSubmit: (event) => {
233
+ event.preventDefault();
234
+ if (submitting) return;
235
+ const failing = Object.keys(errors);
236
+ if (failing.length > 0) {
237
+ setShown(new Set(fields.map((f) => f.key)));
238
+ const first = fields.find((f) => errors[f.key]);
239
+ if (first) formRef.current?.querySelector(`[data-field="${first.key}"] :is(input,select,textarea,button[role=switch])`)?.focus();
240
+ return;
241
+ }
242
+ onSubmit(payloadOf(fields, answers));
243
+ },
244
+ ...props,
245
+ children: [
246
+ /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: main.map(draw) }),
247
+ more.length > 0 && /* @__PURE__ */ jsxs("details", { className: "rounded-lg border border-border px-3 py-2", open: more.some((f) => shown.has(f.key) && errors[f.key]) || void 0, children: [
248
+ /* @__PURE__ */ jsx("summary", { className: "cursor-pointer select-none text-sm font-medium text-fg-secondary", children: words.advanced }),
249
+ /* @__PURE__ */ jsx("div", { className: "mt-3 flex flex-col gap-3", children: more.map(draw) })
250
+ ] }),
251
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
252
+ /* @__PURE__ */ jsx("div", { className: "min-w-0 text-xs text-fg-secondary", children: footer }),
253
+ /* @__PURE__ */ jsx(Button, { type: "submit", variant: "primary", size: "md", loading: submitting, children: words.submit })
254
+ ] })
255
+ ]
256
+ }
257
+ );
258
+ }
259
+ export {
260
+ SchemaForm,
261
+ checkField,
262
+ checkValues,
263
+ fieldsFromSchema,
264
+ initialValues,
265
+ listItems,
266
+ payloadOf
267
+ };
268
+ //# sourceMappingURL=schema-form.js.map