@olenbetong/synergi-react 4.2.5 → 4.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/es/components/Toolbar/Toolbar.css +34 -21
  2. package/es/components/Toolbar/index.js +50 -18
  3. package/package.json +6 -6
  4. package/src/chrome/AppShell/index.tsx +29 -29
  5. package/src/chrome/openReport.ts +34 -34
  6. package/src/colorScheme.ts +81 -81
  7. package/src/components/DateNavigator/index.tsx +186 -186
  8. package/src/components/FilePond.tsx +312 -312
  9. package/src/components/ImageEditor/ImageEditor.tsx +348 -348
  10. package/src/components/ImageEditor/index.ts +9 -9
  11. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +165 -165
  12. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +48 -48
  13. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +405 -405
  14. package/src/components/ImageEditor/plugins/redactPlugin/RedactToolbar.tsx +47 -47
  15. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomContext.tsx +23 -23
  16. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomControls.tsx +40 -40
  17. package/src/components/ImageEditor/useActiveTool.ts +21 -21
  18. package/src/components/ImageEditor/useEdgeDetection.ts +319 -319
  19. package/src/components/ImageEditor/useImageHistory.ts +197 -197
  20. package/src/components/ImageEditor/useOpenCV.ts +184 -184
  21. package/src/components/LinkedCardList/index.scss +95 -95
  22. package/src/components/MergeProgressDialog/index.tsx +249 -249
  23. package/src/components/PageBanner/index.tsx +80 -80
  24. package/src/components/PdfViewer/PdfViewer.tsx +158 -158
  25. package/src/components/ProgressBar/index.scss +96 -96
  26. package/src/components/SplitContainer/index.tsx +333 -333
  27. package/src/components/Toolbar/Toolbar.css +34 -21
  28. package/src/components/Toolbar/index.tsx +265 -232
  29. package/src/designsystemet-web-types.d.ts +24 -24
  30. package/src/elements/ElementDamage/DamageFormButtons.tsx +35 -35
  31. package/src/elements/ElementDamage/DescriptionInput.tsx +120 -120
  32. package/src/elements/ElementDamage/DuplicateDamage/DesktopView.tsx +82 -82
  33. package/src/elements/ElementDamage/DuplicateDamage/DublicateElementDamageDialog.tsx +67 -67
  34. package/src/elements/ElementDamage/DuplicateDamage/PhoneView.tsx +45 -45
  35. package/src/elements/ElementDamage/ElementNumberTextField.tsx +41 -41
  36. package/src/elements/ElementDamage/RegisterFix.tsx +100 -100
  37. package/src/elements/ElementDamage/SubmitButtons.tsx +40 -40
  38. package/src/elements/ElementDamage/TransportElementSelect.tsx +52 -52
  39. package/src/elements/ElementLookup.tsx +123 -123
  40. package/src/elements/ElementLookupDialog/BarcodeScanner/decoder.ts +32 -32
  41. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders/dbr.ts +118 -118
  42. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders/native.ts +103 -103
  43. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.ts +95 -95
  44. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders.test.ts +118 -118
  45. package/src/elements/ElementLookupDialog/BarcodeScanner/duplicateFilter.ts +21 -21
  46. package/src/elements/ElementLookupDialog/BarcodeScanner/index.tsx +90 -90
  47. package/src/elements/ElementLookupDialog/BarcodeScanner/useScanner.ts +280 -280
  48. package/src/elements/ElementLookupDialog/HIDScanner/index.tsx +67 -67
  49. package/src/elements/ElementLookupDialog/Manual/ManualForm.tsx +141 -141
  50. package/src/elements/ElementLookupDialog/index.tsx +226 -226
  51. package/src/elements/ElementLookupDialog/utils/Giai.ts +209 -209
  52. package/src/elements/ProjectSelect.tsx +130 -130
  53. package/src/elements/index.ts +15 -15
  54. package/src/filter/index.ts +34 -34
  55. package/src/i18n.ts +13 -13
  56. package/src/index.ts +77 -77
  57. package/src/mui/MuiThemeProvider.tsx +174 -174
  58. package/src/mui/index.ts +1 -1
  59. package/src/test/setup.ts +8 -8
@@ -19,6 +19,7 @@
19
19
 
20
20
  .ob-breadcrumbs__item {
21
21
  display: flex;
22
+ flex: 0 0 auto;
22
23
  align-items: center;
23
24
  font-size: var(--ds-font-size-100, 0.875rem);
24
25
  white-space: nowrap;
@@ -54,8 +55,6 @@
54
55
  }
55
56
 
56
57
  .ob-breadcrumbs__overflow {
57
- position: relative;
58
-
59
58
  button {
60
59
  background: none;
61
60
  border: 1px solid transparent;
@@ -86,39 +85,53 @@
86
85
  }
87
86
  }
88
87
 
88
+ /*
89
+ * The crumbs there is no room for, behind the "…" button. A popover, so it sits in the top
90
+ * layer where the toolbar cannot clip it; placed under the button by the component. The
91
+ * toolbar's contrast colour is inherited through the DOM even there, so the menu sets its own.
92
+ */
89
93
  .ob-breadcrumbs__overflow-menu {
90
- background: var(--ds-surface-overlay, #fff);
91
- border: 1px solid var(--ds-border-default, currentColor);
92
- border-radius: var(--ds-border-radius-100, 4px);
93
- box-shadow: var(--ds-shadow-overlay, 0 4px 8px rgba(0, 0, 0, 0.16));
94
- left: 0;
95
- list-style: none;
96
- margin: var(--ds-space-050, 0.25rem) 0 0;
94
+ position: fixed;
95
+ inset: auto;
96
+ box-sizing: border-box;
97
97
  min-width: 10rem;
98
- padding: var(--ds-space-100, 0.25rem) 0;
99
- position: absolute;
100
- top: 100%;
101
- z-index: var(--ds-z-index-modal, 400);
98
+ max-width: calc(100vw - 1rem);
99
+ margin: 0;
100
+ padding: var(--ds-size-1, 0.25rem) 0;
101
+ list-style: none;
102
+ border: 1px solid var(--ds-color-neutral-border-subtle, #cbd0d6);
103
+ border-radius: var(--ds-border-radius-md, 4px);
104
+ background: var(--ds-color-neutral-background-default, #fff);
105
+ color: var(--ds-color-neutral-text-default, #1e2b3c);
106
+ box-shadow: var(--ds-shadow-md, 0 4px 8px rgb(0 0 0 / 16%));
107
+ font-size: var(--ds-body-sm-font-size, 0.875rem);
102
108
 
103
109
  li {
104
110
  a,
105
111
  span {
106
- color: var(--ds-text, inherit);
107
112
  display: block;
108
- font-size: var(--ds-font-size-100, 0.875rem);
109
- padding: var(--ds-space-100, 0.25rem) var(--ds-space-200, 0.5rem);
113
+ padding: var(--ds-size-2, 0.5rem) var(--ds-size-4, 1rem);
114
+ overflow: hidden;
115
+ color: inherit;
110
116
  text-decoration: none;
117
+ text-overflow: ellipsis;
111
118
  white-space: nowrap;
119
+ }
112
120
 
113
- &:hover {
114
- background: var(--ds-background-neutral-default, rgba(0, 0, 0, 0.06));
115
- color: var(--ds-text, inherit);
116
- }
121
+ a:hover {
122
+ background: var(--ds-color-neutral-surface-hover, rgb(0 0 0 / 6%));
117
123
  }
118
124
 
119
125
  a:focus-visible {
120
- outline: 2px solid var(--ds-border-focused, currentColor);
126
+ outline: 2px solid var(--ds-color-focus-outer, currentColor);
121
127
  outline-offset: -2px;
122
128
  }
123
129
  }
130
+
131
+ /* Touch sized rows where there is no pointer to aim with. */
132
+ @media (pointer: coarse) {
133
+ li :is(a, span) {
134
+ padding-block: var(--ds-size-3, 0.75rem);
135
+ }
136
+ }
124
137
  }
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import "./Toolbar.css";
3
3
  import { MenuHamburgerIcon } from "@navikt/aksel-icons";
4
- import { useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
5
5
  import { createPortal } from "react-dom";
6
6
  import { Link } from "react-router";
7
7
  import { getLocalizedString } from "../../i18n.js";
@@ -86,19 +86,30 @@ function BreadcrumbLink({ item }) {
86
86
  }
87
87
  function BreadcrumbsInner({ items }) {
88
88
  let [firstVisible, setFirstVisible] = useState(0);
89
- let [overflowOpen, setOverflowOpen] = useState(false);
89
+ let [menuOpen, setMenuOpen] = useState(false);
90
90
  let navRef = useRef(null);
91
91
  let listRef = useRef(null);
92
- let overflowItemRef = useRef(null);
92
+ let buttonRef = useRef(null);
93
+ let menuRef = useRef(null);
94
+ let menuId = useId();
95
+ // A new trail (the user navigated) is measured from scratch. Adjusted during render, so
96
+ // the previous page's collapse never paints on the new one.
97
+ let trail = items.map((item) => item.label).join("\n");
98
+ let [measuredTrail, setMeasuredTrail] = useState(trail);
99
+ if (measuredTrail !== trail) {
100
+ setMeasuredTrail(trail);
101
+ setFirstVisible(0);
102
+ }
93
103
  // Detect overflow: increment firstVisible until the list fits within the nav.
94
104
  // Runs after every render so it keeps pushing items into overflow until the
95
105
  // list stops overflowing or only the last item (current page) remains.
96
106
  useLayoutEffect(() => {
97
- let nav = navRef.current;
98
107
  let list = listRef.current;
99
- if (!nav || !list)
108
+ if (!list)
100
109
  return;
101
- if (list.scrollWidth > nav.clientWidth && firstVisible < items.length - 1) {
110
+ // Against the list's own box, not the nav's: the nav also holds the separator the site
111
+ // stylesheet draws between the brand and the trail.
112
+ if (list.scrollWidth > list.clientWidth + 1 && firstVisible < items.length - 1) {
102
113
  setFirstVisible((prev) => prev + 1);
103
114
  }
104
115
  });
@@ -108,27 +119,48 @@ function BreadcrumbsInner({ items }) {
108
119
  let nav = navRef.current;
109
120
  if (!nav)
110
121
  return;
122
+ let width = nav.clientWidth;
111
123
  let observer = new ResizeObserver(() => {
124
+ // The first callback reports the size the trail was just measured at.
125
+ if (nav.clientWidth === width)
126
+ return;
127
+ width = nav.clientWidth;
112
128
  setFirstVisible(0);
113
129
  });
114
130
  observer.observe(nav);
115
131
  return () => observer.disconnect();
116
132
  }, []);
117
- // Close the overflow dropdown when the user clicks outside of it.
118
- useEffect(() => {
119
- if (!overflowOpen)
133
+ /*
134
+ * The menu is a popover: it renders in the top layer, so the toolbar and the trail, which
135
+ * both clip their overflow, cannot cut it off, and the browser closes it on Escape and on a
136
+ * click outside. The top layer has no positioned ancestor, so it is placed under the button
137
+ * by hand, and pulled back in when it would run past the edge of a narrow screen.
138
+ */
139
+ function placeMenu() {
140
+ let button = buttonRef.current;
141
+ let menu = menuRef.current;
142
+ if (!button || !menu)
120
143
  return;
121
- function handleClickOutside(event) {
122
- if (overflowItemRef.current && !overflowItemRef.current.contains(event.target)) {
123
- setOverflowOpen(false);
124
- }
125
- }
126
- document.addEventListener("mousedown", handleClickOutside);
127
- return () => document.removeEventListener("mousedown", handleClickOutside);
128
- }, [overflowOpen]);
144
+ let rect = button.getBoundingClientRect();
145
+ let margin = 8;
146
+ let left = Math.min(rect.left, window.innerWidth - menu.offsetWidth - margin);
147
+ menu.style.top = `${rect.bottom + 4}px`;
148
+ menu.style.left = `${Math.max(left, margin)}px`;
149
+ }
129
150
  let hiddenItems = items.slice(0, firstVisible);
130
151
  let visibleItems = items.slice(firstVisible);
131
- return (_jsx("nav", { className: "ob-breadcrumbs", "aria-label": "Breadcrumb", ref: navRef, children: _jsxs("ol", { className: "ob-breadcrumbs__list", ref: listRef, children: [firstVisible > 0 && (_jsxs("li", { className: "ob-breadcrumbs__item ob-breadcrumbs__overflow", ref: overflowItemRef, children: [_jsx("button", { type: "button", "aria-label": "Show hidden breadcrumbs", "aria-expanded": overflowOpen, "aria-haspopup": "true", onClick: () => setOverflowOpen((prev) => !prev), children: "\u2026" }), overflowOpen && (_jsx("ul", { className: "ob-breadcrumbs__overflow-menu", role: "menu", children: hiddenItems.map((item, index) => (_jsx("li", { role: "menuitem", children: _jsx(BreadcrumbLink, { item: item }) }, index))) }))] })), visibleItems.map((item, index) => {
152
+ return (_jsx("nav", { className: "ob-breadcrumbs", "aria-label": "Breadcrumb", ref: navRef, children: _jsxs("ol", { className: "ob-breadcrumbs__list", ref: listRef, children: [firstVisible > 0 && (_jsxs("li", { className: "ob-breadcrumbs__item ob-breadcrumbs__overflow", children: [_jsx("button", { ref: buttonRef, type: "button", "aria-label": getLocalizedString("Show hidden breadcrumbs"), "aria-expanded": menuOpen, popoverTarget: menuId, children: "\u2026" }), _jsx("ul", { ref: menuRef, id: menuId, popover: "auto", className: "ob-breadcrumbs__overflow-menu",
153
+ // Placed before it shows, so it never paints in the popover's default
154
+ // spot, and again once it has a width to keep it on the screen.
155
+ onBeforeToggle: (event) => {
156
+ if (event.newState === "open")
157
+ placeMenu();
158
+ }, onToggle: (event) => {
159
+ let open = event.newState === "open";
160
+ setMenuOpen(open);
161
+ if (open)
162
+ placeMenu();
163
+ }, children: hiddenItems.map((item, index) => (_jsx("li", { onClick: () => menuRef.current?.hidePopover(), children: _jsx(BreadcrumbLink, { item: item }) }, index))) })] })), visibleItems.map((item, index) => {
132
164
  let actualIndex = firstVisible + index;
133
165
  let isCurrent = actualIndex === items.length - 1;
134
166
  return (_jsx("li", { className: "ob-breadcrumbs__item", children: isCurrent ? _jsx("span", { "aria-current": "page", children: item.label }) : _jsx(BreadcrumbLink, { item: item }) }, actualIndex));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@olenbetong/synergi-react",
3
- "version": "4.2.5",
3
+ "version": "4.2.7",
4
4
  "description": "Standalone React component for SynergiWeb and Partner Portal",
5
5
  "type": "module",
6
6
  "exports": {
@@ -39,11 +39,11 @@
39
39
  "@emotion/styled": "^11.14.1",
40
40
  "@mui/icons-material": "9.4.0",
41
41
  "@mui/material": "9.4.0",
42
- "@olenbetong/appframe-core": "2.15.1",
43
- "@olenbetong/appframe-data": "1.8.1",
44
- "@olenbetong/appframe-ds": "1.3.6",
45
- "@olenbetong/appframe-mui": "7.0.8",
46
- "@olenbetong/appframe-react": "2.2.6",
42
+ "@olenbetong/appframe-core": "^2.15.2",
43
+ "@olenbetong/appframe-data": "^1.8.2",
44
+ "@olenbetong/appframe-ds": "^1.4.1",
45
+ "@olenbetong/appframe-mui": "^7.0.10",
46
+ "@olenbetong/appframe-react": "^2.2.7",
47
47
  "clsx": "^2.1.1",
48
48
  "filepond": "^4.32.12",
49
49
  "filepond-plugin-file-poster": "^2.5.2",
@@ -1,29 +1,29 @@
1
- import { AppErrorBoundary } from "@olenbetong/appframe-ds";
2
- import type { ReactNode } from "react";
3
-
4
- export type AppShellProps = {
5
- children: ReactNode;
6
- };
7
-
8
- /**
9
- * Standard Synergi app shell: the error boundary around the app.
10
- *
11
- * The site chrome (app menu, user menu, colour scheme, service worker update)
12
- * is no longer part of the app. It is rendered by the `@olenbetong/synergi-chrome`
13
- * bundle the `ob.2026.application` template loads, which marks the page with
14
- * `<html data-ob-chrome="1">`. Toolbar slots stay app owned through
15
- * `ToolbarPortal` and `ToolbarBreadcrumbs`.
16
- *
17
- * This component is Designsystemet-only. Apps that still render MUI components
18
- * should additionally wrap it in `MuiThemeProvider` from
19
- * `@olenbetong/synergi-react/mui`, which bridges the Designsystemet colour
20
- * tokens into a MUI theme.
21
- */
22
- export function AppShell({ children }: AppShellProps) {
23
- return <AppErrorBoundary>{children}</AppErrorBoundary>;
24
- }
25
-
26
- /** Whether the page's template loaded the site chrome (`<html data-ob-chrome="1">`). */
27
- export function hasSiteChrome() {
28
- return typeof document !== "undefined" && document.documentElement.dataset.obChrome !== undefined;
29
- }
1
+ import { AppErrorBoundary } from "@olenbetong/appframe-ds";
2
+ import type { ReactNode } from "react";
3
+
4
+ export type AppShellProps = {
5
+ children: ReactNode;
6
+ };
7
+
8
+ /**
9
+ * Standard Synergi app shell: the error boundary around the app.
10
+ *
11
+ * The site chrome (app menu, user menu, colour scheme, service worker update)
12
+ * is no longer part of the app. It is rendered by the `@olenbetong/synergi-chrome`
13
+ * bundle the `ob.2026.application` template loads, which marks the page with
14
+ * `<html data-ob-chrome="1">`. Toolbar slots stay app owned through
15
+ * `ToolbarPortal` and `ToolbarBreadcrumbs`.
16
+ *
17
+ * This component is Designsystemet-only. Apps that still render MUI components
18
+ * should additionally wrap it in `MuiThemeProvider` from
19
+ * `@olenbetong/synergi-react/mui`, which bridges the Designsystemet colour
20
+ * tokens into a MUI theme.
21
+ */
22
+ export function AppShell({ children }: AppShellProps) {
23
+ return <AppErrorBoundary>{children}</AppErrorBoundary>;
24
+ }
25
+
26
+ /** Whether the page's template loaded the site chrome (`<html data-ob-chrome="1">`). */
27
+ export function hasSiteChrome() {
28
+ return typeof document !== "undefined" && document.documentElement.dataset.obChrome !== undefined;
29
+ }
@@ -1,34 +1,34 @@
1
- export type OpenReportOptions = {
2
- /**
3
- * Overrides the filter the report was designed with, as a criteria string.
4
- * An empty string starts the launcher with no filter at all.
5
- */
6
- initialFilter?: string | null;
7
- /** The tab shown first. */
8
- defaultTab?: "parameters" | "filter";
9
- };
10
-
11
- type ChromeWithReports = {
12
- openReport?: (reportId: string, options?: OpenReportOptions) => void;
13
- };
14
-
15
- /**
16
- * Opens a report in the site chrome's report launcher, the way the app menu does.
17
- *
18
- * The launcher lives in the `@olenbetong/synergi-chrome` bundle the 2026 templates load,
19
- * so an app never bundles it; this only forwards to `window.ob.chrome.openReport`.
20
- * On a page without the chrome (a legacy template) the call is logged and ignored.
21
- *
22
- * @example
23
- * ```ts
24
- * openReport("arpt_Production_ElementsDaily", { initialFilter: `[ProjectID] = '${projectId}'` });
25
- * ```
26
- */
27
- export function openReport(reportId: string, options?: OpenReportOptions) {
28
- let chrome = (globalThis as { ob?: { chrome?: ChromeWithReports } }).ob?.chrome;
29
- if (chrome?.openReport) {
30
- chrome.openReport(reportId, options);
31
- } else {
32
- console.warn(`openReport(${reportId}): the site chrome is not on this page, so there is no report launcher.`);
33
- }
34
- }
1
+ export type OpenReportOptions = {
2
+ /**
3
+ * Overrides the filter the report was designed with, as a criteria string.
4
+ * An empty string starts the launcher with no filter at all.
5
+ */
6
+ initialFilter?: string | null;
7
+ /** The tab shown first. */
8
+ defaultTab?: "parameters" | "filter";
9
+ };
10
+
11
+ type ChromeWithReports = {
12
+ openReport?: (reportId: string, options?: OpenReportOptions) => void;
13
+ };
14
+
15
+ /**
16
+ * Opens a report in the site chrome's report launcher, the way the app menu does.
17
+ *
18
+ * The launcher lives in the `@olenbetong/synergi-chrome` bundle the 2026 templates load,
19
+ * so an app never bundles it; this only forwards to `window.ob.chrome.openReport`.
20
+ * On a page without the chrome (a legacy template) the call is logged and ignored.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * openReport("arpt_Production_ElementsDaily", { initialFilter: `[ProjectID] = '${projectId}'` });
25
+ * ```
26
+ */
27
+ export function openReport(reportId: string, options?: OpenReportOptions) {
28
+ let chrome = (globalThis as { ob?: { chrome?: ChromeWithReports } }).ob?.chrome;
29
+ if (chrome?.openReport) {
30
+ chrome.openReport(reportId, options);
31
+ } else {
32
+ console.warn(`openReport(${reportId}): the site chrome is not on this page, so there is no report launcher.`);
33
+ }
34
+ }
@@ -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 chrome bundle
9
- * (`@olenbetong/synergi-chrome`) owns the same cookie for the toolbar user menu
10
- * and app menu toggles, so all of them write the cookie, apply the attributes,
11
- * and dispatch `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 chrome bundle
9
+ * (`@olenbetong/synergi-chrome`) owns the same cookie for the toolbar user menu
10
+ * and app menu toggles, so all of them write the cookie, apply the attributes,
11
+ * and dispatch `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
+ }