shared-lib-web 0.0.2 → 0.0.3

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 (186) hide show
  1. package/README.md +381 -127
  2. package/dist/components/app-brand.d.ts.map +1 -1
  3. package/dist/components/app-brand.js +9 -5
  4. package/dist/components/app-brand.js.map +1 -1
  5. package/dist/components/coming-soon.d.ts.map +1 -1
  6. package/dist/components/coming-soon.js +3 -2
  7. package/dist/components/coming-soon.js.map +1 -1
  8. package/dist/components/language-switcher.d.ts +5 -1
  9. package/dist/components/language-switcher.d.ts.map +1 -1
  10. package/dist/components/language-switcher.js +20 -7
  11. package/dist/components/language-switcher.js.map +1 -1
  12. package/dist/components/settings-menu.d.ts +4 -0
  13. package/dist/components/settings-menu.d.ts.map +1 -1
  14. package/dist/components/settings-menu.js +15 -2
  15. package/dist/components/settings-menu.js.map +1 -1
  16. package/dist/context/use-ui.d.ts.map +1 -1
  17. package/dist/context/use-ui.js +4 -3
  18. package/dist/context/use-ui.js.map +1 -1
  19. package/dist/i18n/browser-language.d.ts +9 -0
  20. package/dist/i18n/browser-language.d.ts.map +1 -0
  21. package/dist/i18n/browser-language.js +89 -0
  22. package/dist/i18n/browser-language.js.map +1 -0
  23. package/dist/i18n/default-messages.d.ts.map +1 -1
  24. package/dist/i18n/default-messages.js +3 -0
  25. package/dist/i18n/default-messages.js.map +1 -1
  26. package/dist/i18n/locale-groups.d.ts +18 -0
  27. package/dist/i18n/locale-groups.d.ts.map +1 -0
  28. package/dist/i18n/locale-groups.js +74 -0
  29. package/dist/i18n/locale-groups.js.map +1 -0
  30. package/dist/i18n/locale-service.d.ts +22 -4
  31. package/dist/i18n/locale-service.d.ts.map +1 -1
  32. package/dist/i18n/locale-service.js +95 -27
  33. package/dist/i18n/locale-service.js.map +1 -1
  34. package/dist/i18n/locale-signal.d.ts +18 -0
  35. package/dist/i18n/locale-signal.d.ts.map +1 -0
  36. package/dist/i18n/locale-signal.js +142 -0
  37. package/dist/i18n/locale-signal.js.map +1 -0
  38. package/dist/i18n/translator.d.ts +8 -1
  39. package/dist/i18n/translator.d.ts.map +1 -1
  40. package/dist/i18n/translator.js +36 -12
  41. package/dist/i18n/translator.js.map +1 -1
  42. package/dist/index.d.ts +21 -10
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +19 -8
  45. package/dist/index.js.map +1 -1
  46. package/dist/interfaces/app-types.d.ts +6 -0
  47. package/dist/interfaces/app-types.d.ts.map +1 -1
  48. package/dist/interfaces/ui-config.d.ts +162 -15
  49. package/dist/interfaces/ui-config.d.ts.map +1 -1
  50. package/dist/interfaces/ui-context.d.ts +1 -1
  51. package/dist/interfaces/ui-context.d.ts.map +1 -1
  52. package/dist/layouts/auth-layout.js +1 -1
  53. package/dist/layouts/auth-layout.js.map +1 -1
  54. package/dist/providers/provider-effects.d.ts +2 -2
  55. package/dist/providers/provider-effects.d.ts.map +1 -1
  56. package/dist/providers/provider-effects.js +4 -1
  57. package/dist/providers/provider-effects.js.map +1 -1
  58. package/dist/providers/register-config.d.ts.map +1 -1
  59. package/dist/providers/register-config.js +2 -0
  60. package/dist/providers/register-config.js.map +1 -1
  61. package/dist/providers/shared-web-ui-provider.d.ts +7 -19
  62. package/dist/providers/shared-web-ui-provider.d.ts.map +1 -1
  63. package/dist/providers/shared-web-ui-provider.js +21 -22
  64. package/dist/providers/shared-web-ui-provider.js.map +1 -1
  65. package/dist/query/query-param.d.ts +4 -1
  66. package/dist/query/query-param.d.ts.map +1 -1
  67. package/dist/query/query-param.js +6 -3
  68. package/dist/query/query-param.js.map +1 -1
  69. package/dist/state/api-loader.d.ts +19 -0
  70. package/dist/state/api-loader.d.ts.map +1 -0
  71. package/dist/state/api-loader.js +187 -0
  72. package/dist/state/api-loader.js.map +1 -0
  73. package/dist/state/auth-service.d.ts +4 -0
  74. package/dist/state/auth-service.d.ts.map +1 -1
  75. package/dist/state/auth-service.js +47 -3
  76. package/dist/state/auth-service.js.map +1 -1
  77. package/dist/state/branch-service.d.ts +1 -1
  78. package/dist/state/branch-service.js +3 -3
  79. package/dist/state/branch-service.js.map +1 -1
  80. package/dist/state/company-service.d.ts +16 -0
  81. package/dist/state/company-service.d.ts.map +1 -0
  82. package/dist/state/company-service.js +97 -0
  83. package/dist/state/company-service.js.map +1 -0
  84. package/dist/state/language-service.d.ts +5 -2
  85. package/dist/state/language-service.d.ts.map +1 -1
  86. package/dist/state/language-service.js +12 -7
  87. package/dist/state/language-service.js.map +1 -1
  88. package/dist/state/layout-choice-service.d.ts +10 -0
  89. package/dist/state/layout-choice-service.d.ts.map +1 -0
  90. package/dist/state/layout-choice-service.js +34 -0
  91. package/dist/state/layout-choice-service.js.map +1 -0
  92. package/dist/state/menu-service.d.ts +1 -1
  93. package/dist/state/menu-service.js +2 -2
  94. package/dist/state/menu-service.js.map +1 -1
  95. package/dist/state/preference-sync.d.ts +1 -1
  96. package/dist/state/preference-sync.d.ts.map +1 -1
  97. package/dist/state/preference-sync.js +11 -3
  98. package/dist/state/preference-sync.js.map +1 -1
  99. package/dist/state/signals.d.ts +9 -1
  100. package/dist/state/signals.d.ts.map +1 -1
  101. package/dist/state/signals.js +28 -4
  102. package/dist/state/signals.js.map +1 -1
  103. package/dist/theme/custom-themes.d.ts +28 -0
  104. package/dist/theme/custom-themes.d.ts.map +1 -0
  105. package/dist/theme/custom-themes.js +218 -0
  106. package/dist/theme/custom-themes.js.map +1 -0
  107. package/dist/theme/dark-themes.d.ts +9 -1
  108. package/dist/theme/dark-themes.d.ts.map +1 -1
  109. package/dist/theme/dark-themes.js +74 -2
  110. package/dist/theme/dark-themes.js.map +1 -1
  111. package/dist/theme/logo.d.ts +6 -3
  112. package/dist/theme/logo.d.ts.map +1 -1
  113. package/dist/theme/logo.js +17 -3
  114. package/dist/theme/logo.js.map +1 -1
  115. package/dist/theme/theme-service.d.ts +14 -3
  116. package/dist/theme/theme-service.d.ts.map +1 -1
  117. package/dist/theme/theme-service.js +64 -10
  118. package/dist/theme/theme-service.js.map +1 -1
  119. package/dist/utils/app-http.d.ts +29 -1
  120. package/dist/utils/app-http.d.ts.map +1 -1
  121. package/dist/utils/app-http.js +113 -11
  122. package/dist/utils/app-http.js.map +1 -1
  123. package/dist/utils/content-util.d.ts +6 -0
  124. package/dist/utils/content-util.d.ts.map +1 -0
  125. package/dist/utils/content-util.js +45 -0
  126. package/dist/utils/content-util.js.map +1 -0
  127. package/dist/utils/error-util.d.ts +3 -0
  128. package/dist/utils/error-util.d.ts.map +1 -0
  129. package/dist/utils/error-util.js +58 -0
  130. package/dist/utils/error-util.js.map +1 -0
  131. package/dist/utils/language-util.d.ts +3 -3
  132. package/dist/utils/language-util.d.ts.map +1 -1
  133. package/dist/utils/language-util.js +7 -7
  134. package/dist/utils/language-util.js.map +1 -1
  135. package/dist/utils/menu-util.js +1 -1
  136. package/dist/utils/menu-util.js.map +1 -1
  137. package/dist/utils/signal-source.d.ts +4 -0
  138. package/dist/utils/signal-source.d.ts.map +1 -0
  139. package/dist/utils/signal-source.js +13 -0
  140. package/dist/utils/signal-source.js.map +1 -0
  141. package/dist/utils/storage-keys.d.ts +5 -0
  142. package/dist/utils/storage-keys.d.ts.map +1 -1
  143. package/dist/utils/storage-keys.js +5 -0
  144. package/dist/utils/storage-keys.js.map +1 -1
  145. package/package.json +3 -3
  146. package/src/components/app-brand.tsx +9 -5
  147. package/src/components/coming-soon.tsx +3 -2
  148. package/src/components/language-switcher.tsx +26 -7
  149. package/src/components/settings-menu.tsx +28 -2
  150. package/src/context/use-ui.ts +4 -3
  151. package/src/i18n/browser-language.ts +98 -0
  152. package/src/i18n/default-messages.ts +3 -0
  153. package/src/i18n/locale-groups.ts +87 -0
  154. package/src/i18n/locale-service.ts +99 -27
  155. package/src/i18n/locale-signal.ts +173 -0
  156. package/src/i18n/translator.ts +38 -12
  157. package/src/index.ts +71 -3
  158. package/src/interfaces/app-types.ts +6 -0
  159. package/src/interfaces/ui-config.ts +168 -15
  160. package/src/interfaces/ui-context.ts +1 -1
  161. package/src/layouts/auth-layout.tsx +1 -1
  162. package/src/providers/provider-effects.ts +5 -2
  163. package/src/providers/register-config.ts +2 -0
  164. package/src/providers/shared-web-ui-provider.tsx +26 -43
  165. package/src/query/query-param.ts +6 -2
  166. package/src/state/api-loader.ts +205 -0
  167. package/src/state/auth-service.ts +58 -3
  168. package/src/state/branch-service.ts +3 -3
  169. package/src/state/company-service.ts +107 -0
  170. package/src/state/language-service.ts +12 -7
  171. package/src/state/layout-choice-service.ts +40 -0
  172. package/src/state/menu-service.ts +2 -2
  173. package/src/state/preference-sync.ts +11 -3
  174. package/src/state/signals.ts +36 -4
  175. package/src/theme/custom-themes.ts +236 -0
  176. package/src/theme/dark-themes.ts +80 -3
  177. package/src/theme/logo.ts +19 -4
  178. package/src/theme/org-themes.json +70 -0
  179. package/src/theme/theme-service.ts +70 -10
  180. package/src/utils/app-http.ts +125 -11
  181. package/src/utils/content-util.ts +49 -0
  182. package/src/utils/error-util.ts +64 -0
  183. package/src/utils/language-util.ts +7 -7
  184. package/src/utils/menu-util.ts +1 -1
  185. package/src/utils/signal-source.ts +15 -0
  186. package/src/utils/storage-keys.ts +6 -0
@@ -5,16 +5,19 @@
5
5
  import { initializeLanguage, readActiveConfig } from "../i18n/locale-service.ts";
6
6
  import { isTranslationReadySignal } from "../state/signals.ts";
7
7
  import { startDocumentSync } from "../state/document-sync.ts";
8
+ import { followConfigThemes, loadConfigThemes } from "../theme/custom-themes.ts";
8
9
  import { initializeTheme } from "../theme/theme-service.ts";
9
10
 
10
11
  /** Empty dependency list: run the effect only once. */
11
12
  export const RUN_ONCE: never[] = [];
12
13
 
13
- /** Applies the saved theme and starts syncing <html> attributes. */
14
- export function initializeThemeOnMount(): void {
14
+ /** Applies the saved theme, starts syncing <html> attributes and loads / follows config.loadThemes. */
15
+ export function initializeThemeOnMount(): () => void {
15
16
  const config = readActiveConfig();
16
17
  initializeTheme(config);
17
18
  startDocumentSync();
19
+ void loadConfigThemes(config);
20
+ return followConfigThemes(config);
18
21
  }
19
22
 
20
23
  /** Shows the app even when a locale file fails, so the screen is never stuck on loading. */
@@ -9,6 +9,7 @@ import { forgetAppliedLanguages } from "../state/language-service.ts";
9
9
  import { forgetAppliedMenu } from "../state/menu-service.ts";
10
10
  import { initializeNavigation } from "../state/navigation-service.ts";
11
11
  import { languagesSignal, uiConfigSignal } from "../state/signals.ts";
12
+ import { setCustomThemes } from "../theme/custom-themes.ts";
12
13
  import { setAppConfig } from "../utils/app-config.ts";
13
14
  import { AppStorage } from "../utils/app-storage.ts";
14
15
 
@@ -21,6 +22,7 @@ export function registerUiConfig(config: UiConfig): void {
21
22
  setAppConfig(config);
22
23
  uiConfigSignal.value = config;
23
24
  languagesSignal.value = config.languages ?? [];
25
+ setCustomThemes(config.customThemes);
24
26
  forgetAppliedLanguages();
25
27
  initializeNavigation(config);
26
28
  forgetAppliedMenu();
@@ -1,18 +1,17 @@
1
1
  // shared-web-ui-provider.tsx
2
- // The single entry point of the shell. Wrap your app once:
2
+ // The single entry point of the app. Wrap your app once:
3
3
  //
4
- // <SharedWebUiProvider config={config}>
4
+ // <SharedWebUiProvider type="spa" config={config}> type: "spa" (default) | "shell" | "mfe"
5
5
  // <App />
6
6
  // </SharedWebUiProvider>
7
7
  //
8
- // Menu and languages from the backend are passed separately and can change at any time
9
- // (null first, the reply later; { data: [...], meta } or the list):
10
- // <SharedWebUiProvider config={config} nav={menuResponse} lang={langResponse}>
11
- // Branches work the same way (no switcher while null or empty):
12
- // <SharedWebUiProvider config={config} branch={branchResponse}> (isDefault / disabled come with the rows)
8
+ // Menu, languages and branches come from the backend through config loaders (the provider calls them itself):
9
+ // loadSupportLanguages, loadBranches, loadMenuNavigation (like loadThemes)
10
+ // lang on start; branch and nav after sign in (removed on sign out). Type "mfe" calls only lang.
11
+ // By hand (no loaders): setLanguages(reply), setBranches(reply), setMenu(reply).
13
12
  //
14
13
  // It provides: config context, theme, translations, query parameter sync and toasts.
15
- // There is no router: the current page is the ?page query parameter (openPage, setQueryParam, readQueryParam).
14
+ // There is no router: the current page is ?page=... (or the path for pageMode "path" / type "shell").
16
15
 
17
16
  import { useLayoutEffect, type ReactNode } from "react";
18
17
  import { startScrollListener } from "../components/scroll-to-top.tsx";
@@ -20,13 +19,13 @@ import { ToastContainer } from "../components/toast-container.tsx";
20
19
  import { TopProgress } from "../components/top-progress.tsx";
21
20
  import { MediaViewer } from "../types/media-viewer.tsx";
22
21
  import { UiContext, readContextState } from "../context/ui-context.ts";
23
- import type { BranchSource, LangSource, MenuSource } from "../interfaces/app-types.ts";
24
- import type { UiConfig } from "../interfaces/ui-config.ts";
22
+ import type { AppType, UiConfig } from "../interfaces/ui-config.ts";
25
23
  import { startQueryParamSync } from "../query/query-param.ts";
26
- import { registerBranches } from "../state/branch-service.ts";
24
+ import { startApiLoading } from "../state/api-loader.ts";
25
+ import { applySavedLayoutChoice } from "../state/layout-choice-service.ts";
27
26
  import { startPreferenceSync } from "../state/preference-sync.ts";
28
- import { registerLanguages } from "../state/language-service.ts";
29
- import { registerMenu } from "../state/menu-service.ts";
27
+ import { startSessionSync } from "../state/auth-service.ts";
28
+ import { appTypeSignal } from "../state/signals.ts";
30
29
  import { startEscapeListener } from "../utils/event-util.ts";
31
30
  import { RUN_ONCE } from "./provider-effects.ts";
32
31
  import { ThemeProvider } from "./theme-provider.tsx";
@@ -34,53 +33,37 @@ import { TranslationProvider } from "./translation-provider.tsx";
34
33
  import { registerUiConfig } from "./register-config.ts";
35
34
 
36
35
  export interface SharedWebUiProviderProps {
37
- /** The app configuration (usually imported from config.ts). */
36
+ /** The app configuration (usually imported from config.ts). Backend loaders: loadSupportLanguages, loadBranches, loadMenuNavigation. */
38
37
  config: UiConfig;
39
38
  /**
40
- * Menu from the backend: the reply { data: [...], meta } or the list. Replaces config.navigation.
41
- * null = still loading (menu skeleton). Leave it out to use config.navigation.
39
+ * What the app is: "spa" (default), "shell" (hosts microfrontends; pages are paths by default) or "mfe"
40
+ * (a microfrontend: page layouts only; no menu / branch calls; appName, logos, homePath, branchLabel unused).
42
41
  */
43
- nav?: MenuSource | null;
44
- /**
45
- * Languages from the backend: the reply { data: [...], meta } or the list. Replaces config.languages.
46
- * null = not here yet (config.defaultLanguage is shown meanwhile). Texts load with config.loadLocale(code).
47
- */
48
- lang?: LangSource | null;
49
- /**
50
- * Branches from the backend: the reply { data: [...], meta } or the list ({ id, name, nameLang?, isDefault?, disabled? }).
51
- * The row with isDefault is selected when the user has none saved; disabled rows can not be selected.
52
- * null or [] = no branch switcher. The selected branch is sent as x-branch-id by AppHttp.
53
- */
54
- branch?: BranchSource | null;
42
+ type?: AppType;
55
43
  /** Your app. */
56
44
  children?: ReactNode;
57
45
  /** Shown while the first locale file loads. */
58
46
  loadingFallback?: ReactNode;
59
47
  }
60
48
 
61
- /** Applies the backend inputs (each only when it changed). */
62
- export function applyProviderInputs(
63
- nav: MenuSource | null | undefined,
64
- lang: LangSource | null | undefined,
65
- branch: BranchSource | null | undefined,
66
- ): void {
67
- registerMenu(nav);
68
- registerLanguages(lang);
69
- registerBranches(branch);
49
+ /** Saves the app type (before the config, so the page mode is right on the first render). */
50
+ export function registerAppType(type: AppType): void {
51
+ if (appTypeSignal.peek() !== type) {
52
+ appTypeSignal.value = type;
53
+ }
70
54
  }
71
55
 
72
56
  export function SharedWebUiProvider(props: SharedWebUiProviderProps) {
73
- const { config, nav, lang, branch, children, loadingFallback } = props;
57
+ const { config, type = "spa", children, loadingFallback } = props;
58
+ registerAppType(type);
74
59
  registerUiConfig(config);
75
- // nav / lang / branch are written to signals AFTER the render (layout effect, still before the paint), so no other
76
- // component is updated while this one renders (React warns about that).
77
- const applyInputs = applyProviderInputs.bind(null, nav, lang, branch);
78
- const inputs = [nav, lang, branch];
79
- useLayoutEffect(applyInputs, inputs);
80
60
  useLayoutEffect(startQueryParamSync, RUN_ONCE);
81
61
  useLayoutEffect(startEscapeListener, RUN_ONCE);
82
62
  useLayoutEffect(startScrollListener, RUN_ONCE);
83
63
  useLayoutEffect(startPreferenceSync, RUN_ONCE);
64
+ useLayoutEffect(startSessionSync, RUN_ONCE);
65
+ useLayoutEffect(applySavedLayoutChoice, RUN_ONCE);
66
+ useLayoutEffect(startApiLoading, RUN_ONCE);
84
67
  const contextState = readContextState(config);
85
68
 
86
69
  return (
@@ -19,6 +19,7 @@ import {
19
19
  openMegaMenuIdSignal,
20
20
  queryParamsSignal,
21
21
  railFlyoutSignal,
22
+ readIsPathPageMode,
22
23
  uiConfigSignal,
23
24
  } from "../state/signals.ts";
24
25
  import { toPagePath, toPageParamValue } from "./page-path.ts";
@@ -151,10 +152,13 @@ export function readCurrentPage(): string {
151
152
  return currentPageSignal.value;
152
153
  }
153
154
 
154
- /** true when pages live in the path (/profiles) instead of ?page (config.layout.pageMode "path"). */
155
+ /**
156
+ * true when pages live in the path (/profiles) instead of ?page: config.layout.pageMode "path",
157
+ * or no pageMode and the app type "shell".
158
+ */
155
159
  export function isPathPageMode(): boolean {
156
160
  const config = uiConfigSignal.peek();
157
- return config?.layout?.pageMode === "path";
161
+ return readIsPathPageMode(config);
158
162
  }
159
163
 
160
164
  /**
@@ -0,0 +1,205 @@
1
+ // api-loader.ts
2
+ // The backend sources of the config, used by the provider itself (like loadThemes):
3
+ //
4
+ // loadSupportLanguages once, when the provider mounts -> setLanguages(reply)
5
+ // loadCompanyDetails once, when the provider mounts (an "mfe" only when it sets it) -> setCompanyDetails(reply)
6
+ // loadBranches when a user is signed in (sign in, or restored session) -> setBranches(reply)
7
+ // (before the menu: the menu request already sends x-branch-id)
8
+ // loadMenuNavigation when a user is signed in -> skeleton, then setMenu(reply)
9
+ // sign out -> branches and menu are removed
10
+ //
11
+ // A source is your function, a URL / path (AppHttp.Get), or a SIGNAL you fill yourself:
12
+ // loadMenuNavigation: navSignal // null = skeleton, a reply = the menu; every new value is shown at once
13
+ // A signal is followed as it is (no call, no sign-in rule): your code decides when it changes.
14
+ // Type "mfe" uses only loadSupportLanguages and, when set, loadCompanyDetails (the shell owns the rest); no menu.
15
+
16
+ import { effect } from "@preact/signals-react";
17
+ import type { BranchSource, LangSource, MenuSource } from "../interfaces/app-types.ts";
18
+ import type { ApiSource, UiConfig, ValueSignal } from "../interfaces/ui-config.ts";
19
+ import { AppHttp, readJwtToken } from "../utils/app-http.ts";
20
+ import { isSignalSource } from "../utils/signal-source.ts";
21
+ import { isAuthenticatedSignal } from "./auth-service.ts";
22
+ import { registerBranches, setBranches } from "./branch-service.ts";
23
+ import { setCompanyDetails } from "./company-service.ts";
24
+ import { registerLanguages, setLanguages } from "./language-service.ts";
25
+ import { registerMenu, setMenu, setMenuLoading } from "./menu-service.ts";
26
+ import { appTypeSignal, uiConfigSignal } from "./signals.ts";
27
+
28
+ /** Configs whose loadSupportLanguages already ran (StrictMode mounts twice). */
29
+ const languageLoadedConfigs = new WeakSet<UiConfig>();
30
+
31
+ /** Configs whose loadCompanyDetails already ran (StrictMode mounts twice). */
32
+ const companyLoadedConfigs = new WeakSet<UiConfig>();
33
+
34
+ /** The token whose branches and menu were loaded last ("" = signed out), so a second mount does not load again. */
35
+ let loadedSessionToken: string | undefined = undefined;
36
+
37
+ /** Applies one value of a source signal (menu, languages or branches). */
38
+ type SignalValueApplier = (value: never) => void;
39
+
40
+ /** A source the provider calls (a function or a URL), not a signal. */
41
+ function isCallableSource(source: ApiSource | undefined): source is string | (() => Promise<unknown>) {
42
+ return typeof source === "function" || typeof source === "string";
43
+ }
44
+
45
+ /** Calls one loader: your function, or AppHttp.Get(url). A signal answers with its current value. */
46
+ export function callApiSource(source: ApiSource): Promise<unknown> {
47
+ if (typeof source === "function") {
48
+ return source();
49
+ }
50
+ if (isSignalSource(source)) {
51
+ const currentValue = source.peek();
52
+ return Promise.resolve(currentValue);
53
+ }
54
+ return AppHttp.Get(source);
55
+ }
56
+
57
+ /** loadSupportLanguages -> setLanguages. Once per config. On an error the default language stays. */
58
+ export async function loadConfigLanguages(config: UiConfig): Promise<void> {
59
+ const langSource = config.loadSupportLanguages;
60
+ const isLoaded = languageLoadedConfigs.has(config);
61
+ if (!isCallableSource(langSource) || isLoaded) {
62
+ return;
63
+ }
64
+ languageLoadedConfigs.add(config);
65
+ try {
66
+ const reply = await callApiSource(langSource);
67
+ setLanguages(reply as LangSource);
68
+ } catch (error) {
69
+ console.error("shared-lib-web: config.loadSupportLanguages failed; the default language stays.", error);
70
+ }
71
+ }
72
+
73
+ /** loadCompanyDetails -> setCompanyDetails. Once per config. On an error the config values (appName, logos) stay. */
74
+ export async function loadConfigCompany(config: UiConfig): Promise<void> {
75
+ const companySource = config.loadCompanyDetails;
76
+ const isLoaded = companyLoadedConfigs.has(config);
77
+ if (!isCallableSource(companySource) || isLoaded) {
78
+ return;
79
+ }
80
+ companyLoadedConfigs.add(config);
81
+ try {
82
+ const reply = await callApiSource(companySource);
83
+ setCompanyDetails(reply);
84
+ } catch (error) {
85
+ console.error("shared-lib-web: config.loadCompanyDetails failed; the config app name and logos stay.", error);
86
+ setCompanyDetails({});
87
+ }
88
+ }
89
+
90
+ /** loadBranches -> setBranches (no switcher on an error). */
91
+ async function fetchBranchList(branchSource: ApiSource): Promise<void> {
92
+ try {
93
+ const reply = await callApiSource(branchSource);
94
+ setBranches(reply as BranchSource);
95
+ } catch (error) {
96
+ console.error("shared-lib-web: config.loadBranches failed; no branch switcher.", error);
97
+ setBranches(null);
98
+ }
99
+ }
100
+
101
+ /** loadMenuNavigation -> menu skeleton, then setMenu (an empty menu on an error). */
102
+ async function fetchMenuNavigation(navSource: ApiSource): Promise<void> {
103
+ setMenuLoading();
104
+ try {
105
+ const reply = await callApiSource(navSource);
106
+ setMenu(reply as MenuSource);
107
+ } catch (error) {
108
+ console.error("shared-lib-web: config.loadMenuNavigation failed; the menu is empty.", error);
109
+ setMenu([]);
110
+ }
111
+ }
112
+
113
+ /** After sign in: branches first, then the menu (only sources the provider calls; signals follow themselves). */
114
+ export async function loadSessionData(config: UiConfig): Promise<void> {
115
+ const branchSource = config.loadBranches;
116
+ const navSource = config.loadMenuNavigation;
117
+ if (isCallableSource(branchSource)) {
118
+ await fetchBranchList(branchSource);
119
+ }
120
+ if (isCallableSource(navSource)) {
121
+ await fetchMenuNavigation(navSource);
122
+ }
123
+ }
124
+
125
+ /** After sign out: no branches, and the menu waits (skeleton) for the next user. Signal sources are left alone. */
126
+ export function clearSessionData(config: UiConfig): void {
127
+ if (isCallableSource(config.loadBranches)) {
128
+ setBranches(null);
129
+ }
130
+ if (isCallableSource(config.loadMenuNavigation)) {
131
+ setMenuLoading();
132
+ }
133
+ }
134
+
135
+ /** Runs on every sign in / sign out (a signals effect). */
136
+ function followSession(): void {
137
+ const isSignedIn = isAuthenticatedSignal.value;
138
+ const config = uiConfigSignal.peek();
139
+ if (!config) {
140
+ return;
141
+ }
142
+ const token = isSignedIn ? readJwtToken() : "";
143
+ if (token === loadedSessionToken) {
144
+ return;
145
+ }
146
+ loadedSessionToken = token;
147
+ if (isSignedIn) {
148
+ void loadSessionData(config);
149
+ return;
150
+ }
151
+ clearSessionData(config);
152
+ }
153
+
154
+ /** Forgets what was loaded (a new config, or tests). */
155
+ export function forgetApiSession(): void {
156
+ loadedSessionToken = undefined;
157
+ }
158
+
159
+ /** Reads a source signal (so the effect follows it) and applies its value. */
160
+ function applySignalValue(sourceSignal: ValueSignal<unknown>, applyValue: SignalValueApplier): void {
161
+ const value = sourceSignal.value;
162
+ applyValue(value as never);
163
+ }
164
+
165
+ /** Follows a signal source; returns the stop function (or undefined when the source is not a signal). */
166
+ function followSignalSource(source: ApiSource | undefined, applyValue: SignalValueApplier): (() => void) | undefined {
167
+ if (!isSignalSource(source)) {
168
+ return undefined;
169
+ }
170
+ const applySource = applySignalValue.bind(null, source, applyValue);
171
+ return effect(applySource);
172
+ }
173
+
174
+ /** Stops every running follower. */
175
+ function stopAll(stoppers: Array<(() => void) | undefined>): void {
176
+ for (const stop of stoppers) {
177
+ stop?.();
178
+ }
179
+ forgetApiSession();
180
+ }
181
+
182
+ /**
183
+ * Starts the config sources. Called once by SharedWebUiProvider (layout effect); returns the cleanup.
184
+ * Type "mfe": only loadSupportLanguages (+ loadCompanyDetails when set), and an empty menu (no skeleton; the shell shows the menu).
185
+ */
186
+ export function startApiLoading(): () => void {
187
+ const config = uiConfigSignal.peek();
188
+ if (!config) {
189
+ return forgetApiSession;
190
+ }
191
+ void loadConfigLanguages(config);
192
+ const stopLanguages = followSignalSource(config.loadSupportLanguages, registerLanguages);
193
+ // Company details also for an MFE that sets loadCompanyDetails (for example an auth MFE with the brand on its login).
194
+ void loadConfigCompany(config);
195
+ const stopCompany = followSignalSource(config.loadCompanyDetails, setCompanyDetails);
196
+ const appType = appTypeSignal.peek();
197
+ if (appType === "mfe") {
198
+ setMenu([]);
199
+ return stopAll.bind(null, [stopLanguages, stopCompany]);
200
+ }
201
+ const stopBranches = followSignalSource(config.loadBranches, registerBranches);
202
+ const stopMenu = followSignalSource(config.loadMenuNavigation, registerMenu);
203
+ const stopSession = effect(followSession);
204
+ return stopAll.bind(null, [stopLanguages, stopCompany, stopBranches, stopMenu, stopSession]);
205
+ }
@@ -6,13 +6,16 @@
6
6
  // isAuthenticatedSignal.value // true / false
7
7
  // endSession(); // log out (LANG, THEME ... are kept)
8
8
  // endSession([BRANCH_ID]); // log out, also keeps the listed AppStorage keys
9
+ //
10
+ // Microfrontends: each one bundles its own copy of the library. startSession / endSession fire SESSION_EVENT, and
11
+ // every other copy (startSessionSync, started by the provider) applies it: an auth MFE signs in -> the shell is signed in.
9
12
 
10
13
  import { computed, signal } from "@preact/signals-react";
11
14
  import { ConstValue } from "dff-util";
12
15
  import type { AuthUser } from "../interfaces/app-types.ts";
13
16
  import { AppStorage } from "../utils/app-storage.ts";
14
17
  import { resetSessionId } from "../utils/session-id.ts";
15
- import { AUTH_USER, BRANCH_ID, REMEMBER_ME, TOKEN } from "../utils/storage-keys.ts";
18
+ import { AUTH_USER, BRANCH_ID, REMEMBER_ME, SESSION_EVENT, TOKEN } from "../utils/storage-keys.ts";
16
19
  import { clearBranch, forgetAppliedBranches, restoreBranch } from "./branch-service.ts";
17
20
  import { uiConfigSignal } from "./signals.ts";
18
21
 
@@ -33,6 +36,29 @@ function readIsAuthenticated(): boolean {
33
36
  /** true when a token is present. */
34
37
  export const isAuthenticatedSignal = computed(readIsAuthenticated);
35
38
 
39
+ /** Id of this copy of the library: its own session events are not applied again. */
40
+ const randomNumber = Math.random();
41
+ const LIBRARY_COPY_ID = String(randomNumber);
42
+
43
+ /** What SESSION_EVENT carries. */
44
+ interface SessionEventDetail {
45
+ isSignedIn?: boolean;
46
+ copyId?: string;
47
+ }
48
+
49
+ let isSessionSyncStarted = false;
50
+
51
+ /** Tells every other library copy on the page that the session started or ended. */
52
+ function notifySessionChanged(isSignedIn: boolean): void {
53
+ if (typeof window === "undefined") {
54
+ return;
55
+ }
56
+ const detail: SessionEventDetail = { isSignedIn: isSignedIn, copyId: LIBRARY_COPY_ID };
57
+ const eventInit = { detail: detail };
58
+ const sessionEvent = new CustomEvent(SESSION_EVENT, eventInit);
59
+ window.dispatchEvent(sessionEvent);
60
+ }
61
+
36
62
  /** AppStorage key of the token (config.http.tokenKey, default "TOKEN"). */
37
63
  export function readTokenKey(): string {
38
64
  const config = uiConfigSignal.value;
@@ -55,8 +81,10 @@ export function startSession(token: string, user: AuthUser | null, isRemembered:
55
81
  AppStorage.setData(tokenKey, token);
56
82
  AppStorage.setData(AUTH_USER_KEY, user);
57
83
  AppStorage.setData(REMEMBER_ME, isRemembered);
58
- sessionTokenSignal.value = token;
84
+ // The user first: whatever runs on sign in (branches, menu) already reads the user.
59
85
  authUserSignal.value = user;
86
+ sessionTokenSignal.value = token;
87
+ notifySessionChanged(true);
60
88
  }
61
89
 
62
90
  /** Reads a saved session (sessionStorage). Called by SharedWebUiProvider. */
@@ -68,8 +96,8 @@ export function restoreSession(): void {
68
96
  return;
69
97
  }
70
98
  const storedUser = AppStorage.getData(AUTH_USER_KEY);
71
- sessionTokenSignal.value = token;
72
99
  authUserSignal.value = storedUser && typeof storedUser === "object" ? (storedUser as AuthUser) : null;
100
+ sessionTokenSignal.value = token;
73
101
  }
74
102
 
75
103
  /** Sends the browser to config.http.logoutUrl (replace: Back does not return to the signed-in page). */
@@ -98,7 +126,34 @@ export function endSession(keepKeys: string[] = [], isRedirect: boolean = true):
98
126
  sessionTokenSignal.value = ConstValue.EMPTY;
99
127
  authUserSignal.value = null;
100
128
  resetSessionId();
129
+ notifySessionChanged(false);
101
130
  if (isRedirect) {
102
131
  redirectToLogoutUrl();
103
132
  }
104
133
  }
134
+
135
+ /** Another library copy started or ended the session: read it from AppStorage (sign in) or clear it here (sign out). */
136
+ export function handleSessionEvent(event: Event): void {
137
+ const detail = (event as CustomEvent<SessionEventDetail>).detail;
138
+ const isOwnEvent = detail?.copyId === LIBRARY_COPY_ID;
139
+ if (!detail || isOwnEvent) {
140
+ return;
141
+ }
142
+ if (detail.isSignedIn) {
143
+ restoreSession();
144
+ return;
145
+ }
146
+ forgetAppliedBranches();
147
+ sessionTokenSignal.value = ConstValue.EMPTY;
148
+ authUserSignal.value = null;
149
+ }
150
+
151
+ /** Starts following the session events of the other library copies (once; called by SharedWebUiProvider). */
152
+ export function startSessionSync(): void {
153
+ const hasWindow = typeof window !== "undefined";
154
+ if (!hasWindow || isSessionSyncStarted) {
155
+ return;
156
+ }
157
+ isSessionSyncStarted = true;
158
+ window.addEventListener(SESSION_EVENT, handleSessionEvent);
159
+ }
@@ -4,7 +4,7 @@
4
4
  // setBranch(branch.id, branch.name); // after the user picks a branch (saved in AppStorage BRANCH_ID / BRANCH_NAME)
5
5
  // branchIdSignal.value // current id, "" when none (re-renders components)
6
6
  // clearBranch(); // no branch (endSession() clears it too)
7
- // <SharedWebUiProvider branch={reply}> // list for the switcher (see below)
7
+ // config.loadBranches: "/app-api/branches" // the provider calls it after sign in
8
8
 
9
9
  import { signal } from "@preact/signals-react";
10
10
  import { ConstValue } from "dff-util";
@@ -49,7 +49,7 @@ export function restoreBranch(): void {
49
49
 
50
50
  // ---- Branch list (the switcher) ----
51
51
  //
52
- // <SharedWebUiProvider config={config} branch={branchReply}>
52
+ // config.loadBranches (the provider calls it after sign in)
53
53
  // setBranches(branchReply); // the same without the provider (for example before the menu request)
54
54
  //
55
55
  // Which branch is selected when the list arrives (disabled branches are never selected):
@@ -187,7 +187,7 @@ export function setBranches(source: BranchSource | null | undefined): void {
187
187
  }
188
188
 
189
189
  /**
190
- * Used by <SharedWebUiProvider branch={...}>. Applies the value only when it changed.
190
+ * Used by the config loaders (and tests). Applies the value only when it changed.
191
191
  * undefined leaves the branches alone; null or [] hides the switcher.
192
192
  */
193
193
  export function registerBranches(source: BranchSource | null | undefined): void {
@@ -0,0 +1,107 @@
1
+ // company-service.ts
2
+ // Company / brand details from the backend (config.loadCompanyDetails, or setCompanyDetails by hand):
3
+ //
4
+ // { "appName": "YourAppName", "companyName": "YourBrandName",
5
+ // "faviconUrl": "https://www.w3.org/favicon.ico", "logoUrl": "https://www.w3.org/Icons/w3c_home.png",
6
+ // "logoDarkUrl": "https://www.w3.org/Icons/w3c_home.png" }
7
+ //
8
+ // appName header / sidebar / login label and the browser tab title (wins over config.appName)
9
+ // companyName alt text of the logo; read companyDetailsSignal to show it anywhere (a footer, the login page)
10
+ // faviconUrl <link rel="icon" href="...">
11
+ // logoUrl the logo on light themes, and on dark themes without logoDarkUrl (wins over config.logoUrl / logoDarkUrl)
12
+ // logoDarkUrl the logo on dark themes (wins over config.logoDarkUrl)
13
+ // A reply may also be { data: {...} }. A missing field keeps the config value.
14
+
15
+ import type { CompanyDetails, CompanySource, UiConfig } from "../interfaces/ui-config.ts";
16
+ import { companyDetailsSignal } from "./signals.ts";
17
+
18
+ /** The fields of CompanyDetails (only text values are kept). */
19
+ const COMPANY_FIELDS: Array<keyof CompanyDetails> = ["appName", "companyName", "faviconUrl", "logoUrl", "logoDarkUrl"];
20
+
21
+ /** true for a plain object (not null, not a list). */
22
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
23
+ const isObject = typeof value === "object" && value !== null;
24
+ return isObject && !Array.isArray(value);
25
+ }
26
+
27
+ /** The details inside a reply: the object itself, or its "data" object. */
28
+ function unwrapCompanyReply(reply: unknown): Record<string, unknown> | null {
29
+ if (!isPlainObject(reply)) {
30
+ return null;
31
+ }
32
+ const data = reply.data;
33
+ return isPlainObject(data) ? data : reply;
34
+ }
35
+
36
+ /** Reads the company details from a reply ({...} or { data: {...} }); empty or unknown values are left out. */
37
+ export function readCompanyDetails(reply: unknown): CompanyDetails | null {
38
+ const source = unwrapCompanyReply(reply);
39
+ if (!source) {
40
+ return null;
41
+ }
42
+ const details: CompanyDetails = {};
43
+ for (const field of COMPANY_FIELDS) {
44
+ const value = source[field];
45
+ const isText = typeof value === "string" && value !== "";
46
+ if (isText) {
47
+ details[field] = value;
48
+ }
49
+ }
50
+ return details;
51
+ }
52
+
53
+ /** Points <link rel="icon"> at the favicon URL (created when the page has none). */
54
+ function writeFavicon(faviconUrl: string): void {
55
+ let iconElement = document.querySelector<HTMLLinkElement>('link[rel~="icon"]');
56
+ if (!iconElement) {
57
+ iconElement = document.createElement("link");
58
+ iconElement.rel = "icon";
59
+ document.head.append(iconElement);
60
+ }
61
+ iconElement.href = faviconUrl;
62
+ }
63
+
64
+ /** Writes the favicon and the tab title of the company details (fields that are missing are left alone). */
65
+ function applyCompanyToDocument(details: CompanyDetails | null): void {
66
+ const hasDocument = typeof document !== "undefined";
67
+ if (!hasDocument || !details) {
68
+ return;
69
+ }
70
+ if (details.faviconUrl) {
71
+ writeFavicon(details.faviconUrl);
72
+ }
73
+ if (details.appName) {
74
+ document.title = details.appName;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Sets the company details (the backend reply as it is: {...} or { data: {...} }); null = none (config values).
80
+ * The brand (logo, app name) updates at once; faviconUrl and appName also go to the browser tab.
81
+ */
82
+ export function setCompanyDetails(reply: CompanySource | unknown): void {
83
+ const details = readCompanyDetails(reply);
84
+ companyDetailsSignal.value = details;
85
+ applyCompanyToDocument(details);
86
+ }
87
+
88
+ /** true while config.loadCompanyDetails has not answered yet (no reply, and no config.appName to show meanwhile). */
89
+ export function isCompanyPending(config: UiConfig, details: CompanyDetails | null): boolean {
90
+ const hasCompanySource = Boolean(config.loadCompanyDetails);
91
+ return hasCompanySource && !details && !config.appName;
92
+ }
93
+
94
+ /**
95
+ * The app label: company appName, else config.appName, else config.appNameKey (shown with t()).
96
+ * "" while the company details are still loading (so the app key does not flash before the real name).
97
+ */
98
+ export function readAppNameLabel(config: UiConfig, details: CompanyDetails | null): string {
99
+ if (details?.appName) {
100
+ return details.appName;
101
+ }
102
+ const isPending = isCompanyPending(config, details);
103
+ if (isPending) {
104
+ return "";
105
+ }
106
+ return config.appName ?? config.appNameKey;
107
+ }