@poodle64/ui 2026.11.7 → 2026.11.9

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.
package/README.md CHANGED
@@ -1531,15 +1531,15 @@ so it runs in a load function as happily as in a component.
1531
1531
 
1532
1532
  | Function | What it does |
1533
1533
  | -------------------------------------- | -------------------------------------------------------------------------------------------------- |
1534
- | `formatCurrency(dollars, opts)` | `$1,234.56`. `decimals` (default 2), `currency` (default AUD), `fallback`. |
1534
+ | `formatCurrency(dollars, opts)` | `$1,234.56`. `decimals` (default 2) or `minDecimals`/`maxDecimals` (`$1.50`, `$1.2346`), `currency` (default AUD), `fallback`. |
1535
1535
  | `formatCurrencyFromCents(cents, opts)` | The same, for money stored as integer cents. |
1536
1536
  | `formatCurrencyString(str, opts)` | Groups a money STRING without ever parsing it to a float — for a figure that reaches a tax return. |
1537
1537
  | `compactCurrency(value, opts)` | `$1.1m` / `$12k`, for a chart axis or a dense tile. |
1538
1538
  | `isNegativeMoney(value)` | The sign, without a parse, for choosing a tone class. |
1539
1539
  | `dollarsToCents(dollars)` | Whole cents. |
1540
- | `formatNumber(value, opts)` | `1,234,567`. |
1540
+ | `formatNumber(value, opts)` | `1,234,567`. `maxDecimals: 8` trims a quantity (`0.125`). |
1541
1541
  | `formatPercentage(value, opts)` | Value is already in percentage POINTS: `4.5` → `4.5%`. |
1542
- | `formatRatioAsPercentage(value, opts)` | Value is a 0–1 RATIO: `0.045` → `4.5%`. |
1542
+ | `formatRatioAsPercentage(value, opts)` | Value is a 0–1 RATIO: `0.045` → `4.5%`; `maxDecimals: 2` trims `0.5` → `50%`. |
1543
1543
  | `formatDate(value, opts)` | `19 Dec 2024`, `19 December 2024` (`format: 'long'`) or `19/12/2024` (`format: 'numeric'`). |
1544
1544
  | `formatDateTime(value, opts)` | The same plus a 24-hour time: `19 Dec 2024, 14:05`. |
1545
1545
  | `parseApiDate(iso)` | Reads an offset-less timestamp as UTC — the naive-UTC backend trap below. |
@@ -1,10 +1,6 @@
1
- import type { createAjv, JsonSchema } from '@jsonforms/core';
2
- /**
3
- * The Ajv instance `@jsonforms/core` builds. Typed through its own factory so
4
- * this package never names `ajv` — a transitive dependency of the engine, not
5
- * a dependency of ours.
6
- */
7
- export type FormAjv = ReturnType<typeof createAjv>;
1
+ import type { JsonSchema } from '@jsonforms/core';
2
+ import type { FormAjv } from './validator.js';
3
+ export type { FormAjv };
8
4
  /**
9
5
  * The form-wide facts every nested element needs, published once by
10
6
  * `<SchemaForm>` rather than drilled through a recursive component tree.
@@ -22,7 +18,7 @@ export interface SchemaFormContext {
22
18
  readonly idPrefix: string;
23
19
  /** Validation messages by dot path, from the schema itself. */
24
20
  readonly errors: Record<string, string[]>;
25
- /** The shared Ajv instance rule conditions are evaluated with. */
21
+ /** The validator rule conditions are evaluated with. */
26
22
  readonly ajv: FormAjv;
27
23
  /** Commit one field. */
28
24
  change: (path: string, value: unknown) => void;
@@ -1,10 +1,11 @@
1
1
  <script lang="ts">
2
- import { createAjv, Generate, type UISchemaElement } from '@jsonforms/core';
2
+ import { Generate, type UISchemaElement } from '@jsonforms/core';
3
3
  import Panel from '../panel/panel.svelte';
4
4
  import SchemaFormElement from './schema-form-element.svelte';
5
5
  import UnknownField from './widgets/unknown-field.svelte';
6
6
  import { setSchemaFormContext } from './context.js';
7
7
  import { addressedPaths, getAt, setAt, unmappedFields } from './data.js';
8
+ import { createRuleEvaluator, validateValue } from './validator.js';
8
9
  import { cn } from '../../../utils.js';
9
10
  import type { SchemaFormProps } from './types.js';
10
11
 
@@ -41,9 +42,10 @@
41
42
  class: className
42
43
  }: SchemaFormProps = $props();
43
44
 
44
- // One Ajv for the life of the form: rule conditions and validation both use
45
- // it, and compiling per keystroke would be the whole cost of the component.
46
- const ajv = createAjv();
45
+ // Rule conditions and validation both go through the interpreting validator
46
+ // in `validator.ts`: no `new Function`, so the apps' CSP (no `unsafe-eval`)
47
+ // holds.
48
+ const ajv = createRuleEvaluator();
47
49
 
48
50
  // No UI schema is a legitimate mode, not an error: generating one from the
49
51
  // schema is the only arrangement in which a field CANNOT be missing from the
@@ -53,31 +55,19 @@
53
55
  const addressed = $derived(addressedPaths(layout));
54
56
  const unmapped = $derived(unmappedFields(schema, addressed));
55
57
 
56
- /**
57
- * Validation messages by dot path. Ajv is asked about a CLONE, because
58
- * `createAjv` enables `useDefaults` and would otherwise write defaults into
59
- * the caller's value behind its back.
60
- */
58
+ /** Validation messages by dot path, from the schema itself. */
61
59
  const errors = $derived.by(() => {
62
60
  const byPath: Record<string, string[]> = {};
63
61
  if (!validate) return byPath;
64
62
  try {
65
- const check = ajv.compile(schema as object);
66
- const probe = structuredClone($state.snapshot(value));
67
- if (check(probe)) return byPath;
68
- for (const error of check.errors ?? []) {
69
- const missing = (error.params as { missingProperty?: string })?.missingProperty;
70
- const instance = error.instancePath.replace(/^\//, '').split('/').filter(Boolean).join('.');
71
- const path = missing ? [instance, missing].filter(Boolean).join('.') : instance;
72
- if (!path) continue;
73
- (byPath[path] ??= []).push(missing ? 'Required' : (error.message ?? 'is invalid'));
74
- }
63
+ for (const { path, message } of validateValue(schema as object, $state.snapshot(value)))
64
+ (byPath[path] ??= []).push(message);
75
65
  } catch {
76
- // A schema Ajv will not compile, or a value it will not clone, is still
77
- // a form this renderer can lay out — it simply cannot be validated.
78
- // Never let a validation problem blank the form: that is the failure
79
- // mode this whole component exists to remove.
80
- return byPath;
66
+ // A schema the validator will not read is still a form this renderer
67
+ // can lay out — it simply cannot be validated. Never let a validation
68
+ // problem blank the form: that is the failure mode this whole
69
+ // component exists to remove.
70
+ return {};
81
71
  }
82
72
  return byPath;
83
73
  });
@@ -0,0 +1,12 @@
1
+ import type { isVisible } from '@jsonforms/core';
2
+ /** The `ajv` slot `@jsonforms/core`'s rule helpers take. */
3
+ export type FormAjv = NonNullable<Parameters<typeof isVisible>[3]>;
4
+ export interface FieldError {
5
+ /** Dot path of the offending field (the missing one, for `required`). */
6
+ path: string;
7
+ message: string;
8
+ }
9
+ /** What `@jsonforms/core` calls for a rule's schema condition. */
10
+ export declare const createRuleEvaluator: () => FormAjv;
11
+ /** Field errors for `value` against `schema`, empty when valid. */
12
+ export declare const validateValue: (schema: object, value: unknown) => FieldError[];
@@ -0,0 +1,36 @@
1
+ import { Validator } from '@cfworker/json-schema';
2
+ /**
3
+ * The form's validator. It INTERPRETS the schema; Ajv's `compile` and
4
+ * `validate` generate source and run it through `new Function`, which the
5
+ * apps' `script-src 'self'` (no `unsafe-eval`) refuses. The schema arrives at
6
+ * runtime from the server, so Ajv's build-time standalone mode cannot help.
7
+ */
8
+ const check = (schema, value) => {
9
+ // JSON round trip: an `undefined` property is absent, as Ajv read it.
10
+ const result = new Validator(schema, '2019-09', false).validate(JSON.parse(JSON.stringify(value ?? null)));
11
+ return result.valid ? [] : result.errors;
12
+ };
13
+ /** What `@jsonforms/core` calls for a rule's schema condition. */
14
+ export const createRuleEvaluator = () => ({ validate: (schema, value) => check(schema, value).length === 0 });
15
+ const dotPath = (location) => location.replace(/^#\/?/, '').split('/').filter(Boolean).join('.');
16
+ /** Field errors for `value` against `schema`, empty when valid. */
17
+ export const validateValue = (schema, value) => {
18
+ const out = [];
19
+ for (const error of check(schema, value)) {
20
+ // Only leaf keywords name a field; container keywords (properties,
21
+ // allOf...) restate their children's failures.
22
+ if (['properties', 'items', 'allOf', 'anyOf', 'oneOf', '$ref', '$recursiveRef'].includes(error.keyword))
23
+ continue;
24
+ const instance = dotPath(error.instanceLocation);
25
+ if (error.keyword === 'required') {
26
+ const missing = /"([^"]+)"/.exec(error.error)?.[1];
27
+ const path = [instance, missing].filter(Boolean).join('.');
28
+ if (path)
29
+ out.push({ path, message: 'Required' });
30
+ continue;
31
+ }
32
+ if (instance)
33
+ out.push({ path: instance, message: error.error });
34
+ }
35
+ return out;
36
+ };
package/dist/format.d.ts CHANGED
@@ -45,13 +45,22 @@
45
45
  export declare const AU_LOCALE = "en-AU";
46
46
  /** The one timezone the household's records are kept in. */
47
47
  export declare const AU_TIME_ZONE = "Australia/Brisbane";
48
- export interface CurrencyOptions {
48
+ /** Fraction-digit options every numeric formatter shares. */
49
+ export interface DecimalRange {
50
+ /** Exactly this many fraction digits (min and max both). */
51
+ decimals?: number;
52
+ /** At least this many; with `maxDecimals`, trailing zeros between the two are trimmed. */
53
+ minDecimals?: number;
54
+ /** At most this many. */
55
+ maxDecimals?: number;
56
+ }
57
+ export interface CurrencyOptions extends DecimalRange {
49
58
  /**
50
- * Fraction digits. Defaults to 2: dropping cents is a loss of fidelity the
51
- * caller should have to ask for, not the default that quietly rounds
59
+ * Fraction digits (`decimals`; `minDecimals`/`maxDecimals` for a range, a
60
+ * unit price's 2 to 4). Defaults to 2: dropping cents is a loss of fidelity
61
+ * the caller should have to ask for, not the default that quietly rounds
52
62
  * $1,234.56 up to $1,235. Pass `0` for a dashboard figure.
53
63
  */
54
- decimals?: number;
55
64
  /** Rendered when the value is null, undefined, empty or not a number. */
56
65
  fallback?: string;
57
66
  /**
@@ -77,6 +86,8 @@ export interface CurrencyOptions {
77
86
  * formatCurrency('1234.56', { decimals: 0 }) // '$1,235'
78
87
  * formatCurrency(-500, { decimals: 0 }) // '-$500'
79
88
  * formatCurrency(-500, { negative: 'brackets' }) // '($500.00)'
89
+ * formatCurrency(1.5, { minDecimals: 2, maxDecimals: 4 }) // '$1.50'
90
+ * formatCurrency(1.23456, { minDecimals: 2, maxDecimals: 4 }) // '$1.2346'
80
91
  * formatCurrency(null) // 'N/A'
81
92
  */
82
93
  export declare function formatCurrency(value: string | number | null | undefined, options?: CurrencyOptions): string;
@@ -141,10 +152,10 @@ export declare function isNegativeMoney(value: string | number | null | undefine
141
152
  * @example
142
153
  * formatNumber(1234567) // '1,234,567'
143
154
  * formatNumber(1234.567, { decimals: 2 }) // '1,234.57'
155
+ * formatNumber(0.125, { maxDecimals: 8 }) // '0.125'
144
156
  * formatNumber(null) // 'N/A'
145
157
  */
146
- export declare function formatNumber(value: number | string | null | undefined, options?: {
147
- decimals?: number;
158
+ export declare function formatNumber(value: number | string | null | undefined, options?: DecimalRange & {
148
159
  fallback?: string;
149
160
  }): string;
150
161
  /**
@@ -158,10 +169,10 @@ export declare function formatNumber(value: number | string | null | undefined,
158
169
  * @example
159
170
  * formatPercentage(4.5) // '4.5%'
160
171
  * formatPercentage('4.5', { decimals: 2 }) // '4.50%'
172
+ * formatPercentage(4.5, { maxDecimals: 2 }) // '4.5%'
161
173
  * formatPercentage(null) // 'N/A'
162
174
  */
163
- export declare function formatPercentage(value: number | string | null | undefined, options?: {
164
- decimals?: number;
175
+ export declare function formatPercentage(value: number | string | null | undefined, options?: DecimalRange & {
165
176
  fallback?: string;
166
177
  }): string;
167
178
  /**
@@ -170,10 +181,10 @@ export declare function formatPercentage(value: number | string | null | undefin
170
181
  * @example
171
182
  * formatRatioAsPercentage(0.045) // '4.5%'
172
183
  * formatRatioAsPercentage(1) // '100.0%'
184
+ * formatRatioAsPercentage(0.5, { maxDecimals: 2 }) // '50%'
173
185
  * formatRatioAsPercentage(null) // 'N/A'
174
186
  */
175
- export declare function formatRatioAsPercentage(value: number | string | null | undefined, options?: {
176
- decimals?: number;
187
+ export declare function formatRatioAsPercentage(value: number | string | null | undefined, options?: DecimalRange & {
177
188
  fallback?: string;
178
189
  }): string;
179
190
  /** `19 Dec 2024`, `19 December 2024`, or `19/12/2024`. */
package/dist/format.js CHANGED
@@ -47,6 +47,33 @@ export const AU_LOCALE = 'en-AU';
47
47
  export const AU_TIME_ZONE = 'Australia/Brisbane';
48
48
  /** What a formatter renders when it has nothing to render. */
49
49
  const FALLBACK = 'N/A';
50
+ /**
51
+ * Resolve a `DecimalRange` to a [min, max] pair. `decimals` alone (or nothing:
52
+ * `fallbackDecimals`) pins both, so every caller that predates the range reads
53
+ * as it did. Given a range, an omitted `minDecimals` is `decimals` if set, else
54
+ * `defaultMin` (0 for a quantity or a percent, 2 for money, which keeps cents).
55
+ */
56
+ function resolveDecimals(options, fallbackDecimals, defaultMin) {
57
+ const { decimals, minDecimals, maxDecimals } = options;
58
+ if (minDecimals === undefined && maxDecimals === undefined) {
59
+ const n = decimals ?? fallbackDecimals;
60
+ return [n, n];
61
+ }
62
+ const min = minDecimals ?? decimals ?? defaultMin;
63
+ const max = maxDecimals ?? Math.max(decimals ?? fallbackDecimals, min);
64
+ return [Math.min(min, max), max];
65
+ }
66
+ /** `toFixed(max)` with trailing zeros trimmed down to `min` fraction digits. */
67
+ function toTrimmedFixed(num, min, max) {
68
+ const fixed = num.toFixed(max);
69
+ if (max <= min)
70
+ return fixed;
71
+ const [int, frac = ''] = fixed.split('.');
72
+ let end = frac.length;
73
+ while (end > min && frac[end - 1] === '0')
74
+ end--;
75
+ return end > 0 ? `${int}.${frac.slice(0, end)}` : int;
76
+ }
50
77
  /**
51
78
  * Coerce an API value to a finite number, or null.
52
79
  *
@@ -73,18 +100,21 @@ function toFiniteNumber(value) {
73
100
  * formatCurrency('1234.56', { decimals: 0 }) // '$1,235'
74
101
  * formatCurrency(-500, { decimals: 0 }) // '-$500'
75
102
  * formatCurrency(-500, { negative: 'brackets' }) // '($500.00)'
103
+ * formatCurrency(1.5, { minDecimals: 2, maxDecimals: 4 }) // '$1.50'
104
+ * formatCurrency(1.23456, { minDecimals: 2, maxDecimals: 4 }) // '$1.2346'
76
105
  * formatCurrency(null) // 'N/A'
77
106
  */
78
107
  export function formatCurrency(value, options = {}) {
79
- const { decimals = 2, fallback = FALLBACK, currency = 'AUD', negative = 'sign', locale = AU_LOCALE } = options;
108
+ const { fallback = FALLBACK, currency = 'AUD', negative = 'sign', locale = AU_LOCALE } = options;
80
109
  const num = toFiniteNumber(value);
81
110
  if (num === null)
82
111
  return fallback;
112
+ const [minDigits, maxDigits] = resolveDecimals(options, 2, 2);
83
113
  const format = new Intl.NumberFormat(locale, {
84
114
  style: 'currency',
85
115
  currency,
86
- minimumFractionDigits: decimals,
87
- maximumFractionDigits: decimals
116
+ minimumFractionDigits: minDigits,
117
+ maximumFractionDigits: maxDigits
88
118
  });
89
119
  if (negative !== 'brackets' || num >= 0)
90
120
  return format.format(num);
@@ -220,16 +250,18 @@ export function isNegativeMoney(value) {
220
250
  * @example
221
251
  * formatNumber(1234567) // '1,234,567'
222
252
  * formatNumber(1234.567, { decimals: 2 }) // '1,234.57'
253
+ * formatNumber(0.125, { maxDecimals: 8 }) // '0.125'
223
254
  * formatNumber(null) // 'N/A'
224
255
  */
225
256
  export function formatNumber(value, options = {}) {
226
- const { decimals = 0, fallback = FALLBACK } = options;
257
+ const { fallback = FALLBACK } = options;
227
258
  const num = toFiniteNumber(value);
228
259
  if (num === null)
229
260
  return fallback;
261
+ const [minDigits, maxDigits] = resolveDecimals(options, 0, 0);
230
262
  return new Intl.NumberFormat(AU_LOCALE, {
231
- minimumFractionDigits: decimals,
232
- maximumFractionDigits: decimals
263
+ minimumFractionDigits: minDigits,
264
+ maximumFractionDigits: maxDigits
233
265
  }).format(num);
234
266
  }
235
267
  /**
@@ -243,14 +275,16 @@ export function formatNumber(value, options = {}) {
243
275
  * @example
244
276
  * formatPercentage(4.5) // '4.5%'
245
277
  * formatPercentage('4.5', { decimals: 2 }) // '4.50%'
278
+ * formatPercentage(4.5, { maxDecimals: 2 }) // '4.5%'
246
279
  * formatPercentage(null) // 'N/A'
247
280
  */
248
281
  export function formatPercentage(value, options = {}) {
249
- const { decimals = 1, fallback = FALLBACK } = options;
282
+ const { fallback = FALLBACK } = options;
250
283
  const num = toFiniteNumber(value);
251
284
  if (num === null)
252
285
  return fallback;
253
- return `${num.toFixed(decimals)}%`;
286
+ const [minDigits, maxDigits] = resolveDecimals(options, 1, 0);
287
+ return `${toTrimmedFixed(num, minDigits, maxDigits)}%`;
254
288
  }
255
289
  /**
256
290
  * Format a 0–1 RATIO as a percentage: `0.045` renders `4.5%`.
@@ -258,14 +292,16 @@ export function formatPercentage(value, options = {}) {
258
292
  * @example
259
293
  * formatRatioAsPercentage(0.045) // '4.5%'
260
294
  * formatRatioAsPercentage(1) // '100.0%'
295
+ * formatRatioAsPercentage(0.5, { maxDecimals: 2 }) // '50%'
261
296
  * formatRatioAsPercentage(null) // 'N/A'
262
297
  */
263
298
  export function formatRatioAsPercentage(value, options = {}) {
264
- const { decimals = 1, fallback = FALLBACK } = options;
299
+ const { fallback = FALLBACK } = options;
265
300
  const num = toFiniteNumber(value);
266
301
  if (num === null)
267
302
  return fallback;
268
- return `${(num * 100).toFixed(decimals)}%`;
303
+ const [minDigits, maxDigits] = resolveDecimals(options, 1, 0);
304
+ return `${toTrimmedFixed(num * 100, minDigits, maxDigits)}%`;
269
305
  }
270
306
  // --------------------------------------------------------------------------- //
271
307
  // Dates and times //
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@poodle64/ui",
3
- "version": "2026.11.7",
3
+ "version": "2026.11.9",
4
4
  "description": "Household shared component layer: shadcn-svelte primitives (bits-ui) plus the composed page chrome every app builds its routes from, restyled by each app's @poodle64/design-tokens alias layer. One fix reaches every app.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -77,6 +77,7 @@
77
77
  }
78
78
  },
79
79
  "dependencies": {
80
+ "@cfworker/json-schema": "^4.1.6",
80
81
  "@grafana/faro-web-sdk": "^2.11.0",
81
82
  "@grafana/faro-web-tracing": "^2.11.0",
82
83
  "@jsonforms/core": "^3.8.0",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "package": "@poodle64/ui",
4
- "version": "2026.11.7",
4
+ "version": "2026.11.9",
5
5
  "generatedBy": "scripts/generate-registry.mjs",
6
6
  "source": "scripts/situations.json + package source (DO NOT EDIT the outputs by hand)",
7
7
  "componentCount": 76,
@@ -1,7 +1,7 @@
1
1
  # @poodle64/ui — situation → component map
2
2
 
3
3
  <!-- GENERATED by scripts/generate-registry.mjs from scripts/situations.json + package source. DO NOT EDIT. -->
4
- Generated from `@poodle64/ui@2026.11.7`. 76 components, 20 situations.
4
+ Generated from `@poodle64/ui@2026.11.9`. 76 components, 20 situations.
5
5
 
6
6
  **Read this before writing a `<div>`.** Find the SITUATION you are in below, then compose the component named for it — do not hand-build it from raw `Card` or utility classes. Import is `import { Name } from '<import path>'`. Props marked `?` are optional. This map is the retrieval step the [`design-frontend` skill] makes mandatory; the [CHI 2026 study] measured composing-from-a-registry at 95% design-system compliance against 71% for writing the CSS from a prose style guide.
7
7