@entifix/react-controls 0.23.5 → 0.23.7

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 (79) hide show
  1. package/README.md +16 -0
  2. package/dist/i18n/catalog/en.d.ts.map +1 -1
  3. package/dist/i18n/catalog/en.js +45 -1
  4. package/dist/i18n/catalog/en.js.map +1 -1
  5. package/dist/i18n/catalog/es.d.ts +46 -0
  6. package/dist/i18n/catalog/es.d.ts.map +1 -1
  7. package/dist/i18n/catalog/es.js +46 -1
  8. package/dist/i18n/catalog/es.js.map +1 -1
  9. package/dist/i18n/catalog/index.d.ts +82 -0
  10. package/dist/i18n/catalog/index.d.ts.map +1 -1
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/primitives.d.ts +1 -0
  16. package/dist/primitives.d.ts.map +1 -1
  17. package/dist/primitives.js +1 -0
  18. package/dist/primitives.js.map +1 -1
  19. package/dist/theme/theme-context.d.ts.map +1 -1
  20. package/dist/theme/theme-context.js +9 -0
  21. package/dist/theme/theme-context.js.map +1 -1
  22. package/dist/ui/atoms/cell-value/cell-value.d.ts +2 -1
  23. package/dist/ui/atoms/cell-value/cell-value.d.ts.map +1 -1
  24. package/dist/ui/atoms/cell-value/cell-value.js +31 -5
  25. package/dist/ui/atoms/cell-value/cell-value.js.map +1 -1
  26. package/dist/ui/atoms/field-control/field-control.d.ts +2 -1
  27. package/dist/ui/atoms/field-control/field-control.d.ts.map +1 -1
  28. package/dist/ui/atoms/field-control/field-control.js +19 -0
  29. package/dist/ui/atoms/field-control/field-control.js.map +1 -1
  30. package/dist/ui/atoms/money/money-input.d.ts +4 -0
  31. package/dist/ui/atoms/money/money-input.d.ts.map +1 -1
  32. package/dist/ui/atoms/money/money-input.js +10 -13
  33. package/dist/ui/atoms/money/money-input.js.map +1 -1
  34. package/dist/ui/atoms/number-input/quantity-input.d.ts +19 -4
  35. package/dist/ui/atoms/number-input/quantity-input.d.ts.map +1 -1
  36. package/dist/ui/atoms/number-input/quantity-input.js +13 -5
  37. package/dist/ui/atoms/number-input/quantity-input.js.map +1 -1
  38. package/dist/ui/atoms/number-input/scaled-quantity-input.d.ts +16 -0
  39. package/dist/ui/atoms/number-input/scaled-quantity-input.d.ts.map +1 -0
  40. package/dist/ui/atoms/number-input/scaled-quantity-input.js +135 -0
  41. package/dist/ui/atoms/number-input/scaled-quantity-input.js.map +1 -0
  42. package/dist/ui/atoms/number-input/step-button.d.ts +3 -0
  43. package/dist/ui/atoms/number-input/step-button.d.ts.map +1 -0
  44. package/dist/ui/atoms/number-input/step-button.js +3 -0
  45. package/dist/ui/atoms/number-input/step-button.js.map +1 -0
  46. package/dist/ui/atoms/number-input/unparsed.d.ts +10 -0
  47. package/dist/ui/atoms/number-input/unparsed.d.ts.map +1 -0
  48. package/dist/ui/atoms/number-input/unparsed.js +10 -0
  49. package/dist/ui/atoms/number-input/unparsed.js.map +1 -0
  50. package/dist/ui/atoms/scaled/index.d.ts +5 -0
  51. package/dist/ui/atoms/scaled/index.d.ts.map +1 -0
  52. package/dist/ui/atoms/scaled/index.js +6 -0
  53. package/dist/ui/atoms/scaled/index.js.map +1 -0
  54. package/dist/ui/atoms/scaled/scaled-input.d.ts +24 -0
  55. package/dist/ui/atoms/scaled/scaled-input.d.ts.map +1 -0
  56. package/dist/ui/atoms/scaled/scaled-input.js +98 -0
  57. package/dist/ui/atoms/scaled/scaled-input.js.map +1 -0
  58. package/dist/ui/atoms/scaled/scaled-math.d.ts +13 -0
  59. package/dist/ui/atoms/scaled/scaled-math.d.ts.map +1 -0
  60. package/dist/ui/atoms/scaled/scaled-math.js +17 -0
  61. package/dist/ui/atoms/scaled/scaled-math.js.map +1 -0
  62. package/dist/ui/atoms/scaled/scaled-value.d.ts +14 -0
  63. package/dist/ui/atoms/scaled/scaled-value.d.ts.map +1 -0
  64. package/dist/ui/atoms/scaled/scaled-value.js +14 -0
  65. package/dist/ui/atoms/scaled/scaled-value.js.map +1 -0
  66. package/dist/ui/atoms/scaled/use-unit-label.d.ts +4 -0
  67. package/dist/ui/atoms/scaled/use-unit-label.d.ts.map +1 -0
  68. package/dist/ui/atoms/scaled/use-unit-label.js +11 -0
  69. package/dist/ui/atoms/scaled/use-unit-label.js.map +1 -0
  70. package/dist/ui/organisms/entity-detail-grid/entity-detail-grid.d.ts.map +1 -1
  71. package/dist/ui/organisms/entity-detail-grid/entity-detail-grid.js +1 -1
  72. package/dist/ui/organisms/entity-detail-grid/entity-detail-grid.js.map +1 -1
  73. package/dist/ui/organisms/entity-table/entity-table-slots.d.ts +6 -1
  74. package/dist/ui/organisms/entity-table/entity-table-slots.d.ts.map +1 -1
  75. package/dist/ui/organisms/entity-table/entity-table-slots.js.map +1 -1
  76. package/dist/ui/organisms/entity-table/use-entity-table-columns.d.ts.map +1 -1
  77. package/dist/ui/organisms/entity-table/use-entity-table-columns.js +2 -0
  78. package/dist/ui/organisms/entity-table/use-entity-table-columns.js.map +1 -1
  79. package/package.json +5 -5
@@ -32,6 +32,7 @@ export * from './ui/atoms/field/index.js';
32
32
  export * from './ui/atoms/media-image/index.js';
33
33
  export * from './ui/atoms/money/index.js';
34
34
  export * from './ui/atoms/number-input/index.js';
35
+ export * from './ui/atoms/scaled/index.js';
35
36
  export * from './ui/atoms/skeleton/index.js';
36
37
  export * from './ui/atoms/status-tag/index.js';
37
38
  export * from './ui/atoms/switch/index.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/primitives.ts"],"sourcesContent":["// The entity-free half of the design system, published as\n// `@entifix/react-controls/primitives`.\n//\n// It exists because the package's main barrel is one flat re-export of\n// everything, and a bundler cannot drop what a module graph reaches: a\n// storefront page importing `Card` from `.` pulled `EntityTable`,\n// `FilterBuilder`, `SortBuilder`, `ColumnSettings` and the RSQL machinery\n// behind them into its client bundle — 541 KB of back-office UI shipped to a\n// visitor looking at a product.\n//\n// The line drawn here is not \"small vs large\", it is **presentational vs\n// entity-aware**: everything below can be understood without knowing what an\n// entity is. Anything that reads entity metadata (`CellValue`, `FieldControl`,\n// `EntityTable`, `EntityForm`, the filter/sort/column builders, the link\n// inputs) stays behind the main entry, where the back-office already imports it.\n//\n// Consumers that need both may import both; nothing is duplicated, and the main\n// barrel keeps re-exporting all of this so no existing import breaks.\n\n// Providers every app mounts, whatever it renders.\n//\n// `./preferences` is deliberately **not** here. The UI-preferences store is\n// backed by Effect `Layer`s, so re-exporting it drags the whole Effect runtime\n// into the browser — and what it remembers (column visibility, table density)\n// only exists in the back-office. A storefront has no preferences to store.\nexport * from './i18n/index.js';\nexport * from './theme/index.js';\n\n// Atoms — text, buttons, fields, tables, loading placeholders.\nexport * from './ui/atoms/alert/index.js';\nexport * from './ui/atoms/button/index.js';\nexport * from './ui/atoms/external-link/index.js';\nexport * from './ui/atoms/field/index.js';\nexport * from './ui/atoms/media-image/index.js';\nexport * from './ui/atoms/money/index.js';\nexport * from './ui/atoms/number-input/index.js';\nexport * from './ui/atoms/skeleton/index.js';\nexport * from './ui/atoms/status-tag/index.js';\nexport * from './ui/atoms/switch/index.js';\nexport * from './ui/atoms/table/index.js';\nexport * from './ui/atoms/text/index.js';\n\n// Layout primitives (Every Layout): flex-first, with `Grid` the one CSS-Grid\n// escape hatch.\nexport * from './ui/layout/box/index.js';\nexport * from './ui/layout/center/index.js';\nexport * from './ui/layout/cluster/index.js';\nexport * from './ui/layout/cover/index.js';\nexport * from './ui/layout/grid/index.js';\nexport * from './ui/layout/sidebar/index.js';\nexport * from './ui/layout/switcher/index.js';\n\n// Molecules that compose the above and nothing else.\nexport * from './ui/molecules/breadcrumbs/index.js';\nexport * from './ui/molecules/card/index.js';\nexport * from './ui/molecules/confirm-dialog/index.js';\nexport * from './ui/molecules/description-list/index.js';\nexport * from './ui/molecules/empty-state/index.js';\nexport * from './ui/molecules/loading-boundary/index.js';\nexport * from './ui/molecules/media-gallery/index.js';\nexport * from './ui/molecules/menu/index.js';\nexport * from './ui/molecules/nav-menu/index.js';\nexport * from './ui/molecules/pagination/index.js';\nexport * from './ui/molecules/segmented-control/index.js';\nexport * from './ui/molecules/segmented-nav/index.js';\nexport * from './ui/molecules/split-view/index.js';\nexport * from './ui/molecules/stack/index.js';\nexport * from './ui/molecules/summary-tile/index.js';\nexport * from './ui/molecules/tab-strip/index.js';\nexport * from './ui/molecules/theme-switcher/index.js';\nexport * from './ui/utils/active-heading/index.js';\nexport * from './ui/utils/active-section/index.js';\nexport * from './ui/utils/cn.js';\nexport * from './ui/utils/fold-script/index.js';\nexport * from './ui/utils/keep-section/index.js';\nexport * from './ui/utils/media-query/index.js';\n"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,wCAAwC;AACxC,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,kEAAkE;AAClE,0EAA0E;AAC1E,6EAA6E;AAC7E,gCAAgC;AAChC,EAAE;AACF,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,yEAAyE;AACzE,iFAAiF;AACjF,EAAE;AACF,gFAAgF;AAChF,sEAAsE;AAEtE,mDAAmD;AACnD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,cAAc,kBAAkB;AAChC,cAAc,mBAAmB;AAEjC,+DAA+D;AAC/D,cAAc,4BAA4B;AAC1C,cAAc,6BAA6B;AAC3C,cAAc,oCAAoC;AAClD,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,4BAA4B;AAC1C,cAAc,mCAAmC;AACjD,cAAc,+BAA+B;AAC7C,cAAc,iCAAiC;AAC/C,cAAc,6BAA6B;AAC3C,cAAc,4BAA4B;AAC1C,cAAc,2BAA2B;AAEzC,6EAA6E;AAC7E,gBAAgB;AAChB,cAAc,2BAA2B;AACzC,cAAc,8BAA8B;AAC5C,cAAc,+BAA+B;AAC7C,cAAc,6BAA6B;AAC3C,cAAc,4BAA4B;AAC1C,cAAc,+BAA+B;AAC7C,cAAc,gCAAgC;AAE9C,qDAAqD;AACrD,cAAc,sCAAsC;AACpD,cAAc,+BAA+B;AAC7C,cAAc,yCAAyC;AACvD,cAAc,2CAA2C;AACzD,cAAc,sCAAsC;AACpD,cAAc,2CAA2C;AACzD,cAAc,wCAAwC;AACtD,cAAc,+BAA+B;AAC7C,cAAc,mCAAmC;AACjD,cAAc,qCAAqC;AACnD,cAAc,4CAA4C;AAC1D,cAAc,wCAAwC;AACtD,cAAc,qCAAqC;AACnD,cAAc,gCAAgC;AAC9C,cAAc,uCAAuC;AACrD,cAAc,oCAAoC;AAClD,cAAc,yCAAyC;AACvD,cAAc,qCAAqC;AACnD,cAAc,qCAAqC;AACnD,cAAc,mBAAmB;AACjC,cAAc,kCAAkC;AAChD,cAAc,mCAAmC;AACjD,cAAc,kCAAkC"}
1
+ {"version":3,"sources":["../src/primitives.ts"],"sourcesContent":["// The entity-free half of the design system, published as\n// `@entifix/react-controls/primitives`.\n//\n// It exists because the package's main barrel is one flat re-export of\n// everything, and a bundler cannot drop what a module graph reaches: a\n// storefront page importing `Card` from `.` pulled `EntityTable`,\n// `FilterBuilder`, `SortBuilder`, `ColumnSettings` and the RSQL machinery\n// behind them into its client bundle — 541 KB of back-office UI shipped to a\n// visitor looking at a product.\n//\n// The line drawn here is not \"small vs large\", it is **presentational vs\n// entity-aware**: everything below can be understood without knowing what an\n// entity is. Anything that reads entity metadata (`CellValue`, `FieldControl`,\n// `EntityTable`, `EntityForm`, the filter/sort/column builders, the link\n// inputs) stays behind the main entry, where the back-office already imports it.\n//\n// Consumers that need both may import both; nothing is duplicated, and the main\n// barrel keeps re-exporting all of this so no existing import breaks.\n\n// Providers every app mounts, whatever it renders.\n//\n// `./preferences` is deliberately **not** here. The UI-preferences store is\n// backed by Effect `Layer`s, so re-exporting it drags the whole Effect runtime\n// into the browser — and what it remembers (column visibility, table density)\n// only exists in the back-office. A storefront has no preferences to store.\nexport * from './i18n/index.js';\nexport * from './theme/index.js';\n\n// Atoms — text, buttons, fields, tables, loading placeholders.\nexport * from './ui/atoms/alert/index.js';\nexport * from './ui/atoms/button/index.js';\nexport * from './ui/atoms/external-link/index.js';\nexport * from './ui/atoms/field/index.js';\nexport * from './ui/atoms/media-image/index.js';\nexport * from './ui/atoms/money/index.js';\nexport * from './ui/atoms/number-input/index.js';\nexport * from './ui/atoms/scaled/index.js';\nexport * from './ui/atoms/skeleton/index.js';\nexport * from './ui/atoms/status-tag/index.js';\nexport * from './ui/atoms/switch/index.js';\nexport * from './ui/atoms/table/index.js';\nexport * from './ui/atoms/text/index.js';\n\n// Layout primitives (Every Layout): flex-first, with `Grid` the one CSS-Grid\n// escape hatch.\nexport * from './ui/layout/box/index.js';\nexport * from './ui/layout/center/index.js';\nexport * from './ui/layout/cluster/index.js';\nexport * from './ui/layout/cover/index.js';\nexport * from './ui/layout/grid/index.js';\nexport * from './ui/layout/sidebar/index.js';\nexport * from './ui/layout/switcher/index.js';\n\n// Molecules that compose the above and nothing else.\nexport * from './ui/molecules/breadcrumbs/index.js';\nexport * from './ui/molecules/card/index.js';\nexport * from './ui/molecules/confirm-dialog/index.js';\nexport * from './ui/molecules/description-list/index.js';\nexport * from './ui/molecules/empty-state/index.js';\nexport * from './ui/molecules/loading-boundary/index.js';\nexport * from './ui/molecules/media-gallery/index.js';\nexport * from './ui/molecules/menu/index.js';\nexport * from './ui/molecules/nav-menu/index.js';\nexport * from './ui/molecules/pagination/index.js';\nexport * from './ui/molecules/segmented-control/index.js';\nexport * from './ui/molecules/segmented-nav/index.js';\nexport * from './ui/molecules/split-view/index.js';\nexport * from './ui/molecules/stack/index.js';\nexport * from './ui/molecules/summary-tile/index.js';\nexport * from './ui/molecules/tab-strip/index.js';\nexport * from './ui/molecules/theme-switcher/index.js';\nexport * from './ui/utils/active-heading/index.js';\nexport * from './ui/utils/active-section/index.js';\nexport * from './ui/utils/cn.js';\nexport * from './ui/utils/fold-script/index.js';\nexport * from './ui/utils/keep-section/index.js';\nexport * from './ui/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AAoC;AAClD,cAAc,yCAAyC;AACvD,cAAc,qCAAqC;AACnD,cAAc,qCAAqC;AACnD,cAAc,mBAAmB;AACjC,cAAc,kCAAkC;AAChD,cAAc,mCAAmC;AACjD,cAAc,kCAAkC"}
@@ -1 +1 @@
1
- {"version":3,"file":"theme-context.d.ts","sourceRoot":"","sources":["../../src/theme/theme-context.tsx"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EAMvB,MAAM,OAAO,CAAC;AAIf,OAAO,KAAK,EACV,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,YAAY,EACb,MAAM,YAAY,CAAC;AAIpB,MAAM,WAAW,kBAAmB,SAAQ,iBAAiB;IAC3D;uEACmE;IACnE,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,kEAAkE;IAClE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CACzC;AAiCD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAAC,EAC5B,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,cAAc,EACd,UAAyB,EACzB,QAAQ,EACR,YAAY,EACZ,cAAc,GACf,EAAE,kBAAkB,+BAoHpB;AAED,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,QAAO,iBAAiB,GAAG,IAC9B,CAAC;AAE3B,wBAAgB,QAAQ,IAAI,iBAAiB,CAI5C"}
1
+ {"version":3,"file":"theme-context.d.ts","sourceRoot":"","sources":["../../src/theme/theme-context.tsx"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EAMvB,MAAM,OAAO,CAAC;AAIf,OAAO,KAAK,EACV,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,YAAY,EACb,MAAM,YAAY,CAAC;AAIpB,MAAM,WAAW,kBAAmB,SAAQ,iBAAiB;IAC3D;uEACmE;IACnE,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,kEAAkE;IAClE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CACzC;AAiCD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,aAAa,CAAC,EAC5B,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,cAAc,EACd,UAAyB,EACzB,QAAQ,EACR,YAAY,EACZ,cAAc,GACf,EAAE,kBAAkB,+BA4HpB;AAED,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,QAAO,iBAAiB,GAAG,IAC9B,CAAC;AAE3B,wBAAgB,QAAQ,IAAI,iBAAiB,CAI5C"}
@@ -60,10 +60,17 @@ function writeCookie(name, value) {
60
60
  // client corrects after mount. Reading in render would mismatch hydration.
61
61
  // Where the server read it, `initial` already is the stored choice and this
62
62
  // changes nothing. It only reads, so running twice changes nothing.
63
+ // ⚠️ Until the stored choice has been read, nothing is reflected onto the
64
+ // document. A static export's `ThemeScript` has already painted the stored
65
+ // palette before React loads; reflecting `initial` on the first commit would
66
+ // repaint the default over it for one frame, and the stored one again on the
67
+ // next — the flash the script exists to prevent.
68
+ const [adopted, setAdopted] = useState(false);
63
69
  useEffect(()=>{
64
70
  const stored = readCookie(storageKey);
65
71
  // eslint-disable-next-line react-hooks/set-state-in-effect -- one-shot SSR-safe hydration, see comment above
66
72
  if (isKnown(stored)) setThemeState(stored);
73
+ setAdopted(true);
67
74
  // A stored density wins; otherwise the default, otherwise whatever the
68
75
  // document was served with, so the context never reports a density the
69
76
  // page is not in.
@@ -106,9 +113,11 @@ function writeCookie(name, value) {
106
113
  // theme is already right, and even a write of the same value is a change
107
114
  // something watching the document would see.
108
115
  useEffect(()=>{
116
+ if (!adopted) return;
109
117
  const root = document.documentElement;
110
118
  if (root.dataset.theme !== theme) root.dataset.theme = theme;
111
119
  }, [
120
+ adopted,
112
121
  theme
113
122
  ]);
114
123
  useEffect(()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/theme-context.tsx"],"sourcesContent":["'use client';\n\nimport { Effect } from 'effect';\nimport {\n createContext,\n type PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react';\n\nimport { useUiPreferencesState } from '../preferences/ui-preferences-context.js';\nimport { densityCookie, THEME_COOKIE } from './theme-cookie.js';\nimport type {\n Density,\n ThemeContextValue,\n ThemeOption,\n ThemePalette,\n} from './types.js';\n\nconst ThemeContext = createContext<ThemeContextValue | null>(null);\n\nexport interface ThemeProviderProps extends PropsWithChildren {\n /** The themes this app exposes. First entry is the default unless\n * `defaultTheme` is given. Drives `data-theme` + the switcher. */\n themes: ThemeOption[];\n /** Theme id used for the first paint / when nothing is stored. */\n defaultTheme?: string;\n /**\n * The density when nothing is stored. Omitted, the provider leaves\n * `data-density` as the document has it until a density is chosen.\n */\n defaultDensity?: Density;\n /**\n * The cookie the theme is kept in — namespace it per app so apps don't\n * clobber each other. The density is kept beside it, under\n * `${storageKey}-density`. A cookie rather than local storage, so a server\n * can read the choice and render `data-theme` and `data-density` with the\n * page: no paint in the wrong palette before a script corrects it.\n */\n storageKey?: string;\n /**\n * The theme and density the server read from those cookies and rendered\n * the page in (`readThemeCookies` in `@entifix/next-shell/server`). Given,\n * the provider starts there and nothing changes after the page loads.\n */\n initialTheme?: string;\n initialDensity?: Density;\n /**\n * Runtime palettes for brands not shipped as CSS presets (multi-tenant /\n * white-label). Keyed by theme id; injected as `[data-theme='id']{…}` vars\n * appended after the app stylesheet, so they override static presets.\n */\n palettes?: Record<string, ThemePalette>;\n}\n\nconst DENSITIES: readonly Density[] = ['comfortable', 'compact'];\n\nconst isDensity = (value: unknown): value is Density =>\n DENSITIES.includes(value as Density);\n\n/** Storage that may be absent or refuse (a private window, blocked site data). */\n/** A year: a preference outlives a session. */\nconst COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\n/** A first-party cookie's value, or `null` when it is not set. */\nfunction readCookie(name: string): string | null {\n try {\n for (const pair of document.cookie.split('; ')) {\n const at = pair.indexOf('=');\n if (pair.slice(0, at) === name)\n return decodeURIComponent(pair.slice(at + 1));\n }\n } catch {\n // A sandboxed document refuses cookies; nothing was stored, then.\n }\n return null;\n}\n\nfunction writeCookie(name: string, value: string) {\n try {\n document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${COOKIE_MAX_AGE}; samesite=lax`;\n } catch {\n // Nothing to remember it in; the choice still applies to this page.\n }\n}\n\n/**\n * Applies the active palette and density by writing `data-theme` and\n * `data-density` on <html>, and remembers what the user chooses. Static palette\n * VALUES live in CSS (@entifix/style presets or an app-local themes.css); this\n * flips the selector. Dynamic palettes passed via `palettes` are injected at\n * runtime under the same `data-theme` mechanism.\n *\n * ⚠️ **Only a choice is written to storage, never a default.** The provider\n * used to persist whatever theme it held from an effect, and under StrictMode\n * the effect ran before the stored value had been read back: the default\n * overwrote the stored theme, and a reload in development always came back on\n * the default. Writing in `setTheme` and `setDensity` alone means mounting,\n * however many times, can never lose what was chosen.\n */\nexport function ThemeProvider({\n children,\n themes,\n defaultTheme,\n defaultDensity,\n storageKey = THEME_COOKIE,\n palettes,\n initialTheme,\n initialDensity,\n}: ThemeProviderProps) {\n const initial = initialTheme ?? defaultTheme ?? themes[0]?.id ?? '';\n const [theme, setThemeState] = useState<string>(initial);\n const densityKey = densityCookie(storageKey);\n // `undefined` until a density is stored, chosen or defaulted: the document's\n // own `data-density` stands until then.\n const [density, setDensityState] = useState<Density | undefined>(\n initialDensity ?? defaultDensity,\n );\n const preferences = useUiPreferencesState();\n\n const isKnown = useCallback(\n (value: unknown): value is string =>\n typeof value === 'string' && themes.some(t => t.id === value),\n [themes],\n );\n\n // Read the stored choice on mount, for a host that could not: a static\n // export has no server to read the cookie, so it renders `initial` and the\n // client corrects after mount. Reading in render would mismatch hydration.\n // Where the server read it, `initial` already is the stored choice and this\n // changes nothing. It only reads, so running twice changes nothing.\n useEffect(() => {\n const stored = readCookie(storageKey);\n // eslint-disable-next-line react-hooks/set-state-in-effect -- one-shot SSR-safe hydration, see comment above\n if (isKnown(stored)) setThemeState(stored);\n // A stored density wins; otherwise the default, otherwise whatever the\n // document was served with, so the context never reports a density the\n // page is not in.\n const storedDensity = readCookie(densityKey);\n const served = document.documentElement.dataset.density;\n if (isDensity(storedDensity)) setDensityState(storedDensity);\n else if (defaultDensity === undefined && isDensity(served)) {\n setDensityState(served);\n }\n }, [storageKey, densityKey, isKnown, defaultDensity]);\n\n // Inject runtime palettes as a single <style> appended to <head>. Being last\n // in the cascade, these win over any static preset defining the same tokens.\n useEffect(() => {\n if (!palettes || Object.keys(palettes).length === 0) return;\n const styleId = `${storageKey}-runtime-palettes`;\n const css = Object.entries(palettes)\n .map(([id, palette]) => {\n const decls = Object.entries(palette)\n .map(([token, value]) => `--color-${token}: ${value};`)\n .join(' ');\n return `[data-theme='${id}'] { ${decls} }`;\n })\n .join('\\n');\n\n let el = document.getElementById(styleId) as HTMLStyleElement | null;\n if (!el) {\n el = document.createElement('style');\n el.id = styleId;\n document.head.appendChild(el);\n }\n el.textContent = css;\n }, [palettes, storageKey]);\n\n // Reflect the active theme and density onto the document. Storage is not\n // touched here — see the ⚠️ above.\n //\n // Written only when it differs: a page the server rendered in the stored\n // theme is already right, and even a write of the same value is a change\n // something watching the document would see.\n useEffect(() => {\n const root = document.documentElement;\n if (root.dataset.theme !== theme) root.dataset.theme = theme;\n }, [theme]);\n useEffect(() => {\n const root = document.documentElement;\n if (density !== undefined && root.dataset.density !== density)\n root.dataset.density = density;\n }, [density]);\n\n // The cookie is what the next page is rendered in; the UI-preferences port\n // gets a copy, so a host that keeps preferences server-side has them too.\n const remember = useCallback(\n (cookie: string, key: 'theme' | 'density', value: string) => {\n writeCookie(cookie, value);\n void Effect.runPromise(preferences.write(key, value)).catch(\n () => undefined,\n );\n },\n [preferences],\n );\n const setTheme = useCallback(\n (next: string) => {\n setThemeState(next);\n remember(storageKey, 'theme', next);\n },\n [storageKey, remember],\n );\n const setDensity = useCallback(\n (next: Density) => {\n setDensityState(next);\n remember(densityKey, 'density', next);\n },\n [densityKey, remember],\n );\n\n const value = useMemo<ThemeContextValue>(\n () => ({\n theme,\n setTheme,\n themes,\n density: density ?? 'comfortable',\n setDensity,\n }),\n [theme, setTheme, themes, density, setDensity],\n );\n\n return (\n <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>\n );\n}\n\n/** The theme context, or `null` outside a {@link ThemeProvider}. */\nexport const useOptionalTheme = (): ThemeContextValue | null =>\n useContext(ThemeContext);\n\nexport function useTheme(): ThemeContextValue {\n const ctx = useContext(ThemeContext);\n if (!ctx) throw new Error('useTheme must be used within a ThemeProvider');\n return ctx;\n}\n"],"names":["Effect","createContext","useCallback","useContext","useEffect","useMemo","useState","useUiPreferencesState","densityCookie","THEME_COOKIE","ThemeContext","DENSITIES","isDensity","value","includes","COOKIE_MAX_AGE","readCookie","name","pair","document","cookie","split","at","indexOf","slice","decodeURIComponent","writeCookie","encodeURIComponent","ThemeProvider","children","themes","defaultTheme","defaultDensity","storageKey","palettes","initialTheme","initialDensity","initial","id","theme","setThemeState","densityKey","density","setDensityState","preferences","isKnown","some","t","stored","storedDensity","served","documentElement","dataset","undefined","Object","keys","length","styleId","css","entries","map","palette","decls","token","join","el","getElementById","createElement","head","appendChild","textContent","root","remember","key","runPromise","write","catch","setTheme","next","setDensity","Provider","use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ACA;QAACrC;QAAY+B;KAAS;IAGxB,MAAM3D,QAAQR,QACZ,IAAO,CAAA;YACLkC;YACAsC;YACA/C;YACAY,OAAO,EAAEA,kBAAAA,UAAW;YACpBqC;QACF,CAAA,GACA;QAACxC;QAAOsC;QAAU/C;QAAQY;QAASqC;KAAW;IAGhD,qBACE,KAACrE,aAAasE,QAAQ;QAACnE,OAAOA;kBAAQgB;;AAE1C;AAEA,kEAAkE,GAClE,OAAO,MAAMoD,mBAAmB,IAC9B9E,WAAWO,cAAc;AAE3B,OAAO,SAASwE;IACd,MAAMC,MAAMhF,WAAWO;IACvB,IAAI,CAACyE,KAAK,MAAM,IAAIC,MAAM;IAC1B,OAAOD;AACT"}
1
+ {"version":3,"sources":["../../src/theme/theme-context.tsx"],"sourcesContent":["'use client';\n\nimport { Effect } from 'effect';\nimport {\n createContext,\n type PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react';\n\nimport { useUiPreferencesState } from '../preferences/ui-preferences-context.js';\nimport { densityCookie, THEME_COOKIE } from './theme-cookie.js';\nimport type {\n Density,\n ThemeContextValue,\n ThemeOption,\n ThemePalette,\n} from './types.js';\n\nconst ThemeContext = createContext<ThemeContextValue | null>(null);\n\nexport interface ThemeProviderProps extends PropsWithChildren {\n /** The themes this app exposes. First entry is the default unless\n * `defaultTheme` is given. Drives `data-theme` + the switcher. */\n themes: ThemeOption[];\n /** Theme id used for the first paint / when nothing is stored. */\n defaultTheme?: string;\n /**\n * The density when nothing is stored. Omitted, the provider leaves\n * `data-density` as the document has it until a density is chosen.\n */\n defaultDensity?: Density;\n /**\n * The cookie the theme is kept in — namespace it per app so apps don't\n * clobber each other. The density is kept beside it, under\n * `${storageKey}-density`. A cookie rather than local storage, so a server\n * can read the choice and render `data-theme` and `data-density` with the\n * page: no paint in the wrong palette before a script corrects it.\n */\n storageKey?: string;\n /**\n * The theme and density the server read from those cookies and rendered\n * the page in (`readThemeCookies` in `@entifix/next-shell/server`). Given,\n * the provider starts there and nothing changes after the page loads.\n */\n initialTheme?: string;\n initialDensity?: Density;\n /**\n * Runtime palettes for brands not shipped as CSS presets (multi-tenant /\n * white-label). Keyed by theme id; injected as `[data-theme='id']{…}` vars\n * appended after the app stylesheet, so they override static presets.\n */\n palettes?: Record<string, ThemePalette>;\n}\n\nconst DENSITIES: readonly Density[] = ['comfortable', 'compact'];\n\nconst isDensity = (value: unknown): value is Density =>\n DENSITIES.includes(value as Density);\n\n/** Storage that may be absent or refuse (a private window, blocked site data). */\n/** A year: a preference outlives a session. */\nconst COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\n/** A first-party cookie's value, or `null` when it is not set. */\nfunction readCookie(name: string): string | null {\n try {\n for (const pair of document.cookie.split('; ')) {\n const at = pair.indexOf('=');\n if (pair.slice(0, at) === name)\n return decodeURIComponent(pair.slice(at + 1));\n }\n } catch {\n // A sandboxed document refuses cookies; nothing was stored, then.\n }\n return null;\n}\n\nfunction writeCookie(name: string, value: string) {\n try {\n document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${COOKIE_MAX_AGE}; samesite=lax`;\n } catch {\n // Nothing to remember it in; the choice still applies to this page.\n }\n}\n\n/**\n * Applies the active palette and density by writing `data-theme` and\n * `data-density` on <html>, and remembers what the user chooses. Static palette\n * VALUES live in CSS (@entifix/style presets or an app-local themes.css); this\n * flips the selector. Dynamic palettes passed via `palettes` are injected at\n * runtime under the same `data-theme` mechanism.\n *\n * ⚠️ **Only a choice is written to storage, never a default.** The provider\n * used to persist whatever theme it held from an effect, and under StrictMode\n * the effect ran before the stored value had been read back: the default\n * overwrote the stored theme, and a reload in development always came back on\n * the default. Writing in `setTheme` and `setDensity` alone means mounting,\n * however many times, can never lose what was chosen.\n */\nexport function ThemeProvider({\n children,\n themes,\n defaultTheme,\n defaultDensity,\n storageKey = THEME_COOKIE,\n palettes,\n initialTheme,\n initialDensity,\n}: ThemeProviderProps) {\n const initial = initialTheme ?? defaultTheme ?? themes[0]?.id ?? '';\n const [theme, setThemeState] = useState<string>(initial);\n const densityKey = densityCookie(storageKey);\n // `undefined` until a density is stored, chosen or defaulted: the document's\n // own `data-density` stands until then.\n const [density, setDensityState] = useState<Density | undefined>(\n initialDensity ?? defaultDensity,\n );\n const preferences = useUiPreferencesState();\n\n const isKnown = useCallback(\n (value: unknown): value is string =>\n typeof value === 'string' && themes.some(t => t.id === value),\n [themes],\n );\n\n // Read the stored choice on mount, for a host that could not: a static\n // export has no server to read the cookie, so it renders `initial` and the\n // client corrects after mount. Reading in render would mismatch hydration.\n // Where the server read it, `initial` already is the stored choice and this\n // changes nothing. It only reads, so running twice changes nothing.\n // ⚠️ Until the stored choice has been read, nothing is reflected onto the\n // document. A static export's `ThemeScript` has already painted the stored\n // palette before React loads; reflecting `initial` on the first commit would\n // repaint the default over it for one frame, and the stored one again on the\n // next — the flash the script exists to prevent.\n const [adopted, setAdopted] = useState(false);\n useEffect(() => {\n const stored = readCookie(storageKey);\n // eslint-disable-next-line react-hooks/set-state-in-effect -- one-shot SSR-safe hydration, see comment above\n if (isKnown(stored)) setThemeState(stored);\n setAdopted(true);\n // A stored density wins; otherwise the default, otherwise whatever the\n // document was served with, so the context never reports a density the\n // page is not in.\n const storedDensity = readCookie(densityKey);\n const served = document.documentElement.dataset.density;\n if (isDensity(storedDensity)) setDensityState(storedDensity);\n else if (defaultDensity === undefined && isDensity(served)) {\n setDensityState(served);\n }\n }, [storageKey, densityKey, isKnown, defaultDensity]);\n\n // Inject runtime palettes as a single <style> appended to <head>. Being last\n // in the cascade, these win over any static preset defining the same tokens.\n useEffect(() => {\n if (!palettes || Object.keys(palettes).length === 0) return;\n const styleId = `${storageKey}-runtime-palettes`;\n const css = Object.entries(palettes)\n .map(([id, palette]) => {\n const decls = Object.entries(palette)\n .map(([token, value]) => `--color-${token}: ${value};`)\n .join(' ');\n return `[data-theme='${id}'] { ${decls} }`;\n })\n .join('\\n');\n\n let el = document.getElementById(styleId) as HTMLStyleElement | null;\n if (!el) {\n el = document.createElement('style');\n el.id = styleId;\n document.head.appendChild(el);\n }\n el.textContent = css;\n }, [palettes, storageKey]);\n\n // Reflect the active theme and density onto the document. Storage is not\n // touched here — see the ⚠️ above.\n //\n // Written only when it differs: a page the server rendered in the stored\n // theme is already right, and even a write of the same value is a change\n // something watching the document would see.\n useEffect(() => {\n if (!adopted) return;\n const root = document.documentElement;\n if (root.dataset.theme !== theme) root.dataset.theme = theme;\n }, [adopted, theme]);\n useEffect(() => {\n const root = document.documentElement;\n if (density !== undefined && root.dataset.density !== density)\n root.dataset.density = density;\n }, [density]);\n\n // The cookie is what the next page is rendered in; the UI-preferences port\n // gets a copy, so a host that keeps preferences server-side has them too.\n const remember = useCallback(\n (cookie: string, key: 'theme' | 'density', value: string) => {\n writeCookie(cookie, value);\n void Effect.runPromise(preferences.write(key, value)).catch(\n () => undefined,\n );\n },\n [preferences],\n );\n const setTheme = useCallback(\n (next: string) => {\n setThemeState(next);\n remember(storageKey, 'theme', next);\n },\n [storageKey, remember],\n );\n const setDensity = useCallback(\n (next: Density) => {\n setDensityState(next);\n remember(densityKey, 'density', next);\n },\n [densityKey, remember],\n );\n\n const value = useMemo<ThemeContextValue>(\n () => ({\n theme,\n setTheme,\n themes,\n density: density ?? 'comfortable',\n setDensity,\n }),\n [theme, setTheme, themes, density, setDensity],\n );\n\n return (\n <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>\n );\n}\n\n/** The theme context, or `null` outside a {@link ThemeProvider}. */\nexport const useOptionalTheme = (): ThemeContextValue | null =>\n useContext(ThemeContext);\n\nexport function useTheme(): ThemeContextValue {\n const ctx = useContext(ThemeContext);\n if (!ctx) throw new Error('useTheme must be used within a ThemeProvider');\n return ctx;\n}\n"],"names":["Effect","createContext","useCallback","useContext","useEffect","useMemo","useState","useUiPreferencesState","densityCookie","THEME_COOKIE","ThemeContext","DENSITIES","isDensity","value","includes","COOKIE_MAX_AGE","readCookie","name","pair","document","cookie","split","at","indexOf","slice","decodeURIComponent","writeCookie","encodeURIComponent","ThemeProvider","children","themes","defaultTheme","defaultDensity","storageKey","palettes","initialTheme","initialDensity","initial","id","theme","setThemeState","densityKey","density","setDensityState","preferences","isKnown","some","t","adopted","setAdopted","stored","storedDensity","served","documentElement","dataset","undefined","Object","keys","length","styleId","css","entries","map","palette","decls","token","join","el","getElementById","createElement","head","appendChild","textContent","root","remember","key","runPromise","write","catch","setTheme","next","setDensity","Provider","useOptionalTheme","useTheme","ctx","Error"],"mappings":"AAAA;;AAEA,SAASA,MAAM,QAAQ,SAAS;AAChC,SACEC,aAAa,EAEbC,WAAW,EACXC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,QAAQ;AAEf,SAASC,qBAAqB,QAAQ,2CAA2C;AACjF,SAASC,aAAa,EAAEC,YAAY,QAAQ,oBAAoB;AAQhE,MAAMC,6BAAeT,cAAwC;AAoC7D,MAAMU,YAAgC;IAAC;IAAe;CAAU;AAEhE,MAAMC,YAAY,CAACC,QACjBF,UAAUG,QAAQ,CAACD;AAErB,gFAAgF,GAChF,6CAA6C,GAC7C,MAAME,iBAAiB,KAAK,KAAK,KAAK;AAEtC,gEAAgE,GAChE,SAASC,WAAWC,IAAY;IAC9B,IAAI;QACF,KAAK,MAAMC,QAAQC,SAASC,MAAM,CAACC,KAAK,CAAC,MAAO;YAC9C,MAAMC,KAAKJ,KAAKK,OAAO,CAAC;YACxB,IAAIL,KAAKM,KAAK,CAAC,GAAGF,QAAQL,MACxB,OAAOQ,mBAAmBP,KAAKM,KAAK,CAACF,KAAK;QAC9C;IACF,EAAE,eAAM;IACN,kEAAkE;IACpE;IACA,OAAO;AACT;AAEA,SAASI,YAAYT,IAAY,EAAEJ,KAAa;IAC9C,IAAI;QACFM,SAASC,MAAM,GAAG,GAAGH,KAAK,CAAC,EAAEU,mBAAmBd,OAAO,kBAAkB,EAAEE,eAAe,cAAc,CAAC;IAC3G,EAAE,eAAM;IACN,oEAAoE;IACtE;AACF;AAEA;;;;;;;;;;;;;C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IAEZ,2EAA2E;IAC3E,0EAA0E;IAC1E,MAAMgC,WAAWxE,YACf,CAACkB,QAAgBuD,KAA0B9D;QACzCa,YAAYN,QAAQP;QACpB,KAAKb,OAAO4E,UAAU,CAAChC,YAAYiC,KAAK,CAACF,KAAK9D,QAAQiE,KAAK,CACzD,IAAMvB;IAEV,GACA;QAACX;KAAY;IAEf,MAAMmC,WAAW7E,YACf,CAAC8E;QACCxC,cAAcwC;QACdN,SAASzC,YAAY,SAAS+C;IAChC,GACA;QAAC/C;QAAYyC;KAAS;IAExB,MAAMO,aAAa/E,YACjB,CAAC8E;QACCrC,gBAAgBqC;QAChBN,SAASjC,YAAY,WAAWuC;IAClC,GACA;QAACvC;QAAYiC;KAAS;IAGxB,MAAM7D,QAAQR,QACZ,IAAO,CAAA;YACLkC;YACAwC;YACAjD;YACAY,OAAO,EAAEA,kBAAAA,UAAW;YACpBuC;QACF,CAAA,GACA;QAAC1C;QAAOwC;QAAUjD;QAAQY;QAASuC;KAAW;IAGhD,qBACE,KAACvE,aAAawE,QAAQ;QAACrE,OAAOA;kBAAQgB;;AAE1C;AAEA,kEAAkE,GAClE,OAAO,MAAMsD,mBAAmB,IAC9BhF,WAAWO,cAAc;AAE3B,OAAO,SAAS0E;IACd,MAAMC,MAAMlF,WAAWO;IACvB,IAAI,CAAC2E,KAAK,MAAM,IAAIC,MAAM;IAC1B,OAAOD;AACT"}
@@ -10,7 +10,8 @@ export interface CellValueProps {
10
10
  descriptor: EntityFieldDescriptor;
11
11
  /**
12
12
  * The record the value belongs to. A money member whose currency is another
13
- * member of the record (`money.currencyMember`) reads it from here.
13
+ * member of the record (`money.currencyMember`), and a scaled member whose
14
+ * unit is (`scaled.unitMember`), read it from here.
14
15
  */
15
16
  record?: Readonly<Record<string, unknown>>;
16
17
  }
@@ -1 +1 @@
1
- {"version":3,"file":"cell-value.d.ts","sourceRoot":"","sources":["../../../../src/ui/atoms/cell-value/cell-value.tsx"],"names":[],"mappings":"AAGA,OAAO,EAIL,KAAK,qBAAqB,EAK3B,MAAM,eAAe,CAAC;AAgJvB;;;;GAIG;AACH,wBAAgB,YAAY,IAAI,CAC9B,KAAK,EAAE,OAAO,EACd,UAAU,EAAE,qBAAqB,KAC9B,MAAM,CAYV;AAsDD,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,OAAO,CAAC;IACf,UAAU,EAAE,qBAAqB,CAAC;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC5C;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,cAAc,+BAqFtE"}
1
+ {"version":3,"file":"cell-value.d.ts","sourceRoot":"","sources":["../../../../src/ui/atoms/cell-value/cell-value.tsx"],"names":[],"mappings":"AAGA,OAAO,EAIL,KAAK,qBAAqB,EAM3B,MAAM,eAAe,CAAC;AAwJvB;;;;GAIG;AACH,wBAAgB,YAAY,IAAI,CAC9B,KAAK,EAAE,OAAO,EACd,UAAU,EAAE,qBAAqB,KAC9B,MAAM,CAYV;AAsDD,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,OAAO,CAAC;IACf,UAAU,EAAE,qBAAqB,CAAC;IAClC;;;;OAIG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC5C;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,cAAc,+BAwGtE"}
@@ -1,11 +1,14 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { defaultLocale, EntityCollectionLink, EntityLink, isLocalizedText, localize } from '@entifix/core';
3
+ import { defaultLocale, EntityCollectionLink, EntityLink, formatScaled, isLocalizedText, localize } from '@entifix/core';
4
4
  import { useCallback } from 'react';
5
5
  import { useEnumLabel, useFormatters, useLocale, useT } from '../../../i18n/index.js';
6
6
  import { useReferenceLabel, useUnresolvedReference } from '../../utils/reference-labels.js';
7
7
  import { Money } from '../money/money.js';
8
8
  import { currencyOf } from '../money/money-math.js';
9
+ import { scaleOf } from '../scaled/scaled-math.js';
10
+ import { ScaledValue } from '../scaled/scaled-value.js';
11
+ import { useUnitLabel } from '../scaled/use-unit-label.js';
9
12
  import { Skeleton } from '../skeleton/index.js';
10
13
  import { StatusTag } from '../status-tag/index.js';
11
14
  /** Stand-in for an absent value, so an empty cell still reads as intentional. */ const EMPTY = '—';
@@ -35,7 +38,10 @@ function formatByType(value, type, linkLabelProperty, formatting) {
35
38
  case 'date':
36
39
  return formatting.formatters.date(value instanceof Date ? value : String(value));
37
40
  case 'number':
38
- return typeof value === 'number' ? formatting.formatters.number(value) : String(value);
41
+ if (typeof value !== 'number') return String(value);
42
+ // Words have no record to read a unit from, so only a fixed scale can
43
+ // be honoured here.
44
+ return formatting.fixedScale !== undefined && Number.isSafeInteger(value) ? formatScaled(value, formatting.fixedScale, formatting.locale) : formatting.formatters.number(value);
39
45
  case 'boolean':
40
46
  return value ? formatting.yes : formatting.no;
41
47
  case 'enum':
@@ -68,7 +74,9 @@ function formatByType(value, type, linkLabelProperty, formatting) {
68
74
  const formatters = useFormatters();
69
75
  const enumLabel = useEnumLabel();
70
76
  const locale = useLocale();
71
- return useCallback((descriptor)=>({
77
+ return useCallback((descriptor)=>{
78
+ var _descriptor_scaled;
79
+ return {
72
80
  formatters,
73
81
  yes: t('value.yes'),
74
82
  no: t('value.no'),
@@ -76,8 +84,10 @@ function formatByType(value, type, linkLabelProperty, formatting) {
76
84
  rowCount: (count)=>t('value.rowCount', {
77
85
  count
78
86
  }),
79
- locale
80
- }), [
87
+ locale,
88
+ fixedScale: (_descriptor_scaled = descriptor.scaled) == null ? void 0 : _descriptor_scaled.scale
89
+ };
90
+ }, [
81
91
  enumLabel,
82
92
  formatters,
83
93
  locale,
@@ -165,6 +175,7 @@ function formatByType(value, type, linkLabelProperty, formatting) {
165
175
  var _value_locale, _NUMERIC_CLASS_descriptor_type;
166
176
  const formatting = useCellFormatting();
167
177
  const locale = useLocale();
178
+ const unitLabel = useUnitLabel();
168
179
  if (value === undefined || value === null || value === '') {
169
180
  return /*#__PURE__*/ _jsx("span", {
170
181
  className: "text-content-muted",
@@ -194,6 +205,21 @@ function formatByType(value, type, linkLabelProperty, formatting) {
194
205
  });
195
206
  }
196
207
  }
208
+ // A scaled integer reads as the decimal it stands for, beside its unit. One
209
+ // whose record names no declared unit stays the number it is, as money
210
+ // without a currency does.
211
+ if (descriptor.scaled !== undefined) {
212
+ const stored = Number(value);
213
+ const resolved = scaleOf(descriptor.scaled, record);
214
+ if (resolved !== undefined && Number.isSafeInteger(stored)) {
215
+ return /*#__PURE__*/ _jsx(ScaledValue, {
216
+ value: stored,
217
+ scale: resolved.scale,
218
+ unit: unitLabel(descriptor.scaled, resolved.unit),
219
+ locale: locale
220
+ });
221
+ }
222
+ }
197
223
  // A relation whose target has not arrived yet holds its place with a
198
224
  // skeleton — the id is all it has, and the id is not what it means.
199
225
  if (value instanceof EntityLink && value.id != null && value.value === undefined || value instanceof EntityCollectionLink && value.ids.length > 0 && value.values === undefined) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/ui/atoms/cell-value/cell-value.tsx"],"sourcesContent":["'use client';\n\nimport type { Formatters, Locale } from '@entifix/core';\nimport {\n defaultLocale,\n type Entity,\n EntityCollectionLink,\n type EntityFieldDescriptor,\n EntityLink,\n isLocalizedText,\n localize,\n type MetaAccessorType,\n} from '@entifix/core';\nimport { useCallback } from 'react';\n\nimport {\n useEnumLabel,\n useFormatters,\n useLocale,\n useT,\n} from '../../../i18n/index.js';\nimport {\n useReferenceLabel,\n useUnresolvedReference,\n} from '../../utils/reference-labels.js';\nimport { Money } from '../money/money.js';\nimport { currencyOf } from '../money/money-math.js';\nimport { Skeleton } from '../skeleton/index.js';\nimport { StatusTag } from '../status-tag/index.js';\n\n/** Stand-in for an absent value, so an empty cell still reads as intentional. */\nconst EMPTY = '—';\n\n/**\n * A link reads as its target's label once the target is loaded (embedded or\n * resolved). Never as its id: a key is not a name, and showing one fails the\n * reader who came to see which record it is (#200).\n */\nfunction entityLabel(\n target: Entity | undefined,\n linkLabelProperty: string,\n locale: Locale,\n): string | undefined {\n const label = (target as Record<string, unknown> | undefined)?.[\n linkLabelProperty\n ];\n if (label == null) return undefined;\n // A target labelled by a localized member reads in the reader's locale.\n return isLocalizedText(label) ? localize(label, locale) : String(label);\n}\n\nfunction formatLink(\n link: EntityLink<Entity>,\n linkLabelProperty: string,\n locale: Locale,\n): string {\n return link.id == null\n ? EMPTY\n : (entityLabel(link.value, linkLabelProperty, locale) ?? EMPTY);\n}\n\nfunction formatCollectionLink(\n link: EntityCollectionLink<Entity>,\n linkLabelProperty: string,\n locale: Locale,\n): string {\n return (link.values ?? [])\n .map(target => entityLabel(target, linkLabelProperty, locale) ?? EMPTY)\n .join(', ');\n}\n\n/**\n * Everything locale-dependent, resolved once by the component and handed down.\n * The formatters carry an explicit locale, which is what keeps a date rendered\n * on the server byte-identical to the same date rendered in the browser.\n */\ninterface CellFormatting {\n readonly formatters: Formatters;\n readonly yes: string;\n readonly no: string;\n readonly enumLabel: (value: string) => string;\n readonly rowCount: (count: number) => string;\n readonly locale: Locale;\n}\n\nfunction formatByType(\n value: unknown,\n type: MetaAccessorType,\n linkLabelProperty: string,\n formatting: CellFormatting,\n): string {\n switch (type) {\n case 'date':\n return formatting.formatters.date(\n value instanceof Date ? value : String(value),\n );\n case 'number':\n return typeof value === 'number'\n ? formatting.formatters.number(value)\n : String(value);\n case 'boolean':\n return value ? formatting.yes : formatting.no;\n case 'enum':\n return formatting.enumLabel(String(value));\n case 'link':\n return value instanceof EntityLink\n ? formatLink(value, linkLabelProperty, formatting.locale)\n : String(value);\n case 'linkCollection':\n return value instanceof EntityCollectionLink\n ? formatCollectionLink(value, linkLabelProperty, formatting.locale)\n : String(value);\n case 'scalarCollection':\n // The same comma list the draft holds, spaced for reading. Not `String`:\n // an array's own `toString` joins on a bare comma, which reads as one\n // run-on token in a narrow column.\n return Array.isArray(value) ? value.join(', ') : String(value);\n case 'composition':\n // Owned rows have no useful one-line form — a receipt's lines are not a\n // sentence — and the master's own screen is where they are read and\n // edited. So the cell reports the count and stops.\n return Array.isArray(value)\n ? formatting.rowCount(value.length)\n : String(value);\n case 'localized':\n // The reader's locale, falling back to the host's default; a value\n // that is not a text per locale has no reading worth guessing at.\n return isLocalizedText(value)\n ? (localize(value, formatting.locale) ?? '')\n : '';\n default:\n return String(value);\n }\n}\n\n/** The formatting {@link formatByType} reads, resolved for the reader. */\nfunction useCellFormatting(): (\n descriptor: EntityFieldDescriptor,\n) => CellFormatting {\n const t = useT();\n const formatters = useFormatters();\n const enumLabel = useEnumLabel();\n const locale = useLocale();\n return useCallback(\n descriptor => ({\n formatters,\n yes: t('value.yes'),\n no: t('value.no'),\n enumLabel: raw => enumLabel(descriptor, raw),\n rowCount: count => t('value.rowCount', { count }),\n locale,\n }),\n [enumLabel, formatters, locale, t],\n );\n}\n\n/**\n * A filled-in member's value as one line of text, exactly as its cell reads\n * it — for the places that need words rather than an element: a checkbox's\n * name, a confirm dialog's object, a toast.\n */\nexport function useValueText(): (\n value: unknown,\n descriptor: EntityFieldDescriptor,\n) => string {\n const formatting = useCellFormatting();\n return useCallback(\n (value, descriptor) =>\n formatByType(\n value,\n descriptor.type,\n descriptor.linkLabelProperty,\n formatting(descriptor),\n ),\n [formatting],\n );\n}\n\n/**\n * A reference reads as its target's name, in every state the read can be in\n * ([ADR 0030](../../../../../../../docs/adr/0030-a-reference-names-its-target-through-the-owners-read-port.md)):\n * a skeleton while it resolves (the noun and short id for a screen reader); the name; the entity's noun and the short id,\n * muted, when no record answered or the read failed — never an alert, since a\n * list that loaded has not failed because one name could not be read; and the\n * raw id, muted, when the host registered nothing to read it with.\n */\nfunction ReferenceValue({ entity, id }: { entity: string; id: string }) {\n const state = useReferenceLabel(entity, id);\n const unresolved = useUnresolvedReference();\n const locale = useLocale();\n switch (state.status) {\n case 'resolving':\n // The skeleton is hidden from assistive tech, so the noun and short id\n // stand in for it there: a record's title link is never nameless.\n return (\n <>\n <Skeleton shape=\"line\" className=\"w-16\" />\n <span className=\"sr-only\">{unresolved(entity, id)}</span>\n </>\n );\n case 'named': {\n const { label } = state;\n if (typeof label === 'string') return <span>{label}</span>;\n const text = localize(label, locale);\n return (label[locale] ?? '') === '' ? (\n <span lang={defaultLocale()}>{text}</span>\n ) : (\n <span>{text}</span>\n );\n }\n case 'unregistered':\n return <span className=\"text-content-muted\">{id}</span>;\n default:\n return (\n <span className=\"text-content-muted\">{unresolved(entity, id)}</span>\n );\n }\n}\n\n/**\n * Tabular figures, applied once, here — not on `--font-sans` and not per call\n * site. A column of numbers or dates must align on the digit; a paragraph must\n * not, because proportional figures are what prose is set in. The descriptor\n * already knows which is which, so the cell is the only place that has to.\n */\nconst NUMERIC_CLASS: Partial<Record<MetaAccessorType, string>> = {\n number: 'tabular-nums',\n date: 'tabular-nums',\n};\n\nexport interface CellValueProps {\n value: unknown;\n descriptor: EntityFieldDescriptor;\n /**\n * The record the value belongs to. A money member whose currency is another\n * member of the record (`money.currencyMember`) reads it from here.\n */\n record?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Renders one entity member according to its metadata type. Centralizing this\n * is what lets a table stay generic: a link, a date and a number all arrive as\n * \"the value of an accessor\", and only the descriptor decides how they read.\n */\nexport function CellValue({ value, descriptor, record }: CellValueProps) {\n const formatting = useCellFormatting();\n const locale = useLocale();\n\n if (value === undefined || value === null || value === '') {\n return <span className=\"text-content-muted\">{EMPTY}</span>;\n }\n\n // A key into another entity reads as that record's name, never as itself.\n if (descriptor.references !== undefined) {\n return (\n <ReferenceValue\n entity={descriptor.references.entity}\n id={String(value)}\n />\n );\n }\n\n // An amount reads as money in the reader's locale, never as the stored\n // number. A draft holds it as a string, so a numeric string counts too. A\n // currency the record does not carry leaves it a plain number rather than\n // guessing one.\n if (descriptor.money !== undefined) {\n const amount = typeof value === 'number' ? value : Number(value);\n const currency = currencyOf(descriptor.money, record);\n if (currency !== undefined && Number.isFinite(amount)) {\n return (\n <Money\n amount={amount}\n currency={currency}\n unit={descriptor.money.unit}\n locale={locale}\n />\n );\n }\n }\n\n // A relation whose target has not arrived yet holds its place with a\n // skeleton — the id is all it has, and the id is not what it means.\n if (\n (value instanceof EntityLink &&\n value.id != null &&\n value.value === undefined) ||\n (value instanceof EntityCollectionLink &&\n value.ids.length > 0 &&\n value.values === undefined)\n ) {\n return <Skeleton shape=\"line\" className=\"w-16\" />;\n }\n\n const text = formatByType(\n value,\n descriptor.type,\n descriptor.linkLabelProperty,\n formatting(descriptor),\n );\n\n if (text === '') {\n return <span className=\"text-content-muted\">{EMPTY}</span>;\n }\n\n // A status reads as a tag in its declared tone, its words beside the\n // colour; a value given no tone reads neutral. An enum that declared no\n // tones is not a status, and stays text.\n if (descriptor.type === 'enum' && descriptor.enumTones !== undefined) {\n return (\n <StatusTag tone={descriptor.enumTones[String(value)] ?? 'neutral'}>\n {text}\n </StatusTag>\n );\n }\n\n // Text the reader's locale lacks falls back to the default locale's, and is\n // marked as that language, so it is read in its own voice (WCAG 3.1.2).\n if (\n descriptor.type === 'localized' &&\n isLocalizedText(value) &&\n (value[locale] ?? '') === ''\n ) {\n return <span lang={defaultLocale()}>{text}</span>;\n }\n\n return (\n <span className={NUMERIC_CLASS[descriptor.type] ?? undefined}>{text}</span>\n );\n}\n"],"names":["defaultLocale","EntityCollectionLink","EntityLink","isLocalizedText","localize","useCallback","useEnumLabel","useFormatters","useLocale","useT","useReferenceLabel","useUnresolvedReference","Money","currencyOf","Skeleton","StatusTag","EMPTY","entityLabel","target","linkLabelProperty","locale","label","undefined","String","formatLink","link","id","value","formatCollectionLink","values","map","join","formatByType","type","formatting","formatters","date","Date","number","yes","no","enumLabel","Array","isArray","rowCount","length","useCellFormatting","t","descriptor","raw","count","useValueText","ReferenceValue","entity","state","unresolved","status","shape","className","span","text","lang","NUMERIC_CLASS","CellValue","record","references","money","amount","Number","currency","isFinite","unit","ids","enumTones","tone"],"mappings":"AAAA;;AAGA,SACEA,aAAa,EAEbC,oBAAoB,EAEpBC,UAAU,EACVC,eAAe,EACfC,QAAQ,QAEH,gBAAgB;AACvB,SAASC,WAAW,QAAQ,QAAQ;AAEpC,SACEC,YAAY,EACZC,aAAa,EACbC,SAAS,EACTC,IAAI,QACC,yBAAyB;AAChC,SACEC,iBAAiB,EACjBC,sBAAsB,QACjB,kCAAkC;AACzC,SAASC,KAAK,QAAQ,oBAAoB;AAC1C,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SAASC,QAAQ,QAAQ,uBAAuB;AAChD,SAASC,SAAS,QAAQ,yBAAyB;AAEnD,+EAA+E,GAC/E,MAAMC,QAAQ;AAEd;;;;CAIC,GACD,SAASC,YACPC,MAA0B,EAC1BC,iBAAyB,EACzBC,MAAc;IAEd,MAAMC,QAASH,0BAAD,AAACA,MAAgD,CAC7DC,kBACD;IACD,IAAIE,SAAS,MAAM,OAAOC;IAC1B,wEAAwE;IACxE,OAAOnB,gBAAgBkB,SAASjB,SAASiB,OAAOD,UAAUG,OAAOF;AACnE;AAEA,SAASG,WACPC,IAAwB,EACxBN,iBAAyB,EACzBC,MAAc;QAITH;IAFL,OAAOQ,KAAKC,EAAE,IAAI,OACdV,SACCC,eAAAA,YAAYQ,KAAKE,KAAK,EAAER,mBAAmBC,mBAA3CH,eAAsDD;AAC7D;AAEA,SAASY,qBACPH,IAAkC,EAClCN,iBAAyB,EACzBC,MAAc;QAENK;IAAR,OAAO,EAACA,eAAAA,KAAKI,MAAM,YAAXJ,eAAe,EAAE,EACtBK,GAAG,CAACZ,CAAAA;YAAUD;gBAAAA,eAAAA,YAAYC,QAAQC,mBAAmBC,mBAAvCH,eAAkDD;OAChEe,IAAI,CAAC;AACV;AAgBA,SAASC,aACPL,KAA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gC,WAAWf,IAAI,KAAK,UAAUe,WAAWyB,SAAS,KAAKnD,WAAW;YAEjD0B;QADnB,qBACE,KAACjC;YAAU2D,IAAI,GAAE1B,+BAAAA,WAAWyB,SAAS,CAAClD,OAAOI,OAAO,YAAnCqB,+BAAuC;sBACrDY;;IAGP;IAEA,4EAA4E;IAC5E,wEAAwE;IACxE,IACEZ,WAAWf,IAAI,KAAK,eACpB9B,gBAAgBwB,UAChB,EAACA,gBAAAA,KAAK,CAACP,OAAO,YAAbO,gBAAiB,QAAQ,IAC1B;QACA,qBAAO,KAACgC;YAAKE,MAAM7D;sBAAkB4D;;IACvC;IAEA,qBACE,KAACD;QAAKD,SAAS,GAAEI,iCAAAA,aAAa,CAACd,WAAWf,IAAI,CAAC,YAA9B6B,iCAAkCxC;kBAAYsC;;AAEnE"}
1
+ {"version":3,"sources":["../../../../src/ui/atoms/cell-value/cell-value.tsx"],"sourcesContent":["'use client';\n\nimport type { Formatters, Locale } from '@entifix/core';\nimport {\n defaultLocale,\n type Entity,\n EntityCollectionLink,\n type EntityFieldDescriptor,\n EntityLink,\n formatScaled,\n isLocalizedText,\n localize,\n type MetaAccessorType,\n} from '@entifix/core';\nimport { useCallback } from 'react';\n\nimport {\n useEnumLabel,\n useFormatters,\n useLocale,\n useT,\n} from '../../../i18n/index.js';\nimport {\n useReferenceLabel,\n useUnresolvedReference,\n} from '../../utils/reference-labels.js';\nimport { Money } from '../money/money.js';\nimport { currencyOf } from '../money/money-math.js';\nimport { scaleOf } from '../scaled/scaled-math.js';\nimport { ScaledValue } from '../scaled/scaled-value.js';\nimport { useUnitLabel } from '../scaled/use-unit-label.js';\nimport { Skeleton } from '../skeleton/index.js';\nimport { StatusTag } from '../status-tag/index.js';\n\n/** Stand-in for an absent value, so an empty cell still reads as intentional. */\nconst EMPTY = '—';\n\n/**\n * A link reads as its target's label once the target is loaded (embedded or\n * resolved). Never as its id: a key is not a name, and showing one fails the\n * reader who came to see which record it is (#200).\n */\nfunction entityLabel(\n target: Entity | undefined,\n linkLabelProperty: string,\n locale: Locale,\n): string | undefined {\n const label = (target as Record<string, unknown> | undefined)?.[\n linkLabelProperty\n ];\n if (label == null) return undefined;\n // A target labelled by a localized member reads in the reader's locale.\n return isLocalizedText(label) ? localize(label, locale) : String(label);\n}\n\nfunction formatLink(\n link: EntityLink<Entity>,\n linkLabelProperty: string,\n locale: Locale,\n): string {\n return link.id == null\n ? EMPTY\n : (entityLabel(link.value, linkLabelProperty, locale) ?? EMPTY);\n}\n\nfunction formatCollectionLink(\n link: EntityCollectionLink<Entity>,\n linkLabelProperty: string,\n locale: Locale,\n): string {\n return (link.values ?? [])\n .map(target => entityLabel(target, linkLabelProperty, locale) ?? EMPTY)\n .join(', ');\n}\n\n/**\n * Everything locale-dependent, resolved once by the component and handed down.\n * The formatters carry an explicit locale, which is what keeps a date rendered\n * on the server byte-identical to the same date rendered in the browser.\n */\ninterface CellFormatting {\n readonly formatters: Formatters;\n readonly yes: string;\n readonly no: string;\n readonly enumLabel: (value: string) => string;\n readonly rowCount: (count: number) => string;\n readonly locale: Locale;\n readonly fixedScale: number | undefined;\n}\n\nfunction formatByType(\n value: unknown,\n type: MetaAccessorType,\n linkLabelProperty: string,\n formatting: CellFormatting,\n): string {\n switch (type) {\n case 'date':\n return formatting.formatters.date(\n value instanceof Date ? value : String(value),\n );\n case 'number':\n if (typeof value !== 'number') return String(value);\n // Words have no record to read a unit from, so only a fixed scale can\n // be honoured here.\n return formatting.fixedScale !== undefined && Number.isSafeInteger(value)\n ? formatScaled(value, formatting.fixedScale, formatting.locale)\n : formatting.formatters.number(value);\n case 'boolean':\n return value ? formatting.yes : formatting.no;\n case 'enum':\n return formatting.enumLabel(String(value));\n case 'link':\n return value instanceof EntityLink\n ? formatLink(value, linkLabelProperty, formatting.locale)\n : String(value);\n case 'linkCollection':\n return value instanceof EntityCollectionLink\n ? formatCollectionLink(value, linkLabelProperty, formatting.locale)\n : String(value);\n case 'scalarCollection':\n // The same comma list the draft holds, spaced for reading. Not `String`:\n // an array's own `toString` joins on a bare comma, which reads as one\n // run-on token in a narrow column.\n return Array.isArray(value) ? value.join(', ') : String(value);\n case 'composition':\n // Owned rows have no useful one-line form — a receipt's lines are not a\n // sentence — and the master's own screen is where they are read and\n // edited. So the cell reports the count and stops.\n return Array.isArray(value)\n ? formatting.rowCount(value.length)\n : String(value);\n case 'localized':\n // The reader's locale, falling back to the host's default; a value\n // that is not a text per locale has no reading worth guessing at.\n return isLocalizedText(value)\n ? (localize(value, formatting.locale) ?? '')\n : '';\n default:\n return String(value);\n }\n}\n\n/** The formatting {@link formatByType} reads, resolved for the reader. */\nfunction useCellFormatting(): (\n descriptor: EntityFieldDescriptor,\n) => CellFormatting {\n const t = useT();\n const formatters = useFormatters();\n const enumLabel = useEnumLabel();\n const locale = useLocale();\n return useCallback(\n descriptor => ({\n formatters,\n yes: t('value.yes'),\n no: t('value.no'),\n enumLabel: raw => enumLabel(descriptor, raw),\n rowCount: count => t('value.rowCount', { count }),\n locale,\n fixedScale: descriptor.scaled?.scale,\n }),\n [enumLabel, formatters, locale, t],\n );\n}\n\n/**\n * A filled-in member's value as one line of text, exactly as its cell reads\n * it — for the places that need words rather than an element: a checkbox's\n * name, a confirm dialog's object, a toast.\n */\nexport function useValueText(): (\n value: unknown,\n descriptor: EntityFieldDescriptor,\n) => string {\n const formatting = useCellFormatting();\n return useCallback(\n (value, descriptor) =>\n formatByType(\n value,\n descriptor.type,\n descriptor.linkLabelProperty,\n formatting(descriptor),\n ),\n [formatting],\n );\n}\n\n/**\n * A reference reads as its target's name, in every state the read can be in\n * ([ADR 0030](../../../../../../../docs/adr/0030-a-reference-names-its-target-through-the-owners-read-port.md)):\n * a skeleton while it resolves (the noun and short id for a screen reader); the name; the entity's noun and the short id,\n * muted, when no record answered or the read failed — never an alert, since a\n * list that loaded has not failed because one name could not be read; and the\n * raw id, muted, when the host registered nothing to read it with.\n */\nfunction ReferenceValue({ entity, id }: { entity: string; id: string }) {\n const state = useReferenceLabel(entity, id);\n const unresolved = useUnresolvedReference();\n const locale = useLocale();\n switch (state.status) {\n case 'resolving':\n // The skeleton is hidden from assistive tech, so the noun and short id\n // stand in for it there: a record's title link is never nameless.\n return (\n <>\n <Skeleton shape=\"line\" className=\"w-16\" />\n <span className=\"sr-only\">{unresolved(entity, id)}</span>\n </>\n );\n case 'named': {\n const { label } = state;\n if (typeof label === 'string') return <span>{label}</span>;\n const text = localize(label, locale);\n return (label[locale] ?? '') === '' ? (\n <span lang={defaultLocale()}>{text}</span>\n ) : (\n <span>{text}</span>\n );\n }\n case 'unregistered':\n return <span className=\"text-content-muted\">{id}</span>;\n default:\n return (\n <span className=\"text-content-muted\">{unresolved(entity, id)}</span>\n );\n }\n}\n\n/**\n * Tabular figures, applied once, here — not on `--font-sans` and not per call\n * site. A column of numbers or dates must align on the digit; a paragraph must\n * not, because proportional figures are what prose is set in. The descriptor\n * already knows which is which, so the cell is the only place that has to.\n */\nconst NUMERIC_CLASS: Partial<Record<MetaAccessorType, string>> = {\n number: 'tabular-nums',\n date: 'tabular-nums',\n};\n\nexport interface CellValueProps {\n value: unknown;\n descriptor: EntityFieldDescriptor;\n /**\n * The record the value belongs to. A money member whose currency is another\n * member of the record (`money.currencyMember`), and a scaled member whose\n * unit is (`scaled.unitMember`), read it from here.\n */\n record?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Renders one entity member according to its metadata type. Centralizing this\n * is what lets a table stay generic: a link, a date and a number all arrive as\n * \"the value of an accessor\", and only the descriptor decides how they read.\n */\nexport function CellValue({ value, descriptor, record }: CellValueProps) {\n const formatting = useCellFormatting();\n const locale = useLocale();\n const unitLabel = useUnitLabel();\n\n if (value === undefined || value === null || value === '') {\n return <span className=\"text-content-muted\">{EMPTY}</span>;\n }\n\n // A key into another entity reads as that record's name, never as itself.\n if (descriptor.references !== undefined) {\n return (\n <ReferenceValue\n entity={descriptor.references.entity}\n id={String(value)}\n />\n );\n }\n\n // An amount reads as money in the reader's locale, never as the stored\n // number. A draft holds it as a string, so a numeric string counts too. A\n // currency the record does not carry leaves it a plain number rather than\n // guessing one.\n if (descriptor.money !== undefined) {\n const amount = typeof value === 'number' ? value : Number(value);\n const currency = currencyOf(descriptor.money, record);\n if (currency !== undefined && Number.isFinite(amount)) {\n return (\n <Money\n amount={amount}\n currency={currency}\n unit={descriptor.money.unit}\n locale={locale}\n />\n );\n }\n }\n\n // A scaled integer reads as the decimal it stands for, beside its unit. One\n // whose record names no declared unit stays the number it is, as money\n // without a currency does.\n if (descriptor.scaled !== undefined) {\n const stored = Number(value);\n const resolved = scaleOf(descriptor.scaled, record);\n if (resolved !== undefined && Number.isSafeInteger(stored)) {\n return (\n <ScaledValue\n value={stored}\n scale={resolved.scale}\n unit={unitLabel(descriptor.scaled, resolved.unit)}\n locale={locale}\n />\n );\n }\n }\n\n // A relation whose target has not arrived yet holds its place with a\n // skeleton — the id is all it has, and the id is not what it means.\n if (\n (value instanceof EntityLink &&\n value.id != null &&\n value.value === undefined) ||\n (value instanceof EntityCollectionLink &&\n value.ids.length > 0 &&\n value.values === undefined)\n ) {\n return <Skeleton shape=\"line\" className=\"w-16\" />;\n }\n\n const text = formatByType(\n value,\n descriptor.type,\n descriptor.linkLabelProperty,\n formatting(descriptor),\n );\n\n if (text === '') {\n return <span className=\"text-content-muted\">{EMPTY}</span>;\n }\n\n // A status reads as a tag in its declared tone, its words beside the\n // colour; a value given no tone reads neutral. An enum that declared no\n // tones is not a status, and stays text.\n if (descriptor.type === 'enum' && descriptor.enumTones !== undefined) {\n return (\n <StatusTag tone={descriptor.enumTones[String(value)] ?? 'neutral'}>\n {text}\n </StatusTag>\n );\n }\n\n // Text the reader's locale lacks falls back to the default locale's, and is\n // marked as that language, so it is read in its own voice (WCAG 3.1.2).\n if (\n descriptor.type === 'localized' &&\n isLocalizedText(value) &&\n (value[locale] ?? '') === ''\n ) {\n return <span lang={defaultLocale()}>{text}</span>;\n }\n\n return (\n <span className={NUMERIC_CLASS[descriptor.type] ?? undefined}>{text}</span>\n );\n}\n"],"names":["defaultLocale","EntityCollectionLink","EntityLink","formatScaled","isLocalizedText","localize","useCallback","useEnumLabel","useFormatters","useLocale","useT","useReferenceLabel","useUnresolvedReference","Money","currencyOf","scaleOf","ScaledValue","useUnitLabel","Skeleton","StatusTag","EMPTY","entityLabel","target","linkLabelProperty","locale","label","undefined","String","formatLink","link","id","value","formatCollectionLink","values","map","join","formatByType","type","formatting","formatters","date","Date","fixedScale","Number","isSafeInteger","number","yes","no","enumLabel","Array","isArray","rowCount","length","useCellFormatting","t","descriptor","raw","count","scaled","scale","useValueText","ReferenceValue","entity","state","unresolved","status","shape","className","span","text","lang","NUMERIC_CLASS","CellValue","record","unitLabel","references","money","amount","currency","isFinite","unit","stored","resolved","ids","enumTones","tone"],"mappings":"AAAA;;AAGA,SACEA,aAAa,EAEbC,oBAAoB,EAEpBC,UAAU,EACVC,YAAY,EACZC,eAAe,EACfC,QAAQ,QAEH,gBAAgB;AACvB,SAASC,WAAW,QAAQ,QAAQ;AAEpC,SACEC,YAAY,EACZC,aAAa,EACbC,SAAS,EACTC,IAAI,QACC,yBAAyB;AAChC,SACEC,iBAAiB,EACjBC,sBAAsB,QACjB,kCAAkC;AACzC,SAASC,KAAK,QAAQ,oBAAoB;AAC1C,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SAASC,OAAO,QAAQ,2BAA2B;AACnD,SAASC,WAAW,QAAQ,4BAA4B;AACxD,SAASC,YAAY,QAAQ,8BAA8B;AAC3D,SAASC,QAAQ,QAAQ,uBAAuB;AAChD,SAASC,SAAS,QAAQ,yBAAyB;AAEnD,+EAA+E,GAC/E,MAAMC,QAAQ;AAEd;;;;CAIC,GACD,SAASC,YACPC,MAA0B,EAC1BC,iBAAyB,EACzBC,MAAc;IAEd,MAAMC,QAASH,0BAAD,AAACA,MAAgD,CAC7DC,kBACD;IACD,IAAIE,SAAS,MAAM,OAAOC;IAC1B,wEAAwE;IACxE,OAAOtB,gBAAgBqB,SAASpB,SAASoB,OAAO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I,OAAO,YAAnCwB,+BAAuC;sBACrDc;;IAGP;IAEA,4EAA4E;IAC5E,wEAAwE;IACxE,IACEd,WAAWlB,IAAI,KAAK,eACpBjC,gBAAgB2B,UAChB,EAACA,gBAAAA,KAAK,CAACP,OAAO,YAAbO,gBAAiB,QAAQ,IAC1B;QACA,qBAAO,KAACqC;YAAKE,MAAMtE;sBAAkBqE;;IACvC;IAEA,qBACE,KAACD;QAAKD,SAAS,GAAEI,iCAAAA,aAAa,CAAChB,WAAWlB,IAAI,CAAC,YAA9BkC,iCAAkC7C;kBAAY2C;;AAEnE"}
@@ -26,7 +26,8 @@ export interface FieldControlProps {
26
26
  id?: string;
27
27
  /**
28
28
  * The record being edited, as its draft. A money member whose currency is
29
- * another member (`money.currencyMember`) reads it from here.
29
+ * another member (`money.currencyMember`), and a scaled one whose unit is
30
+ * (`scaled.unitMember`), read it from here.
30
31
  */
31
32
  record?: Readonly<Record<string, unknown>>;
32
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"field-control.d.ts","sourceRoot":"","sources":["../../../../src/ui/atoms/field-control/field-control.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAoB,MAAM,eAAe,CAAC;AAO7E,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,qBAAqB,CAAC;IAClC;;;;;;;;;;OAUG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC5C;AAQD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,YAAY,CAAC,EAC3B,UAAU,EACV,KAAK,EACL,QAAQ,EACR,EAAE,EACF,MAAM,EACN,GAAG,IAAI,EACR,EAAE,iBAAiB,+BA2EnB"}
1
+ {"version":3,"file":"field-control.d.ts","sourceRoot":"","sources":["../../../../src/ui/atoms/field-control/field-control.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAoB,MAAM,eAAe,CAAC;AAU7E,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,qBAAqB,CAAC;IAClC;;;;;;;;;;OAUG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC5C;AAQD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,YAAY,CAAC,EAC3B,UAAU,EACV,KAAK,EACL,QAAQ,EACR,EAAE,EACF,MAAM,EACN,GAAG,IAAI,EACR,EAAE,iBAAiB,+BA8FnB"}
@@ -6,6 +6,9 @@ import { useEnumLabel, useLocale } from '../../../i18n/index.js';
6
6
  import { Checkbox, Select, TextInput } from '../field/index.js';
7
7
  import { MoneyInput } from '../money/money-input.js';
8
8
  import { currencyOf } from '../money/money-math.js';
9
+ import { ScaledInput } from '../scaled/scaled-input.js';
10
+ import { scaleOf } from '../scaled/scaled-math.js';
11
+ import { useUnitLabel } from '../scaled/use-unit-label.js';
9
12
  /** Native input type for the text-like controls; text is the default. */ const INPUT_TYPE = {
10
13
  number: 'number',
11
14
  date: 'date'
@@ -42,6 +45,7 @@ import { currencyOf } from '../money/money-math.js';
42
45
  var _INPUT_TYPE_descriptor_type;
43
46
  const enumLabel = useEnumLabel();
44
47
  const locale = useLocale();
48
+ const unitLabel = useUnitLabel();
45
49
  const disabled = descriptor.readonly || descriptor.type === 'link' || descriptor.type === 'linkCollection' || descriptor.type === 'composition';
46
50
  if (descriptor.type === 'boolean') {
47
51
  return /*#__PURE__*/ _jsx(Checkbox, _extends({
@@ -89,6 +93,21 @@ import { currencyOf } from '../money/money-math.js';
89
93
  onChange: onChange
90
94
  }));
91
95
  }
96
+ // A scaled integer is edited as the decimal it stands for. Unlike money it
97
+ // has no plain fallback: without a scale, `3` typed would be stored as 0.003.
98
+ if (descriptor.scaled !== undefined) {
99
+ const resolved = scaleOf(descriptor.scaled, record);
100
+ return /*#__PURE__*/ _jsx(ScaledInput, _extends({
101
+ id: id
102
+ }, aria, {
103
+ value: value,
104
+ scale: resolved == null ? void 0 : resolved.scale,
105
+ unit: unitLabel(descriptor.scaled, resolved == null ? void 0 : resolved.unit),
106
+ locale: locale,
107
+ disabled: disabled,
108
+ onChange: onChange
109
+ }));
110
+ }
92
111
  return /*#__PURE__*/ _jsx(TextInput, _extends({
93
112
  id: id
94
113
  }, aria, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/ui/atoms/field-control/field-control.tsx"],"sourcesContent":["'use client';\n\nimport type { EntityFieldDescriptor, MetaAccessorType } from '@entifix/core';\n\nimport { useEnumLabel, useLocale } from '../../../i18n/index.js';\nimport { Checkbox, Select, TextInput } from '../field/index.js';\nimport { MoneyInput } from '../money/money-input.js';\nimport { currencyOf } from '../money/money-math.js';\n\nexport interface FieldControlProps {\n descriptor: EntityFieldDescriptor;\n /**\n * ARIA wiring the caller owns, because only the caller knows the shape it is\n * rendered into.\n *\n * A form labels its control with a `<label for>` and needs none of this; a\n * detail grid's cell has no label of its own — the column header is the\n * label, and the cell's message is the description — so it points at both by\n * id. Passing them through here rather than duplicating the type→input map\n * in the grid is what keeps one control deciding what a `date` member looks\n * like.\n */\n 'aria-labelledby'?: string;\n 'aria-describedby'?: string;\n 'aria-invalid'?: boolean;\n 'aria-required'?: boolean;\n /**\n * The draft value as a string — the shape a native input round-trips. A form\n * holds its whole draft as `Record<string, string>` and reconstructs typed\n * values only at submit, so the control never sees a domain value.\n */\n value: string;\n onChange: (value: string) => void;\n id?: string;\n /**\n * The record being edited, as its draft. A money member whose currency is\n * another member (`money.currencyMember`) reads it from here.\n */\n record?: Readonly<Record<string, unknown>>;\n}\n\n/** Native input type for the text-like controls; text is the default. */\nconst INPUT_TYPE: Partial<Record<MetaAccessorType, string>> = {\n number: 'number',\n date: 'date',\n};\n\n/**\n * The edit-mode inverse of {@link CellValue}: it turns one metadata descriptor\n * into the input that edits it. Centralizing the type→control choice is what\n * lets a form stay generic, the same way `CellValue` keeps a table generic.\n *\n * A relation (`link`/`linkCollection`) is rendered read-only here, deliberately:\n * editing one needs a picker that can search and page the target, which is a\n * different control with different dependencies. So this atom stays a pure\n * type→input map and a relation never falls back to a broken text box.\n *\n * For a to-one `link` that is only half the story — `EntityForm` wires the\n * picker in one level up from its `linkSources`, so the member does get an\n * editor, just not from here. A `linkCollection` has no editor anywhere yet\n * (#26), and read-only is all it gets. A `composition` is the same: its rows\n * need a detail grid, and a text box holding `[object Object]` would be\n * strictly worse than an honest disabled field.\n *\n * A `scalarCollection` is the exception among the collections and falls through\n * to the plain text input on purpose: a `string[]` has a lossless comma form,\n * so the draft it round-trips through *is* editable text. Splitting on the\n * comma is `reconstructEntity`'s half of that same contract.\n */\nexport function FieldControl({\n descriptor,\n value,\n onChange,\n id,\n record,\n ...aria\n}: FieldControlProps) {\n const enumLabel = useEnumLabel();\n const locale = useLocale();\n const disabled =\n descriptor.readonly ||\n descriptor.type === 'link' ||\n descriptor.type === 'linkCollection' ||\n descriptor.type === 'composition';\n\n if (descriptor.type === 'boolean') {\n return (\n <Checkbox\n id={id}\n {...aria}\n label={descriptor.label}\n checked={value === 'true'}\n disabled={disabled}\n onChange={event => onChange(String(event.currentTarget.checked))}\n />\n );\n }\n\n if (descriptor.type === 'enum') {\n return (\n <Select\n id={id}\n {...aria}\n value={value}\n disabled={disabled}\n onChange={event => onChange(event.currentTarget.value)}\n >\n <option value=\"\">—</option>\n {(descriptor.enumValues ?? []).map(option => (\n <option key={option} value={option}>\n {enumLabel(descriptor, option)}\n </option>\n ))}\n </Select>\n );\n }\n\n // An amount is edited in major units, in the reader's decimal separator,\n // and written back in the unit it is stored in. Without a currency to know\n // the minor units by, it stays a plain number field.\n const currency =\n descriptor.money === undefined\n ? undefined\n : currencyOf(descriptor.money, record);\n if (descriptor.money !== undefined && currency !== undefined) {\n return (\n <MoneyInput\n id={id}\n {...aria}\n value={value}\n currency={currency}\n unit={descriptor.money.unit}\n locale={locale}\n disabled={disabled}\n onChange={onChange}\n />\n );\n }\n\n return (\n <TextInput\n id={id}\n {...aria}\n // What the field is for, so a browser can fill it (WCAG 1.3.5).\n autoComplete={descriptor.autocomplete}\n type={INPUT_TYPE[descriptor.type] ?? 'text'}\n value={value}\n disabled={disabled}\n onChange={event => onChange(event.currentTarget.value)}\n />\n );\n}\n"],"names":["useEnumLabel","useLocale","Checkbox","Select","TextInput","MoneyInput","currencyOf","INPUT_TYPE","number","date","FieldControl","descriptor","value","onChange","id","record","aria","enumLabel","locale","disabled","readonly","type","label","checked","event","String","currentTarget","option","enumValues","map","currency","money","undefined","unit","autoComplete","autocomplete"],"mappings":"AAAA;;;;AAIA,SAASA,YAAY,EAAEC,SAAS,QAAQ,yBAAyB;AACjE,SAASC,QAAQ,EAAEC,MAAM,EAAEC,SAAS,QAAQ,oBAAoB;AAChE,SAASC,UAAU,QAAQ,0BAA0B;AACrD,SAASC,UAAU,QAAQ,yBAAyB;AAkCpD,uEAAuE,GACvE,MAAMC,aAAwD;IAC5DC,QAAQ;IACRC,MAAM;A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N,UAAUA;;IAGhB;IAEA,qBACE,KAACT;QACCU,IAAIA;OACAE;QACJ,gEAAgE;QAChEkB,cAAcvB,WAAWwB,YAAY;QACrCd,IAAI,GAAEd,8BAAAA,UAAU,CAACI,WAAWU,IAAI,CAAC,YAA3Bd,8BAA+B;QACrCK,OAAOA;QACPO,UAAUA;QACVN,UAAUW,CAAAA,QAASX,SAASW,MAAME,aAAa,CAACd,KAAK;;AAG3D"}
1
+ {"version":3,"sources":["../../../../src/ui/atoms/field-control/field-control.tsx"],"sourcesContent":["'use client';\n\nimport type { EntityFieldDescriptor, MetaAccessorType } from '@entifix/core';\n\nimport { useEnumLabel, useLocale } from '../../../i18n/index.js';\nimport { Checkbox, Select, TextInput } from '../field/index.js';\nimport { MoneyInput } from '../money/money-input.js';\nimport { currencyOf } from '../money/money-math.js';\nimport { ScaledInput } from '../scaled/scaled-input.js';\nimport { scaleOf } from '../scaled/scaled-math.js';\nimport { useUnitLabel } from '../scaled/use-unit-label.js';\n\nexport interface FieldControlProps {\n descriptor: EntityFieldDescriptor;\n /**\n * ARIA wiring the caller owns, because only the caller knows the shape it is\n * rendered into.\n *\n * A form labels its control with a `<label for>` and needs none of this; a\n * detail grid's cell has no label of its own — the column header is the\n * label, and the cell's message is the description — so it points at both by\n * id. Passing them through here rather than duplicating the type→input map\n * in the grid is what keeps one control deciding what a `date` member looks\n * like.\n */\n 'aria-labelledby'?: string;\n 'aria-describedby'?: string;\n 'aria-invalid'?: boolean;\n 'aria-required'?: boolean;\n /**\n * The draft value as a string — the shape a native input round-trips. A form\n * holds its whole draft as `Record<string, string>` and reconstructs typed\n * values only at submit, so the control never sees a domain value.\n */\n value: string;\n onChange: (value: string) => void;\n id?: string;\n /**\n * The record being edited, as its draft. A money member whose currency is\n * another member (`money.currencyMember`), and a scaled one whose unit is\n * (`scaled.unitMember`), read it from here.\n */\n record?: Readonly<Record<string, unknown>>;\n}\n\n/** Native input type for the text-like controls; text is the default. */\nconst INPUT_TYPE: Partial<Record<MetaAccessorType, string>> = {\n number: 'number',\n date: 'date',\n};\n\n/**\n * The edit-mode inverse of {@link CellValue}: it turns one metadata descriptor\n * into the input that edits it. Centralizing the type→control choice is what\n * lets a form stay generic, the same way `CellValue` keeps a table generic.\n *\n * A relation (`link`/`linkCollection`) is rendered read-only here, deliberately:\n * editing one needs a picker that can search and page the target, which is a\n * different control with different dependencies. So this atom stays a pure\n * type→input map and a relation never falls back to a broken text box.\n *\n * For a to-one `link` that is only half the story — `EntityForm` wires the\n * picker in one level up from its `linkSources`, so the member does get an\n * editor, just not from here. A `linkCollection` has no editor anywhere yet\n * (#26), and read-only is all it gets. A `composition` is the same: its rows\n * need a detail grid, and a text box holding `[object Object]` would be\n * strictly worse than an honest disabled field.\n *\n * A `scalarCollection` is the exception among the collections and falls through\n * to the plain text input on purpose: a `string[]` has a lossless comma form,\n * so the draft it round-trips through *is* editable text. Splitting on the\n * comma is `reconstructEntity`'s half of that same contract.\n */\nexport function FieldControl({\n descriptor,\n value,\n onChange,\n id,\n record,\n ...aria\n}: FieldControlProps) {\n const enumLabel = useEnumLabel();\n const locale = useLocale();\n const unitLabel = useUnitLabel();\n const disabled =\n descriptor.readonly ||\n descriptor.type === 'link' ||\n descriptor.type === 'linkCollection' ||\n descriptor.type === 'composition';\n\n if (descriptor.type === 'boolean') {\n return (\n <Checkbox\n id={id}\n {...aria}\n label={descriptor.label}\n checked={value === 'true'}\n disabled={disabled}\n onChange={event => onChange(String(event.currentTarget.checked))}\n />\n );\n }\n\n if (descriptor.type === 'enum') {\n return (\n <Select\n id={id}\n {...aria}\n value={value}\n disabled={disabled}\n onChange={event => onChange(event.currentTarget.value)}\n >\n <option value=\"\">—</option>\n {(descriptor.enumValues ?? []).map(option => (\n <option key={option} value={option}>\n {enumLabel(descriptor, option)}\n </option>\n ))}\n </Select>\n );\n }\n\n // An amount is edited in major units, in the reader's decimal separator,\n // and written back in the unit it is stored in. Without a currency to know\n // the minor units by, it stays a plain number field.\n const currency =\n descriptor.money === undefined\n ? undefined\n : currencyOf(descriptor.money, record);\n if (descriptor.money !== undefined && currency !== undefined) {\n return (\n <MoneyInput\n id={id}\n {...aria}\n value={value}\n currency={currency}\n unit={descriptor.money.unit}\n locale={locale}\n disabled={disabled}\n onChange={onChange}\n />\n );\n }\n\n // A scaled integer is edited as the decimal it stands for. Unlike money it\n // has no plain fallback: without a scale, `3` typed would be stored as 0.003.\n if (descriptor.scaled !== undefined) {\n const resolved = scaleOf(descriptor.scaled, record);\n return (\n <ScaledInput\n id={id}\n {...aria}\n value={value}\n scale={resolved?.scale}\n unit={unitLabel(descriptor.scaled, resolved?.unit)}\n locale={locale}\n disabled={disabled}\n onChange={onChange}\n />\n );\n }\n\n return (\n <TextInput\n id={id}\n {...aria}\n // What the field is for, so a browser can fill it (WCAG 1.3.5).\n autoComplete={descriptor.autocomplete}\n type={INPUT_TYPE[descriptor.type] ?? 'text'}\n value={value}\n disabled={disabled}\n onChange={event => onChange(event.currentTarget.value)}\n />\n );\n}\n"],"names":["useEnumLabel","useLocale","Checkbox","Select","TextInput","MoneyInput","currencyOf","ScaledInput","scaleOf","useUnitLabel","INPUT_TYPE","number","date","FieldControl","descriptor","value","onChange","id","record","aria","enumLabel","locale","unitLabel","disabled","readonly","type","label","checked","event","String","currentTarget","option","enumValues","map","currency","money","undefined","unit","scaled","resolved","scale","autoComplete","autocomplete"],"mappings":"AAAA;;;;AAIA,SAASA,YAAY,EAAEC,SAAS,QAAQ,yBAAyB;AACjE,SAASC,QAAQ,EAAEC,MAAM,EAAEC,SAAS,QAAQ,oBAAoB;AAChE,SAASC,UAAU,QAAQ,0BAA0B;AACrD,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SAASC,WAAW,QAAQ,4BAA4B;AACxD,SAASC,OAAO,QAAQ,2BAA2B;AACnD,SAASC,YAAY,QAAQ,8BAA8B;AAmC3D,uEAAuE,GACvE,MAAMC,aAAwD;IAC5DC,QAAQ;IACRC,MAAM;AACR;AAEA;;;;;;;;;;;;;;;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UA;YACVP,UAAUA;;IAGhB;IAEA,2EAA2E;IAC3E,8EAA8E;IAC9E,IAAIF,WAAWwB,MAAM,KAAKF,WAAW;QACnC,MAAMG,WAAW/B,QAAQM,WAAWwB,MAAM,EAAEpB;QAC5C,qBACE,KAACX;YACCU,IAAIA;WACAE;YACJJ,OAAOA;YACPyB,KAAK,EAAED,4BAAAA,SAAUC,KAAK;YACtBH,MAAMf,UAAUR,WAAWwB,MAAM,EAAEC,4BAAAA,SAAUF,IAAI;YACjDhB,QAAQA;YACRE,UAAUA;YACVP,UAAUA;;IAGhB;IAEA,qBACE,KAACZ;QACCa,IAAIA;OACAE;QACJ,gEAAgE;QAChEsB,cAAc3B,WAAW4B,YAAY;QACrCjB,IAAI,GAAEf,8BAAAA,UAAU,CAACI,WAAWW,IAAI,CAAC,YAA3Bf,8BAA+B;QACrCK,OAAOA;QACPQ,UAAUA;QACVP,UAAUY,CAAAA,QAASZ,SAASY,MAAME,aAAa,CAACf,KAAK;;AAG3D"}
@@ -14,6 +14,10 @@ export interface MoneyInputProps extends Omit<NumberInputProps, 'value' | 'onCha
14
14
  * back the stored unit. What was typed is kept as typed (a trailing `64,` is
15
15
  * not reformatted under the cursor), and the field follows the stored value
16
16
  * only when it changes from outside.
17
+ *
18
+ * `1,000` is a thousand in any locale, since no two-decimal currency has
19
+ * three; text with more decimals than the currency holds is refused by
20
+ * validation rather than rounded (`parseScaled`).
17
21
  */
18
22
  export declare function MoneyInput({ value, onChange, currency, unit, locale, ...props }: MoneyInputProps): import("react").JSX.Element;
19
23
  //# sourceMappingURL=money-input.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"money-input.d.ts","sourceRoot":"","sources":["../../../../src/ui/atoms/money/money-input.tsx"],"names":[],"mappings":"AAIA,OAAO,EAEL,KAAK,gBAAgB,EACtB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,KAAK,SAAS,EAEf,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,eAAgB,SAAQ,IAAI,CAC3C,gBAAgB,EAChB,OAAO,GAAG,UAAU,GAAG,WAAW,CACnC;IACC,yEAAyE;IACzE,KAAK,EAAE,MAAM,CAAC;IACd,uDAAuD;IACvD,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAkBD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,EACzB,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,IAAI,EACJ,MAAM,EACN,GAAG,KAAK,EACT,EAAE,eAAe,+BA+CjB"}
1
+ {"version":3,"file":"money-input.d.ts","sourceRoot":"","sources":["../../../../src/ui/atoms/money/money-input.tsx"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,gBAAgB,EACtB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAkB,KAAK,SAAS,EAAgB,MAAM,iBAAiB,CAAC;AAE/E,MAAM,WAAW,eAAgB,SAAQ,IAAI,CAC3C,gBAAgB,EAChB,OAAO,GAAG,UAAU,GAAG,WAAW,CACnC;IACC,yEAAyE;IACzE,KAAK,EAAE,MAAM,CAAC;IACd,uDAAuD;IACvD,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,EACzB,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,IAAI,EACJ,MAAM,EACN,GAAG,KAAK,EACT,EAAE,eAAe,+BA+CjB"}
@@ -2,23 +2,20 @@
2
2
  import { _ as _extends } from "@swc/helpers/_/_extends";
3
3
  import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
4
4
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
5
+ import { parseScaled, scaledToDecimal } from '@entifix/core';
5
6
  import { useEffect, useState } from 'react';
6
7
  import { NumberInput } from '../number-input/number-input.js';
7
- import { fractionDigits, fromMajorUnits, toMajorUnits } from './money-math.js';
8
- const parseMajor = (text)=>{
9
- // Accept either decimal separator: the last `,` or `.` is the decimal one.
10
- const normalised = text.trim().replace(/[\s']/g, '');
11
- if (normalised === '') return undefined;
12
- const last = Math.max(normalised.lastIndexOf(','), normalised.lastIndexOf('.'));
13
- const plain = last === -1 ? normalised : `${normalised.slice(0, last).replace(/[.,]/g, '')}.${normalised.slice(last + 1)}`;
14
- const major = Number(plain);
15
- return Number.isFinite(major) ? major : undefined;
16
- };
8
+ import { typedText, unparsedDraft } from '../number-input/unparsed.js';
9
+ import { fractionDigits, toMajorUnits } from './money-math.js';
17
10
  /**
18
11
  * Edits an amount in major units — what a person means by a price — and writes
19
12
  * back the stored unit. What was typed is kept as typed (a trailing `64,` is
20
13
  * not reformatted under the cursor), and the field follows the stored value
21
14
  * only when it changes from outside.
15
+ *
16
+ * `1,000` is a thousand in any locale, since no two-decimal currency has
17
+ * three; text with more decimals than the currency holds is refused by
18
+ * validation rather than rounded (`parseScaled`).
22
19
  */ export function MoneyInput(_0) {
23
20
  let { value, onChange, currency, unit, locale } = _0, props = _object_without_properties_loose(_0, [
24
21
  "value",
@@ -28,7 +25,7 @@ const parseMajor = (text)=>{
28
25
  "locale"
29
26
  ]);
30
27
  const digits = fractionDigits(currency);
31
- const display = (stored)=>stored === '' || !Number.isFinite(Number(stored)) ? stored : new Intl.NumberFormat(locale, {
28
+ const display = (stored)=>stored === '' || !Number.isFinite(Number(stored)) ? typedText(stored) : new Intl.NumberFormat(locale, {
32
29
  minimumFractionDigits: digits,
33
30
  maximumFractionDigits: digits,
34
31
  useGrouping: false
@@ -57,8 +54,8 @@ const parseMajor = (text)=>{
57
54
  onChange: (event)=>{
58
55
  const next = event.currentTarget.value;
59
56
  setText(next);
60
- const major = parseMajor(next);
61
- const stored = major === undefined ? next.trim() === '' ? '' : next : String(fromMajorUnits(major, currency, unit));
57
+ const minor = parseScaled(next, digits, locale);
58
+ const stored = minor === undefined ? unparsedDraft(next) : unit === 'minor' ? String(minor) : scaledToDecimal(minor, digits);
62
59
  setEmitted(stored);
63
60
  onChange(stored);
64
61
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/ui/atoms/money/money-input.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\n\nimport {\n NumberInput,\n type NumberInputProps,\n} from '../number-input/number-input.js';\nimport {\n fractionDigits,\n fromMajorUnits,\n type MoneyUnit,\n toMajorUnits,\n} from './money-math.js';\n\nexport interface MoneyInputProps extends Omit<\n NumberInputProps,\n 'value' | 'onChange' | 'inputMode'\n> {\n /** The stored amount, as a draft string (`'6499'`), or `''` for none. */\n value: string;\n /** Called with the stored amount as a draft string. */\n onChange: (value: string) => void;\n currency: string;\n unit: MoneyUnit;\n locale: string;\n}\n\nconst parseMajor = (text: string): number | undefined => {\n // Accept either decimal separator: the last `,` or `.` is the decimal one.\n const normalised = text.trim().replace(/[\\s']/g, '');\n if (normalised === '') return undefined;\n const last = Math.max(\n normalised.lastIndexOf(','),\n normalised.lastIndexOf('.'),\n );\n const plain =\n last === -1\n ? normalised\n : `${normalised.slice(0, last).replace(/[.,]/g, '')}.${normalised.slice(last + 1)}`;\n const major = Number(plain);\n return Number.isFinite(major) ? major : undefined;\n};\n\n/**\n * Edits an amount in major units — what a person means by a price — and writes\n * back the stored unit. What was typed is kept as typed (a trailing `64,` is\n * not reformatted under the cursor), and the field follows the stored value\n * only when it changes from outside.\n */\nexport function MoneyInput({\n value,\n onChange,\n currency,\n unit,\n locale,\n ...props\n}: MoneyInputProps) {\n const digits = fractionDigits(currency);\n const display = (stored: string) =>\n stored === '' || !Number.isFinite(Number(stored))\n ? stored\n : new Intl.NumberFormat(locale, {\n minimumFractionDigits: digits,\n maximumFractionDigits: digits,\n useGrouping: false,\n }).format(toMajorUnits(Number(stored), currency, unit));\n\n const [text, setText] = useState(() => display(value));\n const [emitted, setEmitted] = useState(value);\n\n useEffect(() => {\n if (value === emitted) return;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- an outside write (a reset, a load) replaces what was typed\n setText(display(value));\n setEmitted(value);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `display` is derived from props already listed\n }, [value, emitted, currency, unit, locale]);\n\n return (\n <span className=\"inline-flex items-center gap-2xs\">\n <NumberInput\n {...props}\n inputMode={digits === 0 ? 'numeric' : 'decimal'}\n value={text}\n onChange={event => {\n const next = event.currentTarget.value;\n setText(next);\n const major = parseMajor(next);\n const stored =\n major === undefined\n ? next.trim() === ''\n ? ''\n : next\n : String(fromMajorUnits(major, currency, unit));\n setEmitted(stored);\n onChange(stored);\n }}\n />\n <span className=\"text-step-sm text-content-muted\" aria-hidden=\"true\">\n {currency}\n </span>\n </span>\n );\n}\n"],"names":["useEffect","useState","NumberInput","fractionDigits","fromMajorUnits","toMajorUnits","parseMajor","text","normalised","trim","replace","undefined","last","Math","max","lastIndexOf","plain","slice","major","Number","isFinite","MoneyInput","value","onChange","currency","unit","locale","props","digits","display","stored","Intl","NumberFormat","minimumFractionDigits","maximumFractionDigits","useGrouping","format","setText","emitted","setEmitted","span","className","inputMode","event","next","currentTarget","String","aria-hidden"],"mappings":"AAAA;;;;AAEA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAE5C,SACEC,WAAW,QAEN,kCAAkC;AACzC,SACEC,cAAc,EACdC,cAAc,EAEdC,YAAY,QACP,kBAAkB;AAezB,MAAMC,aAAa,CAACC;IAClB,2EAA2E;IAC3E,MAAMC,aAAaD,KAAKE,IAAI,GAAGC,OAAO,CAAC,UAAU;IACjD,IAAIF,eAAe,IAAI,OAAOG;IAC9B,MAAMC,OAAOC,KAAKC,GAAG,CACnBN,WAAWO,WAAW,CAAC,MACvBP,WAAWO,WAAW,CAAC;IAEzB,MAAMC,QAC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XP,SAASO;gBACX;;0BAEF,KAACU;gBAAKC,WAAU;gBAAkCM,eAAY;0BAC3DvB;;;;AAIT"}
1
+ {"version":3,"sources":["../../../../src/ui/atoms/money/money-input.tsx"],"sourcesContent":["'use client';\n\nimport { parseScaled, scaledToDecimal } from '@entifix/core';\nimport { useEffect, useState } from 'react';\n\nimport {\n NumberInput,\n type NumberInputProps,\n} from '../number-input/number-input.js';\nimport { typedText, unparsedDraft } from '../number-input/unparsed.js';\nimport { fractionDigits, type MoneyUnit, toMajorUnits } from './money-math.js';\n\nexport interface MoneyInputProps extends Omit<\n NumberInputProps,\n 'value' | 'onChange' | 'inputMode'\n> {\n /** The stored amount, as a draft string (`'6499'`), or `''` for none. */\n value: string;\n /** Called with the stored amount as a draft string. */\n onChange: (value: string) => void;\n currency: string;\n unit: MoneyUnit;\n locale: string;\n}\n\n/**\n * Edits an amount in major units — what a person means by a price — and writes\n * back the stored unit. What was typed is kept as typed (a trailing `64,` is\n * not reformatted under the cursor), and the field follows the stored value\n * only when it changes from outside.\n *\n * `1,000` is a thousand in any locale, since no two-decimal currency has\n * three; text with more decimals than the currency holds is refused by\n * validation rather than rounded (`parseScaled`).\n */\nexport function MoneyInput({\n value,\n onChange,\n currency,\n unit,\n locale,\n ...props\n}: MoneyInputProps) {\n const digits = fractionDigits(currency);\n const display = (stored: string) =>\n stored === '' || !Number.isFinite(Number(stored))\n ? typedText(stored)\n : new Intl.NumberFormat(locale, {\n minimumFractionDigits: digits,\n maximumFractionDigits: digits,\n useGrouping: false,\n }).format(toMajorUnits(Number(stored), currency, unit));\n\n const [text, setText] = useState(() => display(value));\n const [emitted, setEmitted] = useState(value);\n\n useEffect(() => {\n if (value === emitted) return;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- an outside write (a reset, a load) replaces what was typed\n setText(display(value));\n setEmitted(value);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `display` is derived from props already listed\n }, [value, emitted, currency, unit, locale]);\n\n return (\n <span className=\"inline-flex items-center gap-2xs\">\n <NumberInput\n {...props}\n inputMode={digits === 0 ? 'numeric' : 'decimal'}\n value={text}\n onChange={event => {\n const next = event.currentTarget.value;\n setText(next);\n const minor = parseScaled(next, digits, locale);\n const stored =\n minor === undefined\n ? unparsedDraft(next)\n : unit === 'minor'\n ? String(minor)\n : scaledToDecimal(minor, digits);\n setEmitted(stored);\n onChange(stored);\n }}\n />\n <span className=\"text-step-sm text-content-muted\" aria-hidden=\"true\">\n {currency}\n </span>\n </span>\n );\n}\n"],"names":["parseScaled","scaledToDecimal","useEffect","useState","NumberInput","typedText","unparsedDraft","fractionDigits","toMajorUnits","MoneyInput","value","onChange","currency","unit","locale","props","digits","display","stored","Number","isFinite","Intl","NumberFormat","minimumFractionDigits","maximumFractionDigits","useGrouping","format","text","setText","emitted","setEmitted","span","className","inputMode","event","next","currentTarget","minor","undefined","String","aria-hidden"],"mappings":"AAAA;;;;AAEA,SAASA,WAAW,EAAEC,eAAe,QAAQ,gBAAgB;AAC7D,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAE5C,SACEC,WAAW,QAEN,kCAAkC;AACzC,SAASC,SAAS,EAAEC,aAAa,QAAQ,8BAA8B;AACvE,SAASC,cAAc,EAAkBC,YAAY,QAAQ,kBAAkB;AAe/E;;;;;;;;;CASC,GACD,OAAO,SAASC,WAAW,EAOT;QAPS,EACzBC,KAAK,EACLC,QAAQ,EACRC,QAAQ,EACRC,IAAI,EACJC,MAAM,EAEU,OADbC;;;;;;;IAEH,MAAMC,SAAST,eAAeK;IAC9B,MAAMK,UAAU,CAACC,SACfA,WAAW,MAAM,CAACC,OAAOC,QAAQ,CAACD,OAAOD,WACrCb,UAAUa,UACV,IAAIG,KAAKC,YAAY,CAACR,QAAQ;YAC5BS,uBAAuBP;YACvBQ,uBAAuBR;YACvBS,aAAa;QACf,GAAGC,MAAM,CAAClB,aAAaW,OAAOD,SAASN,UAAUC;IAEvD,MAAM,CAACc,MAAMC,QAAQ,GAAGzB,SAAS,IAAMc,QAAQP;IAC/C,MAAM,CAACmB,SAASC,WAAW,GAAG3B,SAASO;IAEvCR,UAAU;QACR,IAAIQ,UAAUmB,SAAS;QACvB,yHAAyH;QACzHD,QAAQX,QAAQP;QAChBoB,WAAWpB;IACX,yGAAyG;IAC3G,GAAG;QAACA;QAAOmB;QAASjB;QAAUC;QAAMC;KAAO;IAE3C,qBACE,MAACiB;QAAKC,WAAU;;0BACd,KAAC5B,0BACKW;gBACJkB,WAAWjB,WAAW,IAAI,YAAY;gBACtCN,OAAOiB;gBACPhB,UAAUuB,CAAAA;oBACR,MAAMC,OAAOD,MAAME,aAAa,CAAC1B,KAAK;oBACtCkB,QAAQO;oBACR,MAAME,QAAQrC,YAAYmC,MAAMnB,QAAQF;oBACxC,MAAMI,SACJmB,UAAUC,YACNhC,cAAc6B,QACdtB,SAAS,UACP0B,OAAOF,SACPpC,gBAAgBoC,OAAOrB;oBAC/Bc,WAAWZ;oBACXP,SAASO;gBACX;;0BAEF,KAACa;gBAAKC,WAAU;gBAAkCQ,eAAY;0BAC3D5B;;;;AAIT"}
@@ -4,6 +4,20 @@ interface QuantityInputBase {
4
4
  min?: number;
5
5
  max?: number;
6
6
  step?: number;
7
+ /**
8
+ * How many decimals a stored unit is: `3` reads `3500` as 3.5. Given, every
9
+ * number in these props is that stored integer and a typed entry is never
10
+ * clamped or rounded — one outside `min`, `max` or `step` is marked invalid
11
+ * and still reported, and text that is no number is reported as `NaN`.
12
+ * `0` is whole units under those same rules.
13
+ */
14
+ scale?: number;
15
+ /** With `scale`: the unit, as the reader names it. */
16
+ unit?: string;
17
+ /** With `scale`: the caller's own refusal, beside the field's. */
18
+ invalid?: boolean;
19
+ /** With `scale`: what describes the field, usually the refusal's message. */
20
+ 'aria-describedby'?: string;
7
21
  disabled?: boolean;
8
22
  id?: string;
9
23
  /**
@@ -34,9 +48,10 @@ export interface UncontrolledQuantityInputProps extends QuantityInputBase {
34
48
  }
35
49
  export type QuantityInputProps = ControlledQuantityInputProps | UncontrolledQuantityInputProps;
36
50
  /**
37
- * A count, on the WAI-ARIA spinbutton pattern: Up and Down step it, Home and
38
- * End jump to its bounds, and what is typed is committed on Enter or on
39
- * leaving the field, clamped to the bounds. The − and + beside it are named
51
+ * A count — or, given a `scale`, a measure: see that prop — on the WAI-ARIA
52
+ * spinbutton pattern: Up and Down step it, Home and End jump to its bounds,
53
+ * and a count typed is committed on Enter or on leaving the field, clamped
54
+ * to the bounds. The − and + beside it are named
40
55
  * "Decrease {label}" and "Increase {label}" and sit at `--target-min`; they are
41
56
  * out of the Tab order, as the pattern has them, because the arrow keys
42
57
  * already do what they do.
@@ -45,6 +60,6 @@ export type QuantityInputProps = ControlledQuantityInputProps | UncontrolledQuan
45
60
  * — the second is how a Server Action form uses it, since a server component
46
61
  * can pass neither a state nor a handler.
47
62
  */
48
- export declare function QuantityInput({ label, value: controlled, defaultValue, onChange, min, max, step, disabled, id, name, className, }: QuantityInputProps): import("react").JSX.Element;
63
+ export declare function QuantityInput(props: QuantityInputProps): import("react").JSX.Element;
49
64
  export {};
50
65
  //# sourceMappingURL=quantity-input.d.ts.map