shared-lib-web 0.0.3 → 0.0.5

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 (58) hide show
  1. package/README.md +193 -783
  2. package/dist/components/otp-modal.d.ts +5 -0
  3. package/dist/components/otp-modal.d.ts.map +1 -0
  4. package/dist/components/otp-modal.js +77 -0
  5. package/dist/components/otp-modal.js.map +1 -0
  6. package/dist/components/settings-menu.d.ts +1 -1
  7. package/dist/components/settings-menu.d.ts.map +1 -1
  8. package/dist/components/settings-menu.js +1 -1
  9. package/dist/components/settings-menu.js.map +1 -1
  10. package/dist/components/user-menu.d.ts.map +1 -1
  11. package/dist/components/user-menu.js +22 -5
  12. package/dist/components/user-menu.js.map +1 -1
  13. package/dist/i18n/default-messages.d.ts.map +1 -1
  14. package/dist/i18n/default-messages.js +12 -0
  15. package/dist/i18n/default-messages.js.map +1 -1
  16. package/dist/index.d.ts +5 -3
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +4 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/interfaces/ui-config.d.ts +25 -1
  21. package/dist/interfaces/ui-config.d.ts.map +1 -1
  22. package/dist/state/auth-service.d.ts +5 -0
  23. package/dist/state/auth-service.d.ts.map +1 -1
  24. package/dist/state/auth-service.js +25 -2
  25. package/dist/state/auth-service.js.map +1 -1
  26. package/dist/state/layout-choice-service.d.ts +3 -3
  27. package/dist/state/layout-choice-service.d.ts.map +1 -1
  28. package/dist/state/layout-choice-service.js +8 -6
  29. package/dist/state/layout-choice-service.js.map +1 -1
  30. package/dist/state/otp-service.d.ts +69 -0
  31. package/dist/state/otp-service.d.ts.map +1 -0
  32. package/dist/state/otp-service.js +212 -0
  33. package/dist/state/otp-service.js.map +1 -0
  34. package/dist/types/field-wrapper.d.ts +2 -0
  35. package/dist/types/field-wrapper.d.ts.map +1 -1
  36. package/dist/types/field-wrapper.js +3 -2
  37. package/dist/types/field-wrapper.js.map +1 -1
  38. package/dist/types/type.otp.d.ts +2 -0
  39. package/dist/types/type.otp.d.ts.map +1 -1
  40. package/dist/types/type.otp.js +2 -2
  41. package/dist/types/type.otp.js.map +1 -1
  42. package/dist/utils/app-http.d.ts +12 -0
  43. package/dist/utils/app-http.d.ts.map +1 -1
  44. package/dist/utils/app-http.js +75 -1
  45. package/dist/utils/app-http.js.map +1 -1
  46. package/package.json +1 -1
  47. package/src/components/otp-modal.tsx +154 -0
  48. package/src/components/settings-menu.tsx +2 -2
  49. package/src/components/user-menu.tsx +41 -12
  50. package/src/i18n/default-messages.ts +12 -0
  51. package/src/index.ts +31 -1
  52. package/src/interfaces/ui-config.ts +26 -1
  53. package/src/state/auth-service.ts +28 -2
  54. package/src/state/layout-choice-service.ts +8 -6
  55. package/src/state/otp-service.ts +283 -0
  56. package/src/types/field-wrapper.tsx +5 -2
  57. package/src/types/type.otp.tsx +11 -2
  58. package/src/utils/app-http.ts +80 -1
package/README.md CHANGED
@@ -1,885 +1,295 @@
1
1
  # shared-lib-web
2
2
 
3
- A shared **React 19 component library** for DesignForFeature apps, shipped as one npm package.
4
- Open source under the [MIT license](./LICENSE): free for anybody to use.
3
+ React 19 component library for DesignForFeature apps: provider, Type* form controls, layouts, i18n (RTL/LTR),
4
+ DaisyUI themes, Signals state, AppHttp / AppStorage. Built on `dff-util`. MIT license.
5
5
 
6
- | Entry | Required? | What |
7
- | --- | --- | --- |
8
- | `shared-lib-web` | **yes** | Provider, all Type* controls, page blocks, menus, switchers, overlays, skeletons, states, i18n, themes, AppHttp / AppStorage |
9
- | `shared-lib-web/layout` | optional | Ready-made app shell: one **single layout** (`AppLayout`, `AsideLayout`, `AuthLayout`) or its **individual parts** (`Header`, `Sidebar`, `SidebarNav`, `MegaMenuBar`, `MegaMenuPanel`, `RailFlyout`) |
10
- | `shared-lib-web/markdown` | optional | `TypeMdx`, `TypeMdv`, `TypeLangMd` (needs `@uiw/react-md-editor`) |
11
-
12
- The project decides the layout: use `AppLayout` as it is, turn off / replace its parts, build an own layout from the
13
- single parts, or skip `shared-lib-web/layout` completely and write the whole layout itself.
14
-
15
- An app keeps **only**:
16
-
17
- 1. `config.ts` – app name, logos, layout, http and the loaders: `loadLocale`, `loadThemes`, `loadSupportLanguages`,
18
- `loadBranches`, `loadMenuNavigation` (the provider calls them itself)
19
- 2. `<SharedWebUiProvider type="spa" | "shell" | "mfe" config={config}>
20
- 3. `locales/<code>/<group>.json` – its texts, one folder per language and one file per group (`en-US/nav.json` …)
21
- 4. its pages / modules
22
-
23
- Everything else lives in the library: components and (optionally) layouts, header, sidebar (with icon rail),
24
- full-width mega menu, pages by query parameter (no router), DaisyUI light/dark themes, lightweight i18n, RTL/LTR, permissions,
25
- localStorage persistence, toasts, skeletons, overlays and `react-hook-form` controls.
26
-
27
- Stack: React 19 · TypeScript (strict) · Vite · Tailwind CSS 4 · DaisyUI 5 · `@preact/signals-react` ·
28
- `lucide-react` (through `TypeIcon`) · `react-hook-form` · `dff-util`.
29
- **No router (no react-router-dom), no AG Grid.** Markdown fields are an optional extra entry (`shared-lib-web/markdown`).
30
-
31
- The source follows strict readability rules (no nested functions, no `abcd(xyz())`, no chained calls,
32
- lowercase file names) – see [CODING_RULES.md](./CODING_RULES.md). AI agents: read `.agent/skills/` in the repository.
33
-
34
- ---
6
+ | Entry | What |
7
+ | --- | --- |
8
+ | `shared-lib-web` | provider, controls, components, signals, services, AppHttp, AppStorage |
9
+ | `shared-lib-web/layout` | optional app shell: `AppLayout`, `AsideLayout`, `AuthLayout` and parts |
10
+ | `shared-lib-web/markdown` | optional markdown controls (needs `@uiw/react-md-editor`) |
11
+ | `shared-lib-web/styles.css` | Tailwind source hint for the library classes |
35
12
 
36
13
  ## Install
37
14
 
38
15
  ```bash
39
16
  npm install shared-lib-web dff-util react react-dom @preact/signals-react lucide-react react-hook-form
40
- npm install -D tailwindcss daisyui # + your bundler's Tailwind plugin, e.g. @tailwindcss/vite or @tailwindcss/postcss
41
- # optional, only for shared-lib-web/markdown
42
- npm install @uiw/react-md-editor
17
+ npm install -D tailwindcss daisyui @tailwindcss/vite
18
+ npm install @uiw/react-md-editor # only for shared-lib-web/markdown
43
19
  ```
44
20
 
45
- ## CSS
46
-
47
21
  ```css
48
22
  /* src/index.css */
49
23
  @import "tailwindcss";
50
- @import "shared-lib-web/styles.css"; /* lets Tailwind find the classes used inside the library */
51
- @plugin "daisyui" {
52
- themes: all; /* all 35 DaisyUI themes; or list the ones you need */
53
- }
24
+ @import "shared-lib-web/styles.css";
25
+ @plugin "daisyui" { themes: all; }
54
26
  ```
55
27
 
56
- `config.themes` is optional: without it the theme switcher offers all 35 DaisyUI themes (enable them with
57
- `themes: all`, or list the ones you need and pass the same names in `config.themes`). The dark ones (dark logo,
58
- dark markdown editor) default to the DaisyUI dark themes; `config.darkThemes` replaces that list.
59
-
60
- ### Custom themes as JSON (no CSS file, no rebuild)
61
-
62
- Your own themes are plain data: an **object keyed by theme name**, each with `isDark`, `name` and the DaisyUI theme
63
- variables (`name` may be left out — the key is the name; a plain list `[{ name, ... }]` still works). Pass them with
64
- `config.loadThemes` (or `config.customThemes`); they are listed first in the switcher, and `isDark: true` adds them to the dark themes.
65
- The library writes one `<style>` with `[data-theme="org-dark"] { color-scheme: dark; --color-primary: …; }`, which
66
- DaisyUI's components read like a built-in theme.
67
-
68
- ```json
69
- // src/theme/org-themes.json
70
- {
71
- "org-dark": {
72
- "isDark": true,
73
- "name": "org-dark",
74
- "variables": {
75
- "border": "1px",
76
- "color-accent": "oklch(70.4% 0.04 256.8)",
77
- "color-accent-content": "oklch(12.9% 0.042 264.7)",
78
- "color-base-100": "oklch(25.5% 0.04 264.5)",
79
- "color-base-200": "oklch(20.8% 0.042 265.8)",
80
- "color-base-300": "oklch(32% 0.04 262)",
81
- "color-base-content": "oklch(92.9% 0.013 255.5)",
82
- "color-error": "oklch(70.4% 0.191 22.2)",
83
- "color-error-content": "oklch(25.8% 0.092 26)",
84
- "color-info": "oklch(78.9% 0.154 211.5)",
85
- "color-info-content": "oklch(30.2% 0.056 229.7)",
86
- "color-neutral": "oklch(37.2% 0.044 257.3)",
87
- "color-neutral-content": "oklch(96.8% 0.007 247.9)",
88
- "color-primary": "oklch(74.6% 0.16 232.7)",
89
- "color-primary-content": "oklch(29.3% 0.066 243.2)",
90
- "color-secondary": "oklch(82.8% 0.189 84.4)",
91
- "color-secondary-content": "oklch(27.9% 0.077 45.6)",
92
- "color-success": "oklch(79.2% 0.209 151.7)",
93
- "color-success-content": "oklch(26.6% 0.065 152.9)",
94
- "color-warning": "oklch(75% 0.183 55.9)",
95
- "color-warning-content": "oklch(26.6% 0.079 36.3)",
96
- "depth": "1",
97
- "noise": "0",
98
- "radius-box": "0.75rem",
99
- "radius-field": "0.5rem",
100
- "radius-selector": "1rem",
101
- "size-field": "0.25rem",
102
- "size-selector": "0.25rem"
103
- }
104
- },
105
- "org-light": {
106
- "isDark": false,
107
- "name": "org-light",
108
- "variables": {
109
- "border": "1px",
110
- "color-accent": "oklch(55.4% 0.046 257.4)",
111
- "color-accent-content": "oklch(98.4% 0.003 247.9)",
112
- "color-base-100": "oklch(100% 0 0)",
113
- "color-base-200": "oklch(96.8% 0.007 247.9)",
114
- "color-base-300": "oklch(92.9% 0.013 255.5)",
115
- "color-base-content": "oklch(20.8% 0.042 265.8)",
116
- "color-error": "oklch(55% 0.23 27.3)",
117
- "color-error-content": "oklch(97.1% 0.013 17.4)",
118
- "color-info": "oklch(71.5% 0.143 215.2)",
119
- "color-info-content": "oklch(30.2% 0.056 229.7)",
120
- "color-neutral": "oklch(27.9% 0.041 260)",
121
- "color-neutral-content": "oklch(98.4% 0.003 247.9)",
122
- "color-primary": "oklch(55.8% 0.154 249.1)",
123
- "color-primary-content": "oklch(98.5% 0.01 240)",
124
- "color-secondary": "oklch(76.9% 0.188 70.1)",
125
- "color-secondary-content": "oklch(27.9% 0.077 45.6)",
126
- "color-success": "oklch(52.7% 0.154 150.1)",
127
- "color-success-content": "oklch(98.2% 0.018 155.8)",
128
- "color-warning": "oklch(75% 0.183 55.9)",
129
- "color-warning-content": "oklch(26.6% 0.079 36.3)",
130
- "depth": "1",
131
- "noise": "0",
132
- "radius-box": "0.75rem",
133
- "radius-field": "0.5rem",
134
- "radius-selector": "1rem",
135
- "size-field": "0.25rem",
136
- "size-selector": "0.25rem"
137
- }
138
- }
139
- }
140
- ```
141
-
142
- Load them lazily with `loadThemes`, the same way as `loadLocale` (its own chunk, loaded when the provider mounts):
143
-
144
28
  ```ts
145
- // config.ts
146
- import type { CustomThemesModule, UiConfig } from "shared-lib-web";
147
-
148
- function loadThemes(): Promise<CustomThemesModule> {
149
- return import("./theme/org-themes.json");
150
- }
151
-
152
- export const config: UiConfig = {
153
- appNameKey: "ORG",
154
- loadThemes: loadThemes, // + all 35 DaisyUI themes (themes is optional)
155
- };
29
+ // vite.config.ts — dff-util needs Node's global
30
+ export default defineConfig({ plugins: [react(), tailwindcss()], define: { global: "globalThis" } });
156
31
  ```
157
32
 
158
- `loadThemes` can also read from your API or a file deployed next to the app (change the themes without a build):
33
+ ## config.ts
159
34
 
160
35
  ```ts
161
- async function loadThemes(): Promise<CustomThemesModule> {
162
- const response = await fetch("/themes.json");
163
- return response.json();
164
- }
165
- ```
36
+ import { loadLocaleGroups, type UiConfig } from "shared-lib-web";
166
37
 
167
- While they load, a saved custom theme stays on screen (no flash of the default theme); when the load fails or the
168
- saved theme is not in the result, the default theme is used. Themes you already have in code can go straight into
169
- `customThemes: orgThemes` (no loading; the object keyed by name, or a list); both together are merged, and a loaded theme replaces one with the same name.
170
-
171
- The variable names are the DaisyUI ones, with or without `--`: `color-base-100/200/300`, `color-base-content`,
172
- `color-primary`, `color-primary-content`, `color-secondary`, `color-accent`, `color-neutral`, `color-info`,
173
- `color-success`, `color-warning`, `color-error` (each with `-content`), `radius-selector`, `radius-field`,
174
- `radius-box`, `size-selector`, `size-field`, `border`, `depth`, `noise`. Theme names may use lowercase letters,
175
- digits and `-`; values with `; { } < > " \` are skipped (safe for JSON from a server).
176
-
177
- **Or a signal:** `loadThemes: themesSignal` (`signal<CustomThemesModule | null>(null)`). `null` = not here yet (a
178
- saved custom theme stays on screen); every new value replaces the loaded themes:
179
-
180
- ```ts
181
- const themeModule = await import("./theme/org-themes.json");
182
- themesSignal.value = themeModule;
183
- ```
184
-
185
- Any time later (for example after the user signs in) `setCustomThemes(themes)` replaces the custom themes (the object
186
- keyed by name or a list). `toCustomThemeList(themes)` turns the object into a list (`CustomTheme[]`, key order).
187
-
188
- The theme dropdown, the ⚙ settings dialog and the example Settings page show **Light themes** and **Dark themes**
189
- as two groups (split by the dark themes). In your own UI: `const { lightThemes, darkThemes } = useUi();`
190
- or `splitThemesByMode(themes)`, `isDarkThemeName(theme)`. Texts: `ui.lightThemes`, `ui.darkThemes`.
191
-
192
- ## App bundler (Vite example)
193
-
194
- The library itself has no bundler. Your **app** uses its own (Vite, Next.js, webpack …).
195
- `dff-util` uses packages that expect Node's `global`, so define it — with Vite:
196
-
197
- ```ts
198
- export default defineConfig({
199
- plugins: [reactPlugin, tailwindPlugin],
200
- define: { global: "globalThis" },
201
- });
202
- ```
203
-
204
- ---
205
-
206
- ## 1. config.ts
207
-
208
- ```ts
209
- import { loadLocaleGroups, readEnvData, toAbsoluteUrl, type CustomThemesModule, type UiConfig } from "shared-lib-web";
210
-
211
- const APP_NAME_KEY = "ORG";
212
- const APP_API_KEY = APP_NAME_KEY.toLowerCase(); // "org" -> /org-api, /org-sor ...
213
-
214
- // window.env.REACT_APP_ORG_API_BASE_URL (env.js), else the default
215
- const envBaseUrl = readEnvData(APP_NAME_KEY, "API_BASE_URL");
216
- const API_BASE_URL = toAbsoluteUrl(envBaseUrl ?? "https://api.example.com/api");
217
-
218
- // Service paths are PROJECT level (not part of AppHttp). AppHttp adds the base URL to a path:
219
- // AppHttp.Get(`${MsUrl.main}/menu-access`) -> https://api.example.com/api/org-api/menu-access
220
- export const MsUrl = {
221
- api: `/${APP_API_KEY}-api`,
222
- main: `/${APP_API_KEY}-api`,
223
- sor: `/${APP_API_KEY}-sor`,
224
- events: `/${APP_API_KEY}-events`,
225
- tms: `/${APP_API_KEY}-tms`,
226
- utils: `/${APP_API_KEY}-util`,
227
- };
228
-
229
- /** locales/<code>/<group>.json — lazy: only the files of the language in use are downloaded (see section 2) */
38
+ export const MsUrl = { main: "/org-api", sor: "/org-sor", utils: "/org-util" };
230
39
  const localeFiles = import.meta.glob("./locales/*/*.json");
231
40
 
232
- /** theme/org-themes.json, loaded lazily like the locale files (see "Custom themes as JSON") */
233
- function loadThemes(): Promise<CustomThemesModule> {
234
- return import("./theme/org-themes.json");
235
- }
236
-
237
41
  export const config: UiConfig = {
238
- appNameKey: APP_NAME_KEY, // key: storage ORG-TOKEN, env REACT_APP_ORG_API_BASE_URL
239
- loadCompanyDetails: `${MsUrl.sor}/company-details`, // app name, logos, favicon from the backend (see "Company details")
240
- // appName / logoUrl / logoDarkUrl: only for apps WITHOUT company details (static brand)
241
- // defaultLanguage: "en-US", // optional: without it the browser / system language, else en-US
42
+ appNameKey: "ORG", // storage ORG-TOKEN, env REACT_APP_ORG_API_BASE_URL
242
43
  loadLocale: loadLocaleGroups.bind(null, localeFiles),
243
- // defaultTheme: "light", // optional: without it the browser preference picks "dark" or "light"
244
- loadThemes: loadThemes, // optional: your own themes as JSON (see "Custom themes as JSON")
245
- // themes: ["light", "dark"], // optional: default all 35 DaisyUI themes
44
+ loadSupportLanguages: `${MsUrl.sor}/load/LANG`,
45
+ loadCompanyDetails: `${MsUrl.sor}/company-details`,
46
+ loadBranches: `${MsUrl.main}/branches`,
47
+ loadMenuNavigation: `${MsUrl.utils}/menu-access`,
246
48
  layout: { menuMode: "sidebar", isSidebarCollapsible: true },
247
- http: { baseUrl: API_BASE_URL, logoutUrl: "/login" },
49
+ http: {
50
+ baseUrl: "https://api.example.com/api",
51
+ logoutUrl: "/login",
52
+ regenerateUrl: `${MsUrl.utils}/jwt-regenerate`, // optional: auto JWT regenerate
53
+ },
248
54
  };
249
55
  ```
250
56
 
251
- | Setting | What it does |
252
- | --- | --- |
253
- | `defaultLanguage` | Optional. Language of the first visit (nothing saved). Without it the **browser / system language** is used: `navigator.languages` matched to the language list (exact code, else the same base language: `fr-CA` → `fr-FR`); without a list each browser code is tried and a missing locale file is skipped. Nothing matches → `"en-US"`. Keys missing in a language are shown in `defaultLanguage` (else en-US). Without `defaultLanguage`, `languages`, `loadLocale` and `loadSupportLanguages` the app runs in en-US with the library's built-in English texts and no language switcher. |
254
- | `loadLocale(code)` | Loads the texts of a language lazily (dynamic `import()` / `import.meta.glob`): `loadLocaleGroups.bind(null, localeFiles)` for `locales/<code>/<group>.json`, or your own function returning one JSON. |
255
- | `languages` | Not needed: the list comes from `loadSupportLanguages` (below). Only for apps with a fixed list (`{ code, label, flag?, direction?, load? }`). |
256
- | `themes`, `darkThemes` | Optional. The theme switcher list (default: all 35 DaisyUI themes) and the dark ones (default: the DaisyUI dark themes). Dark themes switch to `logoDarkUrl` and dark markdown. |
257
- | `customThemes`, `loadThemes` | Optional. Your own themes as data / JSON — an object keyed by theme name (`{ "org-dark": { isDark, name, variables }, ... }`) or a list — listed first: `customThemes` directly, or `loadThemes()` lazily like `loadLocale` (JSON file or API). Later ones: `setCustomThemes(json)`. |
258
- | `defaultTheme` | Optional. Theme of the first visit (nothing saved yet). Without it the browser preference decides: `"dark"` when it prefers a dark colour scheme, otherwise `"light"`. |
259
- | `layout.headerSettings` | `"inline"` (language + theme switchers in the header) or `"menu"` (one ⚙ button opening a settings dialog with language, theme and navigation style). |
260
- | `layout.showLayoutChoice` | Optional (default `false`). Adds **Layout** (App layout / Aside layout) to the ⚙ settings dialog — for a shell that renders `AppLayout` or `AsideLayout` from `layoutChoiceSignal`. Saved as `LAYOUT_CHOICE`; `<SettingsMenu showLayoutChoice />` does the same for one menu. |
261
- | `layout.toastPosition`, `layout.showScrollToTop` | Toast corner (`top-end` …) and the scroll-to-top button. |
262
- | `layout.showMenu` | Menu shown at start (default `true`); switch at runtime with `setMenuVisible()` / `toggleMenuVisible()`. |
263
- | `layout.menuMode` | `"sidebar"` (drawer + collapsible icon rail) or `"megamenu"` (top bar + full-width panels). Users can switch with `changeNavigationMode()`; the choice is saved. |
264
- | `homePath`, `layout.pageParam` | The page shown when `?page` is missing (default `/`) and the name of the page parameter (default `page`). |
265
- | `http.baseUrl` | API base URL of `AppHttp` (`window.env.REACT_APP_<APPNAMEKEY>_API_BASE_URL` wins when set; a relative `/api` becomes absolute). |
266
- | `http.logoutUrl` | Where the browser goes after `endSession()` (log out), for example `/login` or an SSO logout URL. `endSession(keepKeys, false)` stays on the page. |
267
- | `http.tokenKey`, `http.headers`, `http.loadUrl`, `http.showProgress` | Optional: AppStorage key of the token (default `TOKEN`), extra headers, `AppHttp.Load` URL or path (default `/load` on the base URL), progress bar (default `true`). |
268
- | `appNameKey` | Key of the app (`ENV_BASE_NAME`): prefix of every AppStorage key (`ORG-TOKEN`, `ORG-LANG`) and of the `window.env` names (`REACT_APP_ORG_…`). The key names are fixed constants — no `storage` / `languageKey` / `themeKey` settings. |
269
- | `appName`, `logoUrl`, `logoDarkUrl` | Optional static brand, for apps without `loadCompanyDetails`: label in header, sidebar and login (`t(config.appName)`, default `appNameKey`) and the logos. Not needed when the company details come from the backend. |
270
- | `loadCompanyDetails` | Optional. Company / brand details from the backend (`{ appName, companyName, faviconUrl, logoUrl, logoDarkUrl }`), loaded once on start; they win over `appName`, `logoUrl`, `logoDarkUrl`. See "Company details" below. |
271
- | `loadSupportLanguages`, `loadBranches`, `loadMenuNavigation` | Backend loaders the provider calls (like `loadThemes`): languages on start, branches then menu after sign in. See "Backend data" below. |
272
- | `navigation` | Not needed: the menu comes from `loadMenuNavigation` (below). Only for apps with a fixed menu and no backend (`NavItem[]`). |
273
- | `navOptions` | How the backend menu is converted: `rootMenuIds` (default: groups named "Root" or ids ending in `_ROOT`), `isRootFlattened` (default `true`). |
274
-
275
- ### Backend data: `loadSupportLanguages`, `loadBranches`, `loadMenuNavigation`
276
-
277
- Like `loadThemes`, these are loaders in the config, and the provider calls them itself — no `nav` / `lang` /
278
- `branch` props. A loader is your function returning the reply (or just a URL / path, sent with `AppHttp.Get`).
279
- Replies may be `{ data: [...], meta }` or only the list.
57
+ ## App types
280
58
 
281
- ```ts
282
- // config.ts
283
- function loadSupportLanguages(): Promise<unknown> {
284
- return AppHttp.Get(`${MsUrl.main}/languages`); // { data: [{ code: "en-US", name: "English", isDefault: true }] }
285
- }
59
+ ### spa — single app (pages in `?page=...`)
286
60
 
287
- function loadBranches(): Promise<unknown> {
288
- return AppHttp.Get(`${MsUrl.main}/branches`);
289
- }
61
+ ```tsx
62
+ import { SharedWebUiProvider, useCurrentPage, PageNotFound } from "shared-lib-web";
63
+ import { AppLayout, AuthLayout } from "shared-lib-web/layout";
290
64
 
291
- function loadMenuNavigation(): Promise<unknown> {
292
- return AppHttp.Get(`${MsUrl.main}/menu-access`, { persona: "admin" });
65
+ export function Root() {
66
+ return (
67
+ <SharedWebUiProvider type="spa" config={config}>
68
+ <App />
69
+ </SharedWebUiProvider>
70
+ );
293
71
  }
294
72
 
295
- export const config: UiConfig = {
296
- appNameKey: "ORG",
297
- loadLocale: loadLocale,
298
- loadThemes: loadThemes,
299
- loadSupportLanguages: loadSupportLanguages, // on start -> language switchers
300
- loadBranches: loadBranches, // after sign in -> branch switcher (before the menu)
301
- loadMenuNavigation: loadMenuNavigation, // after sign in -> menu (skeleton until it answers)
302
- };
303
- ```
304
-
305
- | When | What happens |
306
- | --- | --- |
307
- | Provider mounts | `loadSupportLanguages` runs once; on an error the default language stays. |
308
- | Sign in (`startSession`) or a restored session on start | `loadBranches`, then `loadMenuNavigation` (so the menu request sends `x-branch-id`). A menu error shows an empty menu, a branch error no switcher. |
309
- | Sign out (`endSession`) | Branches removed; the menu goes back to the skeleton for the next user. |
310
-
311
- **Or pass signals.** Each of the three can also be a signal you fill yourself (`null` first, then the reply). The
312
- provider follows it: every new value is shown at once, and nothing is called for it (no sign-in rule — your code
313
- decides when it changes):
314
-
315
- ```ts
316
- // nav.service.ts
317
- export const navSignal = signal<MenuSource | null>(null); // null = menu skeleton
318
- export const branchSignal = signal<BranchSource | null>(null); // null = no branch switcher
319
- export const supportLangSignal = signal<LangSource | null>(null); // null = no list yet
320
-
321
- export async function loadNav(): Promise<void> {
322
- navSignal.value = await AppHttp.Get(`${MsUrl.main}/menu-access`) as MenuSource;
73
+ export function App() {
74
+ const page = useCurrentPage();
75
+ if (!isAuthenticatedSignal.value) { // import { isAuthenticatedSignal, RequireAccess } from "shared-lib-web"
76
+ return <AuthLayout><LoginPage /></AuthLayout>;
77
+ }
78
+ const pageElement = PAGES[page] ?? <PageNotFound />;
79
+ return <AppLayout><RequireAccess key={page}>{pageElement}</RequireAccess></AppLayout>;
323
80
  }
324
-
325
- // config.ts
326
- loadSupportLanguages: supportLangSignal,
327
- loadBranches: branchSignal,
328
- loadMenuNavigation: navSignal,
329
81
  ```
330
82
 
331
- Functions, URLs and signals can be mixed (for example languages as a function, the menu as a signal).
83
+ ### shell — hosts microfrontends (pages are paths: `/settings`)
332
84
 
333
- Without `loadMenuNavigation` the menu is `config.navigation` (static). By hand, without loaders: `setLanguages(reply)`,
334
- `setBranches(reply)`, `setMenuLoading()` → `setMenu(reply)`, `clearMenu()`.
335
-
336
- ### Company details: `loadCompanyDetails`
337
-
338
- The app name, company name, favicon and logos can come from the backend:
339
-
340
- ```json
341
- // GET /org-api/company-details (or { "data": { ... } })
342
- {
343
- "appName": "YourAppName",
344
- "companyName": "YourBrandName",
345
- "faviconUrl": "https://www.w3.org/favicon.ico",
346
- "logoUrl": "https://www.w3.org/Icons/w3c_home.png",
347
- "logoDarkUrl": "https://www.w3.org/Icons/w3c_home.png"
348
- }
349
- ```
350
-
351
- ```ts
352
- // config.ts — a function, a URL / path (AppHttp.Get) or a signal, like the other loaders
353
- loadCompanyDetails: `${MsUrl.sor}/company-details`,
354
- // or: loadCompanyDetails: companySignal, // signal<CompanySource | null>(null); null = config values for now
85
+ ```tsx
86
+ <SharedWebUiProvider type="shell" config={shellConfig}>
87
+ <ShellLayout /> {/* AppLayout or AsideLayout (layoutChoiceSignal) + the MFE mount point */}
88
+ </SharedWebUiProvider>
355
89
  ```
356
90
 
357
- | Field | Used for |
358
- | --- | --- |
359
- | `appName` | Label in the header, sidebar and login (wins over `config.appName`) and the browser tab title |
360
- | `companyName` | Alt text of the logo; read `companyDetailsSignal.value?.companyName` to show it anywhere (footer, login) |
361
- | `faviconUrl` | `<link rel="icon">` (created when the page has none) |
362
- | `logoUrl` | Logo on light themes, and on dark themes without `logoDarkUrl` (wins over `config.logoUrl` / `logoDarkUrl`) |
363
- | `logoDarkUrl` | Logo on dark themes (wins over `config.logoDarkUrl`) |
364
-
365
- **No `appName`, `logoUrl` or `logoDarkUrl` in the config is needed** — the brand comes from this reply (the example
366
- apps have none in their config). Until it arrives no app name and no logo are shown (the app key does not flash);
367
- on an error the app key is shown. Every field is optional: a missing one keeps the config value, when the config
368
- has one. Loaded once when the provider mounts; on an error the
369
- config values stay. For type `"mfe"` only when the MFE sets it (the shell owns the brand; an auth MFE with the brand on its login sets it). By hand: `setCompanyDetails(reply)`.
370
- Helpers: `readLogoUrl(config, isDarkTheme, details)`, `readAppNameLabel(config, details)`, `readCompanyDetails(reply)`.
371
- The example apps load sor `/company-details` into `companySignal` on start.
372
-
373
- ### Layout choice (shell with microfrontends)
374
-
375
- `layoutChoiceSignal` (`"app"` | `"aside"`) and `changeLayoutChoice(choice)` keep the picked app layout in
376
- `LAYOUT_CHOICE` (localStorage). The provider reads it on start, and every copy of the library on the page (shell and
377
- MFEs) follows a change at once, like the theme. The shell renders `AppLayout` or `AsideLayout` from it; an MFE uses
378
- it to know whether the shell shows a header (`isAsideLayoutSignal`).
379
-
380
- ### App type: `<SharedWebUiProvider type="...">`
381
-
382
- | `type` | For | Differences |
383
- | --- | --- | --- |
384
- | `"spa"` (default) | a normal app | layouts, menu, login; pages in `?page=...` |
385
- | `"shell"` | the root app that hosts microfrontends | like `spa`, but pages are paths by default (`/settings`) |
386
- | `"mfe"` | a microfrontend inside a shell | page layouts only: no menu (no skeleton), `loadMenuNavigation` / `loadBranches` not called (the shell owns them; `loadCompanyDetails` only when the MFE sets it); `appName`, `logoUrl`, `logoDarkUrl`, `homePath`, `branchLabel` are not used. `loadSupportLanguages` still works. |
387
-
388
- `layout.pageMode` set in the config always wins over the type.
389
-
390
- What happens to the reply (`MenuAccessType`: `id`, `name`, `nameLang`, `href`, `icon`, `type`, `priority`,
391
- `read/create/update/delete` or `permissions`, `active`, `children`):
392
-
393
- - the children of the **Root** group (`ADMIN_ROOT`) move to the top level, in the place of the group;
394
- - sorted by `priority`; the same priority keeps the backend order; `active: false` is removed;
395
- - icons like `layout-dashboard`, `users`, `User-Round-Key` become lucide names (unknown → `Circle`);
396
- - `nameLang` `{ "en-US": "..." }` is used for `en`, `en-US`, … (`trans()`), else `name`;
397
- - `read: false` hides the item and blocks the page; `create/update/delete` feed `canAccess()`.
398
-
399
- `toNavigation(menuResponse, options)` does the conversion if you need the `NavItem[]` yourself.
400
-
401
- ### Languages from the backend (`loadSupportLanguages`)
402
-
403
- Called once on start (see above). Texts come from `locales/<code>/<group>.json` via `loadLocale`.
404
-
405
- - Row fields: `code` (or `langCode` / `languageCode` / `id`), `name` or `label`, `flag`, `direction` or `dir`,
406
- `isDefault` (or `default`), `active` (false hides it), `priority`. RTL is automatic for `ar`, `he`, `fa`, `ur`.
407
- - Until the reply arrives: the saved language, else `defaultLanguage`, else the browser language (when its file
408
- loads), else `en-US` is shown; the switchers have no list yet.
409
- - When the list arrives: the user's saved language stays if it is listed; otherwise the row with `isDefault`,
410
- else `defaultLanguage`, else the browser / system language (matched to the list), else `en-US`,
411
- else the first is loaded. Only a language the user picks is saved to localStorage.
412
- - `TypeLang` / `TypeLangMd` fields get one entry per listed language: `{ "en-US": "...", "ar-SA": "..." }`;
413
- backend `nameLang` with the same codes is shown by `trans()` and the menu.
414
- - By hand: `setLanguages(reply)`. Conversion only: `toLanguageOptions(reply)`, `readDefaultLanguageCode(reply)`.
415
-
416
- ### AppStorage and AppHttp
91
+ The shell owns login, menu, branches and brand. `startSession` / `endSession` and the token regenerate are shared
92
+ with every MFE on the page.
417
93
 
418
- The same helpers the apps had in `utils/services/app.storage.ts` and `app.http.ts`, now in the library:
94
+ ### mfe — microfrontend inside a shell (page layouts only)
419
95
 
420
- ```ts
421
- import { AppHttp, AppStorage, BRANCH_ID, LANG, THEME, TOKEN } from "shared-lib-web";
422
-
423
- AppStorage.setData(BRANCH_ID, branchId); // sessionStorage "ORG-BRANCH_ID"
424
- const token = AppStorage.getData(TOKEN); // objects come back parsed
425
- AppStorage.getText(THEME); // localStorage "ORG-THEME"
426
- AppStorage.removeData(BRANCH_ID); // from both storages
427
- AppStorage.clearData(); // log out: keeps the localStorage preferences
428
- AppStorage.envData("API_BASE_URL"); // window.env.REACT_APP_ORG_API_BASE_URL (env.js of the deployed app)
429
-
430
- // MsUrl comes from the project's config.ts (see section 1)
431
- const rows = await AppHttp.Get(`${MsUrl.main}/profile/search`, params);
432
-
433
- // A path works too: it is appended to http.baseUrl (or window.env API_BASE_URL)
434
- const same = await AppHttp.Get("/org-api/profile/search", params); // -> https://api.example.com/api/org-api/profile/search
96
+ ```tsx
97
+ <SharedWebUiProvider type="mfe" config={mfeConfig}>
98
+ <RequireAccess><FormsPage /></RequireAccess>
99
+ </SharedWebUiProvider>
435
100
  ```
436
101
 
437
- **URLs in every AppHttp method** (`Get`, `Post`, `Put`, `Delete`, `Patch`, `Load`, `Media`, `CloudUpload`, `DownloadFile`): a URL that
438
- starts with `http://` or `https://` is used as it is; anything else is appended to the base URL with one `/` between
439
- (`"/items"` and `"items"` both become `<baseUrl>/items`). `AppHttp.FullUrl(url)` returns the URL a request would use.
102
+ No menu, no `loadBranches` / `loadMenuNavigation`. Theme, language, session and token come from the shell.
103
+ See `example-mfe/`.
440
104
 
441
- **Shared requests (shell + microfrontends):** `AppHttp.GetShared(url, params?)` is a GET that runs **once per page**
442
- for every copy of the library: the shell and each MFE bundle their own copy, and the same URL + params (running or
443
- answered) gives the same promise, so the languages, themes, texts and company details are not loaded again by each MFE.
444
- An MFE that runs alone still loads them itself. Only for data that is the same for everyone (not the menu or branches);
445
- a failed request is not kept; `clearSharedGetCache()` empties it.
105
+ ## HTTP — `AppHttp`
446
106
 
447
107
  ```ts
448
- const reply = await AppHttp.GetShared(`${MsUrl.sor}/load/LANG`, { active: true });
449
- ```
450
-
451
- **Binary files:** `AppHttp.Media(url, params?)` is a GET that returns the body as a `Blob` (images, video, audio, any
452
- file), with the same headers (token, `x-session-id`, `x-branch-id`, no `Content-Type`) and no progress bar:
453
-
454
- ```ts
455
- const blob = await AppHttp.Media(`${MsUrl.utils}/files/${fileId}`);
456
- const objectUrl = URL.createObjectURL(blob); // <img src={objectUrl} />; URL.revokeObjectURL(objectUrl) when done
457
- ```
458
-
459
- **Which storage:** decided only by the key (no argument).
460
-
461
- | localStorage (preferences, kept on log out) | sessionStorage (everything else) |
108
+ const rows = await AppHttp.Get(`${MsUrl.main}/profile/search`, { page: 1 });
109
+ const saved = await AppHttp.Post(`${MsUrl.main}/profile`, body);
110
+ await AppHttp.Put(`${MsUrl.main}/profile`, id, body);
111
+ await AppHttp.Delete(`${MsUrl.main}/profile`, id);
112
+ await AppHttp.Patch(`${MsUrl.main}/profile`, body);
113
+ const langs = await AppHttp.GetShared(`${MsUrl.sor}/load/LANG`); // once per page (shell + MFEs)
114
+ const options = await AppHttp.Load("COUNTRY"); // GET `${http.loadUrl}/COUNTRY`
115
+ const blob = await AppHttp.Media(`${MsUrl.utils}/files/${id}`);
116
+ await AppHttp.DownloadFile(`${MsUrl.utils}/report`, {}, "report.pdf");
117
+ await AppHttp.CloudUpload(signedUrl, file);
118
+ const file = await uploadToSignedUrl(file, uploadUrl, downloadUrl);
119
+ AppHttp.setHeader("x-custom", "value");
120
+ ```
121
+
122
+ | Member | Use |
462
123
  | --- | --- |
463
- | `LANG`, `THEME`, `LAYOUT_CHOICE`, `MENU_MODE`, `SIDEBAR_COLLAPSED`, `REMEMBER_ME` + `config.localStorageKeys` | `TOKEN`, `ACTIVE_SESSION_ID` (tab id, sent as `x-session-id`), `AUTH_USER`, `SESSION_INFO`, `SCREEN_ACCESS`, `SCREEN_ACTION`, `NAV`, `TRANS`, `DIR`, `OTP_ID`, `BRANCH_ID`, `BRANCH_NAME`, `REGEN_EXPIRES_AT`, project keys |
464
-
465
- `startSession(token, user, isRemembered)` keeps the token in sessionStorage; `isRemembered` only saves `REMEMBER_ME`.
466
- On start the provider removes old app values from localStorage that are not preferences (`AppStorage.cleanLocalStorage()`).
467
- Saving a preference (`THEME`, `LANG` …) also fires the window event `PREFERENCE_EVENT`; every copy of the library on the
468
- page (microfrontends) and every other tab applies the new theme / language at once.
469
- `startSession` / `endSession` fire `SESSION_EVENT` the same way: every other library copy on the page reads the session
470
- from AppStorage (sign in) or clears it (sign out). So an **auth microfrontend** can sign in and the shell (its own
471
- library copy) is signed in at once — the shell needs no login of its own (see `example-mfe/auth`).
472
-
473
- Key constants (also as `StorageKeys.*`): `TOKEN`, `AUTH_USER`, `SESSION_INFO`, `SCREEN_ACCESS`, `SCREEN_ACTION`, `NAV`,
474
- `REMEMBER_ME`, `TRANS`, `DIR`, `LANG`, `THEME`, `LAYOUT_CHOICE`, `MENU_MODE`, `SIDEBAR_COLLAPSED`, `OTP_ID`, `BRANCH_ID`, `BRANCH_NAME`,
475
- `REGEN_EXPIRES_AT`. The library saves the chosen language in `LANG`, the theme in `THEME`, the navigation style in
476
- `MENU_MODE` and the rail state in `SIDEBAR_COLLAPSED`.
124
+ | `Get / Post / Put / Delete / Patch` | JSON requests with token, `x-session-id`, `x-branch-id` |
125
+ | `GetShared(url, params)` | GET once per page (shell + MFEs) |
126
+ | `Load(id, params)` | option lists |
127
+ | `Media / DownloadFile / CloudUpload / uploadFile` | files |
128
+ | `BaseUrl() / FullUrl(url)` | base URL / resolved URL |
129
+ | `Headers() / RawHeaders() / setHeader(name, value)` | headers |
130
+ | `withProgress(promise)` | shows the top progress bar |
477
131
 
478
- AppHttp headers on every request: `Content-Type`, `Authorization: Bearer <TOKEN>`, `x-session-id` (per-tab id, saved as `ORG-ACTIVE_SESSION_ID`),
479
- `x-branch-id` (AppStorage `BRANCH_ID`, `""` when no branch), `http.headers` and `AppHttp.setHeader(name, value)`.
480
- Pick the branch with `setBranch(branch.id, branch.name)` (saved as `BRANCH_ID` / `BRANCH_NAME`, read back with
481
- `readBranchId()` or `branchIdSignal`); `clearBranch()` removes it and `endSession()` clears it too.
132
+ ### JWT regenerate
482
133
 
483
- **Branch switcher** – `config.loadBranches` (called after sign in, before the menu); the default and disabled
484
- branches come with the rows:
134
+ With `http.regenerateUrl` set, before every request: `JwtValid(token)` (dff-util) is false → one GET to
135
+ `regenerateUrl` (kept in the shared page cache, so all waiting requests and MFEs share it) → the new token
136
+ (`token` or `data.token`) is saved in sessionStorage. An error → `endSession()` (log out, goes to `http.logoutUrl`).
137
+ An invalid token with an empty `regenerateUrl` throws an error at the time of the call.
485
138
 
486
139
  ```ts
487
- loadBranches: loadBranches, // () => AppHttp.Get(`${MsUrl.main}/branches`)
488
- branchLabel: "branch.title", // title of the switcher, shown with t() (default "ui.branch" = "Branch")
140
+ await ensureFreshToken(); // what every AppHttp request does first
141
+ const token = await jwtRegenerateCall(); // the regenerate call itself (throws when no token)
142
+ readRegenerateUrl(); readJwtToken();
489
143
  ```
490
144
 
491
- - Rows: `{ id | branchId | code, name | branchName | label, nameLang?, isDefault?, disabled?, active?, priority? }`, as `{ data: [...] }` or the list.
492
- - `disabled: true` shows the branch greyed out; it can not be selected. `active: false` hides it.
493
- - Selected when the list arrives: the saved `BRANCH_ID` (if listed and not disabled) → the row with `isDefault` → the first one that is not disabled.
494
- - Shown as a dropdown in the `Header` and as the first section of the settings dialog. `null` or `[]` = no switcher.
495
- - `setBranches(reply)` does the same by hand (call it before the menu request so it already
496
- sends `x-branch-id`). Own layouts: `<BranchSwitcher />`. Helpers: `toBranchOptions`, `pickBranch`, `branchesSignal`.
497
- The token is read from AppStorage (`TOKEN`, sessionStorage then localStorage).
145
+ HTTP helpers: `API_BASE_URL_ENV`, `toAbsoluteUrl`, `isHttpUrl`, `joinUrl`, `clearSharedGetCache`, `setAppConfig`, `readAppConfig`.
146
+ Types: `HttpParams`, `HttpHeaders`, `HttpConfig`.
498
147
 
499
- `AppHttp` and `AppStorage` use no signals: they read the config saved by `<SharedWebUiProvider>`.
500
- Code that runs before the provider (for example at module load) calls `setAppConfig(config)` first, in `main.tsx`.
501
-
502
- ## 2. locales: one folder per language, one file per group
503
-
504
- ```
505
- locales/
506
- en-US/
507
- app.json { "name": "My App" } -> t("app.name")
508
- nav.json { "dashboard": "Dashboard", "users": "Users" } -> t("nav.users")
509
- roles.json { "admin": "Admin", "viewer": "Viewer" } -> t("roles.admin")
510
- root.json { "greeting": "Hello {{name}}", "REQUIRED": "..." } -> t("greeting"), t("REQUIRED") (top level)
511
- fr-FR/
512
- app.json …
513
- ```
148
+ ## Session
514
149
 
515
150
  ```ts
516
- // config.ts
517
- import { loadLocaleGroups } from "shared-lib-web";
518
-
519
- const localeFiles = import.meta.glob("./locales/*/*.json"); // lazy: nothing is downloaded yet
520
-
521
- export const config: UiConfig = {
522
- loadLocale: loadLocaleGroups.bind(null, localeFiles), // fr-FR used -> only locales/fr-FR/*.json load
523
- };
524
- ```
525
-
526
- - **Dynamic:** `import.meta.glob` (without `eager`) gives one lazy loader per file; `loadLocaleGroups` runs only
527
- the files of the language that is used, in parallel, and merges them (the file name is the group, `root.json`
528
- stays at the top level). The default language (en-US) is loaded too, for keys missing in the current one.
529
- - **Several folders:** merge them, `{ ...sharedFiles, ...ownFiles }` (MFEs: shared groups + the MFE's own); the same
530
- group in two folders is merged, the later file wins per key.
531
- - **Or a signal:** `loadLocale: localeSignal`, a `LocaleBundle` (`{ "en-US": {...}, "fr-FR": {...} }`) your app fills.
532
- The library adds the codes it needs to `requestedLocalesSignal` and waits; `fillLocaleBundle` loads them for you
533
- (a code set to `null` = no texts for that language, the next one is tried):
534
-
535
- ```ts
536
- export const localeSignal = signal<LocaleBundle | null>(null);
537
- const loadTexts = loadLocaleGroups.bind(null, import.meta.glob("./locales/*/*.json"));
538
- loadLocale: localeSignal, // config.ts
539
- useEffect(() => fillLocaleBundle(localeSignal, loadTexts)); // start once (returns the stop function)
540
- ```
541
-
542
- This `localeSignal` is your app's own signal. The library also exports a `localeSignal` (the current language
543
- code); in a file that needs both, import the library one with an alias:
544
- `import { localeSignal as currentLanguageSignal } from "shared-lib-web"`.
545
- - One JSON per language still works: `loadLocale: (code) => import(\`./locales/${code}.json\`)`.
546
-
547
- **One sublevel only:** a key is `"key"` or `"group.key"` (`t("user.title")`, `t("branch.title")`). Deeper keys like
548
- `user.role.admin` are not looked up, and the library warns in the console when a locale file has them — use
549
- `role.admin` or `user.roleAdmin` instead.
550
-
551
- Lookup order: current language → `defaultLanguage` (else en-US) → library defaults (`ui.*` and dff-util `ConstMessages`) → the key.
552
- Shell texts to translate: `ui.language, theme, openMenu, expandMenu, collapseMenu, home, loading, close, noData,
553
- selectOption, search, navigation, account, logout, confirm, cancel, translate, permissionDenied,
554
- permissionDeniedText, pageNotFound, pageNotFoundText, backToHome, goBack, reloadPage, comingSoon, comingSoonText,
555
- openPreview, playVideo, mediaError`.
556
-
557
- ## 3. main.tsx and app.tsx
558
-
559
- ```tsx
560
- // root.tsx – one input: the config (menu, languages, branches come from its loaders)
561
- export function Root() {
562
- return (
563
- <SharedWebUiProvider type="spa" config={config}>
564
- <App />
565
- </SharedWebUiProvider>
566
- );
567
- }
568
-
569
- // main.tsx
570
- const root = createRoot(rootElement);
571
- root.render(<Root />);
572
- ```
573
-
574
- ```tsx
575
- // app.tsx – ONE component holds all pages; ?page picks which one is shown
576
- import { AppLayout, AuthLayout } from "shared-lib-web/layout"; // optional, see "Layout" below
577
-
578
- const PAGE_ELEMENTS: Record<string, ReactElement> = {
579
- "/": <DashboardPage />,
580
- "/profiles": <UserPage />, // keys = the menu hrefs
581
- "/app-settings": <SettingsPage />,
582
- };
583
-
584
- function readPageElement(page: string): ReactElement {
585
- return PAGE_ELEMENTS[page] ?? <PageNotFound />;
586
- }
587
-
588
- export function App() {
589
- const page = useCurrentPage(); // "/profiles" from ?page=profiles (re-renders on change)
590
- if (!isLoggedIn.value) {
591
- return (
592
- <AuthLayout>
593
- <LoginPage />
594
- </AuthLayout>
595
- );
596
- }
597
- const pageElement = readPageElement(page);
598
- return (
599
- <AppLayout headerEnd={<UserMenu name={userName} email={email} onLogout={handleLogout} />}>
600
- <RequireAccess key={page}>{pageElement}</RequireAccess>
601
- </AppLayout>
602
- );
603
- }
151
+ startSession(token, user, isRemembered); // after login
152
+ endSession(keepKeys?, isRedirect?); // logout
153
+ refreshSessionToken(token); // new token, user stays
154
+ isAuthenticatedSignal.value; authUserSignal.value; readAccessToken();
604
155
  ```
605
156
 
606
- ### Layout: single, parts or own (optional)
607
-
608
- ```tsx
609
- import { AppLayout, AsideLayout, AuthLayout, Header, Sidebar, SidebarNav } from "shared-lib-web/layout";
610
-
611
- // 1. Single layout – everything ready-made
612
- <AppLayout headerEnd={<UserMenu ... />} sidebarFooter="v1.0">{page}</AppLayout>
613
-
614
- // 2. Single layout with options
615
- <AppLayout showSidebar={false}>{page}</AppLayout> // header + page only
616
- <AppLayout showHeader={false}>{page}</AppLayout> // sidebar + page only
617
- <AppLayout header={<MyHeader />} sidebar={<MySidebar />} footer={<MyFooter />}>{page}</AppLayout>
618
-
619
- // 2b. AsideLayout – no top header, only the side menu and the page
620
- <AsideLayout sidebarUser={<UserMenu isInSidebar ... />}>{page}</AsideLayout>
621
- // desktop: collapsible to an icon rail (button at the bottom, tooltips on the rail)
622
- // small screens: always the icon rail (no drawer, no menu button)
623
- // no mega menu: menuMode is ignored and hidden in the settings dialog
624
- // the user at the bottom of the sidebar; HeadLayout sticks at top-0
625
- // options: sidebarFooter, showSettings (settings button at the bottom, default false), showSidebar, sidebar, footer
626
- // signals: isAsideLayoutSignal, isSmallScreenSignal, isRailEverywhereSignal
627
-
628
- // 3. MainLayout: the project's own layout from the individual parts (any markup around them)
629
- <div className="flex min-h-screen flex-col">
630
- <Header endContent={<UserMenu ... />} isStandalone /> {/* brand always shown on desktop */}
631
- <div className="flex flex-1">
632
- <aside className="w-64"><SidebarNav isAlwaysExpanded /></aside> {/* only the menu */}
633
- <main>{page}</main>
634
- </div>
635
- </div>
636
-
637
- // 4. No layout entry at all – the project writes everything with the main entry:
638
- // AppBrand, UserMenu, LanguageSwitcher, ThemeSwitcher, SettingsMenu, PageLink, toggleSidebar ...
639
- ```
157
+ Also: `restoreSession`, `startSessionSync`, `handleSessionEvent`, `redirectToLogoutUrl`, `readTokenKey`,
158
+ `sessionTokenSignal`, `AUTH_USER_KEY`.
640
159
 
641
- **Menu on / off at runtime** (works with `AppLayout`, `Header`, `SidebarNav` and the mega menu):
160
+ ## Storage — `AppStorage`
642
161
 
643
162
  ```ts
644
- setMenuVisible(false); // hide the sidebar / rail / mega menu bar and the menu buttons, e.g. a full-screen page
645
- setMenuVisible(true); // show it again
646
- toggleMenuVisible(); // switch
647
- isMenuVisibleSignal.value // current state (re-renders components)
648
- // start value: config.layout.showMenu (default true)
163
+ AppStorage.setData(BRANCH_ID, id); AppStorage.getData(TOKEN); AppStorage.getText(THEME);
164
+ AppStorage.removeData(KEY); AppStorage.clearData(keepKeys); AppStorage.envData("API_BASE_URL");
649
165
  ```
650
166
 
651
- | Part | Options |
652
- | --- | --- |
653
- | `AppLayout` | `headerEnd`, `sidebarFooter`, `showHeader`, `showSidebar` (default: `isMenuVisibleSignal`), `header`, `sidebar`, `footer` |
654
- | `Header` | `endContent`, `startContent`, `showMenuButtons`, `showSwitchers`, `isStandalone` |
655
- | `Sidebar` | `footer`, `showBrand` |
656
- | `SidebarNav` | `className`, `isAlwaysExpanded`, `isAlwaysShown` (menu list only, follows permissions and the menu on/off switch, skeleton until `loadMenuNavigation` answers) |
657
-
658
- The example app shows both: Settings → *App layout* switches between `AppLayout` and
659
- `MainLayout` in `example/src/layout/main-layout.tsx`.
660
-
661
- ### No router: query parameters
167
+ Helpers: `readAppStoragePrefix`, `readPrefixedKey`, `readEnvData`, `readEnvPrefix`, `buildEnvPrefix`,
168
+ `isLocalStorageKey`, `readLocalStorageKeys`. Type: `StoredValue`.
169
+ Keys: `TOKEN`, `AUTH_USER`, `SESSION_INFO`, `SCREEN_ACCESS`, `SCREEN_ACTION`, `NAV`, `TRANS`, `DIR`, `LANG`, `THEME`,
170
+ `LAYOUT_CHOICE`, `MENU_MODE`, `SIDEBAR_COLLAPSED`, `REMEMBER_ME`, `OTP_ID`, `BRANCH_ID`, `BRANCH_NAME`,
171
+ `REGEN_EXPIRES_AT`, `ACTIVE_SESSION_ID`, `SESSION_EVENT`, `PREFERENCE_EVENT`, `StorageKeys`, `LOCAL_STORAGE_KEYS`.
662
172
 
663
- There is no router and nothing redirects. A menu click only sets `?page=<menu href>` with the History API
664
- (no reload); the app shows the component for that value. Back / forward work.
173
+ ## Provider and hooks
665
174
 
666
- **Path mode:** `layout: { pageMode: "path" }` puts the page in the path instead — `http://host/profiles` rather than
667
- `http://host/?page=profiles`. Menu links, `openPage`, `PageLink`, `useCurrentPage` and back / forward all follow it;
668
- other query parameters still work (`/profiles?userId=7`). The server must answer every path with `index.html`
669
- (Vite dev does). For code outside React (for example single-spa `activeWhen`) use `readPageFromLocation(location)`,
670
- which reads the page in either mode.
671
-
672
- | Function | What it does |
175
+ | Export | Use |
673
176
  | --- | --- |
674
- | `openPage("/profiles")` | Sets `?page=profiles` (no leading slash in the address bar; inside the app pages stay menu hrefs like `"/profiles"`; old `?page=/profiles` links still work; helpers `toPageParamValue` / `toPagePath`), removes the old page's parameters, closes menus, scrolls up. `openPage(page, { userId: "42" })` adds values; `{ isKeepingOtherParams: true }` keeps the old ones. |
675
- | `setQueryParam("userId", "42")` | Adds or changes one parameter: `?page=profiles&userId=42`. `undefined` / `""` removes it. `{ isReplace: true }` replaces the history entry. |
676
- | `setQueryParams({ userId: "42", mode: "edit" })` | Several at once. |
677
- | `removeQueryParam("userId")` | Removes one. |
678
- | `readQueryParam("userId")`, `readQueryParams()` | Read values (outside components or in handlers). |
679
- | `useQueryParam("userId")`, `useCurrentPage()` | Read values in a component and re-render when they change. |
680
- | `<PageLink page="/profiles">` | A link that calls `openPage` (Ctrl/Cmd-click opens a new tab). |
681
-
682
- Example (users page): row click → `setQueryParams({ userId, mode: "view" })`; on load
683
- `readQueryParams()` reopens the drawer, so a refresh or a shared link shows the same user.
177
+ | `SharedWebUiProvider` | `<SharedWebUiProvider type config>` root of every app |
178
+ | `useUi()` | `{ locale, theme, direction, t, changeLanguage, changeTheme }` |
179
+ | `useCurrentPage()`, `useQueryParam(name)` | current page / query param (re-render on change) |
180
+ | `ThemeProvider`, `TranslationProvider`, `UiContext` | lower-level providers |
684
181
 
685
- ## 4. Pages
182
+ ## Signals
686
183
 
687
- ```tsx
688
- const { locale, theme, direction, t, changeLanguage, changeTheme } = useUi();
689
- ```
690
-
691
- Permissions: wrap the page in `<RequireAccess>` (shows `PermissionDenied` when the menu item of the current `?page` has `read: false`) and use
692
- `canAccess("update")` / `canAccess("delete")` for buttons.
184
+ `uiConfigSignal`, `appTypeSignal`, `localeSignal`, `languagesSignal`, `directionSignal`, `translationSignal`,
185
+ `fallbackTranslationSignal`, `isTranslationReadySignal`, `themeSignal`, `isDarkThemeSignal`, `customThemesSignal`,
186
+ `companyDetailsSignal`, `navigationSignal`, `navigationLoadingSignal`, `navigationModeSignal`, `isMenuVisibleSignal`,
187
+ `isSidebarOpenSignal`, `isSidebarCollapsedSignal`, `isDesktopSidebarSignal`, `isRailEverywhereSignal`,
188
+ `isAsideLayoutSignal`, `isSmallScreenSignal`, `isSettingsOpenSignal`, `pathnameSignal`, `currentPageSignal`,
189
+ `queryParamsSignal`, `progressSignal`, `toastsSignal`, `branchesSignal`, `branchIdSignal`, `branchNameSignal`,
190
+ `layoutChoiceSignal`, `screenAccessSignal`, `mediaPreviewSignal`, `requestedLocalesSignal`.
693
191
 
694
- ## 5. Icons – TypeIcon
695
-
696
- ```tsx
697
- <TypeIcon name="Users" />
698
- <TypeIcon name="Pencil" size={16} title="Edit" onPress={handleEditClick} />
699
- ```
192
+ ## Services
700
193
 
701
- All icons (navigation, buttons, library) use lucide names from https://lucide.dev/icons.
702
-
703
- ## 6. Forms – react-hook-form
704
-
705
- Every control takes `{ control, name, label, rules }` and translates its error message
706
- (use dff-util `ConstKeys` as messages and `RegExp` as patterns).
707
-
708
- | Control | Value |
194
+ | Area | Exports |
709
195
  | --- | --- |
710
- | `TypeInput`, `TypeTextArea` | text |
711
- | `TypeSelect` | option key (dff-util `OptionType`, `option.lang[locale]` shown) |
712
- | `TypeSwitch`, `TypeCheckbox` | boolean |
713
- | `TypeDate` (`isDateTime`) | `"2026-11-05"` / `"2026-11-05T14:30"` |
714
- | `TypeTime` | `"14:30"` |
715
- | `TypeOtp` (`length`) | `"123456"` |
716
- | `TypeList` (`selectionMode`) | `string[]` or `string` |
717
- | `TypeLang` (`type="text" | "textarea"`) | `TranslationType` `{ en: "...", fr: "..." }` for every config language, with translate buttons (dff-util `CallLangText`) |
718
- | `TypeMdx` (from `shared-lib-web/markdown`) | markdown text (editor) |
719
- | `TypeLangMd` (from `shared-lib-web/markdown`) | markdown per language `{ en: "...", fr: "..." }` with translate buttons |
720
-
721
- `TypeMdv` (from `shared-lib-web/markdown`) shows markdown, or the current language of `textByLanguage`. All three follow light/dark themes.
196
+ | Pages (no router) | `openPage`, `PageLink`, `isPageActive`, `buildPageHref`, `buildPagePath`, `buildQueryHref`, `buildQueryString`, `readCurrentPage`, `readPageParam`, `readQueryParam`, `readQueryParams`, `setQueryParam`, `setQueryParams`, `removeQueryParam`, `readPageFromLocation`, `isPathPageMode`, `toPagePath`, `toPageParamValue` |
197
+ | Language / i18n | `changeLanguage`, `translate`, `interpolate`, `lookupMessage`, `trans`, `readNavLabel`, `loadLocaleMessages`, `loadLocaleGroups`, `readLocaleFilePath`, `fillLocaleBundle`, `setLanguages`, `toLanguageOptions`, `toLanguageOption`, `readLanguageRows`, `readDefaultLanguageCode`, `resolveDirection`, `findLanguageOption`, `matchLanguageCode`, `readBrowserLanguage`, `readBrowserLanguageCodes`, `readDefaultLanguage`, `readFallbackLanguage`, `readStartLanguageCandidates`, `unwrapLocaleModule`, `findDeepLocaleKeys`, `DEFAULT_LANGUAGE`, `DEFAULT_UI_MESSAGES`, `RTL_LANGUAGE_CODES`, `ROOT_LOCALE_GROUP`, `LOCALE_WAIT_MS`, `MAX_KEY_PARTS` |
198
+ | Theme | `changeTheme`, `isDarkThemeName`, `readThemeNames`, `readDarkThemeNames`, `splitThemesByMode`, `setCustomThemes`, `mergeCustomThemes`, `loadConfigThemes`, `followConfigThemes`, `buildCustomThemeCss`, `isValidCustomTheme`, `toCustomThemeList`, `unwrapThemesModule`, `readLogoUrl`, `DAISYUI_THEMES`, `DEFAULT_DARK_THEMES` |
199
+ | Menu / navigation | `setMenu`, `setMenuLoading`, `clearMenu`, `setNavigation`, `setNavigationLoading`, `changeNavigationMode`, `setMenuVisible`, `toggleMenuVisible`, `toggleSidebar`, `closeSidebar`, `toggleSidebarCollapsed`, `closeAllMenus`, `filterVisibleNavigation`, `toNavigation`, `toNavItem`, `toNavItems`, `flattenRootMenus`, `sortActiveMenus`, `compareMenuPriority`, `isRootMenu`, `unwrapRootMenu`, `readMenuRows`, `readMenuPermissions`, `findNavTrail`, `isNavItemActive`, `isPathMatch` |
200
+ | Access | `canAccess`, `canAccessPath`, `findNavItemByPath`, `FULL_ACCESS` |
201
+ | Branch | `setBranch`, `setBranches`, `clearBranch`, `readBranchId`, `findBranch`, `pickBranch`, `toBranchOptions`, `handleBranchSelect`, `readBranchName`, `DEFAULT_BRANCH_LABEL` |
202
+ | Company | `setCompanyDetails`, `readCompanyDetails`, `isCompanyPending`, `readAppNameLabel` |
203
+ | Layout choice / prefs | `changeLayoutChoice`, `applySavedLayoutChoice`, `toLayoutChoice`, `applySavedPreference`, `startPreferenceSync` |
204
+ | Backend loaders | `callApiSource`, `loadSessionData`, `clearSessionData`, `loadConfigLanguages`, `loadConfigCompany`, `isSignalSource` |
205
+ | Feedback | `ShowToast`, `removeToast`, `clearToasts`, `ShowProgress`, `openSettings`, `closeSettings`, `openMediaPreview`, `closeMediaPreview`, `scrollToTop` |
206
+ | Utils | `readErrorMessage`, `readContent`, `readResponseRows`, `toOptionTypes`, `readCountryOptions`, `readLanguageOptions`, `readTelCode`, `readTelCodeOptions`, `formatBytes`, `parseSizeToBytes`, `sumFileSizes`, `isFileTypeAllowed`, `normalizeFileTypes`, `readFileExtension`, `readFileIconName`, `readUploadFiles`, `resolveLucideIcon`, `isLucideIcon`, `toLucideName`, `FALLBACK_ICON`, `readSessionId`, `resetSessionId`, `setLeaveGuard`, `encryptPayload`, `decryptResponse`, `isEncryptedEnvelope`, `SharedRegExp`, `readDataValue`, `readRowKey`, `readSearchText`, `readOptionLabel`, `formatDateInputValue`, `buildMediaStyle`, `readInitials`, `goBackInHistory`, `handleDocumentEscape`, `reloadPage`, `joinClassNames` |
207
+
208
+ ## Components
209
+
210
+ | Group | Exports |
211
+ | --- | --- |
212
+ | Form controls (react-hook-form) | `TypeInput`, `TypeTextArea`, `TypeSelect`, `TypeSwitch`, `TypeCheckbox`, `TypeDate`, `TypeTime`, `TypeOtp`, `TypeList`, `TypeLang`, `TypeSearch`, `TypeFilter`, `TypeUpload`, `TypeUploadBox` |
213
+ | Actions / overlays | `TypeButton`, `TypeDropdown`, `TypeModal`, `TypeDrawer`, `TypeConfirm`, `OtpModal`, `TypeTable`, `TypeIcon`, `TypeImage`, `TypeVideo`, `MediaViewer` |
214
+ | App parts | `AppBrand`, `UserMenu`, `LanguageSwitcher`, `ThemeSwitcher`, `BranchSwitcher`, `SettingsMenu`, `ToastContainer`, `TopProgress`, `ScrollToTop`, `PageLoader` |
215
+ | Pages / states | `RequireAccess`, `PermissionDenied`, `PageNotFound`, `ComingSoon`, `EmptyState` |
216
+ | Page blocks | `HeadLayout`, `ArticleLayout`, `ContentLayout`, `GridLayout`, `FloatLayout` |
217
+ | Skeletons | `SkeletonPage`, `SkeletonArticle`, `SkeletonTable`, `SkeletonForm`, `SkeletonCards`, `SkeletonDashboard`, `SkeletonChat`, `SkeletonMenu`, `SkeletonFloat`, `SkeletonAuthForm` |
218
+ | `shared-lib-web/layout` | `AppLayout`, `AsideLayout`, `AuthLayout`, `Header`, `Sidebar`, `SidebarNav`, `SidebarCollapseButton`, `MegaMenuBar`, `MegaMenuPanel`, `RailFlyout`, `RailTooltip`, `DRAWER_ID` |
219
+ | `shared-lib-web/markdown` | `TypeMdx` (editor), `TypeMdv` (viewer), `TypeLangMd` (editor per language) |
722
220
 
723
221
  ```tsx
724
- import { TypeLangMd, TypeMdv, TypeMdx } from "shared-lib-web/markdown";
725
-
726
- <TypeLang control={control} name="title" label={t("page.title")} rules={pageValidation.title} />
727
- <TypeLangMd control={control} name="body" label={t("page.body")} height={250} />
728
- <TypeMdv textByLanguage={page.body} />
222
+ <TypeInput control={control} name="email" label={t("user.email")} type="email" rules={rules.email} />
223
+ <TypeButton action="primary" label={t("save")} icon="Save" type="submit" />
224
+ <TypeIcon name="users" />
729
225
  ```
730
226
 
731
- ### File upload – TypeUpload
732
227
 
733
- ```tsx
734
- <TypeUpload control={control} name="csvFile" label={t("product.csv")} fileType="csv" maxSize="10MB" rules={rules.csvFile} />
735
- <TypeUpload control={control} name="photos" label={t("product.photos")} fileType={["png", "jpg"]} maxSize="5MB" isMultiple totalSize="20MB" />
736
- <TypeUploadBox name="import" fileType="csv" maxSize={10} value={importFile.value} onChange={handleImportFileChange} />
737
- ```
228
+ ### OTP modal — `OtpModal`
738
229
 
739
- Drag & drop or browse, type and size checks (per file and total), warning banner + toast, file list with remove.
740
- Value: `File` (single) or `File[]` (`isMultiple`). Then upload with:
230
+ 1. Set the send / verify URLs in `config.ts`:
741
231
 
742
232
  ```ts
743
- const signed = await AppHttp.Post(`${MsUrl.utils}/s3/upload-url`, { fileName: file.name });
744
- const uploaded = await uploadToSignedUrl(file, signed.data.upload, signed.data.download); // FileType
233
+ http: {
234
+ baseUrl: API_BASE_URL,
235
+ otp: {
236
+ sendUrl: `${MsUrl.sor}/otp-send`, // POST { userid } -> { data: { message, oid, uid } }
237
+ verifyUrl: `${MsUrl.sor}/otp-verify`, // POST { otp, oid, uid } -> { data: { message, oid, uid } }
238
+ resendSeconds: 180, // optional, default 180
239
+ length: 6, // optional, default 6
240
+ },
241
+ },
745
242
  ```
746
243
 
747
- Helpers: `parseSizeToBytes`, `formatBytes`, `normalizeFileTypes`, `isFileTypeAllowed`, `readFileIconName`, `setLeaveGuard`.
748
-
749
- Option lists from dff-util data: `readCountryOptions()`, `readTelCodeOptions()` (+ `readTelCode("IN")` → `"+91"`), `readLanguageOptions()`.
750
-
751
- ## 7. Other components
752
-
753
- ### Sticky page header (HeadLayout)
244
+ 2. Render `<OtpModal />` once (page or layout) and open it. The code is sent on open:
754
245
 
755
246
  ```tsx
756
- const headActions = (
757
- <>
758
- <TypeButton action="ghost" icon="X" label={t("user.cancel")} onPress={handleUserCancel} />
759
- <TypeButton type="submit" form="user-form" icon="Save" label={t("user.save")} />
760
- </>
761
- );
762
-
763
- <HeadLayout title={t("user.editTitle")} actions={headActions} />
764
- <form id="user-form" onSubmit={onSubmit}>...</form>
765
- ```
247
+ import { OtpModal, openOtpModal, type OtpVerifiedResult } from "shared-lib-web";
766
248
 
767
- - Put it first in the page. It sticks at `top-16` (under the 4rem app `Header`); `isBelowHeader={false}` sticks at `top-0`.
768
- - `isFullWidth` (default true) stretches it over the `<main>` padding (`p-4 lg:p-6`) to both edges; `false` gives a rounded card.
769
- - The buttons sit outside the `<form>`, so give the form an `id` and pass it to `TypeButton form="..."`.
770
- - Optional `children` add a row under the title (filters, tabs).
249
+ export function handleEmailVerified(result: OtpVerifiedResult): void {
250
+ // result = { oid, uid, otp }
251
+ }
771
252
 
772
- | Export | What it is |
773
- | --- | --- |
774
- | `AppLayout`, `AuthLayout` (from `shared-lib-web/layout`) | Optional single layouts (children = page) |
775
- | `Header`, `Sidebar`, `SidebarNav`, `SidebarCollapseButton`, `MegaMenuBar`, `MegaMenuPanel`, `RailFlyout` (from `shared-lib-web/layout`) | Optional individual layout parts. The collapse / expand button sits fixed at the bottom of `Sidebar` (desktop, sidebar mode); `<Sidebar showCollapseButton={false} />` hides it, `SidebarCollapseButton` places it in an own layout. User at the bottom of the side menu: `<AppLayout sidebarUser={<UserMenu isInSidebar ... />}>` (avatar + name + email; avatar only on the collapsed rail, menu opens next to it). On the collapsed rail every icon (links, groups, user, expand button) shows a tooltip with its label (`RailTooltip`, rendered by AppLayout; own layouts render `<RailTooltip />` once; any element can opt in with `data-rail-tip="Label"`) |
776
- | `AppBrand`, `PageLink` | Navigation pieces for any layout (main entry) |
777
- | `HeadLayout` | Sticky page header (h-16, same height as the logo box): one-line title on the start side, actions (Cancel, Submit) on the end side; stays under the app header while the page scrolls |
778
- | `ArticleLayout`, `ContentLayout`, `GridLayout`, `FloatLayout` | Page sections |
779
- | `TypeButton`, `TypeTable` (+ `readRowKey`), `TypeDropdown` (+ `readDataValue`) | Actions and lists |
780
- | `TypeSearch` (`onChange` live or `onSearch` on Enter + `readSearchText`), `TypeFilter` | List filters (not form fields) |
781
- | `TypeImage`, `TypeVideo` | Media thumbnails: skeleton while loading, error icon if the file fails; a click opens one shared popup (`MediaViewer`, rendered by the provider) with the full image, or the video playing with controls. `<TypeImage src alt previewSrc? fit? className? width? height? isPreviewable? />`, `<TypeVideo src title poster? className? width? height? isPreviewable? />` (optional `width` / `height`: number = px, string = any CSS size such as `"12rem"` or `"100%"`; only a height keeps the 16:9 shape) (no poster = first frame; `isPreviewable={false}` plays inline). `openMediaPreview({ type, src, title, poster })` / `closeMediaPreview()` open it from code |
782
- | `TypeModal`, `TypeDrawer`, `TypeConfirm` | Overlays (Escape, backdrop and ✕ close them) |
783
- | `UserMenu`, `LanguageSwitcher`, `ThemeSwitcher`, `SettingsMenu` | Header menus |
784
- | `ShowProgress(true/false)`, `TopProgress`, `ScrollToTop` | Request progress bar and scroll-to-top button |
785
- | `EmptyState`, `PermissionDenied`, `RequireAccess`, `PageNotFound`, `ComingSoon`, `PageLoader` | States and pages |
786
- | `SkeletonArticle`, `SkeletonTable`, `SkeletonForm`, `SkeletonCards`, `SkeletonDashboard`, `SkeletonChat`, `SkeletonMenu`, `SkeletonAuthForm`, `SkeletonPage`, `SkeletonFloat` | Loading placeholders |
787
- | `ShowToast(message, type)` | Toasts |
788
- | `trans(textByLanguage, defaultText)` | Pick a backend translation for the current language |
789
- | `AppStorage.getData / getText / setData / removeData / clearData / envData`, `TOKEN`, `LANG`, `THEME`, `BRANCH_ID` … `StorageKeys` | Prefixed session/local storage, shared key constants, `window.env` settings |
790
- | `openPage`, `setQueryParam(s)`, `removeQueryParam`, `readQueryParam(s)`, `useQueryParam`, `useCurrentPage`, `PageLink`, `currentPageSignal`, `queryParamsSignal` | Pages and query parameters (no router) |
791
- | `setLanguages(reply)`, `toLanguageOptions(reply)`, `languagesSignal`, `LangSource`, `LanguageRowType`, `setMenu(reply)`, `setMenuLoading()`, `clearMenu()`, `toNavigation(reply)`, `toNavItems(menus)`, `unwrapRootMenu(menus, "ADMIN_ROOT")`, `MenuAccessType`, `MenuResponseType`, `MenuSource`, `MenuOptions`, `ScreenAccessType`, `TranslationType`, `AuthUser` | Backend menus and shared app types (menu icons are fixed with `resolveLucideIcon`) |
792
- | `AppHttp.Get / GetShared / Post / Put / Patch / Delete / Load / Media / CloudUpload (uploadFile) / DownloadFile`, `clearSharedGetCache()`, `AppHttp.BaseUrl()`, `AppHttp.FullUrl(url)`, `AppHttp.setHeader`, `readEnvData(appNameKey, key)`, `uploadToSignedUrl`, `setAppConfig` / `readAppConfig` | HTTP client on dff-util `Http`: bearer token, session id, branch, extra headers, progress bar |
793
- | `setCompanyDetails(reply)`, `companyDetailsSignal`, `readCompanyDetails(reply)`, `readAppNameLabel(config, details)`, `readLogoUrl(config, isDark, details)`, `CompanyDetails`, `CompanySource` | Company / brand details (app name, company name, favicon, logos) |
794
- | `setCustomThemes(themes)`, `toCustomThemeList(themes)`, `customThemesSignal`, `CustomThemeMap`, `CustomThemes` | Custom themes as data (object keyed by theme name, or a list) |
795
- | `setBranch(id, name)`, `readBranchId()`, `clearBranch()`, `branchIdSignal`, `branchNameSignal` | Selected branch, sent as `x-branch-id` |
796
- | `startSession(token, user, isRemembered)`, `restoreSession()`, `endSession(keepKeys)`, `authUserSignal`, `isAuthenticatedSignal` | Login state (restored on reload) |
797
- | `toOptionTypes(rows)`, `readResponseRows(response)` | Backend option rows → `OptionType[]` |
798
- | `resolveLucideIcon("user-round-key")` | Backend icon names → lucide names |
799
- | `encryptPayload`, `decryptResponse` | AES-GCM payload encryption (key passed in) |
800
- | `SharedRegExp` | dff-util `RegExp` + `MOBILE_10`, `PERSON_NAME`, `ADDRESS_TEXT`, `UPPER_ALPHA_NUMERIC` |
801
- | `canAccessPath(action, path)` | Permission check for any path |
802
- | Signals | `localeSignal`, `themeSignal`, `directionSignal`, `translationSignal`, `isDarkThemeSignal`, `navigationSignal`, `navigationModeSignal`, `pathnameSignal`, `screenAccessSignal` … |
803
-
804
- Every component uses DaisyUI theme colours (`base-*`, `primary` …), so all themes – light and dark – work.
805
-
806
- ---
807
-
808
- ## Example apps
809
-
810
- There are two examples, each its own small Vite app that uses the library source directly:
811
-
812
- | Folder | Port | Shows |
813
- | --- | --- | --- |
814
- | `example-basic/` | 5174 | **One language** (en-US, `defaultLanguage` + `loadLocale`, no `loadSupportLanguages`) and **no branches** (no `loadBranches`): login, dashboard, users CRUD, settings (theme, menu mode, menu on/off). The smallest real setup to copy. |
815
- | `example-mfe/` | 9000 | **Microfrontends**: 4 separate Vite projects — `shell` (the only `AppLayout`, login, single-spa routing from `env.mfe.js`, menu as a signal (`loadMenuNavigation: navSignal`), `type="shell"`) and 3 MFEs `settings`, `forms`, `profile` (`type="mfe"`, page layouts only; theme and language from localStorage, kept in sync between bundles). No shared folder: each project has its own config, texts and theme. See `example-mfe/README.md`. |
816
- | `example/` | 5173 | **10 languages** (`loadSupportLanguages`, 3 RTL) and **stores** (`loadBranches`, `isDefault` / `disabled`), plus every component, 3 layouts and all themes. |
253
+ export function verifyEmail(): void {
254
+ openOtpModal({
255
+ userId: email, // sent as "userid" and shown in the dialog
256
+ title: t("login.otpTitle"), // optional, default t("ui.otpTitle")
257
+ message: t("login.otpMessage"), // optional, default t("ui.otpText")
258
+ onVerified: handleEmailVerified, // optional, called after a successful verify
259
+ onCancel: handleOtpCancel, // optional
260
+ });
261
+ }
817
262
 
818
- ```bash
819
- npm run example-basic:install
820
- npm run example-basic:dev # http://localhost:5174
263
+ <OtpModal />
821
264
  ```
822
265
 
823
- ### Full example
266
+ Every component exports its `*Props` type (`TypeInputProps`, `AppLayoutProps` …).
824
267
 
825
- `example/` is its own small app package (Vite is used only there — an app needs a bundler; the library does not).
826
- It shows login, dashboard, users CRUD (drawer + confirm + permissions), a **Components** section with every control,
827
- upload, overlay, skeleton and state, and settings for language (10, including 3 RTL and Telugu, Kannada, Tamil), theme (all 35 DaisyUI themes + custom `org-light` / `org-dark`) and navigation style.
828
- All pages live in one `App` component (`example/src/app.tsx`) and are picked by `?page`; the languages, branches and
829
- menu are signals in the config (`example/src/app-init/app-init-signals.ts`), filled from the sor replies by
830
- `app-init/app-init.service.ts`. It uses the library source directly, so changes show up without a build.
268
+ ## Types
831
269
 
832
- The example loads everything from the **sor** service (`MsUrl.sor` → `/api/org-sor`), except the menu, which comes
833
- from **utils** (`MsUrl.utils` → `/api/org-util`):
270
+ `UiConfig`, `HttpConfig`, `AppType` (`"spa" | "shell" | "mfe"`), `PageMode`, `LayoutConfig`, `NavItem`,
271
+ `NavigationMode`, `ScreenPermissions`, `ScreenAction`, `ApiSource`, `ValueSignal`, `Direction`, `LanguageOption`,
272
+ `LocaleLoader`, `LocaleCodeLoader`, `LocaleMessages`, `LocaleModule`, `LocaleBundle`, `LocaleFileLoader`,
273
+ `LocaleGroupFiles`, `Theme`, `ThemesLoader`, `ThemeGroups`, `CustomTheme`, `CustomThemeEntry`, `CustomThemeMap`,
274
+ `CustomThemes`, `CustomThemesModule`, `CompanyDetails`, `CompanySource`, `ToastPosition`, `ToastItem`, `ToastType`,
275
+ `AuthUser`, `BranchOption`, `BranchRowType`, `BranchResponseType`, `BranchSource`, `LangResponseType`, `LangSource`,
276
+ `LanguageRowType`, `MenuAccessType`, `MenuOptions`, `MenuResponseType`, `MenuSource`, `ScreenAccessType`,
277
+ `TranslationType`, `TranslationRecord`, `TranslateFunction`, `TranslateParams`, `UiContextState`, `UiContextValue`,
278
+ `OpenPageOptions`, `QueryParamOptions`, `QueryParamValues`, `LayoutChoice`, `FileTypeRules`, `UploadValue`,
279
+ `UploadOptions`, `MediaPreview`, `MediaType`, `MediaFit`, `MediaSize`, `IconName`, `TableColumn`, `ModalSize`,
280
+ `DrawerSide`, `DrawerSize`, `ListSelectionMode`, `LangInputType`, `TimeGranularity`, `ButtonAction`, `ControlSize`,
281
+ `TypeFieldProps`, `EncryptedEnvelope`, `WritableLocaleBundleSignal`, `StoredValue`, `HttpParams`, `HttpHeaders`.
834
282
 
835
- | Data | Request | Signal |
836
- | --- | --- | --- |
837
- | Company details | `GET /company-details` | `companySignal` (on start) |
838
- | Languages | `GET /load/LANG?active=true` | `supportLangSignal` (on start) |
839
- | Themes | `GET /content-load?query=theme` | `themesSignal` (on start) |
840
- | Texts of a language | `GET /content-load?query=locales.<code>` (all languages: `?query=locales`) | `localeSignal` (languages the library asks for) |
841
- | Menu (utils) | `GET /authorization/<persona>?roles=<roles joined with ",">` (from the signed-in user) | `navSignal` (after sign in) |
842
- | Branches | `GET /load/BRANCHS?profile=<user id>` | `branchSignal` (after sign in, before the menu) |
843
-
844
- `readContent(reply, query)` takes the content out of a `content-load` reply (`{ data }` and the query path are
845
- optional: `readContent(reply, "locales.en-US")`). The examples have no fake backend: they call these services at
846
- `http.baseUrl` (`/api`) or `window.env.REACT_APP_ORG_API_BASE_URL` (`public/env.js`), so point that at your backend.
847
- example-basic and the MFE shell work the same way (no branches).
848
-
849
- ```bash
850
- npm run example:install
851
- npm run example:dev # http://localhost:5173 – log in with any email and a 6+ character password
852
- ```
853
283
 
854
284
  ## Development
855
285
 
856
- The library has **no bundler and no Vite**: `tsc` compiles `src/` file by file into `dist/` (readable ES modules + `.d.ts`),
857
- and the tests run on Node's built-in test runner (`node:test` + `jsdom`, setup in `scripts/test-setup.mjs`).
858
-
859
286
  ```bash
860
287
  npm install
861
- npm run verify # typecheck + code style + tests + build
862
- npm run build # tsc -> dist/, fix .d.ts import paths, copy styles.css
863
- npm run check:style # readability rules only
864
- npm test # tsc -> build-test/, then Node's built-in test runner (node --test) with jsdom
288
+ npm run verify # typecheck + code style + tests + build
865
289
  ```
866
290
 
867
- Inside `src/`, relative imports use the real file extension (`./type.icon.ts`); `tsc` rewrites them to `.js` in `dist/`.
868
-
869
- ## Publishing
870
-
871
- ```bash
872
- npm login
873
- npm version minor
874
- npm publish
875
- ```
876
-
877
- Or use `github-workflows/publish.yml` (move it to `.github/workflows/` and add the `NPM_TOKEN` secret).
291
+ Code rules: [CODING_RULES.md](./CODING_RULES.md). Examples: `example-basic/`, `example/`, `example-mfe/`.
878
292
 
879
293
  ## License
880
294
 
881
- [MIT](./LICENSE) © 2026 DesignForFeature.
882
-
883
- Anybody can use this library for free, in personal or commercial projects: use it, copy it, change it, merge it,
884
- publish it, share it and sell software built with it. The only condition is to keep the copyright and license notice
885
- (the `LICENSE` file) with copies of the library. It comes "as is", without warranty.
295
+ [MIT](./LICENSE)