nexus-shared 3.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +1564 -0
  2. package/README.md +1705 -1123
  3. package/dist/Client.Index.d.ts +14 -0
  4. package/dist/Client.Index.js +14 -0
  5. package/dist/Components/Documents/DocumentFrame.d.ts +50 -0
  6. package/dist/Components/Documents/DocumentFrame.js +83 -0
  7. package/dist/Components/Documents/Menu.d.ts +4 -0
  8. package/dist/Components/Documents/Menu.js +40 -24
  9. package/dist/Components/Documents/PrintDocument.d.ts +95 -0
  10. package/dist/Components/Documents/PrintDocument.js +62 -0
  11. package/dist/Components/Documents/Tabs.d.ts +59 -0
  12. package/dist/Components/Documents/Tabs.js +70 -0
  13. package/dist/Components/Forms/ApiForm.js +19 -2
  14. package/dist/Components/Forms/Crud.d.ts +2 -2
  15. package/dist/Components/Forms/Crud.js +576 -243
  16. package/dist/Components/Forms/CrudActions.d.ts +136 -0
  17. package/dist/Components/Forms/CrudActions.js +184 -0
  18. package/dist/Components/Forms/CrudNarrowPicker.d.ts +31 -0
  19. package/dist/Components/Forms/CrudNarrowPicker.js +180 -0
  20. package/dist/Components/Forms/CrudParts.d.ts +30 -2
  21. package/dist/Components/Forms/CrudParts.js +55 -5
  22. package/dist/Components/Forms/CrudRowForms.d.ts +26 -0
  23. package/dist/Components/Forms/CrudRowForms.js +114 -0
  24. package/dist/Components/Forms/CrudScopes.d.ts +28 -0
  25. package/dist/Components/Forms/CrudScopes.js +76 -0
  26. package/dist/Components/Forms/CrudTree.d.ts +90 -0
  27. package/dist/Components/Forms/CrudTree.js +363 -0
  28. package/dist/Components/Forms/CrudWorkspace.d.ts +63 -0
  29. package/dist/Components/Forms/CrudWorkspace.js +169 -0
  30. package/dist/Components/Forms/ExcelImport.js +3 -3
  31. package/dist/Components/Forms/Form.d.ts +4 -4
  32. package/dist/Components/Forms/Form.js +123 -17
  33. package/dist/Components/Forms/FormLeaveGuard.d.ts +44 -0
  34. package/dist/Components/Forms/FormLeaveGuard.js +65 -0
  35. package/dist/Components/Forms/RecordFlows.d.ts +50 -0
  36. package/dist/Components/Forms/RecordFlows.js +282 -0
  37. package/dist/Components/Forms/SubmitForm.d.ts +37 -2
  38. package/dist/Components/Forms/SubmitForm.js +195 -10
  39. package/dist/Components/Inputs/CheckBox.js +1 -1
  40. package/dist/Components/Inputs/ChoiceField.d.ts +21 -1
  41. package/dist/Components/Inputs/ChoiceField.js +28 -2
  42. package/dist/Components/Inputs/Dropdown.d.ts +13 -0
  43. package/dist/Components/Inputs/Dropdown.js +5 -5
  44. package/dist/Components/Inputs/DropdownParts.d.ts +3 -1
  45. package/dist/Components/Inputs/DropdownParts.js +16 -4
  46. package/dist/Components/Inputs/Field.d.ts +7 -1
  47. package/dist/Components/Inputs/Field.js +2 -2
  48. package/dist/Components/Inputs/GroupForm.d.ts +6 -6
  49. package/dist/Components/Inputs/GroupForm.js +10 -11
  50. package/dist/Components/Inputs/InputRenderer.d.ts +9 -6
  51. package/dist/Components/Inputs/InputRenderer.js +37 -32
  52. package/dist/Components/Inputs/PictureInput.d.ts +41 -0
  53. package/dist/Components/Inputs/PictureInput.js +70 -0
  54. package/dist/Components/Inputs/RadioGroup.d.ts +16 -3
  55. package/dist/Components/Inputs/RadioGroup.js +8 -3
  56. package/dist/Components/Inputs/RowsInput.d.ts +1 -1
  57. package/dist/Components/Inputs/RowsInput.js +18 -3
  58. package/dist/Components/Inputs/TabularForm.d.ts +5 -5
  59. package/dist/Components/Inputs/TabularForm.js +29 -29
  60. package/dist/Components/Inputs/TextArea.d.ts +6 -0
  61. package/dist/Components/Inputs/TextArea.js +11 -2
  62. package/dist/Components/Inputs/TextBoxTypes.d.ts +6 -0
  63. package/dist/Components/Inputs/TextBoxTypes.js +17 -0
  64. package/dist/Components/Inputs/TreeView.d.ts +53 -2
  65. package/dist/Components/Inputs/TreeView.js +147 -13
  66. package/dist/Components/Layouts/MessageBox.d.ts +15 -2
  67. package/dist/Components/Layouts/MessageBox.js +56 -7
  68. package/dist/Components/Layouts/Popup.d.ts +13 -6
  69. package/dist/Components/Layouts/Popup.js +37 -9
  70. package/dist/Components/Layouts/PopupDock.d.ts +3 -1
  71. package/dist/Components/Layouts/PopupDock.js +2 -1
  72. package/dist/Components/Layouts/PopupHost.js +5 -4
  73. package/dist/Components/Viewers/DataTable.js +150 -48
  74. package/dist/Components/Viewers/DataTableFilters.d.ts +1 -1
  75. package/dist/Components/Viewers/DataTableFilters.js +17 -2
  76. package/dist/Components/Viewers/DataTableParts.d.ts +21 -5
  77. package/dist/Components/Viewers/DataTableParts.js +26 -14
  78. package/dist/Components/Viewers/OwnerFiles.d.ts +175 -0
  79. package/dist/Components/Viewers/OwnerFiles.js +589 -0
  80. package/dist/Components/Viewers/QrCodeImage.d.ts +22 -0
  81. package/dist/Components/Viewers/QrCodeImage.js +15 -0
  82. package/dist/Components/Viewers/RecordCards.d.ts +16 -0
  83. package/dist/Components/Viewers/RecordCards.js +509 -0
  84. package/dist/Helpers/BusyHooks.d.ts +6 -0
  85. package/dist/Helpers/BusyHooks.js +39 -0
  86. package/dist/Helpers/CrudBackend.d.ts +20 -2
  87. package/dist/Helpers/CrudBackend.js +46 -2
  88. package/dist/Helpers/CrudColumns.d.ts +53 -6
  89. package/dist/Helpers/CrudColumns.js +98 -7
  90. package/dist/Helpers/CrudDetailsTabs.d.ts +58 -0
  91. package/dist/Helpers/CrudDetailsTabs.js +126 -0
  92. package/dist/Helpers/CrudHelpers.d.ts +81 -2
  93. package/dist/Helpers/CrudHelpers.js +195 -0
  94. package/dist/Helpers/CrudNarrowPick.d.ts +83 -0
  95. package/dist/Helpers/CrudNarrowPick.js +157 -0
  96. package/dist/Helpers/CrudRowForms.d.ts +15 -0
  97. package/dist/Helpers/CrudRowForms.js +43 -0
  98. package/dist/Helpers/CrudScopes.d.ts +32 -0
  99. package/dist/Helpers/CrudScopes.js +79 -0
  100. package/dist/Helpers/DropdownHelpers.d.ts +3 -1
  101. package/dist/Helpers/DropdownHelpers.js +6 -2
  102. package/dist/Helpers/ExcelHelpers.d.ts +1 -1
  103. package/dist/Helpers/ExcelHelpers.js +12 -11
  104. package/dist/Helpers/FileAdapter.d.ts +78 -0
  105. package/dist/Helpers/FileAdapter.js +102 -0
  106. package/dist/Helpers/FilePrimaries.d.ts +48 -0
  107. package/dist/Helpers/FilePrimaries.js +138 -0
  108. package/dist/Helpers/FormConfirm.d.ts +32 -0
  109. package/dist/Helpers/FormConfirm.js +40 -0
  110. package/dist/Helpers/FormStore.d.ts +90 -5
  111. package/dist/Helpers/FormStore.js +318 -22
  112. package/dist/Helpers/InputConditions.d.ts +50 -0
  113. package/dist/Helpers/InputConditions.js +168 -0
  114. package/dist/Helpers/InputMemory.d.ts +106 -0
  115. package/dist/Helpers/InputMemory.js +385 -0
  116. package/dist/Helpers/InputNarrowing.d.ts +18 -0
  117. package/dist/Helpers/InputNarrowing.js +67 -0
  118. package/dist/Helpers/InputParamsHelpers.d.ts +44 -1
  119. package/dist/Helpers/InputParamsHelpers.js +157 -74
  120. package/dist/Helpers/NexusDriveAdapter.d.ts +55 -0
  121. package/dist/Helpers/NexusDriveAdapter.js +207 -0
  122. package/dist/Helpers/NumberHelpers.d.ts +95 -0
  123. package/dist/Helpers/NumberHelpers.js +126 -0
  124. package/dist/Helpers/Permissions.js +2 -1
  125. package/dist/Helpers/QrCode.d.ts +26 -0
  126. package/dist/Helpers/QrCode.js +463 -0
  127. package/dist/Helpers/RecordCards.d.ts +205 -0
  128. package/dist/Helpers/RecordCards.js +378 -0
  129. package/dist/Helpers/RequestCache.d.ts +14 -2
  130. package/dist/Helpers/RequestCache.js +22 -3
  131. package/dist/Helpers/RowsStore.d.ts +37 -2
  132. package/dist/Helpers/RowsStore.js +128 -10
  133. package/dist/Helpers/ServerPreview.d.ts +69 -0
  134. package/dist/Helpers/ServerPreview.js +99 -0
  135. package/dist/Helpers/TableColumns.js +4 -3
  136. package/dist/Helpers/TableExport.d.ts +7 -1
  137. package/dist/Helpers/TableExport.js +9 -3
  138. package/dist/Helpers/TableFilters.d.ts +1 -1
  139. package/dist/Helpers/TableFilters.js +24 -23
  140. package/dist/Helpers/TableHelpers.d.ts +23 -2
  141. package/dist/Helpers/TableHelpers.js +51 -10
  142. package/dist/Helpers/TableJoins.d.ts +13 -0
  143. package/dist/Helpers/TableJoins.js +34 -0
  144. package/dist/Helpers/TableStore.d.ts +21 -1
  145. package/dist/Helpers/TableStore.js +64 -7
  146. package/dist/Helpers/TreeStore.d.ts +81 -0
  147. package/dist/Helpers/TreeStore.js +365 -0
  148. package/dist/Interfaces/CrudInterfaces.d.ts +465 -5
  149. package/dist/Interfaces/FileInterfaces.d.ts +162 -0
  150. package/dist/Interfaces/FileInterfaces.js +4 -0
  151. package/dist/Interfaces/FormInterfaces.d.ts +391 -30
  152. package/dist/Interfaces/FormInterfaces.js +79 -1
  153. package/dist/Interfaces/InputInterfaces.d.ts +15 -3
  154. package/dist/Interfaces/RecordInterfaces.d.ts +367 -0
  155. package/dist/Interfaces/RecordInterfaces.js +1 -0
  156. package/dist/Interfaces/TableInterfaces.d.ts +74 -1
  157. package/dist/Services/ExcelApi.js +5 -0
  158. package/dist/Services/FileApi.d.ts +13 -0
  159. package/dist/Services/FileApi.js +29 -0
  160. package/dist/Services/ImageEditorLoader.d.ts +14 -0
  161. package/dist/Services/ImageEditorLoader.js +51 -0
  162. package/dist/Services/JoinSources.d.ts +37 -5
  163. package/dist/Services/JoinSources.js +90 -14
  164. package/dist/Services/ModuleImport.d.ts +7 -0
  165. package/dist/Services/ModuleImport.js +22 -0
  166. package/dist/Shared.Index.d.ts +16 -0
  167. package/dist/Shared.Index.js +16 -0
  168. package/package.json +7 -2
  169. package/src/Styles/Nexus.Avatar.css +6 -5
  170. package/src/Styles/Nexus.Button.css +10 -4
  171. package/src/Styles/Nexus.Choice.css +16 -0
  172. package/src/Styles/Nexus.Crud.css +383 -9
  173. package/src/Styles/Nexus.Dropdown.css +8 -0
  174. package/src/Styles/Nexus.Files.css +410 -0
  175. package/src/Styles/Nexus.Form.css +5 -2
  176. package/src/Styles/Nexus.Index.css +4 -0
  177. package/src/Styles/Nexus.Input.css +42 -0
  178. package/src/Styles/Nexus.Menu.css +10 -1
  179. package/src/Styles/Nexus.Popup.css +77 -1
  180. package/src/Styles/Nexus.Print.css +288 -0
  181. package/src/Styles/Nexus.QrCode.css +12 -0
  182. package/src/Styles/Nexus.Record.css +430 -0
  183. package/src/Styles/Nexus.Tab.Buttons.css +87 -22
  184. package/src/Styles/Nexus.Table.css +67 -5
  185. package/src/Styles/Nexus.Themes.css +12 -6
  186. package/src/Styles/Nexus.Tokens.css +8 -3
  187. package/src/Styles/Nexus.Tree.css +31 -1
package/README.md CHANGED
@@ -1,1123 +1,1705 @@
1
- # nexus-shared
2
-
3
- Lightweight React components, helpers, and design tokens for Nexus apps. No runtime dependencies besides
4
- React and `nexus-icons`.
5
-
6
- ```
7
- npm install nexus-shared nexus-icons
8
- ```
9
-
10
- ```tsx
11
- // Once, in the root layout
12
- import "nexus-shared/styles.css";
13
-
14
- import { Button } from "nexus-shared";
15
- import { InlineIcon, iconPlus } from "nexus-icons";
16
-
17
- <Button variant="primary" icon={<InlineIcon icon={iconPlus} />}>New booking</Button>
18
- ```
19
-
20
- ## Entry points
21
-
22
- | Import | Contains |
23
- |---|---|
24
- | `nexus-shared` | Components and helpers that work in server and client components |
25
- | `nexus-shared/client` | Client components and browser services |
26
- | `nexus-shared/server` | Server-only code |
27
- | `nexus-shared/styles.css` | Tokens, base styles, and component styles |
28
-
29
- ## Themes
30
-
31
- Seven themes, each with a light and a dark palette that meets WCAG AA contrast:
32
- **Nexus** (default), **GitHub**, **Nord**, **Dracula**, **Solarized**, **Catppuccin**, and **Rosé Pine**.
33
- The mode is Light, Dark, or System (follows the operating system).
34
-
35
- ```tsx
36
- // app/layout.tsx
37
- import "nexus-shared/styles.css";
38
- import { ThemeScript } from "nexus-shared";
39
- import { ThemeSwitcher } from "nexus-shared/client";
40
-
41
- export default function RootLayout({ children }) {
42
- return (
43
- <html lang="en" suppressHydrationWarning>
44
- <head>
45
- <ThemeScript />
46
- </head>
47
- <body>
48
- <header>… <ThemeSwitcher /></header>
49
- {children}
50
- </body>
51
- </html>
52
- );
53
- }
54
- ```
55
-
56
- - `ThemeScript` applies the saved choices before the page paints, so there is no flash of the defaults. Options:
57
- `defaultTheme`, `defaultMode`, `defaultDensity`, `defaultAnimations`, `grid`, `themes`, `nonce`. It sets
58
- attributes on `<html>`, hence `suppressHydrationWarning`.
59
- - `ThemeSwitcher` is a palette button with a popover; `ThemePicker` is the same picker placed in a page. Besides the
60
- mode and the theme it offers **Density** (Compact, Cozy), **Animations** (On, Off, System) and, in a development
61
- build only, the **Scale grid** (Off, px, mm); `showMode`, `showDensity`, `showAnimations`, `showGrid` turn them off.
62
- - `useTheme()` returns `{ theme, mode, resolvedMode, density, animations, motion, grid }` and a setter for each.
63
- - The choices are saved in `localStorage` (`nx-theme`, `nx-mode`, `nx-density`, `nx-animations`, `nx-grid`) and
64
- shared by open tabs.
65
-
66
- Without JavaScript, set the attributes yourself: `<html data-nx-theme="nord" data-nx-mode="dark">`.
67
- Without `data-nx-mode`, the system setting applies. `data-nx-theme` also works on any element, which then
68
- draws in that theme (the picker's previews use this).
69
-
70
- **Density** is `data-nx-density="cozy"` on `<html>`: every control 4px taller (`--nx-control-sm/md/lg` 32/38/44) and
71
- every list row 6px (`--nx-row` 38), so buttons, fields, table rows and headers, menus, dropdown options and the table's
72
- footer follow at once. Compact, the default, is the sizes the package always had.
73
-
74
- **Animations** come from one attribute too. `ThemeScript` works out `data-nx-motion` (`reduce` or `full`) from the
75
- visitor's choice and the system's `prefers-reduced-motion`, and keeps it current when the system setting changes;
76
- every stylesheet reads that attribute, never the media query. So **On** animates on a machine whose operating system
77
- has animations turned off, **Off** never animates, and **System** (the default) does what the system says. Popups fade
78
- in and out, and every popover panel (menus, the table's panels, pickers) fades briefly; nothing waits for a fade.
79
-
80
- **Scroll bars** have one look everywhere, the design lab's: thin and quiet, with a thumb of the text colour at 22% on
81
- no track (`Nexus.Base.css` sets `scrollbar-width` and `scrollbar-color` on every element). On Windows, Chrome and Edge
82
- draw the bar 10px wide and Firefox 8px. Safari has no `scrollbar-color`, so it draws its own thin bar. A component
83
- that needs another look sets the two properties on its own scroller: the time picker's columns hide the thumb until
84
- the pointer or the keys are in them. An app overrides the bar the same way, from outside the layers. With forced
85
- colours on, the system's colours come back.
86
-
87
- ### How it works
88
-
89
- - `Nexus.Themes.css` gives each theme its colors once, as `light-dark(light, dark)`; the page's `color-scheme` picks the side.
90
- - `Nexus.Tokens.css` holds sizes, spacing, and type, and derives hover colors, soft backgrounds, and the focus ring from the palette.
91
- - Components use only `--nx-*` variables, so every component follows the theme with no extra code.
92
- - `npm run check:themes` checks every theme in both modes against WCAG contrast. Run it after changing a color.
93
-
94
- ### Custom themes
95
-
96
- A theme is one CSS block. List it for the script and the picker:
97
-
98
- ```css
99
- [data-nx-theme="brand"] {
100
- --nx-primary: light-dark(#0f766e, #2dd4bf); /* the accent as text and lines */
101
- --nx-primary-solid: light-dark(#0f766e, #0d7a70); /* the accent as a fill behind white text: buttons, checks */
102
- --nx-primary-text: light-dark(#ffffff, #ffffff);
103
- /* …any other --nx-* color: bg, surface, surface-2, surface-hover, border, border-strong,
104
- text, text-muted, text-subtle, danger, danger-solid, danger-text, success, warning, info */
105
- }
106
- ```
107
-
108
- ```tsx
109
- const themes = [...NEXUS_THEMES, { id: "brand", name: "Brand", description: "Our colors" }];
110
- <ThemeScript themes={themes} defaultTheme="brand" />
111
- <ThemeSwitcher themes={themes} />
112
- ```
113
-
114
- All styles sit in `@layer nexus.*`, so an app's own CSS overrides any token or component style without `!important`.
115
-
116
- ### Quick preferences
117
-
118
- Under the theme, the `ThemeSwitcher` panel holds the person's own settings (`PreferencesPicker`, or
119
- `<ThemeSwitcher preferences={false} />` for the theme alone). Each applies at once to everything on the page, is saved
120
- on this device, and reaches other open tabs:
121
-
122
- | Section | Setting | Saved as | Read by |
123
- |---|---|---|---|
124
- | Language and region | Interface language: English, नेपाली | `nx-language` | `useUserPreferences().language` |
125
- | | Calendar: AD, BS | `nx-date-calendar` | every date component (`useDatePreferences`) |
126
- | Dates and times | Date picker language: English, नेपाली | `nx-date-script` | every date component |
127
- | | Clock: 12-hour, 24-hour | `nx-time-format` | every time component |
128
- | | Display date format | `nx-date-format` | every date component |
129
- | Numbers | Number scale (the core's `ENumberScales`): International 1,234,567, South Asian 12,34,567 | `nx-number-scale` | `useNumberLocale()` |
130
- | | Thousands separator: 1,200, 1.200 (decimal comma), 1 200, 1200 | `nx-thousands` | `useNumberLocale()` |
131
- | Tables | Default page size | `nx-page-size` | every `DataTable` and `Crud` |
132
- | | A row click opens the record | `nx-row-click` | every `DataTable` and `Crud` |
133
-
134
- - **Numbers:** `useNumberLocale()` turns the two number settings into a locale (`numberLocale(scale, separator)`):
135
- `en-US` and `en-IN` as they are, any other pair a key such as `"en-IN|.|,"` that `formatNumber`, `parseNumber` and
136
- `getNumberSymbols` read. A `NumberBox`, a `Slider` and a table's number cells without a `locale` of their own use it;
137
- a number box rewrites what it shows when the setting changes, so a typed value is never read in the wrong marks.
138
- - **Tables:** once chosen, the page size and the row click go over what a table names itself (`pageSize`,
139
- `openOnClick`); a page size picked in a table with a `stateKey` still wins there, and a size the table does not offer
140
- is not forced on it. Until chosen (`null`), each table keeps its own.
141
- - **Interface language** is stored and read through `useUserPreferences()`; the package's own words are English for
142
- now, and it does not set `lang` on `<html>` until they are translated (a screen reader would read English in a Nepali
143
- voice).
144
- - `setUserPreferences({ … })` and `readUserPreferences()` (`nexus-shared/client`) change and read them from code, as
145
- `setDatePreferences` does the date settings.
146
-
147
- ## Components
148
-
149
- | Component | Import | Notes |
150
- |---|---|---|
151
- | `Button` | `nexus-shared` | Variants `primary`, `secondary`, `ghost`, `danger`; sizes `sm`, `md`, `lg`; `icon`, `iconEnd`, `loading`, `block`; `hoverTone` |
152
- | `TabButtons` | `nexus-shared/client` | Pick one option; sliding indicator; sizes, `tone="primary"`, `labels="selected"` (icons, label on the selected option), `block`, disabled options; `design="list"` for a vertical list with descriptions and badges; `multiple` to pick several, wrapping onto more rows |
153
- | `SplitButton` | `nexus-shared/client` | A main action with a menu of alternatives; the pick becomes the main button, and `storageKey` remembers it for the next visit |
154
- | `Menu`, `ContextMenu` | `nexus-shared/client` | A dropdown menu under a button, and a right-click menu: icons, shortcuts, descriptions, `tone="danger"`, links, `kind="radio"` or `"checkbox"` |
155
- | `Toaster`, `toast` | `nexus-shared/client` | Toast messages from anywhere: `toast.success(title, message)`, `toast.promise`, `toast.loading`, actions, positions; one `<Toaster />` in the layout |
156
- | `Popup` | `nexus-shared/client` | A modal window on the native dialog, with the buttons of a desktop window: minimize (a bar at the bottom right, content kept), maximize, close; moved by its title bar inside the window; title, description, scrolling body, footer, sizes `xs` to `full`, close reasons |
157
- | `PopupHost`, `openPopup` | `nexus-shared/client` | Popups opened from code with a handle (`close`, `update`, `minimize`, `maximize`, `restore`, `windowState`, `closed`), one per `key` (replaced or restored); one `<PopupHost />` in the layout, which also shows the minimized popups |
158
- | `definePopupRules` | `nexus-shared/client` | Rules for popups by key or `prefix-*` pattern, set once: `reopen` (replace or restore), `minimizable`, `maximizable`, `movable`, how it closes, `size`, `defaultWindowState` |
159
- | `useDraggable`, `makeDraggable`, `startDrag`, `moveWithin`, `clampToBounds` | `nexus-shared/client` | Move any element with the pointer (or the keyboard), kept inside bounds: the window, the parent, an element, or a box; by a handle, along one axis, partly outside; Esc puts it back |
160
- | `messageBox` | `nexus-shared/client` | `alert`, `confirm`, `prompt`, and `show` with any buttons, each returning a promise |
161
- | `TextBox` | `nexus-shared/client` | Text input: label designs `standard`, `outlined`, `inbox`; sizes; icons; `prefix`, `suffix`; `clearable`; show password; `showCount`; validation |
162
- | `TextArea` | `nexus-shared/client` | Multi-line text with the same field features; `autoResize` between `rows` and `maxRows` |
163
- | `CheckBox`, `Switch` | `nexus-shared/client` | One checkbox or on/off switch: `label`, `description`, `required` (must be checked), `indeterminate`, `readOnly`, `labelPosition` |
164
- | `CheckBoxGroup` | `nexus-shared/client` | Many choices from `options`: `min`, `max` (disables the rest at the limit), `selectAll`, `columns`, `design="cards"` |
165
- | `RadioGroup` | `nexus-shared/client` | One choice from `options`: arrow keys, `orientation`, `columns`, `design="cards"` |
166
- | `Dropdown` | `nexus-shared/client` | One value, or several with `multiple`, from `options` or server pages (`loadOptions`: search, infinite scroll, loaders, Retry); rows as `columns` like a data table (avatar, image, icon, code); saved values the list no longer offers (`selectedOptions`, `resolveOptions`, inactive items) show and cannot be picked again |
167
- | `Slider`, `RangeSlider` | `nexus-shared/client` | Pick a number or a range: `min`, `max`, `step`, number format with `prefix`/`suffix`, `marks`, `tooltip`, `minDistance`, `onValueCommit` |
168
- | `NumberBox` | `nexus-shared/client` | Numbers only: `min`, `max`, `decimals`, `fixedDecimals`, `grouping` by `locale`, `prefix`, `suffix`, `stepper`, `clamp`; the same field shell |
169
- | `DatePicker` | `nexus-shared/client` | Type or pick a date in the English (AD) or Nepali (BS) calendar from the user's settings; `min`, `max`, `isDateDisabled`; the value is always a Gregorian ISO date |
170
- | `DateRangePicker` | `nexus-shared/client` | A start and an end in one box, picked in a two-month calendar or typed; `startName` and `endName` send two fields; `minDistance`, `maxDistance` in days; booked nights cannot be included |
171
- | `TimePicker` | `nexus-shared/client` | Type or pick a time on a 12- or 24-hour clock from the user's settings: columns of hours and minutes or `view="list"` slots; `min`, `max` (past midnight too), `step` in seconds, `isTimeDisabled`; the value is always an ISO time |
172
- | `DateTimePicker` | `nexus-shared/client` | Type or pick a day and a time: each user sees their own local time in their date and time settings, and the value is always the UTC moment; `timeZone` for a place's zone, `min`, `max`, `minTime`, `maxTime`, `step`, `isDateDisabled`, `isTimeDisabled` |
173
- | `Calendar` | `nexus-shared/client` | The month grid on its own: single or `mode="range"`, `months={2}` side by side, month and year menus, arrow keys, `renderDay` for event markers, `weekStart` |
174
- | `useDatePreferences`, `setDatePreferences` | `nexus-shared/client` | The user's calendar, format, script, and time format, saved in local storage and followed by every date and time component |
175
- | `Form` | `nexus-shared/client` | A list of input params (`InputParams[]`) on a 12-column grid (`span`), with the values in a store outside React; `onFieldChange` for derived values, `validate` for rules across inputs, `draftKey` for unsaved changes that survive a reload, `loading` (the inputs disabled until the values land) |
176
- | `SubmitForm` | `nexus-shared/client` | A `Form` that checks every value on Save and focuses the first problem, then runs `onSubmit` once at a time; a status line with links to what needs attention; Save, Cancel (asks first), Reset; Ctrl+S |
177
- | `ApiForm` | `nexus-shared/client` | A `SubmitForm` that sends to an API (an endpoint such as `ROOMS.update`, `{ url, method }`, or the app's own client), loads the record first (`loadValue`), and shows the server's messages on their inputs: Nexus responses and ASP.NET Core problem details |
178
- | `FormButtons` | `nexus-shared/client` | A form's status line and buttons on their own, such as in a popup's footer |
179
- | `useForm`, `useFormValue`, `useFormValues`, `useFormStatus` | `nexus-shared/client` | A store for the page to hold, and hooks that render again when a value, any value, or the status changes |
180
- | `FormStore` | `nexus-shared` | The store and the form's handle: `getValue`, `getChanges`, `set`, `load` (with `keepChanged`), `reset`, `validate`, `setErrors`, `focus`, `submit` |
181
- | `DataTable`, `useTable` | `nexus-shared/client` | Rows with a search (rows per page inside it), sorting by column, pages, a selection with one split button of actions over the headings, icon buttons and a menu per row, columns the user orders, resizes, pins, and hides, a band of headings over the columns that belong together (`group`), an options menu (filters from `filterInputs`, CSV, print, import), and loading, empty, and failed states; rows given, loaded once, or a page per query from a server; page size, sort, and the columns remembered with `stateKey` |
182
- | `TableStore` | `nexus-shared` | The table's state and handle, outside React: `reload`, `upsert`, `patch`, `remove`, `select`, `getSelected`, `setSearch`, `setFilters`, `setSort`, `setPage` |
183
- | `Crud` | `nexus-shared/client` | A module's records in one component: a controller's endpoints, the table's columns, and the form's input params in; the lists (all, flagged, trash, deleted) and actions the user may use, the records the user pinned above the list, Add and Edit popups on `ApiForm`, details, actions on one record or many, and a cache of lists while the page is open |
184
- | `Permissions`, `NexusPermissions`, `definePermissions`, `canCall` | `nexus-shared` | May the user call this endpoint? The app registers its rules once; `NexusPermissions` reads the Nexus backend's access actions. Everything is allowed until then |
185
- | `CrudBackend`, `NexusCrudBackend`, `defineCrudBackend` | `nexus-shared` | How a CRUD talks to a backend beyond its endpoints: page requests and answers, mass action bodies, flag and pin marks. Nexus's by default |
186
- | `configureCrud`, `getCrudSettings` | `nexus-shared` | What every CRUD in the app follows: how many records a user may pin (100 by default) |
187
- | `queryRows`, `filterRequest`, `formatCellText`, `sortRows`, `pageButtons`, `CrudCache`, `crudRowActions` | `nexus-shared` | Pure helpers behind the table and the CRUD: search, filter, sort, and page rows as the table does, the filters in a server's names, a value as its cell writes it, the page buttons, the cache, and which actions a list offers |
188
- | `readApiResponse`, `readErrorMessages`, `sendApiRequest`, `matchFieldErrors`, `matchInputName`, `formErrorsFromResult` | `nexus-shared` | Pure helpers behind the API form: read an answer as success or failure, every problem it carries as one list, send a URL as it is, match server field names to inputs, and turn a failed answer into what a form shows |
189
- | `api`, `apiOptionsLoader`, `configureApi` | `nexus-shared/client` | API calls from the browser, through the app's proxy or straight to a module: toasts worded by the message builder, `api.confirm` to ask first, one request for the same GET at once; a dropdown's `loadOptions` from a pagination endpoint |
190
- | `serverApi`, `configureServerApi`, `createApiProxy` | `nexus-shared/server` | API calls from the server, straight to each module's root, with the user's token and Next.js caching; the proxy route the browser calls |
191
- | `ApiModules`, `NexusApiModules`, `defineApiModules`, `ApiRegister` | `nexus-shared` | An app's API modules: its own module enum (named once in `ApiRegister`, so endpoints take only those), where each root is, and the proxy on or off. Extend `ApiModules` for another backend |
192
- | `apiController`, `apiEndpoint`, `unwrapApiResult` | `nexus-shared` | Endpoints defined once by module: a controller's standard actions (`NormalListing`, `Detail/{id}`, `Create`, `Update`, `Delete/{id}`, each list's `lists.trash` and `pages.trash`, …); an answer's result, or an `ApiError` |
193
- | `messages`, `buildMessage`, `configureMessages` | `nexus-shared` | Every success, failure, reason, loading, question, and button text from one table: "3 rooms deleted.", "You do not have permission to delete Room 204."; reworded all at once |
194
- | `createApiClient` | `nexus-shared` | The engine behind `api` and `serverApi`, for an API of another shape |
195
- | `Field` | `nexus-shared` | The frame of every input (label, box, icons, hint or error), for building custom inputs |
196
- | `validateText`, `TEXT_PATTERNS` | `nexus-shared` | Pure text validation and common patterns with their messages |
197
- | `validateCheck`, `validateSelection` | `nexus-shared` | Pure checks for a checkbox and for chosen values (`required`, `min`, `max`) |
198
- | `validateNumber`, `formatNumber`, `parseNumber` | `nexus-shared` | Pure number validation, and number text in any locale (`roundDecimal`, `stepNumber` too) |
199
- | `formatDate`, `parseDateText`, `toIsoDate`, `validateDate` | `nexus-shared` | Pure date helpers: ISO dates in and out, either calendar, any format, Devanagari digits; `toCalendar` and `fromCalendar` convert AD and BS |
200
- | `formatDateRange`, `parseDateRangeText`, `toDateRange`, `validateDateRange` | `nexus-shared` | The same for a range: "2026-09-17 – 2026-09-24" in and out, typed with a dash, an arrow, or "to"; rules on both ends and on the days between |
201
- | `filterItems`, `matchesSearch`, `indexItems`, `optionKey`, `initials` | `nexus-shared` | Pure helpers behind the dropdown: search every word with or without accents, index items by value, compare ids from APIs and forms, and initials for avatars |
202
- | `formatTime`, `parseTimeText`, `toIsoTime`, `validateTime` | `nexus-shared` | Pure time helpers: ISO times in and out, 12- or 24-hour formats, Devanagari digits, typed text on either clock; `addMinutes`, `isTimeInRange`, `listTimeSlots` |
203
- | `toUtcDateTime`, `toLocalDateTime`, `fromLocalDateTime`, `formatDateTime`, `parseDateTimeText`, `validateDateTime` | `nexus-shared` | Pure date-time helpers: UTC values in and out, the date and time a moment shows in any IANA zone (daylight saving included), typed text in both calendars; `describeTimeZone`, `getBrowserTimeZone` |
204
- | `ThemeScript` | `nexus-shared` | Applies the saved theme, mode, density and animations (and the scale grid in development) before paint; goes in `<head>` |
205
- | `ThemeSwitcher` | `nexus-shared/client` | Palette button with the theme picker in a popover: mode, theme, density, animations, and the scale grid in development |
206
- | `ThemePicker` | `nexus-shared/client` | Mode control and theme cards with live previews |
207
-
208
- ### Tab buttons
209
-
210
- ```tsx
211
- import { TabButtons } from "nexus-shared/client";
212
-
213
- <TabButtons
214
- aria-label="View"
215
- value={view}
216
- onChange={setView}
217
- options={[
218
- { value: "grid", label: "Grid", icon: <InlineIcon icon={iconLayoutGrid} /> },
219
- { value: "list", label: "List", icon: <InlineIcon icon={iconList} /> },
220
- ]}
221
- />
222
- ```
223
-
224
- - An indicator slides to the selected option. In light mode the track is a soft tint with no frame and the indicator
225
- is lifted by a shadow; in dark mode the indicator is lighter than the track, with a visible edge. The selected icon
226
- takes the primary color, so the choice is clear in every theme.
227
- - `size` (`sm`, `md`, `lg`), `tone="primary"` for a solid primary indicator, `block` to fill the width, `disabled` per option.
228
- - `labels="selected"`: icons only, and the selected option grows to show its label. Every option needs an icon;
229
- hidden labels are still read by screen readers and shown as tooltips.
230
- - `design="list"`: the options stacked as full-width rows, for settings pages and side panels. Each row takes an
231
- `icon`, a `description` on a second line, and a `badge` (a count) at the end. The selected row is tinted, marked
232
- by a bar at its start, and its label turns bold; `tone="primary"` tints it with the primary color. ↑ and ↓ move
233
- the selection. The nav design is the old project's `nav-tabs`, this one its `list-tabs`.
234
- - `multiple`: several at once. `value` is an array and `onChange` hands back the chosen values in option order.
235
- Each chosen option is raised as the one choice's indicator is, the options wrap onto more rows when they do not
236
- fit (never narrower than tall, so single letters line up), and on a touch screen each grows to a medium control's
237
- height. They are checkboxes: Tab moves between them and Space toggles one.
238
- - Native radio buttons: arrow keys move the selection, and `name` makes it part of a form. Needs `aria-label` or `aria-labelledby`.
239
- `form` sets the form the choice belongs to, as in HTML; an id that matches no form keeps a switch that is not a
240
- value (the Markdown editor's views) out of the form around it.
241
- - For choosing a value. For switching page panels, use tabs with panels (planned).
242
-
243
- ### Split button
244
-
245
- ```tsx
246
- import { SplitButton } from "nexus-shared/client";
247
-
248
- <SplitButton storageKey="pull-request" onAction={value => create(value)} options={[
249
- { value: "create", label: "Create pull request", description: "Open a pull request that is ready for review" },
250
- { value: "draft", label: "Create draft pull request", description: "Cannot be merged until marked ready for review" },
251
- ]} />
252
- ```
253
-
254
- - The main button runs the chosen action; the arrow opens the alternatives as a radio menu. Picking one makes it the
255
- main button, and with `storageKey` the browser remembers it (`localStorage`, `nx-split:<key>`), so the next visit
256
- starts with it. `runOnSelect` also runs the pick at once, for Save / Save and close.
257
- - `variant`, `size`, `loading`, `disabled`, `block` as `Button`; `type="submit"` with `name` submits a form and sends
258
- the chosen value; `value` and `onValueChange` for a controlled choice; `align` and `menuLabel` for the menu.
259
-
260
- ### Menus
261
-
262
- ```tsx
263
- import { ContextMenu, Menu } from "nexus-shared/client";
264
-
265
- <Menu items={[
266
- { value: "edit", label: "Edit", icon: <InlineIcon icon={iconPencil} />, shortcut: "Ctrl+E" },
267
- { separator: true },
268
- { value: "delete", label: "Delete", icon: <InlineIcon icon={iconTrash} />, tone: "danger" },
269
- ]} onSelect={value => run(value)}>
270
- <Button iconEnd={<InlineIcon icon={iconChevronDown} />}>Actions</Button>
271
- </Menu>
272
-
273
- <ContextMenu items={rowItems} onSelect={value => run(value, row)}>
274
- <table>…</table>
275
- </ContextMenu>
276
- ```
277
-
278
- - **Native popovers.** The list is a `[popover]` element: it sits above everything, closes with Esc or a click
279
- outside, and needs no library. It opens under its button (above it when there is no room), lined up with the
280
- button's `align="start"` or `"end"` edge, and follows the page as it scrolls.
281
- - **Items are params:** `{ value, label, description?, icon?, shortcut?, tone?: "danger", disabled?, href?, target?, checked?, title? }`,
282
- plus `{ separator: true }` and `{ heading }`. An item with `href` is a link. The trigger is any element that
283
- renders a button and passes its props on, such as `Button`.
284
- - `kind="radio"` or `"checkbox"` adds a check column and `aria-checked`; `closeOnSelect={false}` keeps a checkbox
285
- menu open while options are toggled.
286
- - **Keys:** arrows move between items (wrapping, skipping disabled ones), Home and End jump, a letter jumps to the
287
- next item starting with it, Enter or Space chooses, Esc closes and returns focus to the button, Tab closes and
288
- moves on. Focus follows a moving pointer, so the keys carry on from the hovered item.
289
- - `ContextMenu` opens at the pointer on right-click, or under the focused element on Shift+F10. Its wrapper takes no
290
- space (`display: contents`), so wrap a table once and note the clicked row in the row's own `onContextMenu`.
291
- - A menu opens below its button, or above it when it fits only there, or on the side with more room when it fits on
292
- neither, and is never taller than that room: its items scroll inside it, the scroll bar against the panel's right
293
- wall. It opens scrolled to the top, and a hovered item never scrolls the list.
294
- - `placeUnderAnchor`, `placeAtPoint`, and `followAnchor` (`nexus-shared/client`) place custom popovers the same way, and
295
- `showPanel` opens one with its scroller at the top. A panel (`.nx-popover`) that marks its scrolling part
296
- `.nx-popover__scroll` is capped to the room it was placed in and gets the scroll bar on its wall; set its padding with
297
- `--nx-popover-pad`. `usePopoverPanel` is a panel a menu item opens under a button, as the table's Filters and Columns
298
- open.
299
-
300
- ### Toast messages
301
-
302
- ```tsx
303
- import { Toaster, toast } from "nexus-shared/client";
304
-
305
- // Once, in the root layout
306
- <Toaster position="top-right" />
307
-
308
- // Anywhere: components, services, fetch helpers
309
- toast.success("Booking confirmed", "Room 204, 3 nights");
310
- toast.error("Could not save", { message: error.message, action: { label: "Retry", onClick: save } });
311
- toast.promise(saveBooking(), { loading: "Saving…", success: "Saved", error: e => `Not saved: ${e.message}` });
312
- ```
313
-
314
- - `toast(title, options?)`, `toast.info`, `.success`, `.warning`, `.error`, `.loading` (spinner, no timer), and
315
- `.promise`. Options: `message`, `duration` (default 5000 ms, 0 keeps it; pauses while hovered or focused), `action`,
316
- `closable`, `icon`, `position`, `onClose`, and `id` to update a toast in place. `toast.dismiss(id?)` closes one or all.
317
- - Each toast is a native popover of its own, so it sits above open dialogs; the newest is nearest the edge, and at
318
- most `max` (default 5) show per position. Warnings and errors use `role="alert"`, the rest `role="status"`.
319
-
320
- ### Popup
321
-
322
- ```tsx
323
- import { Popup, definePopupRules, openPopup } from "nexus-shared/client";
324
-
325
- <Popup open={open} onClose={() => setOpen(false)} title="Edit booking" description="NX-2048 · Room 204"
326
- footer={<><Button onClick={() => setOpen(false)}>Cancel</Button><Button type="submit" form="booking" variant="primary">Save</Button></>}>
327
- <form id="booking" onSubmit={save}>…</form>
328
- </Popup>
329
-
330
- // From code, with a handle; needs <PopupHost /> in the layout. Never two popups with one key: opening the key again
331
- // replaces its popup (a fresh one), or with reopen: "restore" brings it back as it was.
332
- const popup = openPopup({ key: "room-edit-204", reopen: "restore", title: "Room 204", content: <RoomDetails id={204} />, footer: p => <Button onClick={() => p.close()}>Close</Button> });
333
- popup.minimize(); popup.restore(); popup.maximize();
334
- await popup.closed;
335
-
336
- // Rules by key, once, in a client module; options given to openPopup win over them
337
- definePopupRules({
338
- "room-new": { reopen: "replace" }, // Add: a fresh form every time (the default)
339
- "room-edit-*": { reopen: "restore" }, // Edit: back as it was, with what was typed
340
- "night-report": { minimizable: false, maximizable: false, movable: false },
341
- });
342
-
343
- // The page in charge of the window state
344
- <Popup open={open} windowState={state} onWindowStateChange={setState} … />
345
- ```
346
-
347
- - Built on the native `<dialog>` shown modally: above everything, the page behind dimmed and locked (without a layout
348
- shift), Tab kept inside, focus returned on close. `onClose(reason)` says whether the close button, Esc, the
349
- backdrop, or code asked; the page decides by setting `open`. `closable`, `closeOnEscape`, `closeOnBackdrop` turn
350
- those off for a popup that must be answered.
351
- - `size`: `xs` 360, `sm` 440, `md` 560, `lg` 720, `xl` 960, `full`. The body scrolls while the title and footer
352
- stay; `flush` removes the body padding for tables. `initialFocus` picks the first focused element (default: the
353
- first control in the body or footer). The content mounts only while open, so forms start fresh.
354
- - Popups open other popups and message boxes above themselves; Esc closes the top one.
355
- - A **title bar** like a desktop window's: 32px high (40px on touch screens), the icon, the title, and the description
356
- on one line (cut with …), and the window buttons filling its top right corner, 46 x 32 each: **minimize**,
357
- **maximize** (restore down when maximized), **close** (red on hover). `variant="dialog"` gives the larger heading
358
- instead (the icon in a circle, the description under the title), which message boxes use. `minimizable` (default: when `closable`, so a popup that must be answered cannot be put aside),
359
- `maximizable` and `movable` (default true); message boxes have only close.
360
- - **Minimized**, the dialog closes so the page can be used, and a bar waits at the bottom right with the popup's icon and
361
- title; its content stays mounted, so typed text, scroll, and the focused field are there when the bar brings it back
362
- (maximized again if it was). Several stack behind the newest with a count that opens the whole list (Esc or a press
363
- elsewhere closes it). An open popup's backdrop covers the dock. `<PopupHost />` renders the dock; without a host
364
- there is no minimize button. Bottom-right toasts stack above it (`--nx-dock-space`).
365
- - **Maximized**, it fills the window edge to edge; a double-click on the title bar does the same, and restore down puts
366
- it back where it was.
367
- - **Moved** by its title bar (not its buttons), kept inside the window, pulled back in when the window shrinks; Esc
368
- during a drag puts it back; dragging a maximized popup restores it under the pointer, as desktop windows do. Each
369
- opening starts centered in `defaultWindowState`.
370
- - **Opened again** while it is still open or minimized, a popup never doubles up. `openPopup` with a `key` whose popup
371
- is there closes that popup (`onClose` and `closed` say `replaced`) and opens a fresh one: `reopen: "replace"`, the
372
- default, right for an Add form, so Add, minimize, Add again cannot pile up popups. `reopen: "restore"` brings the
373
- old one back as it was and returns its handle, right for editing one record. A page popup opens again through the
374
- button that opened it, with the same `reopen` choice. Popups without a key are separate every time.
375
- - **Asking before a close**: `openPopup({ beforeClose })` runs when the user closes the popup (its close button, Esc,
376
- the backdrop, or its bar on the dock); return `false`, or a promise of it, to keep it open, such as after
377
- `confirmDiscard(form)` asked "Discard your changes?". Closing from code does not ask.
378
- - **Rules by key**: `definePopupRules({ "booking-new": {…}, "booking-edit-*": {…} })` sets `reopen`, `minimizable`,
379
- `maximizable`, `movable`, `closable`, `closeOnEscape`, `closeOnBackdrop`, `size`, and `defaultWindowState` for every
380
- `openPopup` with that key. A name ending in `*` matches keys that start with the rest (`*` alone, every key); all
381
- matching rules apply, an exact key over a pattern and a longer pattern over a shorter one; options given to
382
- `openPopup` win. It returns a function that removes the rules; `popupRuleFor(key)` shows what a key gets.
383
- - With motion, minimize flies to the dock and maximize grows from the old box; with reduced motion, both happen in the
384
- same frame.
385
-
386
- ### Drag helpers
387
-
388
- ```tsx
389
- import { clampToBounds, makeDraggable, moveWithin, useDraggable, viewportBounds } from "nexus-shared/client";
390
-
391
- useDraggable(cardRef, { bounds: "parent" }); // the card moves, kept inside its positioned parent
392
- useDraggable(barRef, { target: () => cardRef.current, bounds: "parent", axis: "x", keepVisible: 40 });
393
- const stop = makeDraggable(titleBar, { target: panel, bounds: document.querySelector(".board") }); // without React
394
- moveWithin(card, { x: 10, y: 0 }, { bounds: "parent" }); // the keyboard way
395
- clampToBounds({ left: -20, top: 40, width: 300, height: 200 }, viewportBounds()); // { x: 0, y: 40 }
396
- ```
397
-
398
- - The popup's title bar is built on these; any component can use them. `bounds`: `viewport` (default), `parent`,
399
- an element (inside its borders), a box, a function, or `null`. `margin`, `keepVisible` (how much must stay
400
- inside when it may partly leave), `axis`, `threshold` (default 3 px, so clicks stay clicks), `cancel` (controls in
401
- the handle that do not drag).
402
- - The position is an offset from the element's place in the layout, written to CSS `translate` by default, or to CSS
403
- variables (`cssVariablePosition`), or anywhere through `position: { get, set }`, so a move never shifts the layout.
404
- - `onStart` may cancel or change the target first; `onEnd` says whether Esc cancelled. A drag selects no text, and
405
- the click that ends it does not reach what lies under the pointer. The handle needs `touch-action: none`
406
- (`makeDraggable` and `useDraggable` set it).
407
-
408
- ### Message box
409
-
410
- ```tsx
411
- import { messageBox } from "nexus-shared/client";
412
-
413
- if (await messageBox.confirm({ title: "Delete booking NX-2048?", message: "This cannot be undone.", tone: "danger", confirmLabel: "Delete" })) …
414
- await messageBox.alert({ title: "Saved", tone: "success" });
415
- const name = await messageBox.prompt({ title: "Rename the room", label: "Name", defaultValue: room.name });
416
- const choice = await messageBox.show({ title: "Unsaved changes", tone: "warning", buttons: [{ value: "discard", label: "Don't save" }, { value: "save", label: "Save" }] });
417
- ```
418
-
419
- - Small popups through `<PopupHost />`, the tone in the icon: `info` (alert default), `question` (confirm default),
420
- `success`, `warning`, `danger`, or `neutral` for none. A danger box makes the last button red and focuses the first
421
- one, so Enter cannot delete by accident.
422
- - `confirm` resolves `false` and `show` resolves `null` when the box is dismissed with Esc, the close button, or a
423
- click outside; `prompt` resolves `null` when cancelled and refuses an empty answer while `required` (the default).
424
-
425
- ### Button hover tones
426
-
427
- `hoverTone` keeps a `secondary` or `ghost` button neutral until it is hovered or focused from the keyboard, then
428
- colors its border, a light background, and its text. Tones: `primary`, `danger`, `success`, `warning`, `info`.
429
- Good for rows of actions, where full-color buttons would be too loud:
430
-
431
- ```tsx
432
- <Button hoverTone="danger" icon={<InlineIcon icon={iconTrash} />}>Delete</Button>
433
- <Button variant="ghost" size="sm" hoverTone="primary" aria-label="Edit" icon={<InlineIcon icon={iconPencil} />} />
434
- ```
435
-
436
- Every tone meets WCAG AA contrast on its light background in all themes.
437
-
438
- ### Text box
439
-
440
- ```tsx
441
- import { TEXT_PATTERNS } from "nexus-shared";
442
- import { TextBox, TextArea } from "nexus-shared/client";
443
-
444
- <form onSubmit={save}>
445
- <TextBox name="email" type="email" label="Email" required pattern={TEXT_PATTERNS.email} icon={<InlineIcon icon={iconMail} />} />
446
- <TextBox name="password" type="password" label="Password" required minLength={8} />
447
- <TextArea name="notes" label="Notes" maxLength={500} showCount autoResize />
448
- <Button type="submit" variant="primary">Save</Button>
449
- </form>
450
- ```
451
-
452
- - **Uncontrolled by default**, so typing re-renders nothing. `onValueChange(value)` reports each change; `value` makes it controlled.
453
- - **Validation:** `required`, `minLength`, `maxLength`, `pattern` (a `TEXT_PATTERNS` entry carries its own message), and
454
- `validate(value)` for custom rules. Messages show after a field is left with text in it (`validateOn`: `blur`, `change`,
455
- `submit`). Inside a `<form>`, an invalid field blocks submit, every message shows, and the first invalid field takes focus.
456
- `error` shows a message from outside, such as the server.
457
- - **Read-only says why.** Every input with `readOnly` shows a lock, and a short note for 2.5 seconds when someone tries
458
- to change it anyway, so a click that does nothing does not look like a bug. The value is still sent with a form, and
459
- selecting and copying text work as usual. Esc, leaving the field, or the timeout hide the note; `readOnlyMessage`
460
- changes its text.
461
-
462
- | Input | Lock | Tries that show the note | Default note |
463
- |---|---|---|---|
464
- | `TextBox`, `TextArea` | End of the box | A click, typing, Backspace, Delete, Ctrl+V, Ctrl+X (and Enter in a text area) | Read-only: this field cannot be changed. |
465
- | `NumberBox` | In place of the − and + buttons | The same, and ↑ ↓ Page Up Page Down | Read-only: this number cannot be changed. |
466
- | `DatePicker`, `DateRangePicker` | In place of the calendar button | The same as a text box, and ↓ | Read-only: this date (these dates) cannot be changed. |
467
- | `TimePicker` | In place of the clock button | The same as a text box, and ↓ | Read-only: this time cannot be changed. |
468
- | `DateTimePicker` | In place of the calendar and clock button | The same as a text box, and ↓ | Read-only: this date and time cannot be changed. |
469
- | `Dropdown` | In place of the list button; chips lose their remove buttons | A click on the box or a chip, a typed key, ↓ or ↑ | Read-only: this choice (these choices) cannot be changed. |
470
- | `CheckBox`, `Switch` | After the label | A click or Space | Read-only: this option (this setting) cannot be changed. |
471
- | `CheckBoxGroup`, `RadioGroup` | After the group label | A click, Space, or an arrow key, under that option | Read-only: these options (this choice) cannot be changed. |
472
- | `Slider`, `RangeSlider` | After the label | A press on the track or a mark, the arrow keys, Page Up/Down, Home, End | Read-only: this value (this range) cannot be changed. |
473
-
474
- Nothing renders until an attempt, and an attempt re-renders only the note, so read-only forms of any size cost
475
- nothing extra. `useReadOnlyNotice` gives a custom control the same lock and note.
476
- - **Props are params:** plain, named like HTML attributes, and serializable, so forms and CRUD pages can describe
477
- fields as objects. Design notes for inputs, forms, and CRUD: [src/Components/Inputs/README.md](src/Components/Inputs/README.md).
478
-
479
- ### Number box
480
-
481
- ```tsx
482
- import { NumberBox } from "nexus-shared/client";
483
-
484
- <NumberBox name="nights" label="Nights" stepper="split" required min={1} max={30} defaultValue={1} />
485
- <NumberBox name="rate" label="Rate per night" prefix="Rs" required min={500} decimals={2} fixedDecimals grouping locale="en-IN" />
486
- <NumberBox name="discount" label="Discount" suffix="%" stepper min={0} max={50} step={5} />
487
- ```
488
-
489
- - **Only a number gets in.** Typing accepts digits, one decimal separator, and a minus sign when `min` is below 0 (or
490
- not set). `decimals` stops typing after that many decimals; pasted text such as "Rs 1,250.50" keeps its number, and
491
- text with no single clear number is ignored rather than guessed at.
492
- - **Formats by locale:** `grouping` shows 12,50,000.00 (`en-IN`) or 1.250.000,00 (`de-DE`) while the box is not
493
- being edited; separators come off on focus. Without a `locale`, the box follows the person's Number scale and
494
- Thousands separator (`useNumberLocale`, see Quick preferences), which is `en-US` until they choose, so the server
495
- renders that and the browser takes the saved choice right after hydration.
496
- Inside a `<form>`, a grouped box sends the plain number through a hidden input with its `name`.
497
- - **Steps:** ↑ and ↓ (Shift or Page Up/Down for ten), and `stepper` buttons that repeat while held. Values move along
498
- the grid of `step` from `min` and stay within the limits.
499
- - **Values:** `onValueChange(value)` gets a `number`, or `null` when empty; `validate(value)` too. `clamp` moves an
500
- out-of-range value to the nearest limit on blur instead of showing a message.
501
- - `npm run test:numbers` checks the number helpers (formatting, parsing, paste, rounding, stepping, messages).
502
-
503
- ### Checkbox and radio
504
-
505
- ```tsx
506
- import { CheckBox, CheckBoxGroup, RadioGroup, Switch } from "nexus-shared/client";
507
-
508
- <RadioGroup name="roomType" label="Room type" required design="cards" columns={3} options={roomTypes} />
509
- <CheckBoxGroup name="amenityIds" label="Amenities" columns={3} selectAll options={amenities.map(a => ({ value: a.id, label: a.name }))} />
510
- <Switch name="breakfast" label="Breakfast included" labelPosition="start" />
511
- <CheckBox name="terms" label="I accept the booking terms" required />
512
- ```
513
-
514
- - **Native inputs, drawn with CSS.** Each option is one `<input>`, so forms, arrow keys (radios), and screen readers
515
- work as usual. Box edges use the subtle text color, which meets 3:1 contrast on panels in every theme.
516
- - **Options are params:** `{ value, label, description?, icon?, disabled? }`. Values can be strings or numbers and
517
- come back from `onValueChange` with their type.
518
- - **Limits:** `required`, `min`, `max`, `validate`. At `max` a checkbox group disables the other options and shows a
519
- count. Messages follow the text box: after leaving a changed group, or on submit, where the first invalid option takes focus.
520
- - **Fast:** uncontrolled by default, so clicking re-renders nothing; 10,000 checkboxes mount in 0.5 to 0.7 s
521
- in the development build.
522
-
523
- ### Slider
524
-
525
- ```tsx
526
- import { RangeSlider, Slider } from "nexus-shared/client";
527
-
528
- <Slider name="discount" label="Discount" max={50} suffix="%" defaultValue={10} />
529
- <RangeSlider name="price" label="Price per night" min={1000} max={30000} step={500} minDistance={1000}
530
- prefix="Rs " grouping locale="en-IN" onValueCommit={([from, to]) => loadRooms(from, to)} />
531
- ```
532
-
533
- - **Native range inputs** under a drawn track, so arrow keys, Page Up/Down, Home/End, touch, and screen readers work.
534
- Each thumb announces its formatted value (`aria-valuetext`).
535
- - **Values read like a number box:** `prefix`, `suffix`, `decimals`, `grouping`, `locale`, or a `format` function.
536
- - **`onValueChange`** follows every step; **`onValueCommit`** fires once when a thumb is released or a key step ends,
537
- the moment to call an API from a filter.
538
- - **Range:** two thumbs that never cross and keep `minDistance` apart; a click on the track moves the nearer thumb.
539
- A form receives two values under the name.
540
- - **Marks** label points under the track and move the thumb when clicked; **`tooltip`** shows the value above the thumb.
541
- - Dragging writes the fill and the text straight to the DOM, so nothing re-renders.
542
-
543
- ### Date picker and date range picker
544
-
545
- ```tsx
546
- import { todayIsoDate } from "nexus-shared";
547
- import { Calendar, DatePicker, DateRangePicker, setDatePreferences } from "nexus-shared/client";
548
-
549
- <DatePicker name="checkIn" label="Check-in" required min={todayIsoDate()} onValueChange={iso => …} />
550
- <DatePicker name="fiscalYearStart" label="Fiscal year start" calendar="bs" format="YYYY/MM/DD" />
551
- <DateRangePicker startName="checkIn" endName="checkOut" label="Stay" required min={todayIsoDate()} minDistance={1} maxDistance={30} />
552
- <Calendar mode="range" months={2} range={range} onRangeChange={setRange} min={todayIsoDate()} />
553
-
554
- // A settings page
555
- setDatePreferences({ calendar: "bs", format: "D MMMM YYYY", script: "devanagari" });
556
- ```
557
-
558
- - **The value is a day, not a time.** An ISO date `"2026-09-17"` in the Gregorian calendar, whatever calendar is
559
- shown: what a form sends (through a hidden input with the field's `name`), what an API stores (`DateOnly`), and
560
- what means the same day in every time zone. `toIsoDate` reads a `Date` in local time and an ISO date-time with a
561
- zone as the local day of that instant; `isoDateToDate(iso)` gives UTC midnight, `isoDateToDate(iso, "local")` local midnight.
562
- - **English or Nepali from the user's settings.** `useDatePreferences` reads `nx-date-calendar` (`ad` or `bs`),
563
- `nx-date-format`, and `nx-date-script` (`latin` or `devanagari`) from local storage, with the English calendar in
564
- `YYYY-MM-DD` as the default; `setDatePreferences` changes every date component on the page, and other tabs follow.
565
- A box can fix its own `calendar`, `format`, or `script`.
566
- - **Formats** use the tokens `YYYY` `YY` `MMMM` `MMM` `MM` `M` `DD` `D` `dddd` `ddd`. Typing follows the format's
567
- order and is lenient: `17/9/2026`, `Sep 17, 2026`, `1 asoj 2083`, `२०८३-०६-०१`; a four-digit number is the year wherever it stands.
568
- - **Bikram Sambat** covers BS 1975 to 2100 (AD 1918 to 2044), as the majority of five published tables
569
- (`NepaliCalendar.ts`), converted through day numbers with no `Date` objects. `npm run test:dates` checks known
570
- dates and round-trips every day.
571
- - **DateRangePicker** holds a start and an end in one box, written as "2026-09-17 – 2026-09-24" in the user's
572
- format. Pick the start and then the end in a calendar of two months (one when the window is narrow), with the
573
- days between lit as the pointer moves, or type both dates around a dash, an arrow, or "to". The values are two
574
- ISO dates: `onValueChange` gives `[start, end]` (`null` for an end not chosen yet), and a form sends `startName`
575
- and `endName` as two fields, or both under `name`. Rules: `required`, `min`, `max`, `minDistance` and
576
- `maxDistance` (days from start to end, the nights of a stay), and `isDateDisabled`, which also refuses a range
577
- that includes such a day (a booked night). `validateDateRange` is the pure check behind it.
578
- - **Read-only** boxes have no calendar: a lock sits where the calendar button was, and a click, a typed key, or ↓
579
- shows a note under the box, as in every read-only input (see [Text box](#text-box)).
580
- - **Calendar** is the pickers' panel and a component of its own: month and year menus, arrow keys (Page Up and Page
581
- Down for months, with Shift for years), `min`, `max`, `isDateDisabled`, `weekStart`, `weekendDays` (Saturday is
582
- red in the Nepali calendar), `mode="range"` with a live preview, `months={2}` side by side (a page passes 1 on
583
- a phone; the calendar does not measure), `month` and `onMonthChange` to load a month's events, and `renderDay`
584
- to draw markers in a cell.
585
-
586
- ### Time picker
587
-
588
- ```tsx
589
- import { TimePicker, setDatePreferences } from "nexus-shared/client";
590
-
591
- <TimePicker name="arrival" label="Arrival" required min="14:00" max="22:00" step={1800} view="list" onValueChange={iso => …} />
592
- <TimePicker name="shiftStart" label="Shift start" min="22:00" max="06:00" format="HH:mm" />
593
- <TimePicker name="spa" label="Spa slot" view="list" step={1800} isTimeDisabled={iso => booked.has(iso)} />
594
-
595
- // A settings page
596
- setDatePreferences({ timeFormat: "HH:mm" });
597
- ```
598
-
599
- - **The value is a time of day, not an instant.** An ISO time on a 24-hour clock, `"14:30"` (`"14:30:15"` when
600
- `step` has seconds), with no date and no zone: what a form sends through a hidden input with the field's `name`,
601
- and what a .NET `TimeOnly` stores. `toIsoTime` reads `"9:05"`, `"14:30:00.000"`, a `Date` (its local time), and an
602
- ISO date-time (with a zone, the local time of that instant; without one, its time part).
603
- - **12 or 24 hours from the user's settings.** `nx-time-format` in local storage, next to the date settings, holds
604
- a format of tokens `HH` `H` `hh` `h` `mm` `m` `ss` `s` `A` `a`; the default is `hh:mm A` (02:30 PM).
605
- `useDatePreferences` returns it as `timeFormat`, and `setDatePreferences({ timeFormat })` changes every time picker
606
- on the page. Nepali dates in Devanagari bring Nepali digits and पूर्वाह्न/अपराह्न. A box can fix its own `format` or `script`.
607
- - **Typing** works on either clock: `2:30 pm`, `2.30p`, `230pm`, `14:30`, `1430`, `9`, `१४:३०`. Without AM or PM the
608
- hours are read on a 24-hour clock. Leaving the box writes the time in the format.
609
- - **Columns** (the default) show hours, minutes, seconds when the step needs them, and AM/PM; the chosen items line
610
- up on the middle row, a pick in any column changes the time at once, and ↑ ↓ ← → Home End Page Up/Down move through
611
- them. **`view="list"`** shows one slot per `step` (every 30 minutes for steps under 5 minutes); a click or Enter
612
- picks and closes.
613
- - **Rules:** `required`, `min` and `max` (with `max` earlier than `min` the range runs past midnight, 22:00 to 06:00),
614
- `step` in seconds counted from midnight as in HTML, `isTimeDisabled` for booked slots, and `validate`. Items outside
615
- the rules are dimmed in the panel; a typed time outside them gets a message such as "Arrival must be in steps of 30
616
- minutes, like 02:00 PM or 02:30 PM." `validateTime` is the pure check behind it. `npm run test:times` checks the helpers.
617
- - **Read-only** boxes have no panel: a lock sits where the clock button was, as in every read-only input.
618
-
619
- ### Date and time picker
620
-
621
- ```tsx
622
- import { DateTimePicker } from "nexus-shared/client";
623
-
624
- <DateTimePicker name="pickupAt" label="Airport pickup" required min={new Date()} step={900} minTime="05:00" maxTime="23:00" />
625
- <DateTimePicker name="checkInAt" label="Check-in" timeZone="Asia/Kathmandu" defaultTime="14:00" />
626
- <DateTimePicker name="spaAt" label="Spa slot" view="list" step={1800} isTimeDisabled={(time, date) => booked.has(`${date} ${time}`)} />
627
- ```
628
-
629
- - **The value is a moment, in UTC.** `"2026-09-17T08:45:00.000Z"`, the shape `toISOString` writes, is what the hidden
630
- input sends and `onValueChange` gives, whatever the user sees; the same moment is 02:30 PM in Kathmandu and 04:45 AM
631
- in New York, so no time zone can move a saved value. Store it as UTC: a .NET `DateTimeOffset`, or a `DateTime` of
632
- kind `Utc`. For a day with no time use `DatePicker`; for a time of day with no date, `TimePicker`.
633
- - **Values in** (`toUtcDateTime`): an ISO date-time with `Z` or an offset is that moment; one **without a zone is read
634
- as UTC**, the way a UTC `DateTime` loaded from a database often arrives without its `Z`; a date alone is the first
635
- moment of that day where the user is; a `Date` or milliseconds are that moment. .NET's seven digits of fractions are read.
636
- - **Shown in the user's zone and settings.** The browser's time zone, and the date (`nx-date-calendar`,
637
- `nx-date-format`, `nx-date-script`) and time (`nx-time-format`) settings of the other pickers: "2026-09-17 02:30 PM",
638
- or "२०८३-०६-०१ ०२:३० अपराह्न". The panel names the zone ("Kathmandu · UTC+05:45"). `timeZone` fixes a zone, such as a
639
- hotel's, and writes its city in the box. The server does not know the user's zone, so a box shows its text right
640
- after hydration rather than another zone's time for a moment; the hidden input holds the value from the start.
641
- - **No data loss.** A value changes only when the user changes what it shows: seconds and milliseconds the box does not
642
- show stay as they came (a stamp from the server is sent back exactly), and retyping or re-picking what it shows keeps
643
- the moment. Where clocks go back, one hour happens twice: a box holds whichever it was given, an edit inside that hour
644
- keeps its offset, and a new pick is the first of the two. Where clocks go forward, a skipped time moves on (02:30
645
- becomes 03:30), as `Date` and Temporal do.
646
- - **Typing:** a date in the user's format, then a time on either clock: `2026-09-17 2:30 pm`, `17/09/2026 14:30`,
647
- `Sep 17, 2026 at 2:30 PM`, `2026-09-17T14:30`, `२०८३-०६-०१ १४:३०`. A date alone takes `defaultTime` (default
648
- `minTime`, or midnight). Leaving the box writes it in the settings.
649
- - **The panel** is the calendar and the time columns (or `view="list"` slots) side by side, as tall as each other, with
650
- Now, the zone, and Done. A picked day keeps the time; ↓ opens it on the chosen day, Enter on a day moves on to the
651
- hours, and Tab runs through the calendar, the columns, and the buttons. On a phone the time goes under the calendar,
652
- and a panel taller than the room scrolls, moving to the time once a day is picked.
653
- - **Rules:** `required`; `min` and `max` as moments (days outside are dimmed, and times outside on the first and last
654
- day); `minTime` and `maxTime` as opening hours on every day (past midnight when `maxTime` is earlier); `step` in
655
- seconds from each midnight; `isDateDisabled(date)` and `isTimeDisabled(time, date)` with ISO dates and times where the
656
- user is; `validate`. Messages read like the box: "Airport pickup must be between 05:00 AM and 11:00 PM."
657
- `validateDateTime(value, rules, fieldName, options)` is the pure check. `npm run test:datetimes` checks the helpers
658
- against `Date` in eight zones, including half-hour daylight saving and a skipped day.
659
- - **Read-only** boxes have no panel: a lock sits where the button was, as in every read-only input.
660
-
661
- ### Dropdown
662
-
663
- ```tsx
664
- import { Dropdown } from "nexus-shared/client";
665
-
666
- <Dropdown name="roomType" label="Room type" required options={roomTypes} />
667
- <Dropdown name="amenities" label="Amenities" multiple max={6} options={amenities} /> // { value, label, icon: "wifi" }
668
-
669
- // Rows like a data table
670
- <Dropdown name="assignee" label="Assign to" options={staff} valueKey="id" labelKey="fullName"
671
- columns={[{ key: "photo", type: "avatar" }, { key: "username", header: "Username" }, { key: "fullName", header: "Full name" }]} />
672
- <Dropdown name="country" label="Country" options={countries} valueKey="code" labelKey="name"
673
- columns={[{ key: "flag", type: "image" }, { key: "code", header: "Code", type: "code" }, { key: "name", header: "Country" }]} />
674
-
675
- // A server list, editing a saved value
676
- <Dropdown name="guestId" label="Guest" valueKey="id" labelKey="fullName" defaultValue={booking.guestId} selectedOptions={[booking.guest]}
677
- loadOptions={({ search, skip, pageSize, signal }) => api.guests({ search, skip, take: pageSize }, signal)} /> // { items, total }
678
- ```
679
-
680
- - **Options are any objects.** `{ value, label, description, icon, disabled }` by default (a `ChoiceOption`), or API rows
681
- read through `valueKey`, `labelKey`, `descriptionKey`, and `iconKey`. Values keep their type; a number and its text
682
- are the same value, so id 7 from an API matches "7" from a form. A form gets hidden inputs named `name`, one per value.
683
- - **Columns** turn rows into cells that line up down the list (one grid with subgrid rows), with headings that stay on top.
684
- Types: `text`, `muted`, `code`, `avatar` (a photo URL, or initials of the label on a soft tone), `image` (4:3: flags,
685
- logos), and `icon` (a Tabler name); `width`, `align`, and `render` for the rest. The first picture leads the value in
686
- the box and in chips.
687
- - **Search** matches every typed word in any order, with or without Latin accents, in the label, description, value, and
688
- text columns (`searchKeys` to change). It is on with `loadOptions` or more than 8 options; without it, letters jump to
689
- an option as in a native select. A local list renders 100 rows and adds more while it scrolls: 10,000 options open in
690
- about 30 ms.
691
- - **Server pages:** `loadOptions({ search, page, pageSize, skip, signal })` returns `{ items, total?, hasMore? }`. The first
692
- page loads when the list opens (placeholder rows, a spinner in the box), the next near the end ("Loading more…"), a new
693
- search 250 ms after typing stops, aborting the request before it. A failure shows Retry. `loadKey` drops the loaded
694
- pages, for a list that depends on another field. `loading` shows the same loaders when the page fetches `options` itself.
695
- - **Saved values the list can no longer offer** always show, and are never offered again once removed:
696
- - on a server page not loaded: `selectedOptions` gives their items (a record usually carries the name), or
697
- `resolveOptions(values)` looks them up (a placeholder shows until it answers);
698
- - inactive items (`inactive: true` or `isActive: false`, or `isOptionInactive`): never in the list, shown only as a value;
699
- - values missing from `options`: tagged **Unavailable**, or **Not found** when nothing is known but the value.
700
-
701
- In the list they sit on top under **Selected** with their tag; in the box they carry the tag, or show as dashed chips.
702
- A value only on another server page has no tag: a search finds it as a normal option.
703
- - **Rules:** `required`, `min` and `max` for several (at `max` the other options are disabled), and `validate`, through
704
- `validateSelection`. A pick follows the same message timing as typing. `npm run test:dropdown` checks the helpers.
705
- - **Keys:** ↓ ↑ Page Up/Down Home End move past rows that cannot be picked, Enter picks, Space picks without search,
706
- Backspace in an empty box removes the last value, Esc closes (then clears the search), Tab closes and moves on.
707
- - **Read-only** boxes have no list: a lock sits where the list button was, chips lose their remove buttons, and a click or
708
- a key shows the note, as in every read-only input.
709
-
710
- ### Markdown editor
711
-
712
- ```tsx
713
- import { MarkdownView } from "nexus-shared";
714
- import { MarkdownEditor } from "nexus-shared/client";
715
-
716
- <MarkdownEditor name="description" label="Room description" defaultValue={room.description} defaultMode="split"
717
- height={320} heightKey="room-description" maxLength={5000} required />
718
-
719
- // Wherever the text is shown, also in a server component
720
- <MarkdownView value={room.description} />
721
- ```
722
-
723
- - **Write, split, and preview.** `defaultMode` (or `mode` with `onModeChange`) picks the view, and `modes` the views
724
- offered. The switch is small tab buttons with `labels="selected"`: icons, and the label of the selected view. Split puts the preview beside the text and keeps the two scrolled together; under 560 px wide it stacks
725
- them. The preview renders as a React transition, so typing stays within a frame in a 2,000-line document.
726
- - **Toolbar and shortcuts:** heading, bold (Ctrl+B), italic (Ctrl+I), strikethrough (Ctrl+Shift+X), quote
727
- (Ctrl+Shift+.), code (Ctrl+E), code block, link (Ctrl+K), image, bulleted, numbered, and task lists (Ctrl+Shift+8,
728
- 7, L), table, and horizontal line. Marks wrap the selection or the word at the caret and come off when applied
729
- again. Edits go through the browser's own editing, so Ctrl+Z undoes them. `toolbar` picks and orders the buttons.
730
- - **While typing:** Enter continues a list (the next number, an empty task box) and ends it on an empty item; a URL
731
- pasted over selected text links it; a task ticked in the preview is ticked in the text.
732
- - **Height handle:** the status bar under the editor drags the height between `minHeight` and `maxHeight`, showing
733
- the height as it changes; its grip takes ↑ ↓ (Shift for more), Page Up/Down, Home, and End; a double-click goes back
734
- to `height`. `heightKey` remembers the user's height in local storage. Dragging writes straight to the DOM.
735
- - **Full screen** (`fullscreen`, on by default) lifts the editor into the top layer over a dimmed page, without
736
- moving it in the DOM, so undo history and the form stay. Tab stays inside, and Esc closes it.
737
- - **A form field like `TextArea`:** `name`, `required`, `minLength`, `maxLength`, `pattern`, `validate`, the status bar's
738
- word and character count, and read-only (a lock in the bar and a note under it). An invalid submit while the preview
739
- shows brings the text back and focuses it. The view switch belongs to no form (`TabButtons` `form`), so it is never sent.
740
- - **Safe to show anyone's text.** `parseMarkdown` (GitHub-flavored: tables, tasks, strikethrough, autolinks) never
741
- renders raw HTML, and `safeUrl` keeps only http, https, mailto, tel, and relative addresses for links, and raster
742
- data URLs for images. Links to other sites get `rel="nofollow noopener noreferrer"`.
743
- - **Helpers:** `markdownToPlainText` for excerpts and search, and the editing commands `applyMarkdownTool`,
744
- `continueMarkdownList`, `toggleMarkdownTask`, and `linkPastedUrl` for a custom editor. `npm run test:markdown`
745
- checks the parser and every command.
746
-
747
- ### Forms
748
-
749
- ```tsx
750
- import { TEXT_PATTERNS, type InputParams } from "nexus-shared";
751
- import { ApiForm, SubmitForm } from "nexus-shared/client";
752
-
753
- const ROOM_INPUTS: InputParams[] = [
754
- { type: "text", name: "number", label: "Room number", required: true, pattern: TEXT_PATTERNS.digits, span: 4 },
755
- { type: "number", name: "floor", label: "Floor", required: true, min: 0, span: 4 },
756
- { type: "dropdown", name: "type", label: "Type", required: true, options: ROOM_TYPES, span: 4 },
757
- { type: "tabular", name: "beds", label: "Beds", itemLabel: "Bed", inputs: BED_INPUTS }, // a list is an input too
758
- ];
759
-
760
- <ApiForm
761
- inputs={ROOM_INPUTS}
762
- loadValue={signal => api.get(ROOMS.details, { params: { id }, signal, toast: false }).then(unwrapApiResult)}
763
- api={ROOMS.update} // or in place: { module: NexusModule.Reservation, path: "Room/Update", method: "PUT" }
764
- draftKey={`hotel-3:user-8:room:${id}`}
765
- onSuccess={room => table.updateRow(room)}
766
- onCancel={close}
767
- />
768
- ```
769
-
770
- - **Params in, values out.** Every input is an entry of `inputs`, so a page, a CRUD component, or a server can describe a
771
- form with plain objects. Values come in as each input reports them (a date-time from an API becomes a date, "12.5"
772
- becomes 12.5), and fields the record came with (an `id`) stay in the values.
773
- - **Fast at any size.** The values live in a `FormStore` outside React. Typing renders only the input typed in; an input
774
- renders again only when a message it shows changes, or code sets its value. A keystroke costs about 5 µs in the store
775
- for a form of 200 inputs, and a list of 10,000 rows is not checked again on each keystroke (it checks itself).
776
- - **Checks on Save.** Each input's own rules (they also catch text that is not a date yet), the form's `validate` across
777
- inputs, and rows not on the page. Every message shows, the first problem takes focus (a table scrolls to its row), and
778
- the status line lists what needs attention, each name a link to its input. A rule message on an input shows once the
779
- input was left, and on Save.
780
- - **One save at a time.** Save waits with a spinner; another click, Enter, or Ctrl+S does nothing until it ends. A save
781
- makes the values the form's own ("Unsaved changes" clears; values typed meanwhile stay changes). `onSubmit` returns
782
- `{ ok: false, errors, message }` to say why not, and a thrown error shows its message.
783
- - **Server messages.** The server's own words are what the user reads. `ApiForm` shows **every** message a refusal
784
- carried - a Nexus answer's `errorMessages` (a list, or one message object, or one message and its codes at the top
785
- level) and ASP.NET Core problem details (`errors` by field) - each on the input its `inputName` names, matched without
786
- case and by the first part of a path (`Addresses[1].City`). Names that match no input of this form, messages that name
787
- none, and failures without fields show beside the buttons; nothing is swallowed and nothing is shown twice. A sentence
788
- of ours by HTTP status ("Someone else changed this record…") is the fallback for an answer that explained nothing.
789
- `messageCode` and `errorCode` ride along in `answer.errorMessages` for the log and for `onError` to react to, and are
790
- never shown as the sentence. An input's message clears when its value changes.
791
- - **Nothing lost.** `draftKey` keeps unsaved changes in IndexedDB (after a 600 ms pause, and at once when the page hides
792
- or the form leaves) and brings them back with a note and Discard; drafts changed on the server since are named. Cancel
793
- asks before it drops changes, and the page asks before it closes with some (`confirmLeave`, on without a draft).
794
- `form.load(values, { keepChanged: true })` refreshes a record without touching what the user changed.
795
- - `npm run test:forms` checks the store and the API helpers; `scripts/browser-checks/forms.cjs` in the template checks the
796
- three demo pages.
797
-
798
- ### API calls
799
-
800
- ```ts
801
- // api-modules.ts: the app's modules and where each one's root is (shared by the browser and the server)
802
- import { defineApiModules, NexusApiModules, NexusModule } from "nexus-shared";
803
-
804
- export const MODULES = defineApiModules(new NexusApiModules({ useProxy: process.env.NEXT_PUBLIC_API_PROXY !== "false" }));
805
- export const ROOMS = MODULES.controller(NexusModule.Reservation, "Room", "room");
806
-
807
- // In the browser
808
- import { api } from "nexus-shared/client";
809
- const rooms = await api.get<Room[]>(ROOMS.listing); // GET /api/app/reservation/Room/NormalListing
810
- await api.put(ROOMS.update, values, { subject: "Room 204" }); // toast: "Room 204 saved." or what failed and why
811
- await api.confirm(ROOMS.delete, { params: { id }, subject: "Room 204" }); // asks "Delete Room 204?" first
812
-
813
- // On the server (a server component, a route handler, a server action)
814
- import { serverApi } from "nexus-shared/server";
815
- const list = await serverApi.get<Room[]>(ROOMS.listing, { revalidate: 60, tags: ["rooms"] }); // straight to API_RESERVATION
816
-
817
- // app/api/app/[module]/[...path]/route.ts: the browser's way to every module
818
- export const { GET, HEAD, POST, PUT, PATCH, DELETE } = createApiProxy({ token: readAccessToken });
819
- ```
820
-
821
- - **Modules are the app's.** `ApiModules<TModule>` is an abstract class over the app's own module enum: implement
822
- `modules` (each module's value, its key in proxy URLs, its label for messages, where its root comes from) and
823
- `serverRoot(module)` (from the environment, a settings service, anything; may be async). Register it once with
824
- `defineApiModules`, and define endpoints through it (`MODULES.controller`, `MODULES.endpoint`), so a file that calls
825
- an endpoint has registered the modules on either side. `NexusApiModules` is the Nexus set (roots from `API_<MODULE>`,
826
- as in the previous project; `NexusModule.None` for the app's own `/api` routes) and runs when nothing is registered.
827
- The list is checked: keys and values must be unique, and keys fit in a URL.
828
- - **`NexusModule`'s numbers are the backend's `EModules` flags**, and a permission is a bitmask of them, so a value
829
- that disagrees with the backend by one bit grants or denies the wrong module in silence. They changed after
830
- 2.0.0: `Chat` took bit 6 and `Accounting` through `Portfolio` each moved up one. Code that uses the names needs
831
- nothing; anything holding a stored or hard-coded **number** does. [CHANGELOG.md](CHANGELOG.md) has the table.
832
- - **Module types from one place.** An app names its enum once, next to `defineApiModules`:
833
- `declare module "nexus-shared" { interface ApiRegister { module: HrModule } }`. Every endpoint, call, `ApiForm`,
834
- and CRUD then takes only those modules (`AppModule`), so `{ module: NexusModule.Reservation, … }` in an HR app is a
835
- type error. Without it, the modules are `NexusModule`.
836
- - **The proxy, on or off.** With `useProxy` (the default), the browser calls `/api/app/<module>/<path>` and the proxy
837
- route sends it on to the module's root with the user's token, which never reaches the browser. Off, the browser
838
- calls each module's `browserRoot` (public) and the proxy serves none. `proxies(module)` mixes the two, such as
839
- uploads straight to the Drive module and the rest through the proxy.
840
- - **The proxy hides the backend.** To the browser the app is the backend, and nothing in an answer names the real one:
841
- - **No redirect reaches the browser.** One that stays inside the module (the root's origin, or its host moved to
842
- https by the backend's HTTPS redirection, under the root's path in any casing) is followed on the server as
843
- `fetch` follows it: 307 and 308 keep the method and body, a 303 and a POST's 301 or 302 become a GET, up to
844
- `maxRedirects` (3). Any other answers 502 `BACKEND_REDIRECT_REFUSED`: following it would carry the token elsewhere.
845
- - **Response headers by an allowlist**, `DEFAULT_PROXY_RESPONSE_HEADERS` (Content-Type, Content-Disposition,
846
- Content-Language, Content-Range, Accept-Ranges, Cache-Control, Expires, ETag, Last-Modified, Vary, Retry-After),
847
- the Nexus backend's `X-Nexus-*`, and the names in `responseHeaders`. Server, X-Powered-By, X-AspNet-*,
848
- X-SourceFiles, Via, Alt-Svc, Strict-Transport-Security, Report-To, NEL, CORS, Location, Link and WWW-Authenticate
849
- never pass, even named; Set-Cookie only with `passCookies`. Every answer gets `X-Content-Type-Options: nosniff`,
850
- and `Cache-Control: private, no-store` unless the backend said how to cache it.
851
- - **Error pages replaced.** An error answer that is not JSON (an HTML or text page, a stack trace), JSON that is a
852
- stack trace or repeats the user's token, or one over 1 MB, becomes the failure envelope with the backend's status
853
- and plain words (`BACKEND_ERROR_PAGE`). JSON refusals (the Nexus envelope, problem details) and empty ones pass as
854
- they came, so the backend's own words still reach the form.
855
- - **The request.** The browser's own `X-Forwarded-*`, `Forwarded`, `X-Real-IP` and the like never go on, nor its
856
- cookies, a method or path override (`X-HTTP-Method-Override`, `X-Original-URL`) or Next.js's own headers. The
857
- proxy writes X-Forwarded-For (the last address the app received, which Next.js or the app's reverse proxy wrote;
858
- `clientAddress` reads it elsewhere; an IPv4 or IPv6 address or nothing, never other text) and X-Forwarded-Host
859
- and -Proto (the app's configured origin, else the request's). A module whose root is a path on the app (a pretend
860
- backend) is called at this server's own host and port, over http: the request URL's, which Next.js builds from
861
- where it listens. Never at the configured origin, so an app whose `origin` reads the Host header cannot let a client
862
- choose another port on the machine; `serverApi`, which has no request, uses that `origin`, so build it from
863
- configuration, or take the Host only when it names this server's own port. A body over `maxBodySize` (100 MB) is
864
- refused with 413 before the backend sees it, and a page of another site cannot call through the proxy
865
- (`Sec-Fetch-Site: cross-site`, other than a link followed) unless `allowCrossSite`.
866
- - **A server call can say who the client is too.** `lastForwardedAddress` and `readIpAddress` (`nexus-shared/server`)
867
- read the client's address as the proxy does, from anything with a `get` (Next.js's `headers()` included). The
868
- template's `api-setup.ts` gives Identity calls, and only them, `X-Forwarded-For` and the browser's `User-Agent`
869
- through `configureServerApi({ headers })`: sign-in leaves from the server, and Identity's rate limit counts per
870
- address. Only Identity's, because reading the request makes a page render per request.
871
- - **Refusals** are the Nexus envelope, `{ isSuccess: false, code, message, messageCode, errorCode, errorMessages }`
872
- (`failure` builds another backend's; `PROXY_REFUSALS` lists the codes), and the real cause goes to the server's
873
- log (`onProblem`, default `console.error`), never with the token or a query string.
874
- - **Two things the proxy cannot do for an app.** Node.js does not trust a development certificate (ASP.NET Core's)
875
- unless it starts with `NODE_USE_SYSTEM_CA=1`, so a module whose http root redirects to such an https port answers
876
- 502 until then, and the log says so. And Next.js keeps an X-Forwarded-For a client sent when nothing stands in
877
- front of the app, so only behind a reverse proxy of its own is the client's address certain.
878
- - **One engine, two clients.** `api` and `serverApi` are two settings of `createApiClient`: it fills `{id}` in the path
879
- from `params` or the body, adds the query, headers, and token, waits up to `timeout` (60 s), tries a failed GET once
880
- more (a save never twice), and reads every answer as an `ApiResult` (`ok`, `status`, `result`, `message`,
881
- `errorMessages`, `errors`, `messageCode`, `errorCode`, `network`, `timeout`, `aborted`). A failed call is an answer,
882
- never a throw; an aborted one shows nothing. Next.js's own signals (`headers()` while prerendering, `redirect()`) pass
883
- through untouched.
884
- - **What the server said wins.** A refusal is shown in the backend's own words whenever it sent any:
885
- `{ isSuccess, code, errorMessages: [{ message, messageCode, errorCode, inputName }] }` becomes
886
- `result.errorMessages` in that order (one message object instead of a list, a single `errorMessage`, and an older
887
- answer's one message at the top level all read into the same list), `result.errors` holds the ones that name an input,
888
- and `result.message` is all of them joined for a toast. `messageCode` and `errorCode` are for the log and for a page to
889
- react to - never the sentence a user reads. The messages built from the HTTP status are the fallback for an answer that
890
- explained nothing.
891
- - **Answers of another shape.** Nexus answers and ASP.NET Core problem
892
- details are read out of the box. A backend that answers its own envelope registers one reader for the whole app:
893
-
894
- ```ts
895
- // Reads { success, message, data, error: { code, message, fields } } — the answer becomes ok, result, message, errors
896
- const read: ApiResponseReader = (body, status) => {
897
- const answer = body as BackendAnswer | null;
898
- if (answer?.success) return { ok: true, status, result: answer.data, message: answer.message };
899
- const fields = Object.entries(answer?.error?.fields ?? {}).map(([name, list]) => [name, list.join(" ")]);
900
- return { ok: false, status, message: answer?.error?.message, messageCode: answer?.error?.code, errors: Object.fromEntries(fields) };
901
- };
902
- configureApi({ read }); // the browser
903
- configureServerApi({ read }); // and the server, so both sides read one envelope
904
- ```
905
-
906
- It is the fallback of every call that does not bring a `read` of its own, which is what the components that call
907
- inside themselves need: a `Crud`'s lists and actions and an `ApiForm`'s save have no place to pass one. A call's own
908
- `read`, and an `ApiForm`'s `readResponse`, still win.
909
- - **Toasts in the browser.** Errors always, successes for POST, PUT, PATCH, and DELETE; the same failure twice at once
910
- shows once; `toast: false`, `true`, or `{ success, error, loading }` per call; `configureApi({ toast, headers, read,
911
- onSignedOut })` for the app. The server shows nothing and logs network failures, timeouts, and 5xx.
912
- - **One message builder.** `buildMessage(kind, { action, subject, count, status })` words every message, and
913
- `messages.success`, `.failure`, `.reason`, `.loading`, `.confirm`, `.label`, and `.forResult` are short ways to call
914
- it: "3 rooms deleted.", "Could not move Room 204 to the trash.", "You do not have permission to delete Room 204.". The
915
- texts and action words are one table: `configureMessages` rewords or translates all of them at once, and an action
916
- of the app's own is its words (`{ verb: "check in", done: "checked in", doing: "Checking in", object: "the guest" }`).
917
- - **A controller's lists.** `apiController` names the lists as the Nexus backend does: `listing` and `pagination` are the
918
- active records' (`NormalListing`, `NormalPagination`), and `lists.flag`, `lists.trash`, `pages.trash`, … the others
919
- (`FlagListing`, `TrashListing`, `TrashPagination`, …), for the CRUD component.
920
- - `npm run test:api` checks the builder, routes, modules (another app's enum, the proxy on and off), the engine, the
921
- server client, and the proxy's routing; `npm run test:proxy` checks how the proxy hides the backend (redirects,
922
- headers, error pages, forwarded headers, paths, the body limit, other sites, the log) against a fake backend;
923
- `scripts/browser-checks/api-calls.cjs` in the template checks `/demo/api`.
924
-
925
- ### Data table
926
-
927
- ```tsx
928
- import type { TableColumn } from "nexus-shared";
929
- import { DataTable, useTable } from "nexus-shared/client";
930
-
931
- const COLUMNS: TableColumn<Booking>[] = [
932
- { key: "no", label: "Booking", width: "7rem", movable: false, pinnable: false }, // stays first, and stays put
933
- { key: "guest.name", label: "Guest" }, // a path into the row
934
- { key: "amount", label: "Amount", format: "money", prefix: "Rs. ", group: "Amount details" }, // number, money, percent, date, …
935
- { key: "due", label: "Due", format: "money", prefix: "Rs. ", group: "Amount details" }, // one heading over both: the header is two rows
936
- { key: "status", label: "Status", options: [{ value: 1, label: "Confirmed", tone: "success" }] }, // a tag
937
- { key: "paid", label: "Paid", format: "boolean", resizable: false }, // keeps its width
938
- { key: "created", label: "Booked", format: "date-time", hidden: true }, // shown from the Columns menu
939
- ];
940
-
941
- const table = useTable<Booking>();
942
- <DataTable table={table} aria-label="Bookings" columns={COLUMNS} rows={bookings} selectable massActions={MASS} rowActions={row => ACTIONS(row)} stateKey="bookings" />
943
- <DataTable columns={COLUMNS} paging="server" load={(query, signal) => fetchPage(query, signal)} /> // { search, sort, page, pageSize, filters }
944
- <DataTable columns={COLUMNS} rows={bookings} onImport={askForFile} moreActions={[{ id: "report", label: "Monthly report", onSelect: open }]} />
945
-
946
- table.upsert(saved); table.patch(7, { paid: true }, { flash: true }); table.remove([7, 8]); await table.reload();
947
- ```
948
-
949
- - **Columns are params**, one plain object each, as inputs are: `key` (a field or a path), `label`, `group`, `format`,
950
- `decimals`, `prefix`, `suffix`, `options` (labels for an enum's values; a `tone` draws a tag with a dot of its color),
951
- `value`, `render`, `text`, `width`, `minWidth`, `align`, `wrap`, `sortable`, `sortKey`, `searchable`, `hidden`,
952
- `hideable`, `movable`, `resizable`, `pinnable`, `pinned`. Numbers line up at the end in tabular figures; dates and
953
- times follow the user's settings; moments show in the user's zone once the page has hydrated; long text ends in … at
954
- the column's width.
955
- - **Columns in bands.** `group` is the heading above a column (`{ key: "amount", label: "Total", group: "Amount
956
- details" }`); the columns next to each other that name the same one share it, and the header reads in two rows, the
957
- bands on top and the columns' own headings under them. A column with no group keeps one heading as tall as both rows,
958
- and so do the numbers and checkbox column and the actions. A band is a heading and nothing more: it sorts nothing, has
959
- no menu and no edge to drag, and the columns stay one flat list, so hiding, ordering, widths, pins and the export are
960
- as they were. The bands are read off the order on screen: a column dragged out of its run takes its band's heading
961
- with it, and the run it left draws that heading again. With no group anywhere the header is one row.
962
- - **Rows three ways.** Given (`rows`) or loaded once (`load`), the table searches, sorts, and pages them itself: every word
963
- must match, in any column, with or without accents, and 10,000 rows search in about 0.5 ms a keystroke. A page at a time
964
- (`load` with `paging="server"`), each search (after 300 ms without typing, or Enter), sort, and page is one request; a
965
- newer query stops the one before, so a late answer never shows. A loader may answer without a promise (a cache), and
966
- the rows then paint with the table. `loadKey` starts over for another list behind the same table.
967
- - **What it shows while it waits.** Placeholders in the shape of the rows for the first rows; afterwards the rows stay,
968
- with a thin bar under the headings, and dim only if a load takes a moment. A failed load says why, with Retry; an empty
969
- list has its own message and action; a search or filters that find nothing offer Clear search or Clear filters.
970
- - **The columns are the user's.** Drag a heading to another place, drag its right edge for its width (double-click the
971
- edge, or "Fit to content", to fit it, never under the column's `minWidth`), and use the caret on the heading to sort,
972
- pin it left or right, move it, or hide it; the Columns menu shows and hides them. A column opts out with
973
- `movable`, `resizable`, or `pinnable: false`, and `pinned` starts it on a side. The table itself can refuse all three
974
- (`reorderable`, `resizable`, `pinnable`). Once a width is set the columns are laid out from those widths, so one edge
975
- moves alone; "Reset columns" in the options menu puts everything back.
976
- - **The bar** is one line on a wide table: the Add section (`add`, then the page's `actions`) and the lists
977
- (`toolbar`) on the left; Reload, the options menu (⋮) and the search, rows per page inside it, on the right. A
978
- narrower table moves whole parts, never a lone button, by its own width (a container query, so a table in a narrow
979
- panel does the same): under 670px the search takes the top line (with nothing on the left, it leads the buttons'
980
- line instead), under 375px Reload moves into ⋮, and under 325px, beside lists, the Add section takes the last line,
981
- its buttons sharing it. On the admin shell, whose menu leaves the screen at 900px, those are windows of 695, 400 and
982
- 350px. A bar wider than those widths expect (a long Add label, the page's own buttons, cozy density) takes the next
983
- step as soon as a line would break (`data-squeeze`). A `Crud`'s lists name every tab from 900px and only the chosen
984
- one below.
985
- - **One options menu (⋮)**: **Filters** (`filterInputs`, input params as a form takes them, each named after the
986
- column it filters: a small form under ⋮, applied as it changes; a server gets them flat by name, see `filterRequest`),
987
- the columns shown as a CSV (`exportable`, named by `exportName` or the table's label), a
988
- print view of the same in a frame of its own (`printable`), Import (`onImport`), any `moreActions` of the page, and
989
- Reload, last, on a table too narrow for its button. A client table writes every row the search left; a server table
990
- writes the page it has, and says so.
991
- - **Selection.** The first column counts the rows (`numbered`, on by default when `selectable`) and turns into the row's
992
- checkbox under the pointer; once anything is selected every row shows its checkbox and the heading shows the box that
993
- selects the page (partly checked when some are). Shift+click selects a range, up to `maxSelection` (500). While rows
994
- are selected, a bar with the count, one split button holding every `massAction`, and Clear covers the headings, so
995
- nothing moves: the menu makes the action picked the button, and the next click runs it, with a spinner while it does.
996
- - **Row actions**: `inline` ones as icon buttons, the rest in the row's menu; while one runs (a promise), the row is busy.
997
- `onRowOpen` for a double-click. A row added or saved is highlighted for a moment (steadily, with reduced motion).
998
- - **A pinned section.** `pinnedRows` puts rows in a band above the page with a button that folds them open and shut
999
- (`pinnedLabel`, `pinnedMax` beside the count, `pinnedLoading` while they come); with a `stateKey` the choice is
1000
- remembered on the device. They are the same records as in the list below, and each wears a pin where the rows of the
1001
- page show their number.
1002
- - **Wide tables** scroll inside their frame, with the numbers and checkbox column on the left, the actions on the right,
1003
- any pinned columns beside them, and the headings on top staying in place, and a soft shadow where columns scroll under
1004
- them. Under the table: "Showing 41–50 of 234" (and how many the search and filters left out) on the left, "Page 5 of
1005
- 24" and the pager on the right; rows per page sits inside the search box. At 520px and less the page buttons go.
1006
- - `npm run test:table` checks the helpers, the store, and the CRUD rules; `scripts/browser-checks/data-table.cjs` in the
1007
- template checks `/demo/data-table`.
1008
-
1009
- ### CRUD
1010
-
1011
- ```tsx
1012
- import { Crud } from "nexus-shared/client";
1013
-
1014
- export const GUESTS = MODULES.controller(NexusModule.Reservation, "Guest", "guest"); // every list and action
1015
-
1016
- <Crud<Guest>
1017
- api={GUESTS}
1018
- columns={GUEST_COLUMNS} // as a DataTable takes them
1019
- inputs={GUEST_INPUTS} // or { create, edit }, or (action, row) => inputs
1020
- paging="server" // default "client": each list loaded once
1021
- form={{ load: "details", newValues: { country: "Nepal" } }}
1022
- details={{ columns: GUEST_DETAILS }}
1023
- onChange={({ action, rows, mode }) => audit(action, rows)}
1024
- />
1025
- ```
1026
-
1027
- - **Lists.** All (`NormalListing` or `NormalPagination`), Flagged, Trash, and Deleted, as tabs after Add: every one
1028
- named on a table 900px wide or more, icons with the chosen one named below. A list shows when it is in `modes`, has
1029
- its endpoint, and the user may call it.
1030
- - **Pinned records.** `PinListing` answers the records the user pinned: they sit in a section above the active list that
1031
- folds open and shut, and in the list and its pages as well. One limit holds for every CRUD in the app
1032
- (`configureCrud({ maxPins: 100 })`, 100 by default). Pinning a selection bigger than the room left pins as many as fit,
1033
- in the order they were picked, and says so; lowering the limit never unpins anything, so a user over it can still
1034
- unpin and can pin again once they are under it.
1035
- - **Actions.** On a record in the lists of active records: View details, Edit (an icon on the row), Flag, Pin,
1036
- Move to trash; in the trash: Recover, Delete permanently; in the deleted list: Move back to trash. On selected records: the same, plus a new Description for all of them. Each shows only when it is in
1037
- `actions`, has its endpoint, and is allowed. A controller without a trash (no endpoint, or left out of `actions`) offers
1038
- Delete where Move to trash would be; a trash the user may not use never becomes Delete.
1039
- - **Questions and messages.** Move to trash and Delete ask first ("Move 3 guests to the trash?", "This cannot be
1040
- undone."); Flag, Pin, and Recover are undone by a click and do not ask. Toasts come from the message
1041
- builder ("Sita Sharma moved to the trash.", "3 guests unpinned.").
1042
- - **Rows from the answers.** A record that moves to another list leaves the one in view (and the pinned section); flags,
1043
- pins, and saved values change in place; a new record goes first; a server page loads again in the background to fill up. When a mass
1044
- answer lists the records it changed, only those change.
1045
- - **Add and Edit** open popups built on `ApiForm`, with the Save bar in the footer and the server's messages on their
1046
- inputs. Keys keep them one each: pressing Add again brings back an Add form with changes (minimized or not), or opens a
1047
- fresh one; Edit of a record already open brings that popup back as it was. Closing a form with changes (its close
1048
- button, Esc, the dock) asks "Discard your changes?". Edit opens with the row, the `details` endpoint's record
1049
- (`form.load: "details"`, for fields a list leaves out), or a loader of your own.
1050
- - **Details** (View, or a double-click) shows every column, hidden ones too, and the full record once `details` answers,
1051
- with Edit in its footer.
1052
- - **Cache.** Lists are kept for 5 minutes while the page is open (`cache={{ lifetime }}`, or `false`): going back to a
1053
- list paints it at once. After a change, the list in view keeps its rows and the others load again when shown; Reload
1054
- and the handle's `reload()` go past the cache. The cache goes when the page does.
1055
- - **Permissions** come from the app's rules: `definePermissions(new NexusPermissions())` once, then `setActions(accessActions)`
1056
- after sign-in. While the rules load, the table shows placeholders; a user with no list sees a message. Rules for
1057
- another backend extend `Permissions` (`can(endpoint)`), and its page and mass shapes extend `CrudBackend`.
1058
- - `ref` gives `table`, `mode`, `setMode`, `reload`, `create(values)`, `edit(row)`, and `view(row)`.
1059
- - `scripts/browser-checks/crud.cjs` in the template checks `/demo/crud`: every list and action, the popups, the roles, the
1060
- cache, a phone, and contrast in every theme.
1061
-
1062
- ### Excel import and export
1063
-
1064
- A model's records in and out of a spreadsheet, against the backend's Excel controller bases
1065
- (`NexusExcelController<TContract>` and `NexusExcelExportController<TContract>`): `Excel/Settings`, `Excel/Template`,
1066
- `Excel/Verify`, `Excel/Import`, and the model's own export action.
1067
-
1068
- ```tsx
1069
- export const CITIES = MODULES.controller(NexusModule.Configuration, "City", "city");
1070
- export const CITY_SHEET = excelEndpoints(CITIES, { subject: "city" }); // the four, and Excel/Export
1071
-
1072
- openExcelImport({ endpoints: CITY_SHEET, subject: "city", onImported: reload }); // the panel as a window
1073
- <ExcelImport endpoints={CITY_SHEET} subject="city" onImported={reload} /> // or in the page
1074
- openExcelImport({ endpoints: REGION_SHEET, subject: "region", mode: "bulk", onImported: reload }); // rows typed in
1075
-
1076
- await downloadExcelTemplate(CITY_SHEET);
1077
- await exportExcel(CITY_SHEET, { subject: "city", rows: table.matches, query: { search, sort: "cityName", direction: "asc", filters } });
1078
- ```
1079
-
1080
- - **The template** is the backend's file, downloaded under the name its `Content-Disposition` gives it. Every list in it
1081
- is a dropdown and the ids beside a choice fill themselves, so the person types no code and pastes no id.
1082
- - **A verify writes nothing.** The file goes up as form data, and the answer is the rows, judged: what would be added,
1083
- what is already a record, and what is waiting on a fix.
1084
- - **The review is two editors** over those rows - **New rows** (which includes the rows to fix, since a row with a
1085
- problem is not yet a record) and **Already there**, which folds away - built from the sheet's columns with the rules
1086
- the sheet told the person about, so a fix made here is checked the way the file was. What the server found wrong is
1087
- listed under the rows, each entry naming the cell as a spreadsheet does (`B7 - City name`) and taking the caret to it.
1088
- Rows can be added to the new rows (Add, Insert, Duplicate); one added and left empty is not sent, and an added row is
1089
- numbered after every row of the file, so no two rows share a number. A sheet with a required list takes no added
1090
- rows: a list's key is picked in the spreadsheet, and a row added here could never have one.
1091
- - **A bulk insert is an import with no file** (`mode: "bulk"`): the new rows' editor opens with one empty row, the
1092
- person types the rows, and they go to the same `Excel/Import` with the same checks - a problem then names its row
1093
- (`Row 3 - Region name`). A sheet with a required list cannot be typed in, and the panel says so.
1094
- - **Nothing typed is lost unasked**: closing the window or Start over asks first, and the entry picked again while its
1095
- window is minimized brings that window back. An import that wrote nothing keeps the rows, and lists under them what
1096
- the backend refused and why.
1097
- - **The import sends rows, never the file again**, or every fix made on screen would be lost; every check runs again on
1098
- the way in. **A duplicate is never updated**: one left alone is not sent at all, and editing one sends it as a new
1099
- record. An import writes what it can and names the rest; only one that wrote nothing at all is a failure.
1100
- - **A choice travels as its key**, out and back. The plain id in the sheet is for the person to read and is never read
1101
- back, so nothing copied out of a file or out of an answer can be posted to an endpoint as an id.
1102
- - **The export is the server's file**, written from the search, the sort and the filters on screen - not a CSV of the
1103
- rows this browser holds. The row limit is the backend's (`Excel/Settings`, 5,000 by default, kept for the page's life);
1104
- over it the person is asked first, and the answer's own headers say what was written and what was left out.
1105
- - **Generic, like the rest.** `ExcelBackend` is the class an app on another backend registers
1106
- (`defineExcelBackend(new MyExcelBackend())`): the request shapes, how the answers read, the upload field, and the names
1107
- of a download's headers. `NexusExcelBackend` is the default. `readExcelResponse` reads a refusal's `errorMessages`, so
1108
- "no city could be written" reaches the person in the backend's own words.
1109
- - **A column draws its own input**: text, note, whole number, decimal, amount, date, time, Yes/No, and a choice shown
1110
- read-only with the words the person picked. A **date and time** is a text box, not a picker: the sheet's moment is a
1111
- zone-less wall clock while a picker's value is a UTC moment, so a picker would shift every value by the reader's offset.
1112
- - `scripts/test-excel.mts` checks the endpoints, the answers, the inputs and the round trip; the template's
1113
- `scripts/browser-checks/excel.cjs` checks `/demo/excel`: every state, the two rules about the wire, both downloads, the
1114
- warning before a capped export, a phone, and contrast in every theme.
1115
-
1116
- In a table, `excel={{ endpoints: CITY_SHEET, subject: "city" }}` is the whole of it: the options menu (⋮) then offers
1117
- **Download template**, **Import from a spreadsheet** (the panel as a window, after which the table reads its rows
1118
- again), **Bulk insert** (the same with no file, beside an Add only; `bulk: false` leaves it out) and **Export to
1119
- Excel**, which sends the table's own search, filters and sort with the page's `filters()`. A `Crud` passes it through
1120
- as `table={{ excel }}` and drops the lists it had kept once an import has written. It replaces `onImport`, which stays
1121
- for a page that imports its own way.
1122
-
1123
- Planned, following the previous Nexus project: a page status layout, and in the CRUD, audit logs in the details view.
1
+ # nexus-shared
2
+
3
+ Lightweight React components, helpers, and design tokens for Nexus apps. No runtime dependencies besides
4
+ React and `nexus-icons`.
5
+
6
+ ```
7
+ npm install nexus-shared nexus-icons
8
+ ```
9
+
10
+ ```tsx
11
+ // Once, in the root layout
12
+ import "nexus-shared/styles.css";
13
+
14
+ import { Button } from "nexus-shared";
15
+ import { InlineIcon, iconPlus } from "nexus-icons";
16
+
17
+ <Button variant="primary" icon={<InlineIcon icon={iconPlus} />}>New booking</Button>
18
+ ```
19
+
20
+ ## Entry points
21
+
22
+ | Import | Contains |
23
+ |---|---|
24
+ | `nexus-shared` | Components and helpers that work in server and client components |
25
+ | `nexus-shared/client` | Client components and browser services |
26
+ | `nexus-shared/server` | Server-only code |
27
+ | `nexus-shared/styles.css` | Tokens, base styles, and component styles |
28
+
29
+ ## Themes
30
+
31
+ Seven themes, each with a light and a dark palette that meets WCAG AA contrast:
32
+ **Nexus** (default), **GitHub**, **Nord**, **Dracula**, **Solarized**, **Catppuccin**, and **Rosé Pine**.
33
+ The mode is Light, Dark, or System (follows the operating system).
34
+
35
+ ```tsx
36
+ // app/layout.tsx
37
+ import "nexus-shared/styles.css";
38
+ import { ThemeScript } from "nexus-shared";
39
+ import { ThemeSwitcher } from "nexus-shared/client";
40
+
41
+ export default function RootLayout({ children }) {
42
+ return (
43
+ <html lang="en" suppressHydrationWarning>
44
+ <head>
45
+ <ThemeScript />
46
+ </head>
47
+ <body>
48
+ <header>… <ThemeSwitcher /></header>
49
+ {children}
50
+ </body>
51
+ </html>
52
+ );
53
+ }
54
+ ```
55
+
56
+ - `ThemeScript` applies the saved choices before the page paints, so there is no flash of the defaults. Options:
57
+ `defaultTheme`, `defaultMode`, `defaultDensity`, `defaultAnimations`, `grid`, `themes`, `nonce`. It sets
58
+ attributes on `<html>`, hence `suppressHydrationWarning`.
59
+ - `ThemeSwitcher` is a palette button with a popover; `ThemePicker` is the same picker placed in a page. Besides the
60
+ mode and the theme it offers **Density** (Compact, Cozy), **Animations** (On, Off, System) and, in a development
61
+ build only, the **Scale grid** (Off, px, mm); `showMode`, `showDensity`, `showAnimations`, `showGrid` turn them off.
62
+ - `useTheme()` returns `{ theme, mode, resolvedMode, density, animations, motion, grid }` and a setter for each.
63
+ - The choices are saved in `localStorage` (`nx-theme`, `nx-mode`, `nx-density`, `nx-animations`, `nx-grid`) and
64
+ shared by open tabs.
65
+
66
+ Without JavaScript, set the attributes yourself: `<html data-nx-theme="nord" data-nx-mode="dark">`.
67
+ Without `data-nx-mode`, the system setting applies. `data-nx-theme` also works on any element, which then
68
+ draws in that theme (the picker's previews use this).
69
+
70
+ **Density** is `data-nx-density="cozy"` on `<html>`: every control 4px taller (`--nx-control-sm/md/lg` 32/38/44) and
71
+ every list row 6px (`--nx-row` 38), so buttons, fields, table rows and headers, menus, dropdown options and the table's
72
+ footer follow at once. Compact, the default, is the sizes the package always had.
73
+
74
+ **Animations** come from one attribute too. `ThemeScript` works out `data-nx-motion` (`reduce` or `full`) from the
75
+ visitor's choice and the system's `prefers-reduced-motion`, and keeps it current when the system setting changes;
76
+ every stylesheet reads that attribute, never the media query. So **On** animates on a machine whose operating system
77
+ has animations turned off, **Off** never animates, and **System** (the default) does what the system says. Popups fade
78
+ in and out, and every popover panel (menus, the table's panels, pickers) fades briefly; nothing waits for a fade.
79
+
80
+ **Scroll bars** have one look everywhere, the design lab's: thin and quiet, with a thumb of the text colour at 22% on
81
+ no track (`Nexus.Base.css` sets `scrollbar-width` and `scrollbar-color` on every element). On Windows, Chrome and Edge
82
+ draw the bar 10px wide and Firefox 8px. Safari has no `scrollbar-color`, so it draws its own thin bar. A component
83
+ that needs another look sets the two properties on its own scroller: the time picker's columns hide the thumb until
84
+ the pointer or the keys are in them. An app overrides the bar the same way, from outside the layers. With forced
85
+ colours on, the system's colours come back.
86
+
87
+ ### How it works
88
+
89
+ - `Nexus.Themes.css` gives each theme its colors once, as `light-dark(light, dark)`; the page's `color-scheme` picks the side.
90
+ - `Nexus.Tokens.css` holds sizes, spacing, and type, and derives hover colors, soft backgrounds, and the focus ring from the palette.
91
+ A solid fill under the pointer is the fill with 12% black mixed in, in light and dark mode alike, so a light label on
92
+ it only gains contrast: a `--nx-primary-solid` or `--nx-danger-solid` whose label reads at rest reads hovered and
93
+ pressed too. `--nx-primary-text` and `--nx-danger-text` are therefore white (or near it) in both modes; a fill that
94
+ needs a dark label is too light to be a solid fill. In a dark theme the darker step moves the fill toward the panel,
95
+ so a fill keeps 2:1 on `--nx-surface` under the pointer as it does at rest.
96
+ - Components use only `--nx-*` variables, so every component follows the theme with no extra code.
97
+ - `npm run check:themes` checks every theme in both modes against WCAG contrast. Run it after changing a color.
98
+
99
+ ### Custom themes
100
+
101
+ A theme is one CSS block. List it for the script and the picker:
102
+
103
+ ```css
104
+ [data-nx-theme="brand"] {
105
+ --nx-primary: light-dark(#0f766e, #2dd4bf); /* the accent as text and lines */
106
+ --nx-primary-solid: light-dark(#0f766e, #0d7a70); /* the accent as a fill behind white text: buttons, checks */
107
+ --nx-primary-text: light-dark(#ffffff, #ffffff); /* light in both modes: hover and pressed darken the fill */
108
+ /* …any other --nx-* color: bg, surface, surface-2, surface-hover, border, border-strong,
109
+ text, text-muted, text-subtle, danger, danger-solid, danger-text, success, warning, info */
110
+ }
111
+ ```
112
+
113
+ Give a solid fill a light label at 4.6:1 or more in both modes, and keep it 2:1 off `--nx-surface` once 12% black is
114
+ mixed in (the pointer's step). A dark label on a light fill reads at rest and loses contrast under the pointer. The
115
+ example's dark fill, `#0d7a70`, holds white at 5.2:1 at rest and 6.8:1 hovered. `npm run check:themes` checks this
116
+ package's own themes, not an app's.
117
+
118
+ ```tsx
119
+ const themes = [...NEXUS_THEMES, { id: "brand", name: "Brand", description: "Our colors" }];
120
+ <ThemeScript themes={themes} defaultTheme="brand" />
121
+ <ThemeSwitcher themes={themes} />
122
+ ```
123
+
124
+ All styles sit in `@layer nexus.*`, so an app's own CSS overrides any token or component style without `!important`.
125
+
126
+ ### Quick preferences
127
+
128
+ Under the theme, the `ThemeSwitcher` panel holds the person's own settings (`PreferencesPicker`, or
129
+ `<ThemeSwitcher preferences={false} />` for the theme alone). Each applies at once to everything on the page, is saved
130
+ on this device, and reaches other open tabs:
131
+
132
+ | Section | Setting | Saved as | Read by |
133
+ |---|---|---|---|
134
+ | Language and region | Interface language: English, नेपाली | `nx-language` | `useUserPreferences().language` |
135
+ | | Calendar: AD, BS | `nx-date-calendar` | every date component (`useDatePreferences`) |
136
+ | Dates and times | Date picker language: English, नेपाली | `nx-date-script` | every date component |
137
+ | | Clock: 12-hour, 24-hour | `nx-time-format` | every time component |
138
+ | | Display date format | `nx-date-format` | every date component |
139
+ | Numbers | Number scale (the core's `ENumberScales`): International 1,234,567, South Asian 12,34,567 | `nx-number-scale` | `useNumberLocale()` |
140
+ | | Thousands separator: 1,200, 1.200 (decimal comma), 1 200, 1200 | `nx-thousands` | `useNumberLocale()` |
141
+ | Tables | Default page size | `nx-page-size` | every `DataTable` and `Crud` |
142
+ | | A row click opens the record | `nx-row-click` | every `DataTable` and `Crud` |
143
+
144
+ - **Numbers:** `useNumberLocale()` turns the two number settings into a locale (`numberLocale(scale, separator)`):
145
+ `en-US` and `en-IN` as they are, any other pair a key such as `"en-IN|.|,"` that `formatNumber`, `parseNumber` and
146
+ `getNumberSymbols` read. A `NumberBox`, a `Slider` and a table's number cells without a `locale` of their own use it;
147
+ a number box rewrites what it shows when the setting changes, so a typed value is never read in the wrong marks.
148
+ - **Tables:** once chosen, the page size and the row click go over what a table names itself (`pageSize`,
149
+ `openOnClick`); a page size picked in a table with a `stateKey` still wins there, and a size the table does not offer
150
+ is not forced on it. Until chosen (`null`), each table keeps its own.
151
+ - **Interface language** is stored and read through `useUserPreferences()`; the package's own words are English for
152
+ now, and it does not set `lang` on `<html>` until they are translated (a screen reader would read English in a Nepali
153
+ voice).
154
+ - `setUserPreferences({ … })` and `readUserPreferences()` (`nexus-shared/client`) change and read them from code, as
155
+ `setDatePreferences` does the date settings.
156
+
157
+ ## Components
158
+
159
+ | Component | Import | Notes |
160
+ |---|---|---|
161
+ | `Button` | `nexus-shared` | Variants `primary`, `secondary`, `ghost`, `danger`; sizes `sm`, `md`, `lg`; `icon`, `iconEnd`, `loading`, `block`; `hoverTone` |
162
+ | `TabButtons` | `nexus-shared/client` | Pick one option; sliding indicator; sizes, `tone="primary"`, `labels="selected"` (icons, label on the selected option), `block`, disabled options; `design="list"` for a vertical list with descriptions and badges; `multiple` to pick several, wrapping onto more rows |
163
+ | `Tabs`, `TabPanel` | `nexus-shared/client` | Tabs that switch panels: a `tablist` in the look of `TabButtons` (`design` `list`, `nav`, or `auto`: the list, a strip in a container under 720px), the chosen tab the only one in the Tab order, arrows, Home and End; `TabPanel` joins the panel to its tab |
164
+ | `SplitButton` | `nexus-shared/client` | A main action with a menu of alternatives; the pick becomes the main button, and `storageKey` remembers it for the next visit |
165
+ | `Menu`, `ContextMenu` | `nexus-shared/client` | A dropdown menu under a button, and a right-click menu: icons, shortcuts, descriptions, `tone="danger"`, links, `kind="radio"` or `"checkbox"` |
166
+ | `Toaster`, `toast` | `nexus-shared/client` | Toast messages from anywhere: `toast.success(title, message)`, `toast.promise`, `toast.loading`, actions, positions; one `<Toaster />` in the layout |
167
+ | `Popup` | `nexus-shared/client` | A modal window on the native dialog, with the buttons of a desktop window: maximize, close, and minimize (a bar at the bottom right, content kept) only when it asks (`minimizable`: a CRUD page's Add, Edit and row forms do); moved by its title bar inside the window; title, description, scrolling body, footer, sizes `xs` to `full`, close reasons |
168
+ | `PopupHost`, `openPopup` | `nexus-shared/client` | Popups opened from code with a handle (`close`, `update`, `minimize`, `maximize`, `restore`, `windowState`, `closed`), one per `key` (replaced or restored); one `<PopupHost />` in the layout, which also shows the minimized popups |
169
+ | `definePopupRules` | `nexus-shared/client` | Rules for popups by key or `prefix-*` pattern, set once: `reopen` (replace or restore), `minimizable`, `maximizable`, `movable`, how it closes, `size`, `defaultWindowState` |
170
+ | `useDraggable`, `makeDraggable`, `startDrag`, `moveWithin`, `clampToBounds` | `nexus-shared/client` | Move any element with the pointer (or the keyboard), kept inside bounds: the window, the parent, an element, or a box; by a handle, along one axis, partly outside; Esc puts it back |
171
+ | `messageBox` | `nexus-shared/client` | `alert`, `confirm`, `prompt`, and `show` with any buttons, each returning a promise |
172
+ | `TextBox` | `nexus-shared/client` | Text input: label designs `standard`, `outlined`, `inbox`; sizes; icons; `prefix`, `suffix`; `clearable`; show password; `showCount`; validation |
173
+ | `TextArea` | `nexus-shared/client` | Multi-line text with the same field features; `autoResize` between `rows` and `maxRows` |
174
+ | `CheckBox`, `Switch` | `nexus-shared/client` | One checkbox or on/off switch: `label`, `description`, `required` (must be checked), `indeterminate`, `readOnly`, `labelPosition` |
175
+ | `CheckBoxGroup` | `nexus-shared/client` | Many choices from `options`: `min`, `max` (disables the rest at the limit), `selectAll`, `columns`, `design="cards"` |
176
+ | `RadioGroup` | `nexus-shared/client` | One choice from `options`: arrow keys, `orientation`, `columns`, `design="cards"`, `design="tabs"` (nav-style tabs, descriptions as tooltips) |
177
+ | `Dropdown` | `nexus-shared/client` | One value, or several with `multiple`, from `options` or server pages (`loadOptions`: search, infinite scroll, loaders, Retry); rows as `columns` like a data table (avatar, image, icon, code, money); saved values the list no longer offers (`selectedOptions`, `resolveOptions`, inactive items) show and cannot be picked again |
178
+ | `Slider`, `RangeSlider` | `nexus-shared/client` | Pick a number or a range: `min`, `max`, `step`, number format with `prefix`/`suffix`, `marks`, `tooltip`, `minDistance`, `onValueCommit` |
179
+ | `NumberBox` | `nexus-shared/client` | Numbers only: `min`, `max`, `decimals`, `fixedDecimals`, `grouping` by `locale`, `prefix`, `suffix`, `stepper`, `clamp`; the same field shell |
180
+ | `DatePicker` | `nexus-shared/client` | Type or pick a date in the English (AD) or Nepali (BS) calendar from the user's settings; `min`, `max`, `isDateDisabled`; the value is always a Gregorian ISO date |
181
+ | `DateRangePicker` | `nexus-shared/client` | A start and an end in one box, picked in a two-month calendar or typed; `startName` and `endName` send two fields; `minDistance`, `maxDistance` in days; booked nights cannot be included |
182
+ | `TimePicker` | `nexus-shared/client` | Type or pick a time on a 12- or 24-hour clock from the user's settings: columns of hours and minutes or `view="list"` slots; `min`, `max` (past midnight too), `step` in seconds, `isTimeDisabled`; the value is always an ISO time |
183
+ | `DateTimePicker` | `nexus-shared/client` | Type or pick a day and a time: each user sees their own local time in their date and time settings, and the value is always the UTC moment; `timeZone` for a place's zone, `min`, `max`, `minTime`, `maxTime`, `step`, `isDateDisabled`, `isTimeDisabled` |
184
+ | `Calendar` | `nexus-shared/client` | The month grid on its own: single or `mode="range"`, `months={2}` side by side, month and year menus, arrow keys, `renderDay` for event markers, `weekStart` |
185
+ | `useDatePreferences`, `setDatePreferences` | `nexus-shared/client` | The user's calendar, format, script, and time format, saved in local storage and followed by every date and time component |
186
+ | `Form` | `nexus-shared/client` | A list of input params (`InputParams[]`) on a 12-column grid (`span`), with the values in a store outside React; `onFieldChange` for derived values, `validate` for rules across inputs, `draftKey` for unsaved changes that survive a reload, `loading` (the inputs disabled until the values land) |
187
+ | `SubmitForm` | `nexus-shared/client` | A `Form` that checks every value on Save and focuses the first problem, then runs `onSubmit` once at a time; a status line with links to what needs attention; Save, Cancel (asks first), Reset; Ctrl+S |
188
+ | `ApiForm` | `nexus-shared/client` | A `SubmitForm` that sends to an API (an endpoint such as `ROOMS.update`, `{ url, method }`, or the app's own client), loads the record first (`loadValue`), and shows the server's messages on their inputs: Nexus responses and ASP.NET Core problem details |
189
+ | `FormButtons` | `nexus-shared/client` | A form's status line and buttons on their own, such as in a popup's footer; `submitTone="danger"` for a save that removes something |
190
+ | `downloadText` | `nexus-shared/client` | Hands the user a file made from text in the browser (a CSV, recovery codes as a `.txt`), read as UTF-8 by Excel and Windows editors |
191
+ | `useForm`, `useFormValue`, `useFormValues`, `useFormStatus` | `nexus-shared/client` | A store for the page to hold, and hooks that render again when a value, any value, or the status changes |
192
+ | `FormStore` | `nexus-shared` | The store and the form's handle: `getValue`, `getChanges`, `set`, `load` (with `keepChanged`), `reset`, `validate`, `setErrors`, `focus`, `submit` |
193
+ | `DataTable`, `useTable` | `nexus-shared/client` | Rows with a search (rows per page inside it), sorting by column, pages, a selection with one split button of actions over the headings, icon buttons and a menu per row, columns the user orders, resizes, pins, and hides, a band of headings over the columns that belong together (`group`), an options menu (filters from `filterInputs`, CSV, print, import), and loading, empty, and failed states; rows given, loaded once, or a page per query from a server; page size, sort, and the columns remembered with `stateKey`; a picked row (`onPick`) for a list beside it, and a `caption` |
194
+ | `TableStore` | `nexus-shared` | The table's state and handle, outside React: `reload`, `upsert`, `patch`, `remove`, `select`, `getSelected`, `pick`, `setSearch`, `setFilters`, `setSort`, `setPage` |
195
+ | `Crud` | `nexus-shared/client` | A module's records in one component: a controller's endpoints, the table's columns, and the form's input params in; the lists (all, flagged, trash, deleted) and actions the user may use, the records the user pinned above the list, Add and Edit popups on `ApiForm`, details, actions on one record or many, and a cache of lists while the page is open; a list narrowed to the record picked in another (`narrow`); a list widened to other endpoints by a switch in its toolbar (`scopes`); row actions that open a form of their own for the record (`rowForms`) |
196
+ | `CrudTree` | `nexus-shared/client` | A controller's records as a lazy tree, with the `Crud`'s own Add and Edit forms and its trash, recover and delete calls: icons on each row, a toolbar Add New, and the picked record's fields and buttons for a panel the page draws; every change written into the tree and its kept pages, nothing read again |
197
+ | `CrudTabFooter` | `nexus-shared/client` | The footer of a tab in a record's workspace: its words and Save in one bar that stays at the bottom of the tab while a long form scrolls, and sits in its place at the end; a plain bar elsewhere |
198
+ | `RecordCards` | `nexus-shared/client` | One record that is not a list (a profile, my company) as a hero and cards of fields, of items with icon actions on the right, and of the page's own; every change in a popup (a form, steps such as a code sent then typed, a confirm), its answer drawn at once, and no Save on the page; loading held, a failed read per card with Try again, read-only, an ended session |
199
+ | `Permissions`, `NexusPermissions`, `definePermissions`, `canCall` | `nexus-shared` | May the user call this endpoint? The app registers its rules once; `NexusPermissions` reads the Nexus backend's access actions. Everything is allowed until then |
200
+ | `CrudBackend`, `NexusCrudBackend`, `defineCrudBackend` | `nexus-shared` | How a CRUD talks to a backend beyond its endpoints: page requests and answers, mass action bodies, flag and pin marks. Nexus's by default |
201
+ | `configureCrud`, `getCrudSettings` | `nexus-shared` | What every CRUD in the app follows: how many records a user may pin (100 by default) |
202
+ | `queryRows`, `filterRequest`, `formatCellText`, `sortRows`, `pageButtons`, `CrudCache`, `crudRowActions` | `nexus-shared` | Pure helpers behind the table and the CRUD: search, filter, sort, and page rows as the table does, the filters in a server's names, a value as its cell writes it, the page buttons, the cache, and which actions a list offers |
203
+ | `readApiResponse`, `readErrorMessages`, `sendApiRequest`, `matchFieldErrors`, `matchInputName`, `formErrorsFromResult` | `nexus-shared` | Pure helpers behind the API form: read an answer as success or failure, every problem it carries as one list, send a URL as it is, match server field names to inputs, and turn a failed answer into what a form shows |
204
+ | `api`, `apiOptionsLoader`, `configureApi` | `nexus-shared/client` | API calls from the browser, through the app's proxy or straight to a module: toasts worded by the message builder, `api.confirm` to ask first, one request for the same GET at once; a dropdown's `loadOptions` from a pagination endpoint |
205
+ | `serverApi`, `configureServerApi`, `createApiProxy` | `nexus-shared/server` | API calls from the server, straight to each module's root, with the user's token and Next.js caching; the proxy route the browser calls |
206
+ | `ApiModules`, `NexusApiModules`, `defineApiModules`, `ApiRegister` | `nexus-shared` | An app's API modules: its own module enum (named once in `ApiRegister`, so endpoints take only those), where each root is, and the proxy on or off. Extend `ApiModules` for another backend |
207
+ | `apiController`, `apiEndpoint`, `unwrapApiResult` | `nexus-shared` | Endpoints defined once by module: a controller's standard actions (`NormalListing`, `Detail/{id}`, `Create`, `Update`, `Delete/{id}`, each list's `lists.trash` and `pages.trash`, …); an answer's result, or an `ApiError` |
208
+ | `messages`, `buildMessage`, `configureMessages` | `nexus-shared` | Every success, failure, reason, loading, question, and button text from one table: "3 rooms deleted.", "You do not have permission to delete Room 204."; reworded all at once |
209
+ | `createApiClient` | `nexus-shared` | The engine behind `api` and `serverApi`, for an API of another shape |
210
+ | `Field` | `nexus-shared` | The frame of every input (label, box, icons, hint or error), for building custom inputs |
211
+ | `QrCodeImage` | `nexus-shared` | Any text as a QR code a phone can scan: one SVG path, black on white in every theme, 9rem wide (`nx-qr`); a server component can render it |
212
+ | `PrintDocument` | `nexus-shared` | A receipt, bill or statement by params (head, stamp, facts, lines, totals, footer) on A5 or an 80 mm roll; printed alone, black on white (`nx-print`) |
213
+ | `DocumentFrame` | `nexus-shared/client` | A whole HTML page a server wrote (a print layout's preview) in a sandboxed `<iframe srcdoc>` where no script runs: a bar with its status line and the page's buttons, slow and failed reads over the last page, `print()` through its handle (`nx-document-frame`) |
214
+ | `encodeQr`, `qrPath` | `nexus-shared` | The encoder behind it, written by hand (byte mode, versions 1 to 40, levels L, M, Q and H), and its modules as one SVG path |
215
+ | `validateText`, `TEXT_PATTERNS` | `nexus-shared` | Pure text validation and common patterns with their messages |
216
+ | `validateCheck`, `validateSelection` | `nexus-shared` | Pure checks for a checkbox and for chosen values (`required`, `min`, `max`) |
217
+ | `validateNumber`, `formatNumber`, `parseNumber` | `nexus-shared` | Pure number validation, and number text in any locale (`roundDecimal`, `stepNumber` too) |
218
+ | `formatDate`, `parseDateText`, `toIsoDate`, `validateDate` | `nexus-shared` | Pure date helpers: ISO dates in and out, either calendar, any format, Devanagari digits; `toCalendar` and `fromCalendar` convert AD and BS |
219
+ | `formatDateRange`, `parseDateRangeText`, `toDateRange`, `validateDateRange` | `nexus-shared` | The same for a range: "2026-09-17 – 2026-09-24" in and out, typed with a dash, an arrow, or "to"; rules on both ends and on the days between |
220
+ | `filterItems`, `matchesSearch`, `indexItems`, `optionKey`, `initials` | `nexus-shared` | Pure helpers behind the dropdown: search every word with or without accents, index items by value, compare ids from APIs and forms, and initials for avatars |
221
+ | `formatTime`, `parseTimeText`, `toIsoTime`, `validateTime` | `nexus-shared` | Pure time helpers: ISO times in and out, 12- or 24-hour formats, Devanagari digits, typed text on either clock; `addMinutes`, `isTimeInRange`, `listTimeSlots` |
222
+ | `toUtcDateTime`, `toLocalDateTime`, `fromLocalDateTime`, `formatDateTime`, `parseDateTimeText`, `validateDateTime` | `nexus-shared` | Pure date-time helpers: UTC values in and out, the date and time a moment shows in any IANA zone (daylight saving included), typed text in both calendars; `describeTimeZone`, `getBrowserTimeZone` |
223
+ | `ThemeScript` | `nexus-shared` | Applies the saved theme, mode, density and animations (and the scale grid in development) before paint; goes in `<head>` |
224
+ | `ThemeSwitcher` | `nexus-shared/client` | Palette button with the theme picker in a popover: mode, theme, density, animations, and the scale grid in development |
225
+ | `ThemePicker` | `nexus-shared/client` | Mode control and theme cards with live previews |
226
+
227
+ ### Tab buttons
228
+
229
+ ```tsx
230
+ import { TabButtons } from "nexus-shared/client";
231
+
232
+ <TabButtons
233
+ aria-label="View"
234
+ value={view}
235
+ onChange={setView}
236
+ options={[
237
+ { value: "grid", label: "Grid", icon: <InlineIcon icon={iconLayoutGrid} /> },
238
+ { value: "list", label: "List", icon: <InlineIcon icon={iconList} /> },
239
+ ]}
240
+ />
241
+ ```
242
+
243
+ - An indicator slides to the selected option. In light mode the track is a soft tint with no frame and the indicator
244
+ is lifted by a shadow; in dark mode the indicator is lighter than the track, with a visible edge. The selected icon
245
+ takes the primary color, so the choice is clear in every theme.
246
+ - `size` (`sm`, `md`, `lg`), `tone="primary"` for a solid primary indicator, `block` to fill the width, `disabled` per option.
247
+ - `labels="selected"`: icons only, and the selected option grows to show its label. Every option needs an icon;
248
+ hidden labels are still read by screen readers and shown as tooltips.
249
+ - `design="list"`: the options stacked as full-width rows, for settings pages and side panels. Each row takes an
250
+ `icon`, a `description` on a second line, and a `badge` (a count) at the end. The selected row is tinted, marked
251
+ by a bar at its start, and its label turns bold; `tone="primary"` tints it with the primary color. ↑ and ↓ move
252
+ the selection. The nav design is the old project's `nav-tabs`, this one its `list-tabs`.
253
+ - `multiple`: several at once. `value` is an array and `onChange` hands back the chosen values in option order.
254
+ Each chosen option is raised as the one choice's indicator is, the options wrap onto more rows when they do not
255
+ fit (never narrower than tall, so single letters line up), and on a touch screen each grows to a medium control's
256
+ height. They are checkboxes: Tab moves between them and Space toggles one.
257
+ - Native radio buttons: arrow keys move the selection, and `name` makes it part of a form. Needs `aria-label` or `aria-labelledby`.
258
+ `form` sets the form the choice belongs to, as in HTML; an id that matches no form keeps a switch that is not a
259
+ value (the Markdown editor's views) out of the form around it.
260
+ - For choosing a value. For switching page panels, use tabs with panels (planned).
261
+
262
+ ### Split button
263
+
264
+ ```tsx
265
+ import { SplitButton } from "nexus-shared/client";
266
+
267
+ <SplitButton storageKey="pull-request" onAction={value => create(value)} options={[
268
+ { value: "create", label: "Create pull request", description: "Open a pull request that is ready for review" },
269
+ { value: "draft", label: "Create draft pull request", description: "Cannot be merged until marked ready for review" },
270
+ ]} />
271
+ ```
272
+
273
+ - The main button runs the chosen action; the arrow opens the alternatives as a radio menu. Picking one makes it the
274
+ main button, and with `storageKey` the browser remembers it (`localStorage`, `nx-split:<key>`), so the next visit
275
+ starts with it. `runOnSelect` also runs the pick at once, for Save / Save and close.
276
+ - `variant`, `size`, `loading`, `disabled`, `block` as `Button`; `type="submit"` with `name` submits a form and sends
277
+ the chosen value; `value` and `onValueChange` for a controlled choice; `align` and `menuLabel` for the menu.
278
+
279
+ ### Menus
280
+
281
+ ```tsx
282
+ import { ContextMenu, Menu } from "nexus-shared/client";
283
+
284
+ <Menu items={[
285
+ { value: "edit", label: "Edit", icon: <InlineIcon icon={iconPencil} />, shortcut: "Ctrl+E" },
286
+ { separator: true },
287
+ { value: "delete", label: "Delete", icon: <InlineIcon icon={iconTrash} />, tone: "danger" },
288
+ ]} onSelect={value => run(value)}>
289
+ <Button iconEnd={<InlineIcon icon={iconChevronDown} />}>Actions</Button>
290
+ </Menu>
291
+
292
+ <ContextMenu items={rowItems} onSelect={value => run(value, row)}>
293
+ <table>…</table>
294
+ </ContextMenu>
295
+ ```
296
+
297
+ - **Native popovers.** The list is a `[popover]` element: it sits above everything, closes with Esc or a click
298
+ outside, and needs no library. It opens under its button (above it when there is no room), lined up with the
299
+ button's `align="start"` or `"end"` edge, and follows the page as it scrolls.
300
+ - **Items are params:** `{ value, label, description?, icon?, shortcut?, tone?: "danger", disabled?, href?, target?, checked?, title? }`,
301
+ plus `{ separator: true }` and `{ heading }`. An item with `href` is a link. The trigger is any element that
302
+ renders a button and passes its props on, such as `Button`.
303
+ - `kind="radio"` or `"checkbox"` adds a check column and `aria-checked`; `closeOnSelect={false}` keeps a checkbox
304
+ menu open while options are toggled.
305
+ - A `disabled` item fades its icon and label, not its `description`: give a switched-off item the reason it is off
306
+ there, and it is read at full strength. Descriptions wrap, even in a menu opened from a cell that does not.
307
+ - **A held item** - `disabled` with a `description` - says that reason when it is pressed (a click, Enter or Space),
308
+ in the note a read-only field and a table's held Add show (`.nx-field-notice`, a `status`), beside the item, and the
309
+ menu stays open; the arrow keys reach it, so the keyboard can press it too. The note goes with the menu. A CRUD's
310
+ locked actions (`rowLock`, `rowActionLock`, a row form's `lock`) are held items.
311
+ - **Keys:** arrows move between items (wrapping, skipping disabled ones without a reason), Home and End jump, a letter jumps to the
312
+ next item starting with it, Enter or Space chooses, Esc closes and returns focus to the button, Tab closes and
313
+ moves on. Focus follows a moving pointer, so the keys carry on from the hovered item.
314
+ - `ContextMenu` opens at the pointer on right-click, or under the focused element on Shift+F10. Its wrapper takes no
315
+ space (`display: contents`), so wrap a table once and note the clicked row in the row's own `onContextMenu`.
316
+ - A menu opens below its button, or above it when it fits only there, or on the side with more room when it fits on
317
+ neither, and is never taller than that room: its items scroll inside it, the scroll bar against the panel's right
318
+ wall. It opens scrolled to the top, and a hovered item never scrolls the list.
319
+ - `placeUnderAnchor`, `placeAtPoint`, and `followAnchor` (`nexus-shared/client`) place custom popovers the same way, and
320
+ `showPanel` opens one with its scroller at the top. A panel (`.nx-popover`) that marks its scrolling part
321
+ `.nx-popover__scroll` is capped to the room it was placed in and gets the scroll bar on its wall; set its padding with
322
+ `--nx-popover-pad`. `usePopoverPanel` is a panel a menu item opens under a button, as the table's Filters and Columns
323
+ open.
324
+
325
+ ### Toast messages
326
+
327
+ ```tsx
328
+ import { Toaster, toast } from "nexus-shared/client";
329
+
330
+ // Once, in the root layout
331
+ <Toaster position="top-right" />
332
+
333
+ // Anywhere: components, services, fetch helpers
334
+ toast.success("Booking confirmed", "Room 204, 3 nights");
335
+ toast.error("Could not save", { message: error.message, action: { label: "Retry", onClick: save } });
336
+ toast.promise(saveBooking(), { loading: "Saving…", success: "Saved", error: e => `Not saved: ${e.message}` });
337
+ ```
338
+
339
+ - `toast(title, options?)`, `toast.info`, `.success`, `.warning`, `.error`, `.loading` (spinner, no timer), and
340
+ `.promise`. Options: `message`, `duration` (default 5000 ms, 0 keeps it; pauses while hovered or focused), `action`,
341
+ `closable`, `icon`, `position`, `onClose`, and `id` to update a toast in place. `toast.dismiss(id?)` closes one or all.
342
+ - Each toast is a native popover of its own, so it sits above open dialogs; the newest is nearest the edge, and at
343
+ most `max` (default 5) show per position. Warnings and errors use `role="alert"`, the rest `role="status"`.
344
+
345
+ ### Popup
346
+
347
+ ```tsx
348
+ import { Popup, definePopupRules, openPopup } from "nexus-shared/client";
349
+
350
+ <Popup open={open} onClose={() => setOpen(false)} title="Edit booking" description="NX-2048 · Room 204"
351
+ footer={<><Button onClick={() => setOpen(false)}>Cancel</Button><Button type="submit" form="booking" variant="primary">Save</Button></>}>
352
+ <form id="booking" onSubmit={save}>…</form>
353
+ </Popup>
354
+
355
+ // From code, with a handle; needs <PopupHost /> in the layout. Never two popups with one key: opening the key again
356
+ // replaces its popup (a fresh one), or with reopen: "restore" brings it back as it was.
357
+ const popup = openPopup({ key: "room-edit-204", reopen: "restore", title: "Room 204", content: <RoomDetails id={204} />, footer: p => <Button onClick={() => p.close()}>Close</Button> });
358
+ popup.minimize(); popup.restore(); popup.maximize();
359
+ await popup.closed;
360
+
361
+ // Rules by key, once, in a client module; options given to openPopup win over them
362
+ definePopupRules({
363
+ "room-new": { reopen: "replace" }, // Add: a fresh form every time (the default)
364
+ "room-edit-*": { reopen: "restore" }, // Edit: back as it was, with what was typed
365
+ "night-report": { minimizable: false, maximizable: false, movable: false },
366
+ });
367
+
368
+ // The page in charge of the window state
369
+ <Popup open={open} windowState={state} onWindowStateChange={setState} … />
370
+ ```
371
+
372
+ - Built on the native `<dialog>` shown modally: above everything, the page behind dimmed and locked (without a layout
373
+ shift), Tab kept inside, focus returned on close. `onClose(reason)` says whether the close button, Esc, the
374
+ backdrop, or code asked; the page decides by setting `open`. `closable`, `closeOnEscape`, `closeOnBackdrop` turn
375
+ those off for a popup that must be answered.
376
+ - `size`: `xs` 360, `sm` 440, `md` 560, `lg` 720, `xl` 960, `full`. The body scrolls while the title and footer
377
+ stay; `flush` removes the body padding for tables. `initialFocus` picks the first focused element (default: the
378
+ first control in the body or footer). The content mounts only while open, so forms start fresh.
379
+ - Popups open other popups and message boxes above themselves; Esc closes the top one.
380
+ - A **title bar** like a desktop window's: 32px high (40px on touch screens), the icon, the title, and the description
381
+ on one line (cut with …), and the window buttons filling its top right corner, 46 x 32 each: **minimize** (only when it asks),
382
+ **maximize** (restore down when maximized), **close** (red on hover). `variant="dialog"` gives the larger heading
383
+ instead (the icon in a circle, the description under the title), which message boxes use. `minimizable` (default false: a popup has no minimize button unless it asks; a CRUD page's Add and Edit forms and its row forms ask, and a page's rule for their key may still say no; message boxes, viewers, galleries, histories, imports, record cards and the rest do not),
384
+ `maximizable` and `movable` (default true); message boxes have only close.
385
+ - **Minimized**, the dialog closes so the page can be used, and a bar waits at the bottom right with the popup's icon and
386
+ title; its content stays mounted, so typed text, scroll, and the focused field are there when the bar brings it back
387
+ (maximized again if it was). Several stack behind the newest with a count that opens the whole list (Esc or a press
388
+ elsewhere closes it). An open popup's backdrop covers the dock. `<PopupHost />` renders the dock; without a host
389
+ there is no minimize button. Bottom-right toasts stack above it (`--nx-dock-space`).
390
+ - **Maximized**, it fills the window edge to edge; a double-click on the title bar does the same, and restore down puts
391
+ it back where it was.
392
+ - **Moved** by its title bar (not its buttons), kept inside the window, pulled back in when the window shrinks; Esc
393
+ during a drag puts it back; dragging a maximized popup restores it under the pointer, as desktop windows do. Each
394
+ opening starts centered in `defaultWindowState`.
395
+ - **Opened again** while it is still open or minimized, a popup never doubles up. `openPopup` with a `key` whose popup
396
+ is there closes that popup (`onClose` and `closed` say `replaced`) and opens a fresh one: `reopen: "replace"`, the
397
+ default, right for an Add form, so Add, minimize, Add again cannot pile up popups. `reopen: "restore"` brings the
398
+ old one back as it was and returns its handle, right for editing one record. A page popup opens again through the
399
+ button that opened it, with the same `reopen` choice. Popups without a key are separate every time.
400
+ - **Asking before a close**: `openPopup({ beforeClose })` runs when the user closes the popup (its close button, Esc,
401
+ the backdrop, or its bar on the dock); return `false`, or a promise of it, to keep it open, such as after
402
+ `confirmDiscard(form)` asked "Discard your changes?". Closing from code does not ask.
403
+ - **Rules by key**: `definePopupRules({ "booking-new": {…}, "booking-edit-*": {…} })` sets `reopen`, `minimizable`,
404
+ `maximizable`, `movable`, `closable`, `closeOnEscape`, `closeOnBackdrop`, `size`, and `defaultWindowState` for every
405
+ `openPopup` with that key. A name ending in `*` matches keys that start with the rest (`*` alone, every key); all
406
+ matching rules apply, an exact key over a pattern and a longer pattern over a shorter one; options given to
407
+ `openPopup` win. It returns a function that removes the rules; `popupRuleFor(key)` shows what a key gets.
408
+ - With motion, minimize flies to the dock and maximize grows from the old box; with reduced motion, both happen in the
409
+ same frame.
410
+
411
+ ### Drag helpers
412
+
413
+ ```tsx
414
+ import { clampToBounds, makeDraggable, moveWithin, useDraggable, viewportBounds } from "nexus-shared/client";
415
+
416
+ useDraggable(cardRef, { bounds: "parent" }); // the card moves, kept inside its positioned parent
417
+ useDraggable(barRef, { target: () => cardRef.current, bounds: "parent", axis: "x", keepVisible: 40 });
418
+ const stop = makeDraggable(titleBar, { target: panel, bounds: document.querySelector(".board") }); // without React
419
+ moveWithin(card, { x: 10, y: 0 }, { bounds: "parent" }); // the keyboard way
420
+ clampToBounds({ left: -20, top: 40, width: 300, height: 200 }, viewportBounds()); // { x: 0, y: 40 }
421
+ ```
422
+
423
+ - The popup's title bar is built on these; any component can use them. `bounds`: `viewport` (default), `parent`,
424
+ an element (inside its borders), a box, a function, or `null`. `margin`, `keepVisible` (how much must stay
425
+ inside when it may partly leave), `axis`, `threshold` (default 3 px, so clicks stay clicks), `cancel` (controls in
426
+ the handle that do not drag).
427
+ - The position is an offset from the element's place in the layout, written to CSS `translate` by default, or to CSS
428
+ variables (`cssVariablePosition`), or anywhere through `position: { get, set }`, so a move never shifts the layout.
429
+ - `onStart` may cancel or change the target first; `onEnd` says whether Esc cancelled. A drag selects no text, and
430
+ the click that ends it does not reach what lies under the pointer. The handle needs `touch-action: none`
431
+ (`makeDraggable` and `useDraggable` set it).
432
+
433
+ ### Message box
434
+
435
+ ```tsx
436
+ import { messageBox } from "nexus-shared/client";
437
+
438
+ if (await messageBox.confirm({ title: "Delete booking NX-2048?", message: "This cannot be undone.", tone: "danger", confirmLabel: "Delete" })) …
439
+ await messageBox.alert({ title: "Saved", tone: "success" });
440
+ const name = await messageBox.prompt({ title: "Rename the room", label: "Name", defaultValue: room.name });
441
+ const choice = await messageBox.show({ title: "Unsaved changes", tone: "warning", buttons: [{ value: "discard", label: "Don't save" }, { value: "save", label: "Save" }] });
442
+ ```
443
+
444
+ - Small popups through `<PopupHost />`, the tone in the icon: `info` (alert default), `question` (confirm default),
445
+ `success`, `warning`, `danger`, or `neutral` for none. A danger box makes the last button red and focuses the first
446
+ one, so Enter cannot delete by accident.
447
+ - `confirm` resolves `false` and `show` resolves `null` when the box is dismissed with Esc, the close button, or a
448
+ click outside; `prompt` resolves `null` when cancelled and refuses an empty answer while `required` (the default).
449
+ - `details` puts what the question is about after the message, in the normal text colour (the message is muted), and
450
+ scrolls with the body while the buttons stay: `details: <CrudDetails row={order} columns={ORDER_COLUMNS} />` with a
451
+ `size` of `lg` or `xl`. `closeOnBackdrop: false` keeps a box with much to read open through a stray click (Esc and ×
452
+ still dismiss it, and the focus stays where it was); `signal` dismisses it when the page or form that asked goes.
453
+
454
+ ### Button hover tones
455
+
456
+ `hoverTone` keeps a `secondary` or `ghost` button neutral until it is hovered or focused from the keyboard, then
457
+ colors its border, a light background, and its text. Tones: `primary`, `danger`, `success`, `warning`, `info`.
458
+ Good for rows of actions, where full-color buttons would be too loud:
459
+
460
+ ```tsx
461
+ <Button hoverTone="danger" icon={<InlineIcon icon={iconTrash} />}>Delete</Button>
462
+ <Button variant="ghost" size="sm" hoverTone="primary" aria-label="Edit" icon={<InlineIcon icon={iconPencil} />} />
463
+ ```
464
+
465
+ Every tone meets WCAG AA contrast on its light background in all themes.
466
+
467
+ ### Text box
468
+
469
+ ```tsx
470
+ import { TEXT_PATTERNS } from "nexus-shared";
471
+ import { TextBox, TextArea } from "nexus-shared/client";
472
+
473
+ <form onSubmit={save}>
474
+ <TextBox name="email" type="email" label="Email" required pattern={TEXT_PATTERNS.email} icon={<InlineIcon icon={iconMail} />} />
475
+ <TextBox name="password" type="password" label="Password" required minLength={8} />
476
+ <TextArea name="notes" label="Notes" maxLength={500} showCount autoResize />
477
+ <TextArea name="html" label="Layout HTML" rows={18} code />
478
+ <Button type="submit" variant="primary">Save</Button>
479
+ </form>
480
+ ```
481
+
482
+ - **Uncontrolled by default**, so typing re-renders nothing. `onValueChange(value)` reports each change; `value` makes it controlled.
483
+ - **Code text: `TextArea code`** (in a form's inputs, `{ type: EInputTypes.TextArea, code: true }`). HTML or JSON in the
484
+ monospace font, lines kept as typed (`wrap="off"`: a long line scrolls sideways inside the box), a tab two spaces
485
+ wide, and no spellcheck, capitals, corrections, suggestions or translation. Tab still leaves the box, so a keyboard
486
+ is never trapped in it; read-only and disabled code keep the look.
487
+ - **Validation:** `required`, `minLength`, `maxLength`, `pattern` (a `TEXT_PATTERNS` entry carries its own message), and
488
+ `validate(value)` for custom rules. Messages show after a field is left with text in it (`validateOn`: `blur`, `change`,
489
+ `submit`). Inside a `<form>`, an invalid field blocks submit, every message shows, and the first invalid field takes focus.
490
+ `error` shows a message from outside, such as the server. `invalid` (on `Field` and `Dropdown`) draws the invalid look
491
+ with no message line, for a field the page says why about elsewhere: point its `aria-describedby` at those words.
492
+ - **Read-only says why.** Every input with `readOnly` shows a lock, and a short note for 2.5 seconds when someone tries
493
+ to change it anyway, so a click that does nothing does not look like a bug. The value is still sent with a form, and
494
+ selecting and copying text work as usual. Esc, leaving the field, or the timeout hide the note; `readOnlyMessage`
495
+ changes its text.
496
+
497
+ | Input | Lock | Tries that show the note | Default note |
498
+ |---|---|---|---|
499
+ | `TextBox`, `TextArea` | End of the box | A click, typing, Backspace, Delete, Ctrl+V, Ctrl+X (and Enter in a text area) | Read-only: this field cannot be changed. |
500
+ | `NumberBox` | In place of the − and + buttons | The same, and ↑ ↓ Page Up Page Down | Read-only: this number cannot be changed. |
501
+ | `DatePicker`, `DateRangePicker` | In place of the calendar button | The same as a text box, and ↓ | Read-only: this date (these dates) cannot be changed. |
502
+ | `TimePicker` | In place of the clock button | The same as a text box, and ↓ | Read-only: this time cannot be changed. |
503
+ | `DateTimePicker` | In place of the calendar and clock button | The same as a text box, and ↓ | Read-only: this date and time cannot be changed. |
504
+ | `Dropdown` | In place of the list button; chips lose their remove buttons | A click on the box or a chip, a typed key, ↓ or ↑ | Read-only: this choice (these choices) cannot be changed. |
505
+ | `CheckBox`, `Switch` | After the label | A click or Space | Read-only: this option (this setting) cannot be changed. |
506
+ | `CheckBoxGroup`, `RadioGroup` | After the group label | A click, Space, or an arrow key, under that option | Read-only: these options (this choice) cannot be changed. |
507
+ | `Slider`, `RangeSlider` | After the label | A press on the track or a mark, the arrow keys, Page Up/Down, Home, End | Read-only: this value (this range) cannot be changed. |
508
+
509
+ Nothing renders until an attempt, and an attempt re-renders only the note, so read-only forms of any size cost
510
+ nothing extra. `useReadOnlyNotice` gives a custom control the same lock and note.
511
+ - **Props are params:** plain, named like HTML attributes, and serializable, so forms and CRUD pages can describe
512
+ fields as objects. Design notes for inputs, forms, and CRUD: [src/Components/Inputs/README.md](src/Components/Inputs/README.md).
513
+
514
+ ### Number box
515
+
516
+ ```tsx
517
+ import { NumberBox } from "nexus-shared/client";
518
+
519
+ <NumberBox name="nights" label="Nights" stepper="split" required min={1} max={30} defaultValue={1} />
520
+ <NumberBox name="rate" label="Rate per night" prefix="Rs" required min={500} decimals={2} fixedDecimals grouping locale="en-IN" />
521
+ <NumberBox name="discount" label="Discount" suffix="%" stepper min={0} max={50} step={5} />
522
+ ```
523
+
524
+ - **Only a number gets in.** Typing accepts digits, one decimal separator, and a minus sign when `min` is below 0 (or
525
+ not set). `decimals` stops typing after that many decimals; pasted text such as "Rs 1,250.50" keeps its number, and
526
+ text with no single clear number is ignored rather than guessed at.
527
+ - **Formats by locale:** `grouping` shows 12,50,000.00 (`en-IN`) or 1.250.000,00 (`de-DE`) while the box is not
528
+ being edited; separators come off on focus. Without a `locale`, the box follows the person's Number scale and
529
+ Thousands separator (`useNumberLocale`, see Quick preferences), which is `en-US` until they choose, so the server
530
+ renders that and the browser takes the saved choice right after hydration.
531
+ Inside a `<form>`, a grouped box sends the plain number through a hidden input with its `name`.
532
+ - **Steps:** ↑ and ↓ (Shift or Page Up/Down for ten), and `stepper` buttons that repeat while held. Values move along
533
+ the grid of `step` from `min` and stay within the limits.
534
+ - **Values:** `onValueChange(value)` gets a `number`, or `null` when empty; `validate(value)` too. `clamp` moves an
535
+ out-of-range value to the nearest limit on blur instead of showing a message.
536
+ - `npm run test:numbers` checks the number helpers (formatting, parsing, paste, rounding, stepping, messages).
537
+
538
+ ### Checkbox and radio
539
+
540
+ ```tsx
541
+ import { CheckBox, CheckBoxGroup, RadioGroup, Switch } from "nexus-shared/client";
542
+
543
+ <RadioGroup name="roomType" label="Room type" required design="cards" columns={3} options={roomTypes} />
544
+ <CheckBoxGroup name="amenityIds" label="Amenities" columns={3} selectAll options={amenities.map(a => ({ value: a.id, label: a.name }))} />
545
+ <Switch name="breakfast" label="Breakfast included" labelPosition="start" />
546
+ <CheckBox name="terms" label="I accept the booking terms" required />
547
+ ```
548
+
549
+ - **Native inputs, drawn with CSS.** Each option is one `<input>`, so forms, arrow keys (radios), and screen readers
550
+ work as usual. Box edges use the subtle text color, which meets 3:1 contrast on panels in every theme.
551
+ - **Options are params:** `{ value, label, description?, icon?, disabled? }`. Values can be strings or numbers and
552
+ come back from `onValueChange` with their type.
553
+ - **Limits:** `required`, `min`, `max`, `validate`. At `max` a checkbox group disables the other options and shows a
554
+ count. Messages follow the text box: after leaving a changed group, or on submit, where the first invalid option takes focus.
555
+ - **Fast:** uncontrolled by default, so clicking re-renders nothing; 10,000 checkboxes mount in 0.5 to 0.7 s
556
+ in the development build.
557
+
558
+ **A choice drawn as tabs.** `<RadioGroup design="tabs" />` (or `design: "tabs"` in its params) draws the options as
559
+ nav-style tabs on one `TabButtons` track - still a radio group: arrow keys, `required`, read-only and disabled work as
560
+ in the other designs, and the tabs wrap on a phone. Each option's `description` is its tooltip and what a screen reader
561
+ hears with it; the chosen one's shows under the track.
562
+
563
+ ```tsx
564
+ { type: EInputTypes.RadioGroup, name: "counterType", label: "What is it?", required: true, design: "tabs", options: [
565
+ { value: 0, label: "Payment", description: "Renew: the dates move, the money is taken now." },
566
+ { value: 1, label: "Activate", description: "Switch the service on for a time, with no money." },
567
+ ] }
568
+ ```
569
+
570
+ ### Slider
571
+
572
+ ```tsx
573
+ import { RangeSlider, Slider } from "nexus-shared/client";
574
+
575
+ <Slider name="discount" label="Discount" max={50} suffix="%" defaultValue={10} />
576
+ <RangeSlider name="price" label="Price per night" min={1000} max={30000} step={500} minDistance={1000}
577
+ prefix="Rs " grouping locale="en-IN" onValueCommit={([from, to]) => loadRooms(from, to)} />
578
+ ```
579
+
580
+ - **Native range inputs** under a drawn track, so arrow keys, Page Up/Down, Home/End, touch, and screen readers work.
581
+ Each thumb announces its formatted value (`aria-valuetext`).
582
+ - **Values read like a number box:** `prefix`, `suffix`, `decimals`, `grouping`, `locale`, or a `format` function.
583
+ - **`onValueChange`** follows every step; **`onValueCommit`** fires once when a thumb is released or a key step ends,
584
+ the moment to call an API from a filter.
585
+ - **Range:** two thumbs that never cross and keep `minDistance` apart; a click on the track moves the nearer thumb.
586
+ A form receives two values under the name.
587
+ - **Marks** label points under the track and move the thumb when clicked; **`tooltip`** shows the value above the thumb.
588
+ - Dragging writes the fill and the text straight to the DOM, so nothing re-renders.
589
+
590
+ ### Date picker and date range picker
591
+
592
+ ```tsx
593
+ import { todayIsoDate } from "nexus-shared";
594
+ import { Calendar, DatePicker, DateRangePicker, setDatePreferences } from "nexus-shared/client";
595
+
596
+ <DatePicker name="checkIn" label="Check-in" required min={todayIsoDate()} onValueChange={iso => …} />
597
+ <DatePicker name="fiscalYearStart" label="Fiscal year start" calendar="bs" format="YYYY/MM/DD" />
598
+ <DateRangePicker startName="checkIn" endName="checkOut" label="Stay" required min={todayIsoDate()} minDistance={1} maxDistance={30} />
599
+ <Calendar mode="range" months={2} range={range} onRangeChange={setRange} min={todayIsoDate()} />
600
+
601
+ // A settings page
602
+ setDatePreferences({ calendar: "bs", format: "D MMMM YYYY", script: "devanagari" });
603
+ ```
604
+
605
+ - **The value is a day, not a time.** An ISO date `"2026-09-17"` in the Gregorian calendar, whatever calendar is
606
+ shown: what a form sends (through a hidden input with the field's `name`), what an API stores (`DateOnly`), and
607
+ what means the same day in every time zone. `toIsoDate` reads a `Date` in local time and an ISO date-time with a
608
+ zone as the local day of that instant; `isoDateToDate(iso)` gives UTC midnight, `isoDateToDate(iso, "local")` local midnight.
609
+ - **English or Nepali from the user's settings.** `useDatePreferences` reads `nx-date-calendar` (`ad` or `bs`),
610
+ `nx-date-format`, and `nx-date-script` (`latin` or `devanagari`) from local storage, with the English calendar in
611
+ `YYYY-MM-DD` as the default; `setDatePreferences` changes every date component on the page, and other tabs follow.
612
+ A box can fix its own `calendar`, `format`, or `script`.
613
+ - **Formats** use the tokens `YYYY` `YY` `MMMM` `MMM` `MM` `M` `DD` `D` `dddd` `ddd`. Typing follows the format's
614
+ order and is lenient: `17/9/2026`, `Sep 17, 2026`, `1 asoj 2083`, `२०८३-०६-०१`; a four-digit number is the year wherever it stands.
615
+ - **Bikram Sambat** covers BS 1975 to 2100 (AD 1918 to 2044), as the majority of five published tables
616
+ (`NepaliCalendar.ts`), converted through day numbers with no `Date` objects. `npm run test:dates` checks known
617
+ dates and round-trips every day.
618
+ - **DateRangePicker** holds a start and an end in one box, written as "2026-09-17 – 2026-09-24" in the user's
619
+ format. Pick the start and then the end in a calendar of two months (one when the window is narrow), with the
620
+ days between lit as the pointer moves, or type both dates around a dash, an arrow, or "to". The values are two
621
+ ISO dates: `onValueChange` gives `[start, end]` (`null` for an end not chosen yet), and a form sends `startName`
622
+ and `endName` as two fields, or both under `name`. Rules: `required`, `min`, `max`, `minDistance` and
623
+ `maxDistance` (days from start to end, the nights of a stay), and `isDateDisabled`, which also refuses a range
624
+ that includes such a day (a booked night). `validateDateRange` is the pure check behind it.
625
+ - **Read-only** boxes have no calendar: a lock sits where the calendar button was, and a click, a typed key, or ↓
626
+ shows a note under the box, as in every read-only input (see [Text box](#text-box)).
627
+ - **Calendar** is the pickers' panel and a component of its own: month and year menus, arrow keys (Page Up and Page
628
+ Down for months, with Shift for years), `min`, `max`, `isDateDisabled`, `weekStart`, `weekendDays` (Saturday is
629
+ red in the Nepali calendar), `mode="range"` with a live preview, `months={2}` side by side (a page passes 1 on
630
+ a phone; the calendar does not measure), `month` and `onMonthChange` to load a month's events, and `renderDay`
631
+ to draw markers in a cell.
632
+
633
+ ### Time picker
634
+
635
+ ```tsx
636
+ import { TimePicker, setDatePreferences } from "nexus-shared/client";
637
+
638
+ <TimePicker name="arrival" label="Arrival" required min="14:00" max="22:00" step={1800} view="list" onValueChange={iso => …} />
639
+ <TimePicker name="shiftStart" label="Shift start" min="22:00" max="06:00" format="HH:mm" />
640
+ <TimePicker name="spa" label="Spa slot" view="list" step={1800} isTimeDisabled={iso => booked.has(iso)} />
641
+
642
+ // A settings page
643
+ setDatePreferences({ timeFormat: "HH:mm" });
644
+ ```
645
+
646
+ - **The value is a time of day, not an instant.** An ISO time on a 24-hour clock, `"14:30"` (`"14:30:15"` when
647
+ `step` has seconds), with no date and no zone: what a form sends through a hidden input with the field's `name`,
648
+ and what a .NET `TimeOnly` stores. `toIsoTime` reads `"9:05"`, `"14:30:00.000"`, a `Date` (its local time), and an
649
+ ISO date-time (with a zone, the local time of that instant; without one, its time part).
650
+ - **12 or 24 hours from the user's settings.** `nx-time-format` in local storage, next to the date settings, holds
651
+ a format of tokens `HH` `H` `hh` `h` `mm` `m` `ss` `s` `A` `a`; the default is `hh:mm A` (02:30 PM).
652
+ `useDatePreferences` returns it as `timeFormat`, and `setDatePreferences({ timeFormat })` changes every time picker
653
+ on the page. Nepali dates in Devanagari bring Nepali digits and पूर्वाह्न/अपराह्न. A box can fix its own `format` or `script`.
654
+ - **Typing** works on either clock: `2:30 pm`, `2.30p`, `230pm`, `14:30`, `1430`, `9`, `१४:३०`. Without AM or PM the
655
+ hours are read on a 24-hour clock. Leaving the box writes the time in the format.
656
+ - **Columns** (the default) show hours, minutes, seconds when the step needs them, and AM/PM; the chosen items line
657
+ up on the middle row, a pick in any column changes the time at once, and ↑ ↓ ← → Home End Page Up/Down move through
658
+ them. **`view="list"`** shows one slot per `step` (every 30 minutes for steps under 5 minutes); a click or Enter
659
+ picks and closes.
660
+ - **Rules:** `required`, `min` and `max` (with `max` earlier than `min` the range runs past midnight, 22:00 to 06:00),
661
+ `step` in seconds counted from midnight as in HTML, `isTimeDisabled` for booked slots, and `validate`. Items outside
662
+ the rules are dimmed in the panel; a typed time outside them gets a message such as "Arrival must be in steps of 30
663
+ minutes, like 02:00 PM or 02:30 PM." `validateTime` is the pure check behind it. `npm run test:times` checks the helpers.
664
+ - **Read-only** boxes have no panel: a lock sits where the clock button was, as in every read-only input.
665
+
666
+ ### Date and time picker
667
+
668
+ ```tsx
669
+ import { DateTimePicker } from "nexus-shared/client";
670
+
671
+ <DateTimePicker name="pickupAt" label="Airport pickup" required min={new Date()} step={900} minTime="05:00" maxTime="23:00" />
672
+ <DateTimePicker name="checkInAt" label="Check-in" timeZone="Asia/Kathmandu" defaultTime="14:00" />
673
+ <DateTimePicker name="spaAt" label="Spa slot" view="list" step={1800} isTimeDisabled={(time, date) => booked.has(`${date} ${time}`)} />
674
+ ```
675
+
676
+ - **The value is a moment, in UTC.** `"2026-09-17T08:45:00.000Z"`, the shape `toISOString` writes, is what the hidden
677
+ input sends and `onValueChange` gives, whatever the user sees; the same moment is 02:30 PM in Kathmandu and 04:45 AM
678
+ in New York, so no time zone can move a saved value. Store it as UTC: a .NET `DateTimeOffset`, or a `DateTime` of
679
+ kind `Utc`. For a day with no time use `DatePicker`; for a time of day with no date, `TimePicker`.
680
+ - **Values in** (`toUtcDateTime`): an ISO date-time with `Z` or an offset is that moment; one **without a zone is read
681
+ as UTC**, the way a UTC `DateTime` loaded from a database often arrives without its `Z`; a date alone is the first
682
+ moment of that day where the user is; a `Date` or milliseconds are that moment. .NET's seven digits of fractions are read.
683
+ - **Shown in the user's zone and settings.** The browser's time zone, and the date (`nx-date-calendar`,
684
+ `nx-date-format`, `nx-date-script`) and time (`nx-time-format`) settings of the other pickers: "2026-09-17 02:30 PM",
685
+ or "२०८३-०६-०१ ०२:३० अपराह्न". The panel names the zone ("Kathmandu · UTC+05:45"). `timeZone` fixes a zone, such as a
686
+ hotel's, and writes its city in the box. The server does not know the user's zone, so a box shows its text right
687
+ after hydration rather than another zone's time for a moment; the hidden input holds the value from the start.
688
+ - **No data loss.** A value changes only when the user changes what it shows: seconds and milliseconds the box does not
689
+ show stay as they came (a stamp from the server is sent back exactly), and retyping or re-picking what it shows keeps
690
+ the moment. Where clocks go back, one hour happens twice: a box holds whichever it was given, an edit inside that hour
691
+ keeps its offset, and a new pick is the first of the two. Where clocks go forward, a skipped time moves on (02:30
692
+ becomes 03:30), as `Date` and Temporal do.
693
+ - **Typing:** a date in the user's format, then a time on either clock: `2026-09-17 2:30 pm`, `17/09/2026 14:30`,
694
+ `Sep 17, 2026 at 2:30 PM`, `2026-09-17T14:30`, `२०८३-०६-०१ १४:३०`. A date alone takes `defaultTime` (default
695
+ `minTime`, or midnight). Leaving the box writes it in the settings.
696
+ - **The panel** is the calendar and the time columns (or `view="list"` slots) side by side, as tall as each other, with
697
+ Now, the zone, and Done. A picked day keeps the time; ↓ opens it on the chosen day, Enter on a day moves on to the
698
+ hours, and Tab runs through the calendar, the columns, and the buttons. On a phone the time goes under the calendar,
699
+ and a panel taller than the room scrolls, moving to the time once a day is picked.
700
+ - **Rules:** `required`; `min` and `max` as moments (days outside are dimmed, and times outside on the first and last
701
+ day); `minTime` and `maxTime` as opening hours on every day (past midnight when `maxTime` is earlier); `step` in
702
+ seconds from each midnight; `isDateDisabled(date)` and `isTimeDisabled(time, date)` with ISO dates and times where the
703
+ user is; `validate`. Messages read like the box: "Airport pickup must be between 05:00 AM and 11:00 PM."
704
+ `validateDateTime(value, rules, fieldName, options)` is the pure check. `npm run test:datetimes` checks the helpers
705
+ against `Date` in eight zones, including half-hour daylight saving and a skipped day.
706
+ - **Read-only** boxes have no panel: a lock sits where the button was, as in every read-only input.
707
+
708
+ ### Dropdown
709
+
710
+ ```tsx
711
+ import { Dropdown } from "nexus-shared/client";
712
+
713
+ <Dropdown name="roomType" label="Room type" required options={roomTypes} />
714
+ <Dropdown name="amenities" label="Amenities" multiple max={6} options={amenities} /> // { value, label, icon: "wifi" }
715
+
716
+ // Rows like a data table
717
+ <Dropdown name="assignee" label="Assign to" options={staff} valueKey="id" labelKey="fullName"
718
+ columns={[{ key: "photo", type: "avatar" }, { key: "username", header: "Username" }, { key: "fullName", header: "Full name" }]} />
719
+ <Dropdown name="country" label="Country" options={countries} valueKey="code" labelKey="name"
720
+ columns={[{ key: "flag", type: "image" }, { key: "code", header: "Code", type: "code" }, { key: "name", header: "Country" }]} />
721
+
722
+ // A server list, editing a saved value
723
+ <Dropdown name="guestId" label="Guest" valueKey="id" labelKey="fullName" defaultValue={booking.guestId} selectedOptions={[booking.guest]}
724
+ loadOptions={({ search, skip, pageSize, signal }) => api.guests({ search, skip, take: pageSize }, signal)} /> // { items, total }
725
+ ```
726
+
727
+ - **Options are any objects.** `{ value, label, description, icon, disabled }` by default (a `ChoiceOption`), or API rows
728
+ read through `valueKey`, `labelKey`, `descriptionKey`, and `iconKey`. Values keep their type; a number and its text
729
+ are the same value, so id 7 from an API matches "7" from a form. A form gets hidden inputs named `name`, one per value.
730
+ - **Columns** turn rows into cells that line up down the list (one grid with subgrid rows), with headings that stay on top.
731
+ Types: `text`, `muted`, `code`, `avatar` (a photo URL, or initials of the label on a soft tone), `image` (4:3: flags,
732
+ logos), `icon` (a Tabler name), and `money` (a figure with 2 places in the person's number format, at the end of its
733
+ column in even digits: a fee's price beside its name); `width`, `align`, and `render` for the rest. The first
734
+ picture leads the value in the box and in chips.
735
+ - **Search** matches every typed word in any order, with or without Latin accents, in the label, description, value, and
736
+ text columns (`searchKeys` to change). It is on with `loadOptions` or more than 8 options; without it, letters jump to
737
+ an option as in a native select. A local list renders 100 rows and adds more while it scrolls: 10,000 options open in
738
+ about 30 ms.
739
+ - **Server pages:** `loadOptions({ search, page, pageSize, skip, signal })` returns `{ items, total?, hasMore? }`. The first
740
+ page loads when the list opens (placeholder rows, a spinner in the box), the next near the end ("Loading more…"), a new
741
+ search 250 ms after typing stops, aborting the request before it. A failure shows Retry. `loadKey` drops the loaded
742
+ pages, for a list that depends on another field. `loading` shows the same loaders when the page fetches `options` itself.
743
+ - **Saved values the list can no longer offer** always show, and are never offered again once removed:
744
+ - on a server page not loaded: `selectedOptions` gives their items (a record usually carries the name),
745
+ `peekOption(key)` gives one the page already holds while it is fresh (no call; `crudPicker` gives it), or
746
+ `resolveOptions(values)` looks them up (a placeholder shows until it answers) - one the page marked old too;
747
+ - inactive items (`inactive: true` or `isActive: false`, or `isOptionInactive`): never in the list, shown only as a value;
748
+ - values missing from `options`: tagged **Unavailable**, or **Not found** when nothing is known but the value.
749
+
750
+ In the list they sit on top under **Selected** with their tag; in the box they carry the tag, or show as dashed chips.
751
+ A value only on another server page has no tag: a search finds it as a normal option.
752
+ - **Rules:** `required`, `min` and `max` for several (at `max` the other options are disabled), and `validate`, through
753
+ `validateSelection`. A pick follows the same message timing as typing. `npm run test:dropdown` checks the helpers.
754
+ - **Keys:** ↓ ↑ Page Up/Down Home End move past rows that cannot be picked, Enter picks, Space picks without search,
755
+ Backspace in an empty box removes the last value, Esc closes (then clears the search), Tab closes and moves on.
756
+ - **Read-only** boxes have no list: a lock sits where the list button was, chips lose their remove buttons, and a click or
757
+ a key shows the note, as in every read-only input.
758
+
759
+ ### Markdown editor
760
+
761
+ ```tsx
762
+ import { MarkdownView } from "nexus-shared";
763
+ import { MarkdownEditor } from "nexus-shared/client";
764
+
765
+ <MarkdownEditor name="description" label="Room description" defaultValue={room.description} defaultMode="split"
766
+ height={320} heightKey="room-description" maxLength={5000} required />
767
+
768
+ // Wherever the text is shown, also in a server component
769
+ <MarkdownView value={room.description} />
770
+ ```
771
+
772
+ - **Write, split, and preview.** `defaultMode` (or `mode` with `onModeChange`) picks the view, and `modes` the views
773
+ offered. The switch is small tab buttons with `labels="selected"`: icons, and the label of the selected view. Split puts the preview beside the text and keeps the two scrolled together; under 560 px wide it stacks
774
+ them. The preview renders as a React transition, so typing stays within a frame in a 2,000-line document.
775
+ - **Toolbar and shortcuts:** heading, bold (Ctrl+B), italic (Ctrl+I), strikethrough (Ctrl+Shift+X), quote
776
+ (Ctrl+Shift+.), code (Ctrl+E), code block, link (Ctrl+K), image, bulleted, numbered, and task lists (Ctrl+Shift+8,
777
+ 7, L), table, and horizontal line. Marks wrap the selection or the word at the caret and come off when applied
778
+ again. Edits go through the browser's own editing, so Ctrl+Z undoes them. `toolbar` picks and orders the buttons.
779
+ - **While typing:** Enter continues a list (the next number, an empty task box) and ends it on an empty item; a URL
780
+ pasted over selected text links it; a task ticked in the preview is ticked in the text.
781
+ - **Height handle:** the status bar under the editor drags the height between `minHeight` and `maxHeight`, showing
782
+ the height as it changes; its grip takes ↑ ↓ (Shift for more), Page Up/Down, Home, and End; a double-click goes back
783
+ to `height`. `heightKey` remembers the user's height in local storage. Dragging writes straight to the DOM.
784
+ - **Full screen** (`fullscreen`, on by default) lifts the editor into the top layer over a dimmed page, without
785
+ moving it in the DOM, so undo history and the form stay. Tab stays inside, and Esc closes it.
786
+ - **A form field like `TextArea`:** `name`, `required`, `minLength`, `maxLength`, `pattern`, `validate`, the status bar's
787
+ word and character count, and read-only (a lock in the bar and a note under it). An invalid submit while the preview
788
+ shows brings the text back and focuses it. The view switch belongs to no form (`TabButtons` `form`), so it is never sent.
789
+ - **Safe to show anyone's text.** `parseMarkdown` (GitHub-flavored: tables, tasks, strikethrough, autolinks) never
790
+ renders raw HTML, and `safeUrl` keeps only http, https, mailto, tel, and relative addresses for links, and raster
791
+ data URLs for images. Links to other sites get `rel="nofollow noopener noreferrer"`.
792
+ - **Helpers:** `markdownToPlainText` for excerpts and search, and the editing commands `applyMarkdownTool`,
793
+ `continueMarkdownList`, `toggleMarkdownTask`, and `linkPastedUrl` for a custom editor. `npm run test:markdown`
794
+ checks the parser and every command.
795
+
796
+ ### QR code
797
+
798
+ ```tsx
799
+ import { encodeQr, qrPath, QrCodeImage } from "nexus-shared";
800
+
801
+ <QrCodeImage value={setup.otpauthUri} label="QR code to add your account to an authenticator app" />
802
+ const { version, size, mask } = encodeQr("https://nexus.example", "H");
803
+ ```
804
+
805
+ - **What a camera reads:** black modules on a white square that holds the quiet zone, in every theme and in forced
806
+ colours. `nx-qr` makes it 9rem wide with a control's corners; the page's own class places it.
807
+ - **The encoder** is QR Code Model 2, written by hand: the text as UTF-8 in byte mode, the smallest of versions 1 to 40
808
+ that holds it at the level asked (L, M, Q, H restore about 7%, 15%, 25%, 30%), Reed-Solomon, and the eight masks scored
809
+ by the four penalty rules. A text past version 40 throws, saying how much the level holds (2,331 bytes at M).
810
+ - `npm run test:qr` checks its shape; `Project-Skills/Checks/qr-code-check.mjs` reads every code back with an independent
811
+ decoder (jsQR, installed outside the repository).
812
+
813
+ ### Printable document
814
+
815
+ ```tsx
816
+ import { formatMoney, PRINT_PAPERS, PrintDocument, type PrintPaper } from "nexus-shared";
817
+
818
+ <TabButtons<PrintPaper> aria-label="Paper" options={PRINT_PAPERS} value={paper} onChange={setPaper} size="sm" />
819
+ <Button variant="primary" size="sm" onClick={() => window.print()}>Print</Button>
820
+ <PrintDocument
821
+ paper={paper} // "a5" (default) or "thermal", an 80 mm roll
822
+ logo={billLogo ? { src: billLogo.url, alt: company.name } : undefined} // or any node; logoOnThermal={false} leaves it off a roll
823
+ aria-label={`Receipt ${receipt.number}`}
824
+ title={company.name}
825
+ subtitles={[branch.name]}
826
+ kind={onCredit ? "Bill on credit" : "Receipt"}
827
+ stamp={voided ? `Voided: ${reason}` : undefined}
828
+ blocks={[
829
+ { facts: [{ label: "Receipt no.", value: receipt.number }, phone && { label: "Phone", value: phone }] },
830
+ { columns: [{ label: "For" }, { label: "Amount" }], lines: [{ cells: [item, money(amount)], note: `Paid up to ${day}` }], totals: [{ label: "Total paid", value: formatMoney(net, { currency, locale }) }] },
831
+ ]}
832
+ footer={settings.receiptFooter}
833
+ />
834
+ ```
835
+
836
+ - **Params, not markup.** A head (`title`, `subtitles`, `kind`), a `stamp` across it, `blocks` in order - facts (a
837
+ label and a value per line, the labels in one column) and lines (a table, the last column lined up at the end, a
838
+ `note` under a line's first cell, `totals` under a rule) - and a `footer` whose line breaks are kept. A falsy entry,
839
+ or one with `hidden: true`, is left out.
840
+ - **Printed alone.** On screen it reads in the theme's colours at its paper's width (A5: 128 mm of text; the roll: 72
841
+ mm). `window.print()` prints only the document, black on white, at the paper's edge, on the paper picked: the
842
+ component writes the page's `@page` rule while it is on the page. Any other page prints as it is. No PDF library.
843
+ - **A logo** (`logo`: `{ src, alt }`, or any node). On A5 it sits beside the title lines in a 24 mm column (at most 16
844
+ mm tall), the lines still centred, so the head grows no taller and a one-page receipt stays one page; on a roll, or
845
+ an A5 document shown narrower than 100 mm, it sits small and centred above them (at most 36 x 10 mm on a roll).
846
+ `logoOnThermal={false}` leaves it off a roll. Printed in black and white. An image must have loaded before printing.
847
+
848
+ ### Document frame
849
+
850
+ ```tsx
851
+ import { DocumentFrame, type DocumentFrameHandle } from "nexus-shared/client";
852
+
853
+ const frame = useRef<DocumentFrameHandle>(null);
854
+ <DocumentFrame
855
+ ref={frame}
856
+ title="Voucher preview" // the frame's title, its name to a screen reader
857
+ html={preview} // the server's whole page, <!DOCTYPE html> to </html>; null while none
858
+ loading={reading}
859
+ loadingMessage="Loading the preview…" // default "Loading…"
860
+ error={problem} // why it could not be shown
861
+ emptyMessage="Pick a layout." // default "Nothing to show yet."
862
+ printable // print() may open the dialog
863
+ actions={<Button onClick={() => frame.current?.print()}>Print</Button>}
864
+ />
865
+ ```
866
+
867
+ - **A page that is not this page's.** A server's whole document (its own `@page` sheet, screen style and CSP) goes
868
+ into an `<iframe srcdoc>`, never into this page's DOM or styles. **No script ever runs in it**: the sandbox is `""`
869
+ (an opaque origin; not even this page can reach in), or with `printable` `"allow-same-origin allow-modals"` - the
870
+ parent may call the frame's `print()`, and `print()` may open its dialog (Chrome ignores it without `allow-modals`).
871
+ Never `allow-scripts`, forms, popups or top navigation. A frame that becomes printable is made again, as a new
872
+ sandbox counts only from the frame's next page.
873
+ - **Its height is its container's**: it grows in a flex column (or stretches in a grid row) and is never under 22rem.
874
+ The page scrolls inside the frame; an A4 sheet wider than the frame scrolls sideways there, never the page.
875
+ - **A bar over the page**, the form's bar: the status line, and `actions` at its end, which wrap under the line on a
876
+ phone. It shows only with actions or something to say; out of sight it stays a live region.
877
+ - **States.** `loading` makes the page area `aria-busy` at once; a read that lasts 0.4s dims the page and says
878
+ `loadingMessage` (a quick one says nothing, held 0.3s once shown, as a CRUD's details footer). `error` is a line with
879
+ `role="alert"` over the last page, which stays in view. While loading or failed, an `html` of null keeps the last page.
880
+ A printable page read again keeps its scroll while the `title` stays the same.
881
+ - **`print()`** answers `false` when it cannot: not printable, no page yet, or the frame not loaded.
882
+
883
+ ### Forms
884
+
885
+ ```tsx
886
+ import { EInputTypes, TEXT_PATTERNS, type InputParams } from "nexus-shared";
887
+ import { ApiForm, SubmitForm } from "nexus-shared/client";
888
+
889
+ const ROOM_INPUTS: InputParams[] = [
890
+ { type: EInputTypes.Text, name: "number", label: "Room number", required: true, pattern: TEXT_PATTERNS.digits, span: 4 },
891
+ { type: EInputTypes.Number, name: "floor", label: "Floor", required: true, min: 0, span: 4 },
892
+ { type: EInputTypes.Dropdown, name: "type", label: "Type", required: true, options: ROOM_TYPES, span: 4 },
893
+ { type: EInputTypes.Tabular, name: "beds", label: "Beds", itemLabel: "Bed", inputs: BED_INPUTS }, // a list is an input too
894
+ ];
895
+
896
+ <ApiForm
897
+ inputs={ROOM_INPUTS}
898
+ loadValue={signal => api.get(ROOMS.details, { params: { id }, signal, toast: false }).then(unwrapApiResult)}
899
+ api={ROOMS.update} // or in place: { module: NexusModule.Reservation, path: "Room/Update", method: "PUT" }
900
+ draftKey={`hotel-3:user-8:room:${id}`}
901
+ onSuccess={room => table.updateRow(room)}
902
+ onCancel={close}
903
+ />
904
+ ```
905
+
906
+ - **An input's `type` is a number**, a member of `EInputTypes` (since 4.0.0; a string is refused): text boxes 1–19
907
+ (`Text` 1, `Email` 2, `Password` 3, `Search` 4, `Tel` 5, `Url` 6, `TextArea` 7, `Code` 8), choices 20–39 (`CheckBox`
908
+ 20, `Switch` 21, `Radio` 22, `CheckBoxGroup` 23, `RadioGroup` 24, `Dropdown` 25, one item or many by `multiple`),
909
+ dates and times 40–59 (`Date` 40, `DateRange` 41, `Time` 42, `DateTime` 43), numbers and sliders 60–79 (`Number` 60,
910
+ `Slider` 61, `RangeSlider` 62), editors 80–99 (`Markdown` 80, `RichText` 81) and structures 100–119 (`Tree` 100,
911
+ `Tabular` 101, `Group` 102, `Picture` 103). 0 is never a kind, and a number is never reused, so a database or a C# enum can hold it.
912
+ - **Params in, values out.** Every input is an entry of `inputs`, so a page, a CRUD component, or a server can describe a
913
+ form with plain objects. Values come in as each input reports them (a date-time from an API becomes a date, "12.5"
914
+ becomes 12.5), and fields the record came with (an `id`) stay in the values.
915
+ - **Fast at any size.** The values live in a `FormStore` outside React. Typing renders only the input typed in; an input
916
+ renders again only when a message it shows changes, or code sets its value. A keystroke costs about 5 µs in the store
917
+ for a form of 200 inputs, and a list of 10,000 rows is not checked again on each keystroke (it checks itself).
918
+ - **Checks on Save.** Each input's own rules (they also catch text that is not a date yet), the form's `validate` across
919
+ inputs, and rows not on the page. Every message shows, the first problem takes focus (a table scrolls to its row), and
920
+ the status line lists what needs attention, each name a link to its input. A rule message on an input shows once the
921
+ input was left, and on Save.
922
+ - **An input shown by another's value** (`showWhen`, Form only): `{ name: "counterType", in: [0, 1] }`, `notIn`, or
923
+ `filled: true | false`, or a list that must all hold (`[{ name: "counterType", in: [2] }, { name: "feeId", filled:
924
+ false }]`). The input comes and goes as the other changes, keeps what was typed, and is not checked while hidden; no
925
+ getter, no state in the page. `dependsOn` remains for anything else a getter reads (a `label`, `options`, a `max`).
926
+ - **An input read-only by another's value** (`readOnlyWhen`, Form only): the same conditions. A CRUD's Edit form holds
927
+ the record's key (`rowKey`, default `id`) and its Add form does not, so a field picked on Add and fixed once saved is
928
+ `readOnlyWhen: { name: "id", filled: true }`, with `readOnlyMessage` saying why. It shows its value (a dropdown its
929
+ saved label) with the lock and the note, sends it with the rest, and is not checked while read-only.
930
+ - **A label that follows another input** (`labelWhen`, Form only): `{ name: "registrationType", labels: { 1: "PAN
931
+ number", 2: "VAT number" }, otherwise: "PAN/VAT number", placeholders: { 1: "9 digits" } }`. The label (and the
932
+ placeholder, where listed) is the one for the other input's value as it is now, compared as text, else `otherwise`,
933
+ else its own; its messages name it the same way; the field draws again with no remount, keeping what was typed.
934
+ - **A width that follows a value** (`spanWhen: { when, span }`, Form only): `span` columns while every condition of
935
+ `when` holds (`showWhen`'s conditions; the input's own name follows its own typing), else its own `span`. A Bill date
936
+ that is the whole row until a date is put, then half with the switch that counts from it beside it, so nothing after
937
+ it moves: `span: 6, spanWhen: { when: { name: "billDate", filled: false }, span: 12 }`. The cell takes the new width
938
+ on the key that makes or unmakes the value, with no remount: the text, the caret, the focus and an open calendar
939
+ stay. A narrow form still gives every input the whole row.
940
+ - **An input worked out from others** (`compute: { from, value }`, Form only): shown, never typed - a price's
941
+ Calculated amount after Price, Discount and VAT. It is worked out when the form opens and whenever an input in `from`
942
+ changes (typed, set from code, loaded, reset), and is no form value: never sent, never checked, never a change,
943
+ never remembered or kept in a draft. Its box is an `<output>` on the read-only tint, in the person's number format,
944
+ with no lock, no steppers and no Tab stop; blank for null, "" or NaN, and while the values load. The form's
945
+ **`computeWith`** (state or a `useMemo` value, compared by identity) is what the page knows beside the values, such
946
+ as a server's preview: `compute: { from: [], value: (_values, line) => line?.netAmount }`.
947
+ - **The money presets**: `crudInputs.netAmount()` is that box ("Calculated amount", span 3, blank while the price
948
+ is empty); `...crudColumns.amounts()` gives a list Price, Discount, VAT and Calculated amount under "Amount
949
+ details"; `crudColumns.priceLadder(row, { locale })` gives a record's details a receipt's lines (Rate, Amount,
950
+ "Discount (5%)", "VAT (13%)", Calculated amount; a zero line left out). `PriceKeys` names other fields.
951
+ - **`priceAmounts({ price, quantity, discountPercentage, vatPercentage })`** is the Nexus server's money rule in the
952
+ browser: the amount, the discount off it, the VAT on the rest, each rounded half away from zero on exact decimals,
953
+ so a page's figure equals the server's to the paisa. `priceLadder(row, { locale })` gives the ladder as lines.
954
+ - **An input that remembers** (`remember: { key, viewer, preferred, per, when }`, a Form's input or a row input):
955
+ when the form's values leave it empty (a new record), it opens on the company's `preferred` value (a setting the page
956
+ reads), else on the person's last saved choice, kept in this browser under `nx-input:{key}:{viewer}` each time a form
957
+ holding it saves; each only while the input still offers it (a disabled or inactive option, or one gone, is dropped
958
+ without a word and a kept one forgotten), else its own `defaultValue`. It is the value the form opened with, not a
959
+ change; a form reset after a save opens on the new choice. No `viewer`, nothing kept.
960
+ `{ type: EInputTypes.RadioGroup, name: "paidBy", ..., remember: { key: "counter-paid-by", viewer: `${userId}|${companyId}`, preferred: settings.defaultPaymentMode } }`.
961
+ - **A picker** (`...crudPicker(...)`, options from `loadOptions`) confirms a kept value by its key before it opens -
962
+ found, not inactive, inside its `narrowedBy` narrowing - with its spinner meanwhile; never over the person's own pick.
963
+ - **`per: "subscriptionGroupId"`** keeps one value per value of that input (`nx-input:{key}-{group}:{viewer}`): a
964
+ package per group. **`when: { name: "id", filled: false }`** remembers on a CRUD's Add only (Edit holds the key).
965
+ - **In rows** (a tabular or group form): a new row's input opens on the kept value (give its first choice as the
966
+ input's `defaultValue`, not in `newRow`, which wins), and a save keeps the value of the last row added.
967
+ - **Ask before saving** (`confirm`: SubmitForm, ApiForm, and a CRUD's `form.confirm`): after every value has passed its
968
+ checks, a question with what will be saved in full - `{ title: "Place this order?", message, details: (values, body) =>
969
+ ({ row: body, columns, currency }), confirmLabel: "Place order", size: "xl", when }`. `body` is what is sent: an
970
+ ApiForm's `transform` runs once, before the question, and that very body is sent after Confirm. The details are drawn
971
+ as a record's (`CrudDetails`), a section under a heading for each run of columns with one `group`. Confirm has the
972
+ focus, so Enter saves; Back to the form, Esc and × send nothing and leave the form as it was, the focus back where it
973
+ was; a click outside leaves it open. While it asks nothing else submits and nothing says "Saving…"; a throw while it
974
+ is prepared shows under the form and asks nothing. `when` limits it to some saves.
975
+ - **One save at a time.** Save waits with a spinner; another click, Enter, or Ctrl+S does nothing until it ends. A save
976
+ makes the values the form's own ("Unsaved changes" clears; values typed meanwhile stay changes). `onSubmit` returns
977
+ `{ ok: false, errors, message }` to say why not, and a thrown error shows its message.
978
+ - **Server messages.** The server's own words are what the user reads. `ApiForm` shows **every** message a refusal
979
+ carried - a Nexus answer's `errorMessages` (a list, or one message object, or one message and its codes at the top
980
+ level) and ASP.NET Core problem details (`errors` by field) - each on the input its `inputName` names, matched without
981
+ case and by the first part of a path (`Addresses[1].City`). Names that match no input of this form, messages that name
982
+ none, and failures without fields show beside the buttons; nothing is swallowed and nothing is shown twice. A sentence
983
+ of ours by HTTP status ("Someone else changed this record…") is the fallback for an answer that explained nothing.
984
+ `messageCode` and `errorCode` ride along in `answer.errorMessages` for the log and for `onError` to react to, and are
985
+ never shown as the sentence. An input's message clears when its value changes.
986
+ - **Nothing lost.** `draftKey` keeps unsaved changes in IndexedDB (after a 600 ms pause, and at once when the page hides
987
+ or the form leaves) and brings them back with a note and Discard; drafts changed on the server since are named. Cancel
988
+ asks before it drops changes, and the page asks before it closes with some (`confirmLeave`, on without a draft).
989
+ The same form on the page also asks "Discard your changes?" before a navigation inside the app takes it away: every
990
+ same-origin link (next/link or a plain `<a>`: a side menu, the brand, a trail, a menu's link row) is held in the
991
+ capture phase while one has changes, and followed once Discard is chosen; Keep editing stays. A navigation of the
992
+ app's own asks through `confirmPageLeave()` (`if (await confirmPageLeave()) router.push(href)`), as nexus-admin's
993
+ module and account menus do; a move to the page in view asks nothing (`keepsPage(href)`), nor does a link inside text
994
+ being edited. A form in a `PopupHost` popup is left out: the popup stays open through a navigation, and keeps its own
995
+ close question. A confirmed navigation is not asked about again by the browser's close question. A move that loads a
996
+ whole page (a sign-out, `location.assign`) asks with `confirmPageLeave({ unload: true })`: about every form, the
997
+ popups' too, and once confirmed nothing asks again until the page goes (`endPageLeave()` if it did not).
998
+ `form.load(values, { keepChanged: true })` refreshes a record without touching what the user changed.
999
+ - **A save that removes something** (remove an app, turn a setting off, replace codes) says so on its button:
1000
+ `submitTone="danger"` fills it with the danger colour, as every solid danger fill is. `aria-describedby` on the form
1001
+ points at the line that says what goes, so a screen reader hears it when the focus lands straight in the password box.
1002
+ - `npm run test:forms` checks the store and the API helpers; `scripts/browser-checks/forms.cjs` in the template checks the
1003
+ three demo pages.
1004
+
1005
+
1006
+ **A preview the server works out as the person types** (`useServerPreview`, `nexus-shared/client`): a counter's
1007
+ amount and dates, a layout's printed page. `request(values)` on each change asks a moment after the last one (`delay`,
1008
+ 300 ms); an older question is aborted and its late answer never shown; `result` (and the `question` it answers) stays
1009
+ while a newer one runs and after one fails (`error`, the thrown message); `waiting` during the pause and `loading`
1010
+ while it is with the server; `cancel()` drops what waits or runs, `clear()` the answer too; leaving the page stops it.
1011
+ `ServerPreviewStore` is the same outside React.
1012
+
1013
+ ```tsx
1014
+ const preview = useServerPreview(async (body: CounterBody, signal) => {
1015
+ const answer = await api.send<CounterPreview>(COUNTER_PREVIEW, { body, signal, toast: false });
1016
+ if (!answer.ok || !answer.result) throw new Error(answer.message ?? "This cannot be worked out just now.");
1017
+ return answer.result;
1018
+ });
1019
+ <Form inputs={inputs} onValueChange={values => (missingFor(values) ? preview.cancel() : preview.request(counterBody(values)))} />
1020
+ <DocumentFrame html={preview.result} loading={preview.loading} error={preview.error} /> // a layout editor's page
1021
+ ```
1022
+
1023
+ ### API calls
1024
+
1025
+ ```ts
1026
+ // api-modules.ts: the app's modules and where each one's root is (shared by the browser and the server)
1027
+ import { defineApiModules, NexusApiModules, NexusModule } from "nexus-shared";
1028
+
1029
+ export const MODULES = defineApiModules(new NexusApiModules({ useProxy: process.env.NEXT_PUBLIC_API_PROXY !== "false" }));
1030
+ export const ROOMS = MODULES.controller(NexusModule.Reservation, "Room", "room");
1031
+
1032
+ // In the browser
1033
+ import { api } from "nexus-shared/client";
1034
+ const rooms = await api.get<Room[]>(ROOMS.listing); // GET /api/app/reservation/Room/NormalListing
1035
+ await api.put(ROOMS.update, values, { subject: "Room 204" }); // toast: "Room 204 saved." or what failed and why
1036
+ await api.confirm(ROOMS.delete, { params: { id }, subject: "Room 204" }); // asks "Delete Room 204?" first
1037
+
1038
+ // On the server (a server component, a route handler, a server action)
1039
+ import { serverApi } from "nexus-shared/server";
1040
+ const list = await serverApi.get<Room[]>(ROOMS.listing, { revalidate: 60, tags: ["rooms"] }); // straight to API_RESERVATION
1041
+
1042
+ // app/api/app/[module]/[...path]/route.ts: the browser's way to every module
1043
+ export const { GET, HEAD, POST, PUT, PATCH, DELETE } = createApiProxy({ token: readAccessToken });
1044
+ ```
1045
+
1046
+ - **Modules are the app's.** `ApiModules<TModule>` is an abstract class over the app's own module enum: implement
1047
+ `modules` (each module's value, its key in proxy URLs, its label for messages, where its root comes from) and
1048
+ `serverRoot(module)` (from the environment, a settings service, anything; may be async). Register it once with
1049
+ `defineApiModules`, and define endpoints through it (`MODULES.controller`, `MODULES.endpoint`), so a file that calls
1050
+ an endpoint has registered the modules on either side. `NexusApiModules` is the Nexus set (roots from `API_<MODULE>`,
1051
+ as in the previous project; `NexusModule.None` for the app's own `/api` routes) and runs when nothing is registered.
1052
+ The list is checked: keys and values must be unique, and keys fit in a URL.
1053
+ - **`NexusModule`'s numbers are the backend's `EModules` flags**, and a permission is a bitmask of them, so a value
1054
+ that disagrees with the backend by one bit grants or denies the wrong module in silence. They changed after
1055
+ 2.0.0: `Chat` took bit 6 and `Accounting` through `Portfolio` each moved up one. Code that uses the names needs
1056
+ nothing; anything holding a stored or hard-coded **number** does. [CHANGELOG.md](CHANGELOG.md) has the table.
1057
+ - **Module types from one place.** An app names its enum once, next to `defineApiModules`:
1058
+ `declare module "nexus-shared" { interface ApiRegister { module: HrModule } }`. Every endpoint, call, `ApiForm`,
1059
+ and CRUD then takes only those modules (`AppModule`), so `{ module: NexusModule.Reservation, … }` in an HR app is a
1060
+ type error. Without it, the modules are `NexusModule`.
1061
+ - **The proxy, on or off.** With `useProxy` (the default), the browser calls `/api/app/<module>/<path>` and the proxy
1062
+ route sends it on to the module's root with the user's token, which never reaches the browser. Off, the browser
1063
+ calls each module's `browserRoot` (public) and the proxy serves none. `proxies(module)` mixes the two, such as
1064
+ uploads straight to the Drive module and the rest through the proxy.
1065
+ - **The proxy hides the backend.** To the browser the app is the backend, and nothing in an answer names the real one:
1066
+ - **No redirect reaches the browser.** One that stays inside the module (the root's origin, or its host moved to
1067
+ https by the backend's HTTPS redirection, under the root's path in any casing) is followed on the server as
1068
+ `fetch` follows it: 307 and 308 keep the method and body, a 303 and a POST's 301 or 302 become a GET, up to
1069
+ `maxRedirects` (3). Any other answers 502 `BACKEND_REDIRECT_REFUSED`: following it would carry the token elsewhere.
1070
+ - **Response headers by an allowlist**, `DEFAULT_PROXY_RESPONSE_HEADERS` (Content-Type, Content-Disposition,
1071
+ Content-Language, Content-Range, Accept-Ranges, Cache-Control, Expires, ETag, Last-Modified, Vary, Retry-After),
1072
+ the Nexus backend's `X-Nexus-*`, and the names in `responseHeaders`. Server, X-Powered-By, X-AspNet-*,
1073
+ X-SourceFiles, Via, Alt-Svc, Strict-Transport-Security, Report-To, NEL, CORS, Location, Link and WWW-Authenticate
1074
+ never pass, even named; Set-Cookie only with `passCookies`. Every answer gets `X-Content-Type-Options: nosniff`,
1075
+ and `Cache-Control: private, no-store` unless the backend said how to cache it.
1076
+ - **Error pages replaced.** An error answer that is not JSON (an HTML or text page, a stack trace), JSON that is a
1077
+ stack trace or repeats the user's token, or one over 1 MB, becomes the failure envelope with the backend's status
1078
+ and plain words (`BACKEND_ERROR_PAGE`). JSON refusals (the Nexus envelope, problem details) and empty ones pass as
1079
+ they came, so the backend's own words still reach the form.
1080
+ - **The request.** The browser's own `X-Forwarded-*`, `Forwarded`, `X-Real-IP` and the like never go on, nor its
1081
+ cookies, a method or path override (`X-HTTP-Method-Override`, `X-Original-URL`) or Next.js's own headers. The
1082
+ proxy writes X-Forwarded-For (the last address the app received, which Next.js or the app's reverse proxy wrote;
1083
+ `clientAddress` reads it elsewhere; an IPv4 or IPv6 address or nothing, never other text) and X-Forwarded-Host
1084
+ and -Proto (the app's configured origin, else the request's). A module whose root is a path on the app (a pretend
1085
+ backend) is called at this server's own host and port, over http: the request URL's, which Next.js builds from
1086
+ where it listens. Never at the configured origin, so an app whose `origin` reads the Host header cannot let a client
1087
+ choose another port on the machine; `serverApi`, which has no request, uses that `origin`, so build it from
1088
+ configuration, or take the Host only when it names this server's own port. A body over `maxBodySize` (100 MB) is
1089
+ refused with 413 before the backend sees it, and a page of another site cannot call through the proxy
1090
+ (`Sec-Fetch-Site: cross-site`, other than a link followed) unless `allowCrossSite`.
1091
+ - **A server call can say who the client is too.** `lastForwardedAddress` and `readIpAddress` (`nexus-shared/server`)
1092
+ read the client's address as the proxy does, from anything with a `get` (Next.js's `headers()` included). The
1093
+ template's `api-setup.ts` gives Identity calls, and only them, `X-Forwarded-For` and the browser's `User-Agent`
1094
+ through `configureServerApi({ headers })`: sign-in leaves from the server, and Identity's rate limit counts per
1095
+ address. Only Identity's, because reading the request makes a page render per request.
1096
+ - **Refusals** are the Nexus envelope, `{ isSuccess: false, code, message, messageCode, errorCode, errorMessages }`
1097
+ (`failure` builds another backend's; `PROXY_REFUSALS` lists the codes), and the real cause goes to the server's
1098
+ log (`onProblem`, default `console.error`), never with the token or a query string.
1099
+ - **Two things the proxy cannot do for an app.** Node.js does not trust a development certificate (ASP.NET Core's)
1100
+ unless it starts with `NODE_USE_SYSTEM_CA=1`, so a module whose http root redirects to such an https port answers
1101
+ 502 until then, and the log says so. And Next.js keeps an X-Forwarded-For a client sent when nothing stands in
1102
+ front of the app, so only behind a reverse proxy of its own is the client's address certain.
1103
+ - **One engine, two clients.** `api` and `serverApi` are two settings of `createApiClient`: it fills `{id}` in the path
1104
+ from `params` or the body, adds the query, headers, and token, waits up to `timeout` (60 s), tries a failed GET once
1105
+ more (a save never twice), and reads every answer as an `ApiResult` (`ok`, `status`, `result`, `message`,
1106
+ `errorMessages`, `errors`, `messageCode`, `errorCode`, `network`, `timeout`, `aborted`). A failed call is an answer,
1107
+ never a throw; an aborted one shows nothing. Next.js's own signals (`headers()` while prerendering, `redirect()`) pass
1108
+ through untouched.
1109
+ - **What the server said wins.** A refusal is shown in the backend's own words whenever it sent any:
1110
+ `{ isSuccess, code, errorMessages: [{ message, messageCode, errorCode, inputName }] }` becomes
1111
+ `result.errorMessages` in that order (one message object instead of a list, a single `errorMessage`, and an older
1112
+ answer's one message at the top level all read into the same list), `result.errors` holds the ones that name an input,
1113
+ and `result.message` is all of them joined for a toast. `messageCode` and `errorCode` are for the log and for a page to
1114
+ react to - never the sentence a user reads. The messages built from the HTTP status are the fallback for an answer that
1115
+ explained nothing.
1116
+ - **Answers of another shape.** Nexus answers and ASP.NET Core problem
1117
+ details are read out of the box. A backend that answers its own envelope registers one reader for the whole app:
1118
+
1119
+ ```ts
1120
+ // Reads { success, message, data, error: { code, message, fields } } — the answer becomes ok, result, message, errors
1121
+ const read: ApiResponseReader = (body, status) => {
1122
+ const answer = body as BackendAnswer | null;
1123
+ if (answer?.success) return { ok: true, status, result: answer.data, message: answer.message };
1124
+ const fields = Object.entries(answer?.error?.fields ?? {}).map(([name, list]) => [name, list.join(" ")]);
1125
+ return { ok: false, status, message: answer?.error?.message, messageCode: answer?.error?.code, errors: Object.fromEntries(fields) };
1126
+ };
1127
+ configureApi({ read }); // the browser
1128
+ configureServerApi({ read }); // and the server, so both sides read one envelope
1129
+ ```
1130
+
1131
+ It is the fallback of every call that does not bring a `read` of its own, which is what the components that call
1132
+ inside themselves need: a `Crud`'s lists and actions and an `ApiForm`'s save have no place to pass one. A call's own
1133
+ `read`, and an `ApiForm`'s `readResponse`, still win.
1134
+ - **Toasts in the browser.** Errors always, successes for POST, PUT, PATCH, and DELETE; the same failure twice at once
1135
+ shows once; `toast: false`, `true`, or `{ success, error, loading }` per call; `configureApi({ toast, headers, read,
1136
+ onSignedOut })` for the app. The server shows nothing and logs network failures, timeouts, and 5xx.
1137
+ - **One message builder.** `buildMessage(kind, { action, subject, count, status })` words every message, and
1138
+ `messages.success`, `.failure`, `.reason`, `.loading`, `.confirm`, `.label`, and `.forResult` are short ways to call
1139
+ it: "3 rooms deleted.", "Could not move Room 204 to the trash.", "You do not have permission to delete Room 204.". The
1140
+ texts and action words are one table: `configureMessages` rewords or translates all of them at once, and an action
1141
+ of the app's own is its words (`{ verb: "check in", done: "checked in", doing: "Checking in", object: "the guest" }`).
1142
+ - **A controller's lists.** `apiController` names the lists as the Nexus backend does: `listing` and `pagination` are the
1143
+ active records' (`NormalListing`, `NormalPagination`), and `lists.flag`, `lists.trash`, `pages.trash`, … the others
1144
+ (`FlagListing`, `TrashListing`, `TrashPagination`, …), for the CRUD component.
1145
+ - `npm run test:api` checks the builder, routes, modules (another app's enum, the proxy on and off), the engine, the
1146
+ server client, and the proxy's routing; `npm run test:proxy` checks how the proxy hides the backend (redirects,
1147
+ headers, error pages, forwarded headers, paths, the body limit, other sites, the log) against a fake backend;
1148
+ `scripts/browser-checks/api-calls.cjs` in the template checks `/demo/api`.
1149
+
1150
+ ### Data table
1151
+
1152
+ ```tsx
1153
+ import type { TableColumn } from "nexus-shared";
1154
+ import { DataTable, useTable } from "nexus-shared/client";
1155
+
1156
+ const COLUMNS: TableColumn<Booking>[] = [
1157
+ { key: "no", label: "Booking", width: "7rem", movable: false, pinnable: false }, // stays first, and stays put
1158
+ { key: "guest.name", label: "Guest" }, // a path into the row
1159
+ { key: "amount", label: "Amount", format: "money", prefix: "Rs. ", group: "Amount details" }, // number, money, percent, date, …
1160
+ { key: "due", label: "Due", format: "money", prefix: "Rs. ", group: "Amount details" }, // one heading over both: the header is two rows
1161
+ { key: "status", label: "Status", options: [{ value: 1, label: "Confirmed", tone: "success" }] }, // a tag
1162
+ { key: "paid", label: "Paid", format: "boolean", resizable: false }, // keeps its width
1163
+ { key: "created", label: "Booked", format: "date-time", hidden: true }, // shown from the Columns menu
1164
+ ];
1165
+
1166
+ const table = useTable<Booking>();
1167
+ <DataTable table={table} aria-label="Bookings" columns={COLUMNS} rows={bookings} selectable massActions={MASS} rowActions={row => ACTIONS(row)} stateKey="bookings" />
1168
+ <DataTable columns={COLUMNS} paging="server" load={(query, signal) => fetchPage(query, signal)} /> // { search, sort, page, pageSize, filters }
1169
+ <DataTable columns={COLUMNS} rows={bookings} onImport={askForFile} moreActions={[{ id: "report", label: "Monthly report", onSelect: open }]} />
1170
+
1171
+ table.upsert(saved); table.patch(7, { paid: true }, { flash: true }); table.remove([7, 8]); await table.reload();
1172
+ ```
1173
+
1174
+ - **Columns are params**, one plain object each, as inputs are: `key` (a field or a path), `label`, `group`, `format`,
1175
+ `decimals`, `prefix`, `suffix`, `currency`, `options` (labels for an enum's values; a `tone` draws a tag with a dot of its color),
1176
+ `value`, `render`, `text`, `width`, `minWidth`, `align`, `wrap`, `sortable`, `sortKey`, `searchable`, `hidden`,
1177
+ `hideable`, `movable`, `resizable`, `pinnable`, `pinned`. Numbers line up at the end in tabular figures; dates and
1178
+ times follow the user's settings; moments show in the user's zone once the page has hydrated; long text ends in … at
1179
+ the column's width.
1180
+ - **Money in the company's currency.** `<DataTable currency="Rs." />` (a `Crud`'s `table.currency`) writes every
1181
+ `money` column "Rs. 1,250.00" - in the cells, the details, the CSV and the print - with no `render` of the page's; a
1182
+ column's own `currency` (a text, or `row => row.currencyText`) wins. `formatMoney(value, { currency, locale })` writes
1183
+ the same anywhere else, a dashboard's figure or a receipt's total.
1184
+ - **Columns in bands.** `group` is the heading above a column (`{ key: "amount", label: "Total", group: "Amount
1185
+ details" }`); the columns next to each other that name the same one share it, and the header reads in two rows, the
1186
+ bands on top and the columns' own headings under them. A column with no group keeps one heading as tall as both rows,
1187
+ and so do the numbers and checkbox column and the actions. A band is a heading and nothing more: it sorts nothing, has
1188
+ no menu and no edge to drag, and the columns stay one flat list, so hiding, ordering, widths, pins and the export are
1189
+ as they were. The bands are read off the order on screen: a column dragged out of its run takes its band's heading
1190
+ with it, and the run it left draws that heading again. With no group anywhere the header is one row.
1191
+ - **Rows three ways.** Given (`rows`) or loaded once (`load`), the table searches, sorts, and pages them itself: every word
1192
+ must match, in any column, with or without accents, and 10,000 rows search in about 0.5 ms a keystroke. A page at a time
1193
+ (`load` with `paging="server"`), each search (after 300 ms without typing, or Enter), sort, and page is one request; a
1194
+ newer query stops the one before, so a late answer never shows. A loader may answer without a promise (a cache), and
1195
+ the rows then paint with the table. `loadKey` starts over for another list behind the same table.
1196
+ - **What it shows while it waits.** Placeholders in the shape of the rows for the first rows; afterwards the rows stay,
1197
+ with a thin bar under the headings, and dim only if a load takes a moment. A failed load says why, with Retry; an empty
1198
+ list has its own message and action; a search or filters that find nothing offer Clear search or Clear filters.
1199
+ - **The columns are the user's.** Drag a heading to another place, drag its right edge for its width (double-click the
1200
+ edge, or "Fit to content", to fit it, never under the column's `minWidth`), and use the caret on the heading to sort,
1201
+ pin it left or right, move it, or hide it; the Columns menu shows and hides them. A column opts out with
1202
+ `movable`, `resizable`, or `pinnable: false`, and `pinned` starts it on a side. The table itself can refuse all three
1203
+ (`reorderable`, `resizable`, `pinnable`). Once a width is set the columns are laid out from those widths, so one edge
1204
+ moves alone; "Reset columns" in the options menu puts everything back.
1205
+ - **The bar** is one line on a wide table: the Add section (`add`, then the page's `actions`) and the lists
1206
+ (`toolbar`) on the left; Reload, the options menu (⋮) and the search, rows per page inside it, on the right. A
1207
+ narrower table moves whole parts, never a lone button, by its own width (a container query, so a table in a narrow
1208
+ panel does the same): under 670px the search takes the top line (with nothing on the left, it leads the buttons'
1209
+ line instead), under 375px Reload moves into ⋮, and under 325px, beside lists, the Add section takes the last line,
1210
+ its buttons sharing it. On the admin shell, whose menu leaves the screen at 900px, those are windows of 695, 400 and
1211
+ 350px. A bar wider than those widths expect (a long Add label, the page's own buttons, cozy density) takes the next
1212
+ step as soon as a line would break (`data-squeeze`). Each item of the Add section keeps its own width on a shared
1213
+ line (a switch's label never breaks between its words, nothing runs into the lists); on the line the section takes
1214
+ of its own its items share it, and one that would not fit its share takes a line of its own, whole. A `Crud`'s lists
1215
+ name every tab from 900px and only the chosen one below.
1216
+ - **One options menu (⋮)**: **Filters** (`filterInputs`, input params as a form takes them, each named after the
1217
+ column it filters: a small form under ⋮, applied as it changes; a server gets them flat by name, see `filterRequest`),
1218
+ the columns shown as a CSV (`exportable`, named by `exportName` or the table's label), a
1219
+ print view of the same in a frame of its own (`printable`), Import (`onImport`), any `moreActions` of the page, and
1220
+ Reload, last, on a table too narrow for its button. A client table writes every row the search left; a server table
1221
+ writes the page it has, and says so.
1222
+ - **Selection.** The first column counts the rows (`numbered`, on by default when `selectable`) and turns into the row's
1223
+ checkbox under the pointer; once anything is selected every row shows its checkbox and the heading shows the box that
1224
+ selects the page (partly checked when some are). Shift+click selects a range, up to `maxSelection` (500). While rows
1225
+ are selected, a bar with the count, one split button holding every `massAction`, and Clear covers the headings, so
1226
+ nothing moves: the menu makes the action picked the button, and the next click runs it, with a spinner while it does.
1227
+ - **Row actions**: `inline` ones as icon buttons, the rest in the row's menu; while one runs (a promise), the row is busy.
1228
+ `onRowOpen` for a double-click. A row added or saved is highlighted for a moment (steadily, with reduced motion).
1229
+ - **A picked row** (`onPick`), for a page that shows the picked one's records beside the table. A click picks a row, and
1230
+ a double-click still opens it. The keyboard reaches the rows through a radio button each, out of sight in the first
1231
+ column and named with the row: Tab to the picked one, and the arrow keys move the pick.
1232
+ - The picked row wears a selected row's tint, and a ring round it while its radio has the focus.
1233
+ - The pick is the store's (`TableState.picked`, `table.pick(row)`) and follows the record: it is kept through a search
1234
+ or another page, handed over anew after an edit, and let go once the record leaves the rows.
1235
+ - **`caption`**: a line inside the frame, over the bar, saying what the rows are. **An Add that waits**:
1236
+ `add.disabled` with a `description` stays in the Tab order, and a press shows why in a note under it, unless
1237
+ `add.onDisabledPress` answers it first (returns true): a CRUD's narrowing box takes the cursor instead.
1238
+ - **A pinned section.** `pinnedRows` puts rows in a band above the page with a button that folds them open and shut
1239
+ (`pinnedLabel`, `pinnedMax` beside the count, `pinnedLoading` while they come); with a `stateKey` the choice is
1240
+ remembered on the device. They are the same records as in the list below, and each wears a pin where the rows of the
1241
+ page show their number.
1242
+ - **A `stateKey` that changes** (a `Crud` scope's list) reads that key's settings as the first draw does - its page
1243
+ size, sort, hidden columns, order, widths and pins, each column's own default where nothing is kept - and the
1244
+ settings on screen are never written under the new key.
1245
+ - **Wide tables** scroll inside their frame, with the numbers and checkbox column on the left, the actions on the right,
1246
+ any pinned columns beside them, and the headings on top staying in place, and a soft shadow where columns scroll under
1247
+ them. On a narrow table the pinned columns give way: the columns that stay take at most 60% of the width on screen
1248
+ (`PINNED_SHARE`), pins kept from the outer edge in, and the others scroll with the rest - keeping their side and their
1249
+ menu's Unpin - until there is room again. Under the table: "Showing 41–50 of 234" (and how many the search and filters left out) on the left, "Page 5 of
1250
+ 24" and the pager on the right; rows per page sits inside the search box. At 520px and less the page buttons go.
1251
+ - **Where the paging lives** (`pager`). `"bar"` (the default) is the above. `"footer"` puts rows per page beside the
1252
+ pager, so a table with nothing else on top (no search, no ⋮, no lists) draws no bar. `"none"` is for a short list
1253
+ read whole, such as a record's notes (at most 50): every row on one page, no pager, no rows per page, and no footer
1254
+ unless a search or the filters leave rows out; the count is still read to a screen reader. With `searchable={false}`,
1255
+ `columnsMenu={false}`, `exportable={false}` and `printable={false}` such a table is its rows alone, in its frame. A
1256
+ server's pages cannot all be shown, so `paging="server"` takes `"none"` as `"footer"`. A `Crud` passes it as
1257
+ `table: { pager }`.
1258
+
1259
+ ```tsx
1260
+ <DataTable aria-label="Notes" columns={NOTE_COLUMNS} rows={notes} pager="none" searchable={false} columnsMenu={false} exportable={false} printable={false} />
1261
+ ```
1262
+
1263
+ - `npm run test:table` checks the helpers, the store, and the CRUD rules; `scripts/browser-checks/data-table.cjs` in the
1264
+ template checks `/demo/data-table`.
1265
+
1266
+ ### CRUD
1267
+
1268
+ ```tsx
1269
+ import { Crud } from "nexus-shared/client";
1270
+
1271
+ export const GUESTS = MODULES.controller(NexusModule.Reservation, "Guest", "guest"); // every list and action
1272
+
1273
+ <Crud<Guest>
1274
+ api={GUESTS}
1275
+ columns={GUEST_COLUMNS} // as a DataTable takes them
1276
+ inputs={GUEST_INPUTS} // or { create, edit }, or (action, row) => inputs
1277
+ paging="server" // default "client": each list loaded once
1278
+ form={{ load: "details", newValues: { country: "Nepal" } }}
1279
+ details={{ columns: GUEST_DETAILS }}
1280
+ onChange={({ action, rows, mode }) => audit(action, rows)}
1281
+ />
1282
+ ```
1283
+
1284
+ - **Lists.** All (`NormalListing` or `NormalPagination`), Flagged, Trash, and Deleted, as tabs after Add: every one
1285
+ named on a table 900px wide or more, icons with the chosen one named below. A list shows when it is in `modes`, has
1286
+ its endpoint, and the user may call it.
1287
+ - **Pinned records.** `PinListing` answers the records the user pinned: they sit in a section above the active list that
1288
+ folds open and shut, and in the list and its pages as well. One limit holds for every CRUD in the app
1289
+ (`configureCrud({ maxPins: 100 })`, 100 by default). Pinning a selection bigger than the room left pins as many as fit,
1290
+ in the order they were picked, and says so; lowering the limit never unpins anything, so a user over it can still
1291
+ unpin and can pin again once they are under it.
1292
+ - **Actions.** On a record in the lists of active records: View details, Edit (an icon on the row), Flag, Pin,
1293
+ Move to trash; in the trash: Recover, Delete permanently; in the deleted list: Move back to trash. On selected records: the same, plus a new Description for all of them. Each shows only when it is in
1294
+ `actions`, has its endpoint, and is allowed. A controller without a trash (no endpoint, or left out of `actions`) offers
1295
+ Delete where Move to trash would be; a trash the user may not use never becomes Delete.
1296
+ - **Questions and messages.** Move to trash and Delete ask first ("Move 3 guests to the trash?", "This cannot be
1297
+ undone."); Flag, Pin, and Recover are undone by a click and do not ask. Toasts come from the message
1298
+ builder ("Sita Sharma moved to the trash.", "3 guests unpinned.").
1299
+ - **Rows from the answers.** A record that moves to another list leaves the one in view (and the pinned section); flags,
1300
+ pins, and saved values change in place; a new record goes first; a server page loads again in the background to fill up. When a mass
1301
+ answer lists the records it changed, only those change.
1302
+ - **A save is never read back** (Nexus: an Add is one Create, an Edit one Update). The row is what was sent under what the
1303
+ answer said, with the fields only the server keeps written by `CrudBackend.savedRow` (Nexus: Active, no marks, added
1304
+ now; an edit keeps them and was changed now), and the names the database joins written again by `crudJoinedNames` for
1305
+ each `crudColumns.dbJoin` column given `from` (the key's field): from the record the user picked in the form, one the
1306
+ page holds (`peekOption`), or the name the row had when the key did not change. An edit takes the status, the marks
1307
+ and, with `trees`, the child count from the row the page holds now, over its form's older copies; the parents' own rows
1308
+ on the table count their children too. Read back once (`details`), and only then: a record of a backend whose save
1309
+ says no status, or one with a joined name nothing names (`crudJoinsMissing`) - a `dbJoin` column without `from`, or a
1310
+ new key no picked or held record names.
1311
+ - **Add and Edit** open popups built on `ApiForm`, with the Save bar in the footer and the server's messages on their
1312
+ inputs. Keys keep them one each: pressing Add again brings back an Add form with changes (minimized or not), or opens a
1313
+ fresh one in place of every untouched one; a record has one Edit popup, brought back as it was when Edit is pressed
1314
+ again - from a table or a tree. Closing a form with changes (its close
1315
+ button, Esc, the dock) asks "Discard your changes?". Edit opens with the row, the `details` endpoint's record
1316
+ (`form.load: "details"`, for fields a list leaves out), or a loader of your own.
1317
+ - **Details** (View, or a double-click) shows every column, hidden ones too, and the full record once `details` answers,
1318
+ with Edit in its footer. Columns that name a `group` (a table's band) are drawn in sections, a small muted heading
1319
+ over each run of them (`CrudDetails`, `crudDetailsRuns`); with no group anywhere the list is one grid, as before.
1320
+ - **A record's workspace** (`details.profile`, `details.tabs`, `details.remember`): View, and a click on a row under
1321
+ `table.openOnClick`, open the record as a wide popup (`full` unless `size` says otherwise) - who it is and its tabs in
1322
+ a 20rem column on the left, the chosen tab on the right, scrolling inside itself. A page passes it in a few lines:
1323
+
1324
+ ```tsx
1325
+ details={{
1326
+ profile: row => ({
1327
+ picture: { ...GUEST_PICTURE, ownerId: String(row.id) }, // the picture column's params: a click opens the pictures
1328
+ title: row.fullName,
1329
+ subtitle: row.email,
1330
+ tags: [{ label: "Gold", tone: "warning" }],
1331
+ }),
1332
+ tabs: [
1333
+ // `details` (the fields, with `aside` under them) comes first unless listed: { id: "details" } moves it.
1334
+ { id: "stays", label: "Stays", icon: <InlineIcon icon={iconCalendar} />, endpoint: STAYS.create,
1335
+ render: ({ row, refresh }) => <StayForm guest={row} onSaved={refresh} /> },
1336
+ { id: "bills", label: "Bills", icon: <InlineIcon icon={iconReceipt} />, badge: row => row.openBills,
1337
+ render: ({ row }) => <Bills guestId={row.id} /> },
1338
+ { id: "gold", label: "Gold desk", hidden: row => row.vipLevel !== 2, render: context => <GoldDesk {...context} /> },
1339
+ ],
1340
+ remember: { key: "guest-tab", viewer }, // the last tab, in this browser, for this viewer
1341
+ }}
1342
+ ```
1343
+
1344
+ - A tab that names an `endpoint` shows only to a person who may call it; `hidden(row)` hides it for a record. Only
1345
+ the chosen tab is drawn, and a switch never changes the popup's size.
1346
+ - `profile.fields` puts a few of the record's fields under the tags, a label and a value each, drawn as the table
1347
+ draws them (the person's date format, an option's tone, the column's `tag` after the value). A field is a column
1348
+ given whole or a key of the details' `columns`; one with no value for the record is left out. The Details tab leaves
1349
+ out every key named there, so no field shows twice. Beside the tabs they are a small grid in the 20rem column; on a
1350
+ phone they follow the tags as one wrapped line.
1351
+
1352
+ ```tsx
1353
+ profile: row => ({ title: row.fullName, tags: [{ label: "Due", tone: "warning" }], fields: [EXPIRY_COLUMN, "inactiveDate"] }),
1354
+ ```
1355
+ - `render` is handed `row` (as the list has it now), `form` (the record: the row, then the `details` endpoint's, then
1356
+ each refresh's), `popup`, `tab`, `select(tabId)` and `refresh()`. Call `refresh()` after a tab changed the record on
1357
+ the server (a stay recorded): it reads the record again and writes it into the table, the pinned band, every list
1358
+ kept and every tree, so the row's visits and dates change with one request and no list read again - in place on
1359
+ every page kept, also for a record opened from the pinned band, and also when the popup closed before it landed.
1360
+ - A `SubmitForm` or `ApiForm` in a tab joins the workspace by itself: while it has changes, choosing another tab or
1361
+ closing the popup (Close, Edit, its X, Esc, its bar on the dock) asks "Discard your changes?" first.
1362
+ - A tab's form longer than the window puts its line and Save last, in a **`CrudTabFooter`**: it stays at the bottom
1363
+ of the tab while the form scrolls and sits in its place at the end, across the tab's whole width under a hairline;
1364
+ a field the keyboard moves to is scrolled clear of it, and on a phone its words and buttons wrap as whole groups.
1365
+
1366
+ ```tsx
1367
+ function StayTab({ refresh }: CrudDetailsTabContext<Guest>) { // { id: "stay", render: context => <StayTab {...context} /> }
1368
+ const form = useForm<Stay>();
1369
+ const stay = useFormValues(form);
1370
+ return (
1371
+ <>
1372
+ <ApiForm form={form} buttons={false} api={STAYS.create} inputs={STAY_INPUTS} onSuccess={() => void refresh()} />
1373
+ <CrudTabFooter>
1374
+ <p role="status" aria-live="polite">{stay.nights} nights · To pay Rs. {formatNumber(price(stay), { decimals: 2 })}</p>
1375
+ <FormButtons form={form} submitLabel="Save" />
1376
+ </CrudTabFooter>
1377
+ </>
1378
+ );
1379
+ }
1380
+ ```
1381
+ - The built-in `details` tab: list `{ id: "details", label: "Profile" }` to move or rename it, add
1382
+ `hidden: () => true` to leave it out, or a `render` to replace it. Without a second tab for the person, there is no
1383
+ tab list: the profile and the details.
1384
+ - Its `aside` (a subscriber's notes) goes **under** the fields, each across the whole width, the panel as tall as it
1385
+ needs and scrolled with the fields (`details.asidePlace`, `"below"` by default in a workspace); `asidePlace:
1386
+ "beside"` puts it beside them from 1000px, as a plain details popup does by default.
1387
+ - Below 720px of popup width (a phone) the profile is one row and the tabs one strip above the tab. The tabs are a
1388
+ `Tabs` tablist: the focus opens on the chosen tab, the arrow keys, Home and End move and open, Tab goes into the tab.
1389
+ - **A list beside the record picked in another** - a person's places beside the people. The page holds the picked record
1390
+ and passes it on; every behaviour is the `Crud`'s:
1391
+
1392
+ ```tsx
1393
+ const [person, setPerson] = useState<CompanyUser | null>(null);
1394
+ <AdminSplit>
1395
+ <Crud<CompanyUser> api={COMPANY_USERS} columns={PEOPLE} inputs={PEOPLE_INPUTS} onPick={setPerson} />
1396
+ <Crud<BranchUser> api={BRANCH_USERS} columns={PLACES} inputs={PLACE_INPUTS} narrow={{ picked: person, key: "userId", labelKey: "fullname" }} />
1397
+ </AdminSplit>
1398
+ ```
1399
+
1400
+ - The narrowed list shows the records whose `key` field holds the picked record's value (its `valueKey` field, `key`
1401
+ by default), under a caption naming it ("Places of: Ram Thapa"). With nothing picked it says so and asks for nothing.
1402
+ - Paged in the browser, it keeps the whole list and reads each pick's rows from it, with no request. Paged on the
1403
+ server, it sends the value as a filter named `key`.
1404
+ - Add New fixes the value in the new record, in a form titled for whom it adds. It waits, saying why, while nothing
1405
+ is picked or the picked record may take nothing: `addLock`, by default the backend's rule, so a Nexus record that is
1406
+ pending, trashed or deleted takes no new records.
1407
+ - A save lands in the list of the record it names, and in no other, even when another record is picked by then.
1408
+ - **Pickers of another controller's records** (`crudPicker(STAFF, { labelKey, valueKey, find })`): the active list read
1409
+ once and searched in the browser, and a saved value it does not offer looked up by key through `findListing`. A
1410
+ `valueKey` other than `id` - a person's account rather than their row's key - is looked up through `find`, an endpoint
1411
+ of its own that takes those values. Without it such a value is never looked up, since `findListing` takes keys.
1412
+ - **A record nobody may change here** (`rowLock={row => row.isLocked ? row.lockReason : null}`): its Edit, Flag, Move to
1413
+ trash, Recover and the deletes are listed switched off with that sentence under each, its details have no Edit, the
1414
+ handle's `edit` opens its details, and a selection holding it has those mass actions switched off. View, History, Pin
1415
+ and Favourite stay. The page's own `rowActions` are its own to switch off; the backend still decides.
1416
+ - **One action locked on a record** (`rowActionLock={row => row.isHeadOffice ? { trash: "The head office stays open." } : null}`):
1417
+ only the actions named are listed switched off, each with its sentence, and switched off in a selection that holds
1418
+ the record; a locked `edit` opens the details instead. The rest still run.
1419
+ - **A list narrowed by a box of its own** (`narrowPicker={{ picker: crudPicker(GROUPS, { labelKey: "groupName" }), label: "Group", key: "subscriptionGroupId", labelKey: "groupName", remember: { key: "subscribers-group", viewer }, onPick }}`):
1420
+ the CRUD draws the box in its toolbar and narrows by the pick as `narrow` does. `remember` keeps the pick in this
1421
+ browser per viewer (pass a short hash of the person and the company, so a shared PC never opens on another's pick)
1422
+ and opens it again while the box still offers it; only the record's key is stored, and nothing without a `viewer`.
1423
+ `onPick` tells the page, for inputs that follow it. The empty list, Add and the Add form's fixed field name the box
1424
+ ("Pick a group in the Group box to see its subscribers."); `emptyMessage`, `addMessage` and `fixedMessage` replace them.
1425
+ While nothing is picked the box asks for a pick: as the page opens it settles (a spinner in it, the list waiting) on
1426
+ the remembered pick, or else on the one record it offers, picked by itself and remembered as a person's pick is; with
1427
+ neither it is required and drawn with a field's invalid edge (`Dropdown` / `Field` `invalid`), the list's words read
1428
+ with it, and it takes the cursor - unless the person is already at work on the page, a popup is open, the box is
1429
+ below the fold, or the screen is touch-only (a cursor would raise the keyboard over the list). The empty list has a
1430
+ button to the box ("↑ Pick a group"), and Add pressed with nothing picked sends the cursor there and nudges the box
1431
+ (still, with reduced motion) while a screen reader hears Add's reason instead of a note under Add.
1432
+ - **A list that can be widened** (`scopes={{ options: [{ id: "all", label: "All branches", description: "Every branch's people", api: ALL_BRANCH_USERS, columns, inputs, form: { newValues }, "aria-label" }], remember: { key: "branch-users-scope", viewer }, onChange }}`):
1433
+ the CRUD's own props are its own list (one branch's places); each scope is another list of the same records on
1434
+ endpoints of its own, with its own `columns`, `inputs`, `form` (over the CRUD's, field by field), `table` settings and
1435
+ name where they differ. One scope is a switch after Add, its `description` the tooltip; two or more are tabs, the
1436
+ CRUD's own list first (`label`, `description` for its tab). A scope is offered only to a person who may call one of
1437
+ its lists and passes its `when` (the page's own rule), again whenever their rights change. Switching reads the new
1438
+ list on its endpoints with the CRUD left in place (the switch keeps the focus, popups stay open); each scope keeps
1439
+ its lists while the page is open, so going back shows them at once, and a change made on one drops the others' (only
1440
+ the server knows which hold the record). Each scope keeps its own table settings (`{stateKey}:{id}`, or its own
1441
+ `table.stateKey`). `remember` keeps the choice in this browser per viewer (`nx-crud-scope:{key}:{viewer}`), read after
1442
+ the first draw and before any list is asked for; a kept scope not offered now opens the CRUD's own list and stays kept.
1443
+ An answer that lands after a switch writes nothing into the list on screen, which is read again; it still marks the
1444
+ lookups of both lists' endpoints old and drops a tree's kept pages. A form belongs to the scope it was opened on: an
1445
+ Edit pressed in details opened on another scope is that scope's form on its endpoints, and each scope keeps its own
1446
+ Add and its draft. The handle's `scope` and `setScope(id | null)` read and set it; `onChange` hears every change of
1447
+ the list shown.
1448
+ - **A row's own form** (`rowForms={[{ id: "permissions", label: "Permissions", icon, inline: true, modes: ["normal"], size: "lg", load: SETS.details, submit: SETS.update, inputs: (row, loaded) => setInputs(loaded), transform: (values, row) => ({ branchUserId: row.id, ...values }), writes: ["assignedPermissionCount"], lock, when, target, title, submitLabel, onSaved }]}`):
1449
+ a row action (an icon beside Edit with `inline`, else a line of the row's menu) that opens a form of its own for the
1450
+ record in a popup - one per record, brought back if open - after the built-in actions and before `rowActions`. It is
1451
+ offered on the lists that offer Edit unless `modes` says otherwise, to a person who may call `submit` and, when it is
1452
+ an endpoint, `load`, and by the page's `when`; `lock` lists it switched off with its sentence. `load` reads the values
1453
+ (an endpoint called with `{id}`, the record's key or `target`, or a function that must reject on a failure), and the
1454
+ inputs may be made from what was read; until it is, Save waits, and a read that fails - an answer that is not ok, or
1455
+ no record - shows "Could not load the values" with Retry and **no Save**, so an empty form is never saved over the
1456
+ record. `writes` names the answer's fields that change the record (or is a function of the answer): only those, merged
1457
+ over the record as the CRUD holds it when the answer lands (an Edit made while the popup was minimized stays), written
1458
+ into the table, every list kept and the pinned sections with no list read again. The handle's `openRowForm(id, row)`
1459
+ opens one.
1460
+ - **Options narrowed by another input** (`narrowedBy: { name: "subscriptionGroupId" }` on an input, Form only): a
1461
+ Package list only of the Group picked. Static `options` are filtered by the records' `key` field (default the other
1462
+ input's name); `loadOptions` is asked with `request.narrow`, which `crudPicker` answers from its kept list, or from
1463
+ the server with `crudPicker(PACKAGES, { labelKey, narrowQuery: "subscriptionGroupId" })`. While the other input is
1464
+ empty nothing is offered ("Pick a group first"), and a person changing it clears the value picked here.
1465
+ **Or by a fixed value** the page knows when the form opens (`narrowedBy: { key: "subscriptionGroupId", value:
1466
+ subscriber.subscriptionGroupId }`): nothing is followed or cleared, and a `null` value offers nothing. `orUnset: true`
1467
+ (both forms) also offers the options whose field is empty: the Fee list of the group, and the fees of every group.
1468
+ - **Cache.** Lists are kept for 5 minutes while the page is open (`cache={{ lifetime }}`, or `false`): going back to a
1469
+ list paints it at once. After a change, the list in view keeps its rows and the others load again when shown; Reload
1470
+ and the handle's `reload()` go past the cache. The cache goes when the page does.
1471
+ - **Permissions** come from the app's rules: `definePermissions(new NexusPermissions())` once, then `setActions(accessActions)`
1472
+ after sign-in. While the rules load, the table shows placeholders; a user with no list sees a message. Rules for
1473
+ another backend extend `Permissions` (`can(endpoint)`), and its page and mass shapes extend `CrudBackend`.
1474
+ - `ref` gives `table`, `mode`, `setMode`, `reload`, `create(values)`, `edit(row)`, and `view(row)`.
1475
+ - `scripts/browser-checks/crud.cjs` in the template checks `/demo/crud`: every list and action, the popups, the roles, the
1476
+ cache, a phone, and contrast in every theme.
1477
+
1478
+ ### CRUD in a tree
1479
+
1480
+ ```tsx
1481
+ import { CrudTree } from "nexus-shared/client";
1482
+
1483
+ // Where the records sit in the tree: one definition for the tree page and for a Crud whose changes it must follow.
1484
+ export const REGION_TREE: CrudTreePlacement<Region, RegionItem> = {
1485
+ cacheKey: "regions-tree",
1486
+ rules: { valueKey: "key", hasChildrenKey: "childCount", compare: bySortOrderThenName },
1487
+ itemOf: region => ({ key: `r${region.id}`, label: region.name, childCount: region.childCount ?? 0, region }),
1488
+ parentOf: region => `r${region.parentId}`,
1489
+ recordOf: item => (item.region ? { ...item.region, childCount: item.childCount } : null), // the count goes back
1490
+ childValues: parent => ({ parentId: parent.region?.id }),
1491
+ placeKeys: ["parentId"], // where a record sits: fixed in the tree's forms, moved only on the data table page
1492
+ };
1493
+
1494
+ <CrudTree<Region, RegionItem>
1495
+ api={REGIONS} inputs={REGION_INPUTS} columns={REGION_COLUMNS} form={REGION_FORM} place={REGION_TREE}
1496
+ tree={{ loadChildren, fill: true, "aria-label": "Regions" }}
1497
+ details={({ row, body, actions }) => <AdminPanel title={row?.name ?? "Details"} action={actions}>{body}</AdminPanel>}
1498
+ />
1499
+ <Crud<Region> api={REGIONS} columns={REGION_COLUMNS} inputs={REGION_INPUTS} trees={[REGION_TREE]} /> // the data table page
1500
+ ```
1501
+
1502
+ - **Actions.** Add New under any row (Insert), Edit (F2) and Move to trash (Delete) on a record's row, all three in its
1503
+ context menu, Add New in the toolbar; the picked record's panel offers what its list offers - Recover and Delete
1504
+ permanently once it is in the trash. The forms, questions and calls are the `Crud`'s own.
1505
+ - **The selected row.** A click or Enter on a row selects it (`TreeView` `selectedValue`): tinted, and staying so while
1506
+ focus, the arrow keys and the chevrons move on. A record's row shows the record in the panel; a row that is no record
1507
+ (a country) empties the panel and opens.
1508
+ - **A fixed place** (`placeKeys`). Every Add goes inside a row - the toolbar's inside the selected row, the one the panel
1509
+ shows; with none (or one in the trash) a press says why - and the fields that say where a record sits show read-only in
1510
+ the Add and Edit forms, with the lock and a note on any try: from the row added inside (`childValues`; a field it
1511
+ leaves out is fixed empty), or the record's own. A record moves only where those fields are offered, such as the data
1512
+ table's form. An Add started inside one row is a popup of its own, titled with its place ("Inside Bagmati", on the dock
1513
+ too): it never comes back inside another row. A record's Edit stays one popup: asked for from the other page with
1514
+ changes in it, it comes back as it is and says why, so an older form never undoes a newer save.
1515
+ - **Nothing read again.** A change is written into the tree and the pages it keeps (`writeTreeChanges`): an added record
1516
+ goes where `compare` puts it among its loaded siblings and is shown there - or, under a parent never opened, into its
1517
+ count, the parent left closed, since opening it would read its page - an edit is written in place or moved, a trashed
1518
+ one leaves, and each parent's count and chevron follow. A save is not read back either: the record is built as `Crud`
1519
+ builds it, its joined names from the form, the page, or the parent the tree holds.
1520
+ - **Another page's changes.** A `Crud` given the same placement in `trees` writes its changes into the tree's kept pages,
1521
+ so the tree opened next shows them without a call.
1522
+
1523
+ ### Excel import and export
1524
+
1525
+ A model's records in and out of a spreadsheet, against the backend's Excel controller bases
1526
+ (`NexusExcelController<TContract>` and `NexusExcelExportController<TContract>`): `Excel/Settings`, `Excel/Template`,
1527
+ `Excel/Verify`, `Excel/Import`, and the model's own export action.
1528
+
1529
+ ```tsx
1530
+ export const CITIES = MODULES.controller(NexusModule.Configuration, "City", "city");
1531
+ export const CITY_SHEET = excelEndpoints(CITIES, { subject: "city" }); // the four, and Excel/Export
1532
+
1533
+ openExcelImport({ endpoints: CITY_SHEET, subject: "city", onImported: reload }); // the panel as a window
1534
+ <ExcelImport endpoints={CITY_SHEET} subject="city" onImported={reload} /> // or in the page
1535
+ openExcelImport({ endpoints: REGION_SHEET, subject: "region", mode: "bulk", onImported: reload }); // rows typed in
1536
+
1537
+ await downloadExcelTemplate(CITY_SHEET);
1538
+ await exportExcel(CITY_SHEET, { subject: "city", rows: table.matches, query: { search, sort: "cityName", direction: "asc", filters } });
1539
+ ```
1540
+
1541
+ - **The template** is the backend's file, downloaded under the name its `Content-Disposition` gives it. Every list in it
1542
+ is a dropdown and the ids beside a choice fill themselves, so the person types no code and pastes no id.
1543
+ - **A verify writes nothing.** The file goes up as form data, and the answer is the rows, judged: what would be added,
1544
+ what is already a record, and what is waiting on a fix.
1545
+ - **The review is two editors** over those rows - **New rows** (which includes the rows to fix, since a row with a
1546
+ problem is not yet a record) and **Already there**, which folds away - built from the sheet's columns with the rules
1547
+ the sheet told the person about, so a fix made here is checked the way the file was. What the server found wrong is
1548
+ listed under the rows, each entry naming the cell as a spreadsheet does (`B7 - City name`) and taking the caret to it.
1549
+ Rows can be added to the new rows (Add, Insert, Duplicate); one added and left empty is not sent, and an added row is
1550
+ numbered after every row of the file, so no two rows share a number. A sheet with a required list takes no added
1551
+ rows: a list's key is picked in the spreadsheet, and a row added here could never have one.
1552
+ - **A bulk insert is an import with no file** (`mode: "bulk"`): the new rows' editor opens with one empty row, the
1553
+ person types the rows, and they go to the same `Excel/Import` with the same checks - a problem then names its row
1554
+ (`Row 3 - Region name`). A sheet with a required list cannot be typed in, and the panel says so.
1555
+ - **Nothing typed is lost unasked**: closing the window or Start over asks first, and the entry picked again while its
1556
+ window is minimized (by a page's rule or from code: the window has no minimize button of its own) brings that window back. An import that wrote nothing keeps the rows, and lists under them what
1557
+ the backend refused and why.
1558
+ - **The import sends rows, never the file again**, or every fix made on screen would be lost; every check runs again on
1559
+ the way in. **A duplicate is never updated**: one left alone is not sent at all, and editing one sends it as a new
1560
+ record. An import writes what it can and names the rest; only one that wrote nothing at all is a failure.
1561
+ - **A choice travels as its key**, out and back. The plain id in the sheet is for the person to read and is never read
1562
+ back, so nothing copied out of a file or out of an answer can be posted to an endpoint as an id.
1563
+ - **The export is the server's file**, written from the search, the sort and the filters on screen - not a CSV of the
1564
+ rows this browser holds. The row limit is the backend's (`Excel/Settings`, 5,000 by default, kept for the page's life);
1565
+ over it the person is asked first, and the answer's own headers say what was written and what was left out.
1566
+ - **Generic, like the rest.** `ExcelBackend` is the class an app on another backend registers
1567
+ (`defineExcelBackend(new MyExcelBackend())`): the request shapes, how the answers read, the upload field, and the names
1568
+ of a download's headers. `NexusExcelBackend` is the default. `readExcelResponse` reads a refusal's `errorMessages`, so
1569
+ "no city could be written" reaches the person in the backend's own words.
1570
+ - **A column draws its own input**: text, note, whole number, decimal, amount, date, time, Yes/No, and a choice shown
1571
+ read-only with the words the person picked. A **date and time** is a text box, not a picker: the sheet's moment is a
1572
+ zone-less wall clock while a picker's value is a UTC moment, so a picker would shift every value by the reader's offset.
1573
+ - `scripts/test-excel.mts` checks the endpoints, the answers, the inputs and the round trip; the template's
1574
+ `scripts/browser-checks/excel.cjs` checks `/demo/excel`: every state, the two rules about the wire, both downloads, the
1575
+ warning before a capped export, a phone, and contrast in every theme.
1576
+
1577
+ In a table, `excel={{ endpoints: CITY_SHEET, subject: "city" }}` is the whole of it: the options menu (⋮) then offers
1578
+ **Download template**, **Import from a spreadsheet** (the panel as a window, after which the table reads its rows
1579
+ again), **Bulk insert** (the same with no file, beside an Add only; `bulk: false` leaves it out) and **Export to
1580
+ Excel**, which sends the table's own search, filters and sort with the page's `filters()`. A `Crud` passes it through
1581
+ as `table={{ excel }}` and drops the lists it had kept once an import has written. It replaces `onImport`, which stays
1582
+ for a page that imports its own way. Each item asks the app's permissions (`canCall`) for every endpoint it needs, the
1583
+ settings included - the template and the export their own, the import and the bulk insert Verify and Import - so a
1584
+ person the backend would refuse is not offered it. A download whose settings call fails stops there: one toast.
1585
+
1586
+ Planned, following the previous Nexus project: a page status layout, and in the CRUD, audit logs in the details view.
1587
+
1588
+ ### Pictures and documents
1589
+
1590
+ A record's pictures and documents are the files of an **owner** (a row of a module) in a **category** (what they are
1591
+ for: the kinds it takes, the size, how many an owner keeps, the thumbnail's size). A page declares them by params - the
1592
+ owner's `module`, the `category`, the `ownerId`, and for a picture its `aspect`, `shape`, `maxWidth`/`maxHeight`,
1593
+ `type` and `quality` - and every piece runs on the app's `FileAdapter`:
1594
+
1595
+ | Piece | From | What it is |
1596
+ |---|---|---|
1597
+ | `EInputTypes.Picture` (`PictureInput`) | `nexus-shared` / `/client` | In a form: the owner's main picture, Upload, Edit, Remove, All pictures (a click on the picture opens them too); in a category that keeps one file, Replace and Delete. Changed at once: the form keeps no field for it (`holdsValue`), so a save sends nothing under its name, and it takes no `required`. `ownerId` null: "Save the record first". |
1598
+ | `PictureGallery`, `openPictureGallery` | `nexus-shared/client` | An owner's pictures in two panes: the main picture large with Upload and Remove and the count, then a grid of rounded squares, each with View, Make main, Edit and Delete inside it (on hover, on a keyboard's focus, always by touch; neither Make main nor Delete on the main one). Upload several, up to the category's count; edits are saved as new pictures. Under 560px the main picture sits small over the grid |
1599
+ | `DocumentList` | `nexus-shared/client` | The same as a list, for a category that takes PDF (the gallery picks it itself): kind, size, date, open, rename, delete |
1600
+ | `pictureColumn` | `nexus-shared/client` | A table column with each row's picture: the page's rows in one call (`primaryPictures`), a click opens the row's gallery |
1601
+ | `OwnerPicture`, `usePrimaryPicture`, `useOwnerFiles` | `nexus-shared/client` | The small picture, the kept main picture, and the files with every change, for a page's own layout |
1602
+ | `loadImageEditor`, `preloadImageEditor` | `nexus-shared/client` | The image editor, downloaded from the file backend the first time it is needed; never in the bundle |
1603
+ | `FileAdapter`, `NexusDriveAdapter`, `defineFileAdapter` | `nexus-shared` / `/client` | Where files are kept: the Nexus Drive by default, any other backend by one class |
1604
+
1605
+ ```tsx
1606
+ import { EInputTypes, NexusModule } from "nexus-shared";
1607
+ import { openPictureGallery, pictureColumn } from "nexus-shared/client";
1608
+
1609
+ const LOGO = { module: NexusModule.Enterprise, category: "company-logo", aspect: 1 };
1610
+ inputs: (action, row) => [{ type: EInputTypes.Picture, name: "logo", label: "Logo", ...LOGO, ownerId: row?.id, subject: "company" }, ...];
1611
+ columns: [pictureColumn({ ...LOGO, rowTitle: row => row.companyName }), ...];
1612
+ ```
1613
+
1614
+ - **Every picture goes through the editor before it is stored**: the picture input's Upload and Edit, and the gallery's
1615
+ Upload one picture at a time ("Picture 2 of 5" in its title; Cancel skips one and asks "Go on with the next file?" -
1616
+ Next file or Stop here). Documents (a PDF) are sent as they are. **The browser makes what is stored, within the
1617
+ category's picture limits**, which Drive's `File/List` answers from its settings (`pictureMaxSide`, `pictureQuality`,
1618
+ `pictureMaxBytes`; `pictureLimits` gives `PICTURE_LIMITS`, 1920 px, 80% and 300 KB, when a backend says none): the
1619
+ editor crops to the shape, brings the long edge down to `pictureMaxSide` (less when the params say), starts the
1620
+ quality at most at `pictureQuality` (its slider's top), and writes the file under `pictureMaxBytes` - a PNG with
1621
+ nothing see-through as a JPEG, one with see-through parts as a WebP where the browser writes it (else a smaller PNG),
1622
+ then a lower quality step by step, then a smaller picture - showing the real size in its Save panel and saying when it
1623
+ had to shrink; the toast says so too. It writes only kinds the category takes (`types`): where it takes neither JPEG
1624
+ nor WebP, a PNG too large is made smaller. A picture the browser could not type (a phone's share, a name with no
1625
+ extension) is typed from its bytes (`typedFile`) and goes through the editor too. When the editor cannot be
1626
+ downloaded, the picture input and the gallery say why under their buttons until a try opens it. It makes the thumbnail at the category's size. A kind the category refuses is
1627
+ said before anything is made; a picture's size is checked against `pictureMaxBytes`, a document's against the
1628
+ category's own (`fileRefusal`). The gallery's line says both. The backend checks the bytes again.
1629
+ - **A gallery opened without `view`** takes its title and icon from the category once it is read: "Documents" for one
1630
+ that takes PDF. A page's rows whose read is refused or fails show no picture for 30 s (`retryAfter`), not one call
1631
+ per redraw.
1632
+ - **With Nexus** (`NexusDriveAdapter`), the owner's module decides who may change the files: the adapter asks it for a
1633
+ write ticket (`{module}/Files/Ticket/{category}/{ownerId}`, `me` for a person's own), keeps it until a minute before
1634
+ it runs out and asks again once when Drive says it ran out (`DRV_X011`); a person refused a write ticket sees the
1635
+ files read only through a read ticket (`Files/Owners/{category}`), which also reads a page's rows at once. The bytes
1636
+ are Drive's `File/View/{id}/{Original|Thumbnail}` through the app's proxy.
1637
+ - **The editor** is served by the backend at a versioned address (Drive: `Assets/File/nexus-image-editor.txt` names the
1638
+ current `nexus-image-editor.<hash>.js`), imported with the bundler told to leave it alone, once per page
1639
+ (`importModule`, built without the import-extension rewrite so `dist` keeps a plain `import(url)` that webpack,
1640
+ Turbopack and Vite leave to the browser; `test-dist-loader` guards it). When it cannot load (the network, a 404, a
1641
+ bundler), the person gets a toast in plain words and the console the cause.
1642
+ - **Read only, and why.** `lockReason: "The branch is closed."` makes the files read only with that sentence under
1643
+ them; a person the backend lets only look is told the backend's words (`OwnerFiles.readOnlyReason`), and the files
1644
+ of an owner not in use (trashed, ended) say so (`OWNER_NOT_IN_USE_REASON`).
1645
+ - **Initials.** `pictureColumn({ ..., nameKey: "fullname" })` (or `OwnerPicture name`) shows an owner with no picture
1646
+ as the name's initials, on the shared `Avatar`'s tone for that name.
1647
+ - **The keyboard's focus stays.** While a change saves, the buttons stay focusable (`aria-disabled`, the press ignored:
1648
+ `busyProps`), and when the focused one goes with the change (Remove, a star, a deleted file's) the focus moves to the
1649
+ first control left in its tile, else in the input (`useFocusThroughChange`), never to the page.
1650
+ - **Another backend**: `defineFileAdapter(new MyFiles())`, a class with `list`, `primaries`, `upload`, `setPrimary`,
1651
+ `rename`, `remove`, `fileUrl` and `editorModuleUrl`, answering `ApiResult`s; nothing else changes.
1652
+
1653
+ ### A record's page of cards
1654
+
1655
+ `RecordCards` draws one record that is not a list - a person's profile, my company, a subscriber's details - as a hero
1656
+ across the top and cards under it, from params alone. **The page never saves**: a card's Edit, a list's Add and an
1657
+ item's icon actions open popups, and each answer is written into the card at once (every card on the same source
1658
+ follows, the hero too, with nothing read again).
1659
+
1660
+ ```tsx
1661
+ <RecordCards
1662
+ name="profile"
1663
+ sources={{ profile: { read: ACCOUNT_API.profile, held: { fullName: user.fullName } }, emails: ACCOUNT_API.emails }}
1664
+ hero={{ source: "profile", title: p => p.fullName, lines: p => [`@${p.username}`], picture: p => ({ ...OWN_PICTURE, ownerId: p.id }) }}
1665
+ signedOut={{ onSignIn: () => window.location.assign(signInHref("profile")) }}
1666
+ cards={[
1667
+ fieldsCard<Profile>({ id: "personal", source: "profile", title: "Personal details", fields: [FULL_NAME, DATE_OF_BIRTH, GENDER], edit: { submit: ACCOUNT_API.saveProfile } }),
1668
+ itemsCard<ContactList, Contact>({
1669
+ id: "emails", source: "emails", title: "Emails", items: "items", itemKey: "id", limit: "maxCount",
1670
+ item: e => ({ title: e.address, marks: e.isPrimary ? [{ label: "Primary", tone: "primary" }] : [] }),
1671
+ add: { title: "Add an email", inputs: [EMAIL], submit: ACCOUNT_API.addEmail },
1672
+ itemActions: [{ id: "remove", label: "Remove", icon: <InlineIcon icon={iconTrash} />, tone: "danger",
1673
+ held: e => (e.isPrimary ? "The primary email cannot be removed." : null),
1674
+ confirm: { title: ({ item }) => `Remove ${item!.address}?`, submit: ACCOUNT_API.removeEmail, transform: ({ item }) => ({ id: item!.id }) } }],
1675
+ }),
1676
+ ]}
1677
+ />
1678
+ ```
1679
+
1680
+ - **Sources** are read once each (GET through `api`, or a function answering an `ApiResult`); `held` is drawn while a
1681
+ read runs. A card names its `source` (default the first).
1682
+ - **Fields cards** draw each value by the `InputParams` that edit it: a choice by its label, a date in the person's
1683
+ format, Yes or No, chips (`look: "chips"`, a multiple choice), long text on its lines, "Not said" (`empty`) when empty.
1684
+ `edit` opens a popup of those inputs on the record; the values are sent merged over the record as held now, so an
1685
+ endpoint that takes the whole record works.
1686
+ - **Items cards** list rows with icon actions on the right, each named as a tooltip and to a screen reader with its
1687
+ item, hidden (`hidden`), or held with its reason (`held`: aria-disabled, said in a note when pressed). `add` sits in
1688
+ the heading, held at the `limit` ("5 of 5").
1689
+ - **Popups** are one step or `steps` (`start`, `next`): a sentence (`lead`), inputs, `submit`, `transform`, `writes`, a
1690
+ button that calls and stays (`also`, held while the server says to wait), and `done` to run another action next
1691
+ (`run("verify", added)`). A form opens only on the plain values its inputs name (and a rows input on its rows).
1692
+ `confirm` asks, then calls.
1693
+ - **A step's form**: each step is handed its `form`, and `inputs` as a function gets it, so a label or `hidden` can
1694
+ follow another input as typed (`inputs: ({ form }) => addressInputs(form)`, getters with `dependsOn`). `validate`
1695
+ is the step's own rule over its values; `fresh: true` (or `goTo(id, { fresh: true })`) shows a step reached again
1696
+ with nothing of before (an old code, a password). A password or a code typed is never asked about before it goes.
1697
+ - **Heading buttons** are named with their card ("Edit: Personal details"), held ("Still being read.") until the data is
1698
+ read - their `hidden` and `held` are asked only then, `loading: "hidden"` draws one only then - and go under the
1699
+ title where the card is narrow. `heldRows`, `heldRowLines` and a field's `heldLines` hold what the data usually
1700
+ takes, so nothing under a card moves when it comes.
1701
+ - **`writes`**: the answer merged over the data (default), the values, one item replaced or added (`"item"`), the item
1702
+ removed (`"remove"`), a read again, named fields, or a function.
1703
+ - **States** are the piece's: the cards held as they will be while they load, a failed read in each of its cards with
1704
+ Try again, `readOnly` with no button anywhere, and `signedOut` - an answer that ended the session closes the popups
1705
+ and leaves the page's words and its way back in.