@whity/ui 0.5.0 → 1.0.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 (205) hide show
  1. package/README.md +107 -107
  2. package/package.json +221 -192
  3. package/src/access-denied.stories.tsx +179 -179
  4. package/src/access-denied.tsx +305 -305
  5. package/src/action-proposal.tsx +338 -302
  6. package/src/actor-chip.tsx +71 -71
  7. package/src/agent-activity.tsx +163 -163
  8. package/src/agent-collaboration.stories.tsx +156 -156
  9. package/src/agent-run-status.tsx +196 -196
  10. package/src/alert-dialog.stories.tsx +45 -45
  11. package/src/alert-dialog.tsx +147 -147
  12. package/src/alert.stories.tsx +91 -91
  13. package/src/alert.tsx +89 -89
  14. package/src/app-sidebar.stories.tsx +195 -195
  15. package/src/app-sidebar.tsx +604 -500
  16. package/src/approval-queue.tsx +109 -108
  17. package/src/audience-group-picker.stories.tsx +198 -198
  18. package/src/audience-group-picker.tsx +362 -362
  19. package/src/audience-people-picker.stories.tsx +102 -102
  20. package/src/audience-people-picker.tsx +279 -279
  21. package/src/avatar-pattern.ts +138 -0
  22. package/src/avatar.tsx +125 -83
  23. package/src/badge.stories.tsx +105 -105
  24. package/src/badge.tsx +68 -68
  25. package/src/beta-warning.stories.tsx +79 -79
  26. package/src/beta-warning.tsx +189 -189
  27. package/src/bilingual-input.stories.tsx +82 -82
  28. package/src/bilingual-input.tsx +188 -183
  29. package/src/board.tsx +216 -0
  30. package/src/breadcrumb.stories.tsx +51 -51
  31. package/src/breadcrumb.tsx +90 -90
  32. package/src/built-on-whity.tsx +52 -0
  33. package/src/button.stories.tsx +87 -87
  34. package/src/button.tsx +123 -118
  35. package/src/card.stories.tsx +423 -423
  36. package/src/card.tsx +180 -180
  37. package/src/chart.stories.tsx +66 -66
  38. package/src/chart.tsx +228 -228
  39. package/src/checkbox.stories.tsx +62 -62
  40. package/src/checkbox.tsx +54 -54
  41. package/src/collapsible.stories.tsx +48 -48
  42. package/src/collapsible.tsx +34 -34
  43. package/src/color-card.stories.tsx +61 -61
  44. package/src/color-card.tsx +270 -270
  45. package/src/color-picker.stories.tsx +65 -65
  46. package/src/color-picker.tsx +425 -425
  47. package/src/column-matcher.tsx +84 -0
  48. package/src/command-palette.tsx +398 -306
  49. package/src/confirm-action.tsx +98 -0
  50. package/src/copy-block.stories.tsx +38 -38
  51. package/src/copy-block.tsx +85 -85
  52. package/src/data-table.stories.tsx +200 -200
  53. package/src/data-table.tsx +1686 -1106
  54. package/src/date-picker.stories.tsx +61 -61
  55. package/src/date-picker.tsx +456 -422
  56. package/src/design-cards.stories.tsx +551 -458
  57. package/src/dialog.stories.tsx +48 -48
  58. package/src/dialog.tsx +179 -166
  59. package/src/display-preferences.tsx +50 -0
  60. package/src/documents/barcode-svg.stories.tsx +72 -72
  61. package/src/documents/barcode-svg.tsx +79 -79
  62. package/src/dropdown-menu.stories.tsx +77 -77
  63. package/src/dropdown-menu.tsx +271 -271
  64. package/src/editor/agent-panel.tsx +222 -0
  65. package/src/editor/agents.stories.tsx +81 -0
  66. package/src/editor/agents.ts +55 -0
  67. package/src/editor/behaviour.ts +279 -279
  68. package/src/editor/block-ids.ts +44 -44
  69. package/src/editor/block-list.tsx +104 -101
  70. package/src/editor/block-toolbar.tsx +490 -477
  71. package/src/editor/bubble.tsx +119 -93
  72. package/src/editor/catalogue.ts +169 -103
  73. package/src/editor/collab-rail.tsx +746 -746
  74. package/src/editor/collab.stories.tsx +207 -207
  75. package/src/editor/collab.ts +87 -87
  76. package/src/editor/contract.ts +476 -408
  77. package/src/editor/convert.ts +414 -362
  78. package/src/editor/doc-editor.stories.tsx +98 -98
  79. package/src/editor/doc-editor.tsx +1492 -1287
  80. package/src/editor/editor.css +636 -536
  81. package/src/editor/extensions.ts +86 -86
  82. package/src/editor/field-bar.tsx +154 -0
  83. package/src/editor/field-picker.tsx +109 -107
  84. package/src/editor/fields.ts +100 -100
  85. package/src/editor/gutter.tsx +443 -367
  86. package/src/editor/index.ts +23 -22
  87. package/src/editor/label-sheet.tsx +289 -289
  88. package/src/editor/labels.ts +394 -310
  89. package/src/editor/link-tools.tsx +141 -141
  90. package/src/editor/node-views.tsx +461 -450
  91. package/src/editor/page-view.tsx +372 -353
  92. package/src/editor/phone.tsx +310 -0
  93. package/src/editor/plugin-block-view.tsx +230 -0
  94. package/src/editor/plugin-blocks.stories.tsx +96 -0
  95. package/src/editor/plugin-blocks.ts +52 -0
  96. package/src/editor/publish-check.tsx +201 -182
  97. package/src/editor/rich-blocks.stories.tsx +146 -146
  98. package/src/editor/sample.ts +40 -40
  99. package/src/editor/save-block-dialog.tsx +141 -0
  100. package/src/editor/saved-block-view.tsx +205 -0
  101. package/src/editor/saved-blocks.stories.tsx +105 -0
  102. package/src/editor/saved-parts.ts +192 -0
  103. package/src/editor/schema-rich.ts +156 -150
  104. package/src/editor/schema.ts +368 -315
  105. package/src/editor/services.tsx +205 -127
  106. package/src/editor/slash.ts +64 -64
  107. package/src/editor/suggesting.ts +372 -372
  108. package/src/editor/suggestions.ts +763 -763
  109. package/src/editor/table-keys.ts +66 -66
  110. package/src/editor/templates.stories.tsx +324 -324
  111. package/src/editor/toolbar.tsx +364 -358
  112. package/src/empty-state.stories.tsx +51 -51
  113. package/src/empty-state.tsx +126 -100
  114. package/src/empty-state.usage-notes.md +30 -30
  115. package/src/form.stories.tsx +112 -112
  116. package/src/form.tsx +176 -176
  117. package/src/globals.css +20 -20
  118. package/src/icon-button.tsx +85 -85
  119. package/src/icon-map.ts +335 -244
  120. package/src/icon.tsx +41 -41
  121. package/src/index.ts +90 -67
  122. package/src/input.stories.tsx +157 -157
  123. package/src/input.tsx +768 -759
  124. package/src/kpi-strip.tsx +47 -0
  125. package/src/localized-text.ts +76 -0
  126. package/src/locked-screen.stories.tsx +29 -29
  127. package/src/locked-screen.tsx +75 -61
  128. package/src/lockup.tsx +42 -0
  129. package/src/lottie.tsx +441 -0
  130. package/src/mark.tsx +62 -62
  131. package/src/math-text.stories.tsx +33 -33
  132. package/src/math-text.tsx +43 -43
  133. package/src/menu-bar.stories.tsx +198 -198
  134. package/src/menu-bar.tsx +373 -373
  135. package/src/message-thread.tsx +181 -0
  136. package/src/money/currency.ts +244 -230
  137. package/src/money/money-input.tsx +131 -0
  138. package/src/money/money.tsx +33 -0
  139. package/src/open-on-computer.tsx +150 -0
  140. package/src/otp-input.tsx +161 -0
  141. package/src/page-header.stories.tsx +95 -95
  142. package/src/page-header.tsx +122 -122
  143. package/src/page-shell.stories.tsx +42 -42
  144. package/src/page-shell.tsx +32 -32
  145. package/src/page-states.tsx +277 -0
  146. package/src/pagination.stories.tsx +45 -45
  147. package/src/pagination.tsx +98 -98
  148. package/src/paper-sheet.stories.tsx +88 -0
  149. package/src/paper-sheet.tsx +85 -0
  150. package/src/phone-tab-bar.tsx +152 -0
  151. package/src/plugin-card.stories.tsx +208 -180
  152. package/src/plugin-card.tsx +931 -848
  153. package/src/popover.stories.tsx +48 -48
  154. package/src/popover.tsx +55 -55
  155. package/src/radio-group.stories.tsx +26 -26
  156. package/src/radio-group.tsx +44 -44
  157. package/src/route-flow/editor.tsx +1087 -1014
  158. package/src/route-flow/model.ts +771 -716
  159. package/src/save-bar.tsx +94 -0
  160. package/src/scope-grant.tsx +139 -139
  161. package/src/screen-too-small.stories.tsx +61 -61
  162. package/src/screen-too-small.tsx +104 -104
  163. package/src/search-field.tsx +65 -0
  164. package/src/select.stories.tsx +44 -44
  165. package/src/select.tsx +197 -197
  166. package/src/separator.stories.tsx +34 -34
  167. package/src/separator.tsx +34 -34
  168. package/src/sheet.stories.tsx +49 -49
  169. package/src/sheet.tsx +168 -168
  170. package/src/skeleton.stories.tsx +28 -28
  171. package/src/skeleton.tsx +19 -19
  172. package/src/slider.stories.tsx +78 -78
  173. package/src/slider.tsx +300 -300
  174. package/src/spinner.stories.tsx +33 -33
  175. package/src/spinner.tsx +55 -55
  176. package/src/stepper.tsx +85 -0
  177. package/src/switch.stories.tsx +42 -42
  178. package/src/switch.tsx +41 -41
  179. package/src/switcher.stories.tsx +111 -111
  180. package/src/switcher.tsx +131 -131
  181. package/src/system-state.tsx +55 -0
  182. package/src/table.stories.tsx +48 -48
  183. package/src/table.tsx +121 -121
  184. package/src/tabs.stories.tsx +74 -74
  185. package/src/tabs.tsx +90 -90
  186. package/src/tag-input.stories.tsx +67 -67
  187. package/src/tag-input.tsx +117 -117
  188. package/src/tenant-logo.tsx +63 -63
  189. package/src/tenant-switcher.stories.tsx +38 -38
  190. package/src/tenant-switcher.tsx +164 -164
  191. package/src/textarea.stories.tsx +27 -27
  192. package/src/textarea.tsx +18 -18
  193. package/src/theme-mode.ts +52 -52
  194. package/src/time-grid.tsx +163 -0
  195. package/src/time-picker.stories.tsx +62 -62
  196. package/src/time-picker.tsx +615 -615
  197. package/src/toggle-group.tsx +138 -138
  198. package/src/tooltip.stories.tsx +43 -43
  199. package/src/tooltip.tsx +73 -73
  200. package/src/top-nav.stories.tsx +58 -58
  201. package/src/top-nav.tsx +324 -324
  202. package/src/undo-bar.tsx +107 -107
  203. package/src/utils.ts +45 -45
  204. package/src/view-toggle.stories.tsx +84 -84
  205. package/src/view-toggle.tsx +110 -110
@@ -1,230 +1,244 @@
1
- /**
2
- * Minor units, major units, and the exponent that separates them — the client
3
- * half of `Whity\Core\Money\Currency`.
4
- *
5
- * WHY THERE IS A CLIENT HALF AT ALL. Amounts cross the wire as integers of
6
- * minor units, which is the only representation that does not lose money to
7
- * floating point. Turning 5000 into something a person reads therefore happens
8
- * here, and it cannot be done without knowing that the Jordanian dinar has
9
- * THREE decimal places: 5000 fils is 5.000 JOD, not 50.00. Dividing by 100 —
10
- * which is what every hand-rolled formatter does — shows every customer an
11
- * amount ten times too large.
12
- *
13
- * WHY `Intl` IS NOT THE SOURCE OF THE EXPONENT. It is the obvious idea — the
14
- * engine ships ISO 4217 data, so why transcribe a table? — and it is wrong.
15
- * `Intl.NumberFormat(...).resolvedOptions().maximumFractionDigits` reports
16
- * CLDR's DISPLAY convention, not the currency's official exponent, and the two
17
- * disagree for thirteen currencies whose minor unit is worthless in practice.
18
- * ICU says the Iraqi dinar has 0 decimal places; ISO 4217 says 3. Lebanese
19
- * pounds, Afghanis, Serbian dinars and ten others are the same story with 0
20
- * against 2.
21
- *
22
- * Deriving the exponent from `Intl` here would therefore have made the client
23
- * disagree with the server about what an IQD amount MEANS — by a factor of a
24
- * thousand — while every JOD and USD test passed. So the table below is the
25
- * authority, it is ISO's numbers, and it is identical to the PHP one by
26
- * construction; a test asserts the two tables entry-for-entry and separately
27
- * pins the ICU divergences so they cannot change unnoticed.
28
- *
29
- * `Intl` is still used for what it is actually good at: placing symbols and
30
- * digits for a locale. `formatMoney` forces the fraction digits to OUR
31
- * exponent, so the figure is ISO-correct even where CLDR would round it away.
32
- *
33
- * WHAT IS DELIBERATELY SPLIT IN TWO. `toDecimalString` is exact — integer
34
- * arithmetic only, correct for any amount an integer can hold. `formatMoney`
35
- * is the locale-aware one, and it is what screens use: `Intl` places the symbol
36
- * and picks the digits, which is how the Arabic build gets Arabic-Indic
37
- * numerals and correct RTL placement without this file knowing anything about
38
- * either.
39
- */
40
-
41
- /** Two decimal places, which is every active ISO 4217 code not listed below. */
42
- const DEFAULT_EXPONENT = 2;
43
-
44
- /**
45
- * Every active ISO 4217 currency whose exponent is not two. THE AUTHORITY, not
46
- * a fallback: see the note above on why `Intl` cannot play this role. Identical
47
- * to the PHP table by construction — `currency-exponent-parity.test.ts` asserts
48
- * it entry for entry.
49
- */
50
- const EXPONENT_EXCEPTIONS: Readonly<Record<string, number>> = {
51
- BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
52
- BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0,
53
- RWF: 0, UGX: 0, UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
54
- CLF: 4, UYW: 4,
55
- };
56
-
57
- const exponentCache = new Map<string, number>();
58
-
59
- /** Uppercased and trimmed, or `null` when it is not a three-letter code. */
60
- function normalize(currency: string): string | null {
61
- const code = currency.trim().toUpperCase();
62
- return /^[A-Z]{3}$/.test(code) ? code : null;
63
- }
64
-
65
- /**
66
- * The currency's ISO 4217 exponent.
67
- *
68
- * Throws on a malformed code rather than assuming two, because an amount
69
- * rendered against a guessed currency is wrong in a way nobody can see.
70
- */
71
- export function currencyExponent(currency: string): number {
72
- const code = normalize(currency);
73
- if (code === null) {
74
- throw new Error(`Not an ISO 4217 currency code: '${currency}'`);
75
- }
76
-
77
- const cached = exponentCache.get(code);
78
- if (cached !== undefined) return cached;
79
-
80
- // The table, never Intl — see the module note. Asking the engine here would
81
- // silently make this disagree with the server for IQD, LBP and eleven others.
82
- const exponent = EXPONENT_EXCEPTIONS[code] ?? DEFAULT_EXPONENT;
83
-
84
- exponentCache.set(code, exponent);
85
- return exponent;
86
- }
87
-
88
- /** 1000 for JOD, 100 for USD, 1 for JPY. */
89
- export function minorUnitsPerMajor(currency: string): number {
90
- return 10 ** currencyExponent(currency);
91
- }
92
-
93
- /**
94
- * Minor units as an exact decimal string: `5000` JOD becomes `"5.000"`.
95
- *
96
- * Integer arithmetic throughout, so this is correct for every amount a
97
- * JavaScript integer holds and never introduces a fractional artefact of its
98
- * own. No currency code is appended — that is the caller's or `Intl`'s job.
99
- */
100
- export function toDecimalString(minorUnits: number, currency: string): string {
101
- if (!Number.isInteger(minorUnits)) {
102
- throw new Error(
103
- `Expected an integer of minor units, got ${minorUnits}. A fractional ` +
104
- 'minor unit is not an amount of money.',
105
- );
106
- }
107
-
108
- const exponent = currencyExponent(currency);
109
- if (exponent === 0) return String(minorUnits);
110
-
111
- // The sign is taken off first: -1 fil must render "-0.001", and leaving the
112
- // minus in the arithmetic produces "0.-01".
113
- const sign = minorUnits < 0 ? '-' : '';
114
- const magnitude = Math.abs(minorUnits);
115
- const divisor = 10 ** exponent;
116
-
117
- const major = Math.floor(magnitude / divisor);
118
- const minor = magnitude % divisor;
119
-
120
- return `${sign}${major}.${String(minor).padStart(exponent, '0')}`;
121
- }
122
-
123
- /**
124
- * The amount as a person in this locale reads it — symbol, grouping, digits and
125
- * direction all decided by `Intl`.
126
- *
127
- * Pass the UI's active locale so the Arabic build renders Arabic-Indic numerals
128
- * and places the currency correctly for RTL; this file must not try to do
129
- * either itself.
130
- *
131
- * PRECISION NOTE: the exact decimal string is handed to `Intl` directly where
132
- * the engine accepts one (ES2023), so no precision is lost. Where it does not,
133
- * this falls back to a `Number`, which is exact below 2^53 — about nine
134
- * quadrillion fils, or nine trillion dinars. `toDecimalString` has no such
135
- * bound if an exact rendering is what is needed.
136
- */
137
- export function formatMoney(
138
- minorUnits: number,
139
- currency: string,
140
- locale?: string,
141
- ): string {
142
- const code = normalize(currency);
143
- if (code === null) {
144
- throw new Error(`Not an ISO 4217 currency code: '${currency}'`);
145
- }
146
-
147
- const decimal = toDecimalString(minorUnits, code);
148
- const exponent = currencyExponent(code);
149
-
150
- let formatter: Intl.NumberFormat;
151
- try {
152
- formatter = new Intl.NumberFormat(locale, {
153
- style: 'currency',
154
- currency: code,
155
- minimumFractionDigits: exponent,
156
- maximumFractionDigits: exponent,
157
- });
158
- } catch {
159
- // Unknown to this engine's ICU data: show the exact figure and the code
160
- // rather than nothing.
161
- return `${decimal} ${code}`;
162
- }
163
-
164
- try {
165
- // Intl.NumberFormat v3 accepts a decimal string, which keeps full
166
- // precision. Older engines throw or coerce, hence the fallback.
167
- return formatter.format(decimal as unknown as number);
168
- } catch {
169
- return formatter.format(Number(decimal));
170
- }
171
- }
172
-
173
- /**
174
- * Read a human-entered major-unit amount into minor units.
175
- *
176
- * Mirrors the PHP `Currency::parse` exactly, and that exactness is the point:
177
- * if the client accepted what the server refuses, the user would see a
178
- * validation error on an amount the form told them was fine; if it accepted
179
- * what the server silently rounds, they would be billed something they did not
180
- * type.
181
- *
182
- * So: more precision than the currency has is REFUSED, not rounded, and group
183
- * separators are refused rather than guessed at — "1.234,56" and "1,234.56"
184
- * are the same string to different halves of the world and mean amounts a
185
- * thousand times apart.
186
- */
187
- export function parseMoney(input: string, currency: string): number {
188
- const code = normalize(currency);
189
- if (code === null) {
190
- throw new Error(`Not an ISO 4217 currency code: '${currency}'`);
191
- }
192
-
193
- const exponent = currencyExponent(code);
194
- const trimmed = input.trim();
195
-
196
- if (trimmed === '') {
197
- throw new Error(`Cannot read an empty amount as ${code}.`);
198
- }
199
-
200
- const match = /^(-?)(\d+)(?:\.(\d*))?$/.exec(trimmed);
201
- if (match === null) {
202
- throw new Error(
203
- `Cannot read "${input}" as ${code}: expected digits with at most one "." ` +
204
- 'and an optional leading "-". Group and decimal separators are ambiguous ' +
205
- 'between locales and are refused rather than guessed at.',
206
- );
207
- }
208
-
209
- const [, sign, whole, fraction = ''] = match;
210
-
211
- if (fraction.length > exponent) {
212
- throw new Error(
213
- `Cannot read "${input}" as ${code}: ${code} has ${exponent} decimal ` +
214
- `place${exponent === 1 ? '' : 's'}, and this has ${fraction.length}. ` +
215
- 'Refusing to round an amount somebody typed.',
216
- );
217
- }
218
-
219
- const digits = whole + fraction.padEnd(exponent, '0');
220
- const value = Number(`${sign}${digits}`);
221
-
222
- if (!Number.isSafeInteger(value)) {
223
- throw new Error(
224
- `Cannot read "${input}" as ${code}: ${digits} minor units is beyond the ` +
225
- 'range in which an integer is exact.',
226
- );
227
- }
228
-
229
- return value;
230
- }
1
+ /**
2
+ * Minor units, major units, and the exponent that separates them — the client
3
+ * half of `Whity\Core\Money\Currency`.
4
+ *
5
+ * WHY THERE IS A CLIENT HALF AT ALL. Amounts cross the wire as integers of
6
+ * minor units, which is the only representation that does not lose money to
7
+ * floating point. Turning 5000 into something a person reads therefore happens
8
+ * here, and it cannot be done without knowing that the Jordanian dinar has
9
+ * THREE decimal places: 5000 fils is 5.000 JOD, not 50.00. Dividing by 100 —
10
+ * which is what every hand-rolled formatter does — shows every customer an
11
+ * amount ten times too large.
12
+ *
13
+ * WHY `Intl` IS NOT THE SOURCE OF THE EXPONENT. It is the obvious idea — the
14
+ * engine ships ISO 4217 data, so why transcribe a table? — and it is wrong.
15
+ * `Intl.NumberFormat(...).resolvedOptions().maximumFractionDigits` reports
16
+ * CLDR's DISPLAY convention, not the currency's official exponent, and the two
17
+ * disagree for thirteen currencies whose minor unit is worthless in practice.
18
+ * ICU says the Iraqi dinar has 0 decimal places; ISO 4217 says 3. Lebanese
19
+ * pounds, Afghanis, Serbian dinars and ten others are the same story with 0
20
+ * against 2.
21
+ *
22
+ * Deriving the exponent from `Intl` here would therefore have made the client
23
+ * disagree with the server about what an IQD amount MEANS — by a factor of a
24
+ * thousand — while every JOD and USD test passed. So the table below is the
25
+ * authority, it is ISO's numbers, and it is identical to the PHP one by
26
+ * construction; a test asserts the two tables entry-for-entry and separately
27
+ * pins the ICU divergences so they cannot change unnoticed.
28
+ *
29
+ * HOW AN AMOUNT IS WRITTEN (design 3.5.1, CU.2). `toDecimalString` is exact —
30
+ * integer arithmetic only. `moneyText` (and `formatMoney`, its old name) puts
31
+ * that figure in the one form the register gives for every language: a symbol
32
+ * before the number for dollars and euros ($312.00), otherwise the code and a
33
+ * space (JOD 312.000), Western digits, a real minus (−$35.00). Until 3.5.1
34
+ * this used `Intl`, which gave Arabic-Indic digits and moved the symbol by
35
+ * locale; the register now keeps amounts in Western digits in Arabic too.
36
+ */
37
+
38
+ /** Two decimal places, which is every active ISO 4217 code not listed below. */
39
+ const DEFAULT_EXPONENT = 2;
40
+
41
+ /**
42
+ * Every active ISO 4217 currency whose exponent is not two. THE AUTHORITY, not
43
+ * a fallback: see the note above on why `Intl` cannot play this role. Identical
44
+ * to the PHP table by construction — `currency-exponent-parity.test.ts` asserts
45
+ * it entry for entry.
46
+ */
47
+ const EXPONENT_EXCEPTIONS: Readonly<Record<string, number>> = {
48
+ BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
49
+ BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0,
50
+ RWF: 0, UGX: 0, UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
51
+ CLF: 4, UYW: 4,
52
+ };
53
+
54
+ const exponentCache = new Map<string, number>();
55
+
56
+ /** Uppercased and trimmed, or `null` when it is not a three-letter code. */
57
+ function normalize(currency: string): string | null {
58
+ const code = currency.trim().toUpperCase();
59
+ return /^[A-Z]{3}$/.test(code) ? code : null;
60
+ }
61
+
62
+ /**
63
+ * The currency's ISO 4217 exponent.
64
+ *
65
+ * Throws on a malformed code rather than assuming two, because an amount
66
+ * rendered against a guessed currency is wrong in a way nobody can see.
67
+ */
68
+ export function currencyExponent(currency: string): number {
69
+ const code = normalize(currency);
70
+ if (code === null) {
71
+ throw new Error(`Not an ISO 4217 currency code: '${currency}'`);
72
+ }
73
+
74
+ const cached = exponentCache.get(code);
75
+ if (cached !== undefined) return cached;
76
+
77
+ // The table, never Intl — see the module note. Asking the engine here would
78
+ // silently make this disagree with the server for IQD, LBP and eleven others.
79
+ const exponent = EXPONENT_EXCEPTIONS[code] ?? DEFAULT_EXPONENT;
80
+
81
+ exponentCache.set(code, exponent);
82
+ return exponent;
83
+ }
84
+
85
+ /** 1000 for JOD, 100 for USD, 1 for JPY. */
86
+ export function minorUnitsPerMajor(currency: string): number {
87
+ return 10 ** currencyExponent(currency);
88
+ }
89
+
90
+ /**
91
+ * Minor units as an exact decimal string: `5000` JOD becomes `"5.000"`.
92
+ *
93
+ * Integer arithmetic throughout, so this is correct for every amount a
94
+ * JavaScript integer holds and never introduces a fractional artefact of its
95
+ * own. No currency code is appended — that is the caller's or `Intl`'s job.
96
+ */
97
+ export function toDecimalString(minorUnits: number, currency: string): string {
98
+ if (!Number.isInteger(minorUnits)) {
99
+ throw new Error(
100
+ `Expected an integer of minor units, got ${minorUnits}. A fractional ` +
101
+ 'minor unit is not an amount of money.',
102
+ );
103
+ }
104
+
105
+ const exponent = currencyExponent(currency);
106
+ if (exponent === 0) return String(minorUnits);
107
+
108
+ // The sign is taken off first: -1 fil must render "-0.001", and leaving the
109
+ // minus in the arithmetic produces "0.-01".
110
+ const sign = minorUnits < 0 ? '-' : '';
111
+ const magnitude = Math.abs(minorUnits);
112
+ const divisor = 10 ** exponent;
113
+
114
+ const major = Math.floor(magnitude / divisor);
115
+ const minor = magnitude % divisor;
116
+
117
+ return `${sign}${major}.${String(minor).padStart(exponent, '0')}`;
118
+ }
119
+
120
+ /**
121
+ * The currencies written with a symbol before the number (CU.2), as the
122
+ * design's `Whity.currencies` has them. Every other currency writes its code.
123
+ * Identical to the PHP `Currency::SYMBOLS`.
124
+ */
125
+ const SYMBOLS: Readonly<Record<string, string>> = { USD: '$', EUR: '€' };
126
+
127
+ /** The minus a person reads (U+2212), as the design writes −$35.00. */
128
+ const MINUS = '−';
129
+
130
+ /** The symbol CU.2 writes before the number, or null when the code is written. */
131
+ export function currencySymbol(currency: string): string | null {
132
+ const code = normalize(currency);
133
+ return code === null ? null : (SYMBOLS[code] ?? null);
134
+ }
135
+
136
+ /**
137
+ * The sub-unit's name for the currencies the design names one for — what
138
+ * MoneyInput's decimals message says in brackets.
139
+ */
140
+ const SUB_UNITS: Readonly<Record<string, string>> = { USD: 'cents', EUR: 'cents', JOD: 'fils', SAR: 'halalas', AED: 'fils' };
141
+
142
+ export function currencySubUnit(currency: string): string | null {
143
+ const code = normalize(currency);
144
+ return code === null ? null : (SUB_UNITS[code] ?? null);
145
+ }
146
+
147
+ /**
148
+ * The amount as a person reads it, by CU.2: "$312.00", "−$35.00",
149
+ * "JOD 1,234.500", "SAR 312.00". The same text as the PHP
150
+ * `Currency::display`, in every language.
151
+ *
152
+ * Western digits and comma grouping in English and Arabic alike (CU.1, 3.7b):
153
+ * an amount is a code, not prose, so the Arabic page shows the same figures.
154
+ * The caller isolates it (`<bdi>` or the `Money` component) so it never
155
+ * flips inside Arabic text.
156
+ *
157
+ * Exact: built from `toDecimalString`, so no float is involved.
158
+ */
159
+ export function moneyText(minorUnits: number, currency: string): string {
160
+ const code = normalize(currency);
161
+ if (code === null) {
162
+ throw new Error(`Not an ISO 4217 currency code: '${currency}'`);
163
+ }
164
+
165
+ const decimal = toDecimalString(Math.abs(minorUnits), code);
166
+ const [whole = '0', fraction] = decimal.split('.');
167
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
168
+ const number = fraction === undefined ? grouped : `${grouped}.${fraction}`;
169
+ const symbol = SYMBOLS[code];
170
+
171
+ return (minorUnits < 0 ? MINUS : '') + (symbol !== undefined ? `${symbol}${number}` : `${code} ${number}`);
172
+ }
173
+
174
+ /**
175
+ * The amount as a person reads it. Since design 3.5.1 this is `moneyText`:
176
+ * one form in every language (CU.2), so `locale` no longer changes it. Kept
177
+ * so existing callers need not change.
178
+ */
179
+ export function formatMoney(
180
+ minorUnits: number,
181
+ currency: string,
182
+ _locale?: string,
183
+ ): string {
184
+ return moneyText(minorUnits, currency);
185
+ }
186
+
187
+ /**
188
+ * Read a human-entered major-unit amount into minor units.
189
+ *
190
+ * Mirrors the PHP `Currency::parse` exactly, and that exactness is the point:
191
+ * if the client accepted what the server refuses, the user would see a
192
+ * validation error on an amount the form told them was fine; if it accepted
193
+ * what the server silently rounds, they would be billed something they did not
194
+ * type.
195
+ *
196
+ * So: more precision than the currency has is REFUSED, not rounded, and group
197
+ * separators are refused rather than guessed at — "1.234,56" and "1,234.56"
198
+ * are the same string to different halves of the world and mean amounts a
199
+ * thousand times apart.
200
+ */
201
+ export function parseMoney(input: string, currency: string): number {
202
+ const code = normalize(currency);
203
+ if (code === null) {
204
+ throw new Error(`Not an ISO 4217 currency code: '${currency}'`);
205
+ }
206
+
207
+ const exponent = currencyExponent(code);
208
+ const trimmed = input.trim();
209
+
210
+ if (trimmed === '') {
211
+ throw new Error(`Cannot read an empty amount as ${code}.`);
212
+ }
213
+
214
+ const match = /^(-?)(\d+)(?:\.(\d*))?$/.exec(trimmed);
215
+ if (match === null) {
216
+ throw new Error(
217
+ `Cannot read "${input}" as ${code}: expected digits with at most one "." ` +
218
+ 'and an optional leading "-". Group and decimal separators are ambiguous ' +
219
+ 'between locales and are refused rather than guessed at.',
220
+ );
221
+ }
222
+
223
+ const [, sign, whole, fraction = ''] = match;
224
+
225
+ if (fraction.length > exponent) {
226
+ throw new Error(
227
+ `Cannot read "${input}" as ${code}: ${code} has ${exponent} decimal ` +
228
+ `place${exponent === 1 ? '' : 's'}, and this has ${fraction.length}. ` +
229
+ 'Refusing to round an amount somebody typed.',
230
+ );
231
+ }
232
+
233
+ const digits = whole + fraction.padEnd(exponent, '0');
234
+ const value = Number(`${sign}${digits}`);
235
+
236
+ if (!Number.isSafeInteger(value)) {
237
+ throw new Error(
238
+ `Cannot read "${input}" as ${code}: ${digits} minor units is beyond the ` +
239
+ 'range in which an integer is exact.',
240
+ );
241
+ }
242
+
243
+ return value;
244
+ }
@@ -0,0 +1,131 @@
1
+ import * as React from "react"
2
+
3
+ import { cn } from "../utils"
4
+ import { currencyExponent, currencySubUnit, currencySymbol } from "./currency"
5
+
6
+ /**
7
+ * A money field (docs/design/components/MoneyInput): the currency as a fixed
8
+ * prefix, figures end-aligned and left to right, formatted to the currency's
9
+ * decimals on blur ($1,234.50, JOD 1,234.500; CU.2: the symbol for dollars and
10
+ * euros, otherwise the code). Arabic-Indic digits and the Arabic decimal
11
+ * mark are accepted as typed and become Western digits (3.7b).
12
+ *
13
+ * The value is a decimal STRING in normal units ("1234.5"), never minor units.
14
+ * Screens convert at the API boundary with `parseMoney` and `toDecimalString`.
15
+ */
16
+ export interface MoneyInputProps extends Omit<React.ComponentProps<"input">, "value" | "onChange" | "type"> {
17
+ currency: string
18
+ value: string
19
+ onValueChange: (value: string) => void
20
+ /** "USD has 2 decimals (cents). Use up to 2." Shown when there are too many (CU.4). */
21
+ tooManyDecimalsLabel?: (decimals: number, currency: string) => string
22
+ }
23
+
24
+ /** Western digits and a plain "." from whatever was typed, separators dropped. */
25
+ function normaliseMoneyText(raw: string): string {
26
+ return raw
27
+ .replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660))
28
+ .replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06f0))
29
+ .replace(/٫/g, ".")
30
+ .replace(/[,٬\s]/g, "")
31
+ }
32
+
33
+ function decimalsOf(text: string): number {
34
+ const dot = text.indexOf(".")
35
+ return dot === -1 ? 0 : text.length - dot - 1
36
+ }
37
+
38
+ function isDigits(text: string): boolean {
39
+ for (const ch of text) {
40
+ if (ch < "0" || ch > "9") return false
41
+ }
42
+ return true
43
+ }
44
+
45
+ function groupThousands(digits: string): string {
46
+ const groups: string[] = []
47
+ for (let end = digits.length; end > 0; end -= 3) {
48
+ groups.unshift(digits.slice(Math.max(0, end - 3), end))
49
+ }
50
+ return groups.join(",")
51
+ }
52
+
53
+ function formatForBlur(text: string, decimals: number): string {
54
+ const negative = text.startsWith("-")
55
+ const [whole = "", fraction = "", ...rest] = (negative ? text.slice(1) : text).split(".")
56
+ // Text that isn't a plain number stays as typed, for the field's error to show.
57
+ if (rest.length > 0 || (whole === "" && fraction === "") || !isDigits(whole) || !isDigits(fraction)) return text
58
+ let firstDigit = 0
59
+ while (firstDigit < whole.length - 1 && whole[firstDigit] === "0") firstDigit++
60
+ const grouped = groupThousands(whole.slice(firstDigit) || "0")
61
+ const padded = decimals > 0 ? `.${fraction.padEnd(decimals, "0")}` : ""
62
+ return `${negative ? "-" : ""}${grouped}${padded}`
63
+ }
64
+
65
+ /** The design's MoneyInput message (CU.4): it names the currency's own count. */
66
+ function defaultDecimalsMessage(decimals: number, currency: string): string {
67
+ const unit = currencySubUnit(currency)
68
+ return `${currency} has ${decimals} decimals${unit ? ` (${unit})` : ""}. Use up to ${decimals}.`
69
+ }
70
+
71
+ function MoneyInput({
72
+ currency,
73
+ value,
74
+ onValueChange,
75
+ tooManyDecimalsLabel,
76
+ className,
77
+ onBlur,
78
+ onFocus,
79
+ disabled,
80
+ ...props
81
+ }: MoneyInputProps) {
82
+ const [focused, setFocused] = React.useState(false)
83
+ const exponent = currencyExponent(currency)
84
+ const tooMany = decimalsOf(value) > exponent
85
+
86
+ return (
87
+ <div className="grid gap-1">
88
+ <div
89
+ data-slot="money-input"
90
+ data-invalid={tooMany ? "" : undefined}
91
+ className={cn(
92
+ "flex h-10 items-stretch overflow-hidden rounded-control border border-input bg-card focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/30 data-invalid:border-destructive has-disabled:cursor-not-allowed has-disabled:opacity-55",
93
+ className
94
+ )}
95
+ >
96
+ <span
97
+ title={currency}
98
+ className="grid place-items-center border-e border-border bg-muted px-2.5 font-mono text-xs font-medium text-muted-foreground"
99
+ >
100
+ {currencySymbol(currency) ?? currency}
101
+ </span>
102
+ <input
103
+ {...props}
104
+ type="text"
105
+ inputMode="decimal"
106
+ dir="ltr"
107
+ disabled={disabled}
108
+ aria-invalid={tooMany || undefined}
109
+ value={focused || tooMany ? value : formatForBlur(value, exponent)}
110
+ onChange={(event) => onValueChange(normaliseMoneyText(event.target.value))}
111
+ onFocus={(event) => {
112
+ setFocused(true)
113
+ onFocus?.(event)
114
+ }}
115
+ onBlur={(event) => {
116
+ setFocused(false)
117
+ onBlur?.(event)
118
+ }}
119
+ className="min-w-0 flex-1 border-0 bg-transparent px-2.5 text-right text-sm tabular-nums text-foreground outline-none"
120
+ />
121
+ </div>
122
+ {tooMany && (
123
+ <p className="text-xs text-destructive">
124
+ {tooManyDecimalsLabel?.(exponent, currency) ?? defaultDecimalsMessage(exponent, currency)}
125
+ </p>
126
+ )}
127
+ </div>
128
+ )
129
+ }
130
+
131
+ export { MoneyInput, normaliseMoneyText }
@@ -0,0 +1,33 @@
1
+ import * as React from "react"
2
+
3
+ import { cn } from "../utils"
4
+ import { moneyText } from "./currency"
5
+
6
+ /**
7
+ * An amount as people read it (docs/design/components/Money, CU.2): $312.00,
8
+ * JOD 312.000, −$35.00. Western digits, isolated left to right so it never
9
+ * flips in Arabic text, in the mono face amounts use.
10
+ *
11
+ * `minor` is the stored integer of minor units; `currency` is the amount's own
12
+ * currency (the row's), or the workspace's when the screen has no row.
13
+ */
14
+ export interface MoneyProps extends Omit<React.ComponentProps<"bdi">, "children"> {
15
+ minor: number
16
+ currency: string
17
+ }
18
+
19
+ function Money({ minor, currency, className, ...props }: MoneyProps) {
20
+ return (
21
+ <bdi
22
+ {...props}
23
+ dir="ltr"
24
+ data-slot="money"
25
+ data-negative={minor < 0 ? "" : undefined}
26
+ className={cn("font-mono tabular-nums whitespace-nowrap", className)}
27
+ >
28
+ {moneyText(minor, currency)}
29
+ </bdi>
30
+ )
31
+ }
32
+
33
+ export { Money }