@olenbetong/synergi-react 2.6.0 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es/components/AppMenu/AppMenu.css +648 -546
- package/es/components/AppMenu/AppMenu.d.ts +17 -8
- package/es/components/AppMenu/AppMenu.js +44 -123
- package/es/components/AppMenu/AppMenuColorScheme.js +1 -1
- package/es/components/AppMenu/AppMenuFavoriteButton.d.ts +18 -0
- package/es/components/AppMenu/AppMenuFavoriteButton.js +11 -0
- package/es/components/AppMenu/AppMenuHeader.d.ts +24 -0
- package/es/components/AppMenu/AppMenuHeader.js +18 -0
- package/es/components/AppMenu/AppMenuList.d.ts +18 -0
- package/es/components/AppMenu/AppMenuList.js +39 -0
- package/es/components/AppMenu/AppMenuRail.d.ts +26 -0
- package/es/components/AppMenu/AppMenuRail.js +30 -0
- package/es/components/AppMenu/icons.d.ts +15 -0
- package/es/components/AppMenu/icons.js +13 -0
- package/es/components/AppMenu/index.d.ts +6 -1
- package/es/components/AppMenu/index.js +4 -0
- package/es/components/AppMenu/menuEntries.d.ts +51 -0
- package/es/components/AppMenu/menuEntries.js +93 -0
- package/es/components/AppMenu/types.d.ts +10 -0
- package/es/components/AppMenu/useFavorites.d.ts +13 -0
- package/es/components/AppMenu/useFavorites.js +28 -0
- package/es/components/AppMenu/useRovingTabIndex.d.ts +4 -0
- package/es/components/AppMenu/useRovingTabIndex.js +12 -1
- package/es/components/AppShell/index.js +23 -2
- package/package.json +3 -3
- package/src/colorScheme.ts +81 -81
- package/src/components/AppMenu/AppMenu.css +648 -546
- package/src/components/AppMenu/AppMenu.tsx +285 -478
- package/src/components/AppMenu/AppMenuColorScheme.tsx +1 -0
- package/src/components/AppMenu/AppMenuFavoriteButton.tsx +47 -0
- package/src/components/AppMenu/AppMenuHeader.tsx +79 -0
- package/src/components/AppMenu/AppMenuList.tsx +89 -0
- package/src/components/AppMenu/AppMenuRail.tsx +117 -0
- package/src/components/AppMenu/icons.tsx +76 -0
- package/src/components/AppMenu/index.ts +17 -12
- package/src/components/AppMenu/menuEntries.ts +128 -0
- package/src/components/AppMenu/types.ts +45 -35
- package/src/components/AppMenu/useFavorites.ts +40 -0
- package/src/components/AppMenu/useRovingTabIndex.ts +130 -118
- package/src/components/AppShell/index.tsx +287 -259
- package/src/components/LinkedCardList/index.scss +93 -93
- package/src/components/ProgressBar/index.scss +94 -94
- package/src/index.ts +61 -61
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { getLocalizedString } from "@olenbetong/appframe-core";
|
|
2
|
+
/** Sentinel group key for apps that have no MenuGroup set. */
|
|
3
|
+
export const UNGROUPED = "\u0000ungrouped";
|
|
4
|
+
/** Sentinel group key for the virtual group holding the user's favorites. */
|
|
5
|
+
export const FAVORITES = "\u0000favorites";
|
|
6
|
+
/** Strip version suffixes (`my-app.0000012`) from an ArticleId. */
|
|
7
|
+
export function stripVersionSuffix(articleId) {
|
|
8
|
+
return articleId.replace(/\.\d+$/, "");
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Normalize the raw article rows into a deduplicated, sorted list of apps.
|
|
12
|
+
*
|
|
13
|
+
* `aviw_WebShared_Articles` contains one row per published article version, so
|
|
14
|
+
* the same app can appear dozens of times. Deduplicating on the version-less
|
|
15
|
+
* ArticleId guarantees a single entry per app even if the data object's where
|
|
16
|
+
* clause is relaxed.
|
|
17
|
+
*/
|
|
18
|
+
export function toAppEntries(articles) {
|
|
19
|
+
let byId = new Map();
|
|
20
|
+
for (let article of articles) {
|
|
21
|
+
let id = stripVersionSuffix(article.ArticleId);
|
|
22
|
+
if (byId.has(id))
|
|
23
|
+
continue;
|
|
24
|
+
byId.set(id, {
|
|
25
|
+
id,
|
|
26
|
+
title: article.Title?.trim() || id,
|
|
27
|
+
group: article.MenuGroup?.trim() || UNGROUPED,
|
|
28
|
+
href: `/${article.Path?.trim() || id}`,
|
|
29
|
+
isFavorite: article.IsFavorite === true,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return [...byId.values()].sort((a, b) => a.title.localeCompare(b.title));
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Group entries by group key. The favorites are a virtual group listed first,
|
|
36
|
+
* and ungrouped apps are always listed last.
|
|
37
|
+
*/
|
|
38
|
+
export function groupEntries(entries) {
|
|
39
|
+
let map = new Map();
|
|
40
|
+
for (let entry of entries) {
|
|
41
|
+
let list = map.get(entry.group);
|
|
42
|
+
if (!list) {
|
|
43
|
+
list = [];
|
|
44
|
+
map.set(entry.group, list);
|
|
45
|
+
}
|
|
46
|
+
list.push(entry);
|
|
47
|
+
}
|
|
48
|
+
let groups = [...map.entries()].sort(([a], [b]) => {
|
|
49
|
+
if (a === b)
|
|
50
|
+
return 0;
|
|
51
|
+
if (a === UNGROUPED)
|
|
52
|
+
return 1;
|
|
53
|
+
if (b === UNGROUPED)
|
|
54
|
+
return -1;
|
|
55
|
+
return a.localeCompare(b);
|
|
56
|
+
});
|
|
57
|
+
let favorites = entries.filter((entry) => entry.isFavorite);
|
|
58
|
+
return favorites.length > 0 ? [[FAVORITES, favorites], ...groups] : groups;
|
|
59
|
+
}
|
|
60
|
+
/** Human readable title for a group key, resolving the sentinel keys. */
|
|
61
|
+
export function groupLabel(group) {
|
|
62
|
+
if (group === UNGROUPED)
|
|
63
|
+
return getLocalizedString("Other");
|
|
64
|
+
if (group === FAVORITES)
|
|
65
|
+
return getLocalizedString("Favorites");
|
|
66
|
+
return group;
|
|
67
|
+
}
|
|
68
|
+
/** Drop entries that don't match the search term, then empty groups. */
|
|
69
|
+
export function filterCategory(category, term) {
|
|
70
|
+
if (!term)
|
|
71
|
+
return category;
|
|
72
|
+
let groups = category.groups
|
|
73
|
+
.map((group) => ({ ...group, items: group.items.filter((item) => item.label.toLowerCase().includes(term)) }))
|
|
74
|
+
.filter((group) => group.items.length > 0);
|
|
75
|
+
return { ...category, groups };
|
|
76
|
+
}
|
|
77
|
+
export function countItems(category) {
|
|
78
|
+
return category.groups.reduce((total, group) => total + group.items.length, 0);
|
|
79
|
+
}
|
|
80
|
+
/** Split the categories into their rail sections, preserving the given order. */
|
|
81
|
+
export function toRailSections(categories) {
|
|
82
|
+
let sections = new Map();
|
|
83
|
+
for (let category of categories) {
|
|
84
|
+
let key = category.section ?? "";
|
|
85
|
+
let list = sections.get(key);
|
|
86
|
+
if (!list) {
|
|
87
|
+
list = [];
|
|
88
|
+
sections.set(key, list);
|
|
89
|
+
}
|
|
90
|
+
list.push(category);
|
|
91
|
+
}
|
|
92
|
+
return [...sections.entries()];
|
|
93
|
+
}
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
/** A single entry in the app menu's right hand pane or in the user menu. */
|
|
2
2
|
export type AppMenuLink = {
|
|
3
3
|
label: string;
|
|
4
|
+
/**
|
|
5
|
+
* Stable identifier for the entry. Set for app entries (the version-less
|
|
6
|
+
* ArticleId), and used as the key when toggling the favorite state.
|
|
7
|
+
*/
|
|
8
|
+
id?: string;
|
|
9
|
+
/**
|
|
10
|
+
* Current favorite state. A favorite toggle is only rendered for entries
|
|
11
|
+
* where this is a boolean and the menu got an `onToggleFavorite` handler.
|
|
12
|
+
*/
|
|
13
|
+
isFavorite?: boolean;
|
|
4
14
|
/** Renders an anchor. Without an href the entry is rendered as a button. */
|
|
5
15
|
href?: string;
|
|
6
16
|
target?: string;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AppEntry } from "./menuEntries.js";
|
|
2
|
+
/**
|
|
3
|
+
* Tracks the favorite state the user has changed while the menu is open.
|
|
4
|
+
*
|
|
5
|
+
* The changes are applied optimistically on top of the article rows and rolled
|
|
6
|
+
* back if the handler rejects. The overrides are kept for the lifetime of the
|
|
7
|
+
* menu, since the article list is only loaded the first time it is opened and
|
|
8
|
+
* would otherwise show a stale state the second time around.
|
|
9
|
+
*/
|
|
10
|
+
export declare function useFavorites(onToggleFavorite?: (id: string, favorite: boolean) => void | Promise<unknown>): {
|
|
11
|
+
applyOverrides: (entries: AppEntry[]) => AppEntry[];
|
|
12
|
+
toggleFavorite: ((id: string, favorite: boolean) => Promise<void>) | undefined;
|
|
13
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { useCallback, useState } from "react";
|
|
2
|
+
/**
|
|
3
|
+
* Tracks the favorite state the user has changed while the menu is open.
|
|
4
|
+
*
|
|
5
|
+
* The changes are applied optimistically on top of the article rows and rolled
|
|
6
|
+
* back if the handler rejects. The overrides are kept for the lifetime of the
|
|
7
|
+
* menu, since the article list is only loaded the first time it is opened and
|
|
8
|
+
* would otherwise show a stale state the second time around.
|
|
9
|
+
*/
|
|
10
|
+
export function useFavorites(onToggleFavorite) {
|
|
11
|
+
let [overrides, setOverrides] = useState({});
|
|
12
|
+
let applyOverrides = useCallback((entries) => {
|
|
13
|
+
if (Object.keys(overrides).length === 0)
|
|
14
|
+
return entries;
|
|
15
|
+
return entries.map((entry) => (entry.id in overrides ? { ...entry, isFavorite: overrides[entry.id] } : entry));
|
|
16
|
+
}, [overrides]);
|
|
17
|
+
let toggleFavorite = useCallback(async (id, favorite) => {
|
|
18
|
+
setOverrides((current) => ({ ...current, [id]: favorite }));
|
|
19
|
+
try {
|
|
20
|
+
await onToggleFavorite?.(id, favorite);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.error(error);
|
|
24
|
+
setOverrides((current) => ({ ...current, [id]: !favorite }));
|
|
25
|
+
}
|
|
26
|
+
}, [onToggleFavorite]);
|
|
27
|
+
return { applyOverrides, toggleFavorite: onToggleFavorite ? toggleFavorite : undefined };
|
|
28
|
+
}
|
|
@@ -99,5 +99,16 @@ export function useRovingTabIndex(itemCount, { columns = false } = {}) {
|
|
|
99
99
|
onFocus: () => setActiveIndex(index),
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Props for a secondary control belonging to item `index`, e.g. the favorite
|
|
104
|
+
* toggle next to an app link. It shares the item's tab stop — so Tab reaches
|
|
105
|
+
* it from the link — but the arrow keys skip it.
|
|
106
|
+
*/
|
|
107
|
+
function getSecondaryProps(index) {
|
|
108
|
+
return {
|
|
109
|
+
tabIndex: index === activeIndex ? 0 : -1,
|
|
110
|
+
onFocus: () => setActiveIndex(index),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
return { onKeyDown, getItemProps, getSecondaryProps };
|
|
103
114
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { StyledEngineProvider, ThemeProvider } from "@mui/material";
|
|
3
3
|
import { createTheme as muiCreateTheme } from "@mui/material/styles";
|
|
4
|
+
import { getLocalizedString } from "@olenbetong/appframe-core";
|
|
4
5
|
import { AppErrorBoundary } from "@olenbetong/appframe-mui";
|
|
5
|
-
import { useEffect, useMemo, useState } from "react";
|
|
6
|
+
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
6
7
|
import { createPortal } from "react-dom";
|
|
7
8
|
import { AppMenu } from "../AppMenu/AppMenu.js";
|
|
8
9
|
import { AppMenuToggle } from "../AppMenu/AppMenuToggle.js";
|
|
@@ -39,6 +40,7 @@ const dsMenuArticles = af.data.generateApiDataObject({
|
|
|
39
40
|
{ name: "Title", type: "string", nullable: true },
|
|
40
41
|
{ name: "MenuGroup", type: "string", nullable: true },
|
|
41
42
|
{ name: "Path", type: "string", nullable: true },
|
|
43
|
+
{ name: "IsFavorite", type: "boolean", nullable: true },
|
|
42
44
|
],
|
|
43
45
|
parameters: {
|
|
44
46
|
maxRecords: -1,
|
|
@@ -46,6 +48,16 @@ const dsMenuArticles = af.data.generateApiDataObject({
|
|
|
46
48
|
sortOrder: [{ MenuGroup: af.data.SortOrder.Asc }, { Title: af.data.SortOrder.Asc }],
|
|
47
49
|
},
|
|
48
50
|
});
|
|
51
|
+
// Toggles the current user's favorite state for an article.
|
|
52
|
+
const procSetArticleFavorite = new af.ProcedureAPI({
|
|
53
|
+
procedureId: "astp_WebShared_SetArticleFavorite",
|
|
54
|
+
parameters: [
|
|
55
|
+
{ name: "HostName", type: "string", required: true, hasDefault: false },
|
|
56
|
+
{ name: "ArticleID", type: "string", required: true, hasDefault: false },
|
|
57
|
+
{ name: "Favorite", type: "boolean", required: false, hasDefault: true },
|
|
58
|
+
],
|
|
59
|
+
timeout: 30000,
|
|
60
|
+
});
|
|
49
61
|
// The current user's employee record, used for the photo and full name.
|
|
50
62
|
const dsAppMenuUser = af.data.generateApiDataObject({
|
|
51
63
|
resource: "aviw_Personnel_Employees_Lookup",
|
|
@@ -192,6 +204,15 @@ export function AppShell({ children }) {
|
|
|
192
204
|
// The developer tools are only reachable for developers, so hide them for
|
|
193
205
|
// everyone else instead of showing links that all return 403.
|
|
194
206
|
const categories = useMemo(() => (globalThis.af?.userSession?.isDeveloper ? createDeveloperCategories() : []), []);
|
|
207
|
+
// The portal isn't listed with the apps, so link to it from the menu itself
|
|
208
|
+
// unless that's the article we're already on.
|
|
209
|
+
const homeLink = useMemo(() => {
|
|
210
|
+
const articleId = (globalThis.af?.article?.id ?? "").replace(/\.\d+$/, "");
|
|
211
|
+
return articleId === "portal" ? undefined : { label: getLocalizedString("Front page"), href: "/portal" };
|
|
212
|
+
}, []);
|
|
213
|
+
const toggleFavorite = useCallback(async (articleId, favorite) => {
|
|
214
|
+
await procSetArticleFavorite.execute({ HostName: hostName, ArticleID: articleId, Favorite: favorite });
|
|
215
|
+
}, []);
|
|
195
216
|
// Rebuilt whenever the color scheme changes so MUI components (notably the
|
|
196
217
|
// data grid) follow Designsystemet instead of staying stuck in light mode.
|
|
197
218
|
// Also re-read after mount, since the stylesheets are imported from JS and
|
|
@@ -202,5 +223,5 @@ export function AppShell({ children }) {
|
|
|
202
223
|
}, [colorScheme]);
|
|
203
224
|
const appMenuSlot = document.getElementById("ob-toolbar-app-menu");
|
|
204
225
|
return (_jsx(StyledEngineProvider, { injectFirst: true, children: _jsx(ThemeProvider, { theme: theme, children: _jsxs(AppErrorBoundary, { children: [appMenuSlot &&
|
|
205
|
-
createPortal(_jsx(AppMenuToggle, { open: isAppMenuOpen, hasUpdate: isUpdateAvailable, "aria-controls": "ob-app-menu", onClick: () => setIsAppMenuOpen((open) => !open) }), appMenuSlot), _jsx(AppMenu, { id: "ob-app-menu", dataObject: dsMenuArticles, userDataObject: dsAppMenuUser, categories: categories, hasUpdate: isUpdateAvailable, onInstallUpdate: installUpdate, open: isAppMenuOpen, onClose: () => setIsAppMenuOpen(false) }), children] }) }) }));
|
|
226
|
+
createPortal(_jsx(AppMenuToggle, { open: isAppMenuOpen, hasUpdate: isUpdateAvailable, "aria-controls": "ob-app-menu", onClick: () => setIsAppMenuOpen((open) => !open) }), appMenuSlot), _jsx(AppMenu, { id: "ob-app-menu", dataObject: dsMenuArticles, userDataObject: dsAppMenuUser, categories: categories, homeLink: homeLink, onToggleFavorite: toggleFavorite, hasUpdate: isUpdateAvailable, onInstallUpdate: installUpdate, open: isAppMenuOpen, onClose: () => setIsAppMenuOpen(false) }), children] }) }) }));
|
|
206
227
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@olenbetong/synergi-react",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.1",
|
|
4
4
|
"description": "Standalone React component for SynergiWeb and Partner Portal",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -44,10 +44,10 @@
|
|
|
44
44
|
"pdf-lib": "^1.17.1",
|
|
45
45
|
"pdfjs-dist": "5.7.284",
|
|
46
46
|
"react-pdf": "^10.4.1",
|
|
47
|
+
"@olenbetong/appframe-react": "2.0.0",
|
|
47
48
|
"@olenbetong/appframe-core": "2.11.10",
|
|
48
49
|
"@olenbetong/appframe-mui": "6.6.0",
|
|
49
|
-
"@olenbetong/appframe-data": "1.5.0"
|
|
50
|
-
"@olenbetong/appframe-react": "2.0.0"
|
|
50
|
+
"@olenbetong/appframe-data": "1.5.0"
|
|
51
51
|
},
|
|
52
52
|
"repository": {
|
|
53
53
|
"type": "git",
|
package/src/colorScheme.ts
CHANGED
|
@@ -1,81 +1,81 @@
|
|
|
1
|
-
import { useCallback, useEffect, useState } from "react";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Color scheme preference (system / light / dark).
|
|
5
|
-
*
|
|
6
|
-
* The preference lives in the `ob-color-scheme` cookie so the article template
|
|
7
|
-
* can read it server side and render `data-color-scheme` on `<html>` and
|
|
8
|
-
* `<body>` before the first paint. The site script for the 2026 template
|
|
9
|
-
* (`ob.2026.application.min.js`) owns the same cookie for the toolbar user menu
|
|
10
|
-
* toggle, so both write the cookie, apply the attributes, and dispatch
|
|
11
|
-
* `COLOR_SCHEME_CHANGE_EVENT` to keep every toggle on the page in sync.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
export type ColorSchemePreference = "auto" | "light" | "dark";
|
|
15
|
-
|
|
16
|
-
const COOKIE_NAME = "ob-color-scheme";
|
|
17
|
-
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
|
18
|
-
const DEFAULT_PREFERENCE: ColorSchemePreference = "auto";
|
|
19
|
-
const PREFERENCES: ColorSchemePreference[] = ["auto", "light", "dark"];
|
|
20
|
-
|
|
21
|
-
/** Dispatched on `window` whenever the preference changes. */
|
|
22
|
-
export const COLOR_SCHEME_CHANGE_EVENT = "ob:colorschemechange";
|
|
23
|
-
|
|
24
|
-
function isColorSchemePreference(value: unknown): value is ColorSchemePreference {
|
|
25
|
-
return typeof value === "string" && PREFERENCES.includes(value as ColorSchemePreference);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function getColorSchemePreference(): ColorSchemePreference {
|
|
29
|
-
if (typeof document === "undefined") return DEFAULT_PREFERENCE;
|
|
30
|
-
|
|
31
|
-
let match = document.cookie.match(new RegExp(`(?:^|;\\s*)${COOKIE_NAME}=([^;]*)`));
|
|
32
|
-
let value = match ? decodeURIComponent(match[1]) : null;
|
|
33
|
-
|
|
34
|
-
return isColorSchemePreference(value) ? value : DEFAULT_PREFERENCE;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function setColorSchemePreference(preference: ColorSchemePreference) {
|
|
38
|
-
if (typeof document === "undefined" || !isColorSchemePreference(preference)) return;
|
|
39
|
-
|
|
40
|
-
let secure = window.location.protocol === "https:" ? ";secure" : "";
|
|
41
|
-
document.cookie = `${COOKIE_NAME}=${preference};path=/;max-age=${COOKIE_MAX_AGE};samesite=lax${secure}`;
|
|
42
|
-
|
|
43
|
-
/*
|
|
44
|
-
* Both elements are updated: `<html>` so the browser applies `color-scheme`
|
|
45
|
-
* to scrollbars and native controls, `<body>` because Designsystemet declares
|
|
46
|
-
* the light tokens on `:root` as well (`:root, [data-color-scheme="light"]`).
|
|
47
|
-
*/
|
|
48
|
-
document.documentElement.dataset.colorScheme = preference;
|
|
49
|
-
if (document.body) document.body.dataset.colorScheme = preference;
|
|
50
|
-
|
|
51
|
-
window.dispatchEvent(new CustomEvent(COLOR_SCHEME_CHANGE_EVENT, { detail: preference }));
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Reads the stored preference and keeps it in sync with other toggles on the page. */
|
|
55
|
-
export function useColorSchemePreference(): [ColorSchemePreference, (value: ColorSchemePreference) => void] {
|
|
56
|
-
let [preference, setPreference] = useState<ColorSchemePreference>(() => getColorSchemePreference());
|
|
57
|
-
|
|
58
|
-
useEffect(() => {
|
|
59
|
-
function update() {
|
|
60
|
-
setPreference(getColorSchemePreference());
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
update();
|
|
64
|
-
|
|
65
|
-
window.addEventListener(COLOR_SCHEME_CHANGE_EVENT, update);
|
|
66
|
-
// Cookies fire no change event, so also pick up changes made in another tab.
|
|
67
|
-
document.addEventListener("visibilitychange", update);
|
|
68
|
-
|
|
69
|
-
return () => {
|
|
70
|
-
window.removeEventListener(COLOR_SCHEME_CHANGE_EVENT, update);
|
|
71
|
-
document.removeEventListener("visibilitychange", update);
|
|
72
|
-
};
|
|
73
|
-
}, []);
|
|
74
|
-
|
|
75
|
-
let setValue = useCallback((value: ColorSchemePreference) => {
|
|
76
|
-
setColorSchemePreference(value);
|
|
77
|
-
setPreference(value);
|
|
78
|
-
}, []);
|
|
79
|
-
|
|
80
|
-
return [preference, setValue];
|
|
81
|
-
}
|
|
1
|
+
import { useCallback, useEffect, useState } from "react";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Color scheme preference (system / light / dark).
|
|
5
|
+
*
|
|
6
|
+
* The preference lives in the `ob-color-scheme` cookie so the article template
|
|
7
|
+
* can read it server side and render `data-color-scheme` on `<html>` and
|
|
8
|
+
* `<body>` before the first paint. The site script for the 2026 template
|
|
9
|
+
* (`ob.2026.application.min.js`) owns the same cookie for the toolbar user menu
|
|
10
|
+
* toggle, so both write the cookie, apply the attributes, and dispatch
|
|
11
|
+
* `COLOR_SCHEME_CHANGE_EVENT` to keep every toggle on the page in sync.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type ColorSchemePreference = "auto" | "light" | "dark";
|
|
15
|
+
|
|
16
|
+
const COOKIE_NAME = "ob-color-scheme";
|
|
17
|
+
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
|
18
|
+
const DEFAULT_PREFERENCE: ColorSchemePreference = "auto";
|
|
19
|
+
const PREFERENCES: ColorSchemePreference[] = ["auto", "light", "dark"];
|
|
20
|
+
|
|
21
|
+
/** Dispatched on `window` whenever the preference changes. */
|
|
22
|
+
export const COLOR_SCHEME_CHANGE_EVENT = "ob:colorschemechange";
|
|
23
|
+
|
|
24
|
+
function isColorSchemePreference(value: unknown): value is ColorSchemePreference {
|
|
25
|
+
return typeof value === "string" && PREFERENCES.includes(value as ColorSchemePreference);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function getColorSchemePreference(): ColorSchemePreference {
|
|
29
|
+
if (typeof document === "undefined") return DEFAULT_PREFERENCE;
|
|
30
|
+
|
|
31
|
+
let match = document.cookie.match(new RegExp(`(?:^|;\\s*)${COOKIE_NAME}=([^;]*)`));
|
|
32
|
+
let value = match ? decodeURIComponent(match[1]) : null;
|
|
33
|
+
|
|
34
|
+
return isColorSchemePreference(value) ? value : DEFAULT_PREFERENCE;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function setColorSchemePreference(preference: ColorSchemePreference) {
|
|
38
|
+
if (typeof document === "undefined" || !isColorSchemePreference(preference)) return;
|
|
39
|
+
|
|
40
|
+
let secure = window.location.protocol === "https:" ? ";secure" : "";
|
|
41
|
+
document.cookie = `${COOKIE_NAME}=${preference};path=/;max-age=${COOKIE_MAX_AGE};samesite=lax${secure}`;
|
|
42
|
+
|
|
43
|
+
/*
|
|
44
|
+
* Both elements are updated: `<html>` so the browser applies `color-scheme`
|
|
45
|
+
* to scrollbars and native controls, `<body>` because Designsystemet declares
|
|
46
|
+
* the light tokens on `:root` as well (`:root, [data-color-scheme="light"]`).
|
|
47
|
+
*/
|
|
48
|
+
document.documentElement.dataset.colorScheme = preference;
|
|
49
|
+
if (document.body) document.body.dataset.colorScheme = preference;
|
|
50
|
+
|
|
51
|
+
window.dispatchEvent(new CustomEvent(COLOR_SCHEME_CHANGE_EVENT, { detail: preference }));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Reads the stored preference and keeps it in sync with other toggles on the page. */
|
|
55
|
+
export function useColorSchemePreference(): [ColorSchemePreference, (value: ColorSchemePreference) => void] {
|
|
56
|
+
let [preference, setPreference] = useState<ColorSchemePreference>(() => getColorSchemePreference());
|
|
57
|
+
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
function update() {
|
|
60
|
+
setPreference(getColorSchemePreference());
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
update();
|
|
64
|
+
|
|
65
|
+
window.addEventListener(COLOR_SCHEME_CHANGE_EVENT, update);
|
|
66
|
+
// Cookies fire no change event, so also pick up changes made in another tab.
|
|
67
|
+
document.addEventListener("visibilitychange", update);
|
|
68
|
+
|
|
69
|
+
return () => {
|
|
70
|
+
window.removeEventListener(COLOR_SCHEME_CHANGE_EVENT, update);
|
|
71
|
+
document.removeEventListener("visibilitychange", update);
|
|
72
|
+
};
|
|
73
|
+
}, []);
|
|
74
|
+
|
|
75
|
+
let setValue = useCallback((value: ColorSchemePreference) => {
|
|
76
|
+
setColorSchemePreference(value);
|
|
77
|
+
setPreference(value);
|
|
78
|
+
}, []);
|
|
79
|
+
|
|
80
|
+
return [preference, setValue];
|
|
81
|
+
}
|