@olenbetong/synergi-react 2.5.6 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/es/colorScheme.d.ts +17 -0
  2. package/es/colorScheme.js +54 -0
  3. package/es/components/AppMenu/AppMenu.css +480 -92
  4. package/es/components/AppMenu/AppMenu.d.ts +47 -0
  5. package/es/components/AppMenu/AppMenu.js +224 -0
  6. package/es/components/AppMenu/AppMenuColorScheme.d.ts +2 -0
  7. package/es/components/AppMenu/AppMenuColorScheme.js +18 -0
  8. package/es/components/AppMenu/AppMenuToggle.d.ts +15 -0
  9. package/es/components/AppMenu/AppMenuToggle.js +14 -0
  10. package/es/components/AppMenu/AppMenuUserMenu.d.ts +32 -0
  11. package/es/components/AppMenu/AppMenuUserMenu.js +110 -0
  12. package/es/components/AppMenu/developerCategories.d.ts +24 -0
  13. package/es/components/AppMenu/developerCategories.js +116 -0
  14. package/es/components/AppMenu/index.d.ts +7 -12
  15. package/es/components/AppMenu/index.js +6 -85
  16. package/es/components/AppMenu/types.d.ts +33 -0
  17. package/es/components/AppMenu/types.js +1 -0
  18. package/es/components/AppMenu/useRovingTabIndex.d.ts +24 -0
  19. package/es/components/AppMenu/useRovingTabIndex.js +103 -0
  20. package/es/components/AppMenu/useServiceWorkerUpdate.d.ts +16 -0
  21. package/es/components/AppMenu/useServiceWorkerUpdate.js +62 -0
  22. package/es/components/AppShell/index.js +107 -13
  23. package/es/components/ImageEditor/ImageEditor.css +22 -11
  24. package/es/components/ImageEditor/ImageEditor.js +12 -12
  25. package/es/components/ImageEditor/ResponsiveButton.d.ts +1 -1
  26. package/es/components/ImageEditor/ResponsiveButton.js +5 -5
  27. package/es/components/ImageEditor/plugins/cropPlugin/CropOverlay.js +2 -2
  28. package/es/components/ImageEditor/plugins/cropPlugin/CropToolbar.js +3 -4
  29. package/es/components/ImageEditor/plugins/cropPlugin/index.js +2 -2
  30. package/es/components/ImageEditor/plugins/redactPlugin/RedactToolbar.js +3 -5
  31. package/es/components/ImageEditor/plugins/redactPlugin/index.js +2 -2
  32. package/es/components/ImageEditor/plugins/rotatePlugin.js +1 -2
  33. package/es/components/ImageEditor/plugins/zoomPlugin/ZoomControls.js +2 -4
  34. package/es/components/ImageEditor/useIsSmall.d.ts +5 -0
  35. package/es/components/ImageEditor/useIsSmall.js +21 -0
  36. package/es/index.d.ts +2 -1
  37. package/es/index.js +2 -1
  38. package/package.json +7 -3
  39. package/src/colorScheme.ts +81 -0
  40. package/src/components/AppMenu/AppMenu.css +480 -92
  41. package/src/components/AppMenu/AppMenu.tsx +478 -0
  42. package/src/components/AppMenu/AppMenuColorScheme.tsx +41 -0
  43. package/src/components/AppMenu/AppMenuToggle.tsx +51 -0
  44. package/src/components/AppMenu/AppMenuUserMenu.tsx +190 -0
  45. package/src/components/AppMenu/developerCategories.ts +142 -0
  46. package/src/components/AppMenu/index.ts +12 -0
  47. package/src/components/AppMenu/types.ts +35 -0
  48. package/src/components/AppMenu/useRovingTabIndex.ts +118 -0
  49. package/src/components/AppMenu/useServiceWorkerUpdate.ts +68 -0
  50. package/src/components/AppShell/index.tsx +140 -14
  51. package/src/components/ImageEditor/ImageEditor.css +22 -11
  52. package/src/components/ImageEditor/ImageEditor.tsx +38 -40
  53. package/src/components/ImageEditor/ResponsiveButton.tsx +8 -10
  54. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +6 -6
  55. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +6 -10
  56. package/src/components/ImageEditor/plugins/cropPlugin/index.ts +2 -2
  57. package/src/components/ImageEditor/plugins/redactPlugin/RedactToolbar.tsx +8 -17
  58. package/src/components/ImageEditor/plugins/redactPlugin/index.ts +2 -2
  59. package/src/components/ImageEditor/plugins/rotatePlugin.ts +1 -2
  60. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomControls.tsx +4 -6
  61. package/src/components/ImageEditor/useIsSmall.ts +27 -0
  62. package/src/index.ts +25 -1
  63. package/src/components/AppMenu/index.tsx +0 -179
@@ -0,0 +1,190 @@
1
+ import { getLocalizedString, getUserImage } from "@olenbetong/appframe-core";
2
+ import type { DataObject } from "@olenbetong/appframe-data";
3
+ import { useData } from "@olenbetong/appframe-react";
4
+ import { useEffect, useId, type KeyboardEvent, useRef, useState } from "react";
5
+
6
+ import type { AppMenuLink } from "./types.js";
7
+
8
+ /** Fields required from `aviw_Personnel_Employees_Lookup`. */
9
+ export type AppMenuUser = {
10
+ PrimKey: string;
11
+ PersonID: string;
12
+ FirstName: string | null;
13
+ LastName: string | null;
14
+ Fullname: string | null;
15
+ ImageHash: number | null;
16
+ };
17
+
18
+ /** Same entries as the sidebar user disclosure menu. */
19
+ export function defaultUserMenuItems(): AppMenuLink[] {
20
+ return [
21
+ { label: getLocalizedString("My profile"), href: "/edit-profile" },
22
+ { label: getLocalizedString("Change domain"), href: "/change-domain" },
23
+ { label: getLocalizedString("Change theme"), href: "/change-theme" },
24
+ { label: getLocalizedString("Change password"), href: "/change-password" },
25
+ { label: getLocalizedString("Troubleshooting"), href: "/diagnostics", separatorBefore: true },
26
+ { label: getLocalizedString("Log out"), href: "/logout", separatorBefore: true },
27
+ ];
28
+ }
29
+
30
+ export type AppMenuUserMenuProps = {
31
+ /**
32
+ * Data object over `aviw_Personnel_Employees_Lookup` filtered to the current
33
+ * user (`PersonID = af.userSession.login`). See `AppMenuUser`.
34
+ */
35
+ dataObject: DataObject<AppMenuUser>;
36
+ /** Overrides the default menu entries. */
37
+ items?: AppMenuLink[];
38
+ /** Shown below the name. Defaults to `af.userSession.domain`. */
39
+ subtitle?: string;
40
+ };
41
+
42
+ /**
43
+ * Disclosure menu showing the signed in user's photo and full name, with the
44
+ * account related links from the old sidebar.
45
+ *
46
+ * Users without an employee record still get the menu, using the name from the
47
+ * Appframe user session, so log out and password changes stay reachable.
48
+ */
49
+ export function AppMenuUserMenu({ dataObject, items, subtitle }: AppMenuUserMenuProps) {
50
+ let containerRef = useRef<HTMLDivElement>(null);
51
+ let triggerRef = useRef<HTMLButtonElement>(null);
52
+ let listRef = useRef<HTMLUListElement>(null);
53
+ let panelId = useId();
54
+ let [isOpen, setIsOpen] = useState(false);
55
+ let [hasPhotoError, setHasPhotoError] = useState(false);
56
+
57
+ let [user] = useData<AppMenuUser>(dataObject);
58
+ let session = globalThis.af?.userSession;
59
+ let menuItems = items ?? defaultUserMenuItems();
60
+
61
+ // Close when the pointer goes down outside the disclosure.
62
+ useEffect(() => {
63
+ if (!isOpen) return;
64
+
65
+ function onDocumentPointerDown(event: PointerEvent) {
66
+ if (!containerRef.current?.contains(event.target as Node)) setIsOpen(false);
67
+ }
68
+
69
+ document.addEventListener("pointerdown", onDocumentPointerDown);
70
+ return () => document.removeEventListener("pointerdown", onDocumentPointerDown);
71
+ }, [isOpen]);
72
+
73
+ function menuLinks() {
74
+ return [...(listRef.current?.querySelectorAll<HTMLElement>("a, button") ?? [])];
75
+ }
76
+
77
+ /** Focus a menu entry once the list has been shown. */
78
+ function focusEntry(position: "first" | "last") {
79
+ requestAnimationFrame(() => {
80
+ let links = menuLinks();
81
+ (position === "first" ? links[0] : links[links.length - 1])?.focus();
82
+ });
83
+ }
84
+
85
+ function close({ focusTrigger = true } = {}) {
86
+ setIsOpen(false);
87
+ if (focusTrigger) triggerRef.current?.focus();
88
+ }
89
+
90
+ function onTriggerKeyDown(event: KeyboardEvent<HTMLButtonElement>) {
91
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
92
+ event.preventDefault();
93
+ setIsOpen(true);
94
+ focusEntry(event.key === "ArrowDown" ? "first" : "last");
95
+ }
96
+ }
97
+
98
+ function onListKeyDown(event: KeyboardEvent<HTMLUListElement>) {
99
+ let links = menuLinks();
100
+ let index = links.indexOf(document.activeElement as HTMLElement);
101
+ if (index < 0 || links.length === 0) return;
102
+
103
+ let next: number;
104
+ if (event.key === "ArrowDown") next = (index + 1) % links.length;
105
+ else if (event.key === "ArrowUp") next = (index - 1 + links.length) % links.length;
106
+ else if (event.key === "Home") next = 0;
107
+ else if (event.key === "End") next = links.length - 1;
108
+ else return;
109
+
110
+ event.preventDefault();
111
+ event.stopPropagation();
112
+ links[next].focus();
113
+ }
114
+
115
+ let fullName =
116
+ user?.Fullname?.trim() ||
117
+ [user?.FirstName, user?.LastName].filter(Boolean).join(" ").trim() ||
118
+ session?.name ||
119
+ session?.login ||
120
+ getLocalizedString("Account");
121
+ let photo = user && !hasPhotoError ? getUserImage(user.PrimKey, user.PersonID, user.ImageHash, "sm") : "";
122
+ // The domain is set server side when the session is created.
123
+ let domain = subtitle ?? session?.domain ?? "";
124
+
125
+ return (
126
+ <div
127
+ ref={containerRef}
128
+ className="ob-app-menu-user"
129
+ onKeyDown={(event) => {
130
+ // Don't let Escape bubble to the dialog and close the whole menu.
131
+ if (event.key === "Escape" && isOpen) {
132
+ event.stopPropagation();
133
+ event.preventDefault();
134
+ close();
135
+ }
136
+ }}
137
+ onBlur={(event) => {
138
+ // Tabbing (or clicking) out of the disclosure closes it.
139
+ if (isOpen && !event.currentTarget.contains(event.relatedTarget)) close({ focusTrigger: false });
140
+ }}
141
+ >
142
+ <button
143
+ ref={triggerRef}
144
+ type="button"
145
+ className="ob-app-menu-user__trigger"
146
+ aria-expanded={isOpen}
147
+ aria-controls={panelId}
148
+ onClick={() => setIsOpen((open) => !open)}
149
+ onKeyDown={onTriggerKeyDown}
150
+ >
151
+ <span className="ob-app-menu-user__avatar">
152
+ {photo ? (
153
+ <img className="ob-app-menu-user__image" src={photo} alt="" onError={() => setHasPhotoError(true)} />
154
+ ) : (
155
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false">
156
+ <path d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10m0 2c-4.42 0-8 2.24-8 5v1a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1c0-2.76-3.58-5-8-5" />
157
+ </svg>
158
+ )}
159
+ </span>
160
+ <span className="ob-app-menu-user__meta">
161
+ <span className="ob-app-menu-user__name">{fullName}</span>
162
+ {domain && <span className="ob-app-menu-user__domain">{domain}</span>}
163
+ </span>
164
+ </button>
165
+
166
+ <ul id={panelId} ref={listRef} className="ob-app-menu-user__list" hidden={!isOpen} onKeyDown={onListKeyDown}>
167
+ {menuItems.map((item) => (
168
+ <li key={item.label} className={item.separatorBefore ? "ob-app-menu-user__item--divided" : undefined}>
169
+ {item.href ? (
170
+ <a href={item.href} target={item.target} rel={item.rel} onClick={item.onClick}>
171
+ {item.label}
172
+ </a>
173
+ ) : (
174
+ <button
175
+ type="button"
176
+ {...item.attributes}
177
+ onClick={() => {
178
+ item.onClick?.();
179
+ if (!item.keepOpen) close();
180
+ }}
181
+ >
182
+ {item.label}
183
+ </button>
184
+ )}
185
+ </li>
186
+ ))}
187
+ </ul>
188
+ </div>
189
+ );
190
+ }
@@ -0,0 +1,142 @@
1
+ import { getLocalizedString } from "@olenbetong/appframe-core";
2
+
3
+ import type { AppMenuCategory } from "./types.js";
4
+
5
+ export type DeveloperCategoryOptions = {
6
+ /** Article the "Edit article"/"Edit app" links point at. Defaults to `af.article.id`. */
7
+ articleId?: string;
8
+ /** CMS host name used by the app designer links. Defaults to `af.article.hostName`. */
9
+ hostName?: string;
10
+ /** App designer host. */
11
+ devUrl?: string;
12
+ /** Content editor host. */
13
+ testUrl?: string;
14
+ /**
15
+ * Include the cache clearing buttons. They post to `/api/debug/cache/...`,
16
+ * which requires two verified authentication factors.
17
+ */
18
+ includeCacheTools?: boolean;
19
+ };
20
+
21
+ /**
22
+ * Build the Articles/Developer/Debug categories that used to live in the
23
+ * sidebar's developer disclosure menu.
24
+ *
25
+ * Only render these for users where `af.userSession.isDeveloper` is true — the
26
+ * targets are all developer-only and will return 403 for everyone else.
27
+ */
28
+ export function createDeveloperCategories({
29
+ articleId = globalThis.af?.article?.id ?? "",
30
+ hostName = globalThis.af?.article?.hostName ?? "",
31
+ devUrl = "https://dev.obet.no",
32
+ testUrl = "https://test.synergi.olenbetong.no",
33
+ includeCacheTools = true,
34
+ }: DeveloperCategoryOptions = {}): AppMenuCategory[] {
35
+ let section = getLocalizedString("Developer");
36
+
37
+ return [
38
+ {
39
+ id: "dev-articles",
40
+ label: getLocalizedString("Articles"),
41
+ section,
42
+ groups: [
43
+ {
44
+ title: getLocalizedString("Apps & articles"),
45
+ items: [
46
+ { label: getLocalizedString("New article"), href: `${testUrl}/content` },
47
+ { label: getLocalizedString("Edit article"), href: `${testUrl}/content?${articleId}` },
48
+ ],
49
+ },
50
+ {
51
+ title: getLocalizedString("App designer"),
52
+ items: [
53
+ { label: getLocalizedString("New app"), href: `${devUrl}/appdesigner?${hostName}` },
54
+ { label: getLocalizedString("Edit app"), href: `${devUrl}/appdesigner?${hostName}/${articleId}` },
55
+ { label: getLocalizedString("Article List"), href: "/appdesigner-articlelist" },
56
+ { label: getLocalizedString("Manage translations"), href: "/system-translate" },
57
+ ],
58
+ },
59
+ {
60
+ title: getLocalizedString("Navigation"),
61
+ items: [
62
+ { label: getLocalizedString("Edit sidebar"), href: `${devUrl}/appdesigner?${hostName}/sidebar` },
63
+ { label: getLocalizedString("Sidebar applications"), href: `${devUrl}/manage-sidebar-applications` },
64
+ { label: getLocalizedString("Article Icons"), href: "/article-icons" },
65
+ ],
66
+ },
67
+ ],
68
+ },
69
+ {
70
+ id: "dev-tools",
71
+ label: getLocalizedString("Development"),
72
+ section,
73
+ groups: [
74
+ {
75
+ title: getLocalizedString("Developer"),
76
+ items: [
77
+ { label: "DB Manager", href: "/af-dbmanager" },
78
+ { label: "Code Modules", href: "/code-modules" },
79
+ { label: "Assemblies", href: "/af-assemblies" },
80
+ { label: "Site Setup", href: "/sitesetup" },
81
+ { label: "Bundles", href: "/af-bundle" },
82
+ { label: "Updater", href: "/af-updater" },
83
+ { label: "Scheduler", href: "/af-scheduler" },
84
+ ],
85
+ },
86
+ {
87
+ title: "System",
88
+ items: [
89
+ { label: getLocalizedString("Manage Users"), href: "/system-users" },
90
+ { label: getLocalizedString("Manage Roles"), href: "/system-roles" },
91
+ { label: getLocalizedString("Manage Domains"), href: "/system-domains" },
92
+ ],
93
+ },
94
+ ],
95
+ },
96
+ {
97
+ id: "dev-debug",
98
+ label: getLocalizedString("Debugging"),
99
+ section,
100
+ groups: [
101
+ {
102
+ title: getLocalizedString("Debug"),
103
+ items: [
104
+ { label: getLocalizedString("Cache Control"), href: "/api/debug/cache" },
105
+ { label: getLocalizedString("Razor"), href: "/api/debug/razor" },
106
+ { label: getLocalizedString("Placeholders"), href: "/api/debug/placeholders" },
107
+ { label: getLocalizedString("Routes"), href: "/api/debug/routes" },
108
+ { label: getLocalizedString("DB Trace"), href: "/api/debug/trace" },
109
+ { label: getLocalizedString("DB Profiler"), href: "/api/debug/profiler" },
110
+ { label: getLocalizedString("Errors"), href: "/api/debug/errors" },
111
+ { label: getLocalizedString("Modules"), href: "/api/debug/modules" },
112
+ { label: getLocalizedString("Assemblies"), href: "/api/debug/assemblies" },
113
+ ],
114
+ },
115
+ ...(includeCacheTools
116
+ ? [
117
+ {
118
+ title: getLocalizedString("Clear cache"),
119
+ // Handled by the delegated `[data-action=clear-cache]` listener in the site scripts.
120
+ items: [
121
+ { label: getLocalizedString("Data object definition"), cache: "object-definitions" },
122
+ { label: getLocalizedString("Article"), cache: "article-cache" },
123
+ { label: getLocalizedString("File groups"), cache: "file-groups" },
124
+ { label: getLocalizedString("Content delivery"), cache: "content-delivery" },
125
+ { label: getLocalizedString("Localization"), cache: "localization" },
126
+ { label: getLocalizedString("Code modules"), cache: "code-modules", method: "reload" },
127
+ ].map(({ label, cache, method }) => ({
128
+ label,
129
+ keepOpen: true,
130
+ attributes: {
131
+ "data-action": "clear-cache",
132
+ "data-cache": cache,
133
+ ...(method ? { "data-cache-method": method } : {}),
134
+ },
135
+ })),
136
+ },
137
+ ]
138
+ : []),
139
+ ],
140
+ },
141
+ ];
142
+ }
@@ -0,0 +1,12 @@
1
+ export { AppMenu, type AppMenuArticle, type AppMenuProps } from "./AppMenu.js";
2
+ export { AppMenuColorScheme } from "./AppMenuColorScheme.js";
3
+ export { AppMenuToggle, type AppMenuToggleProps } from "./AppMenuToggle.js";
4
+ export {
5
+ AppMenuUserMenu,
6
+ type AppMenuUser,
7
+ type AppMenuUserMenuProps,
8
+ defaultUserMenuItems,
9
+ } from "./AppMenuUserMenu.js";
10
+ export { createDeveloperCategories, type DeveloperCategoryOptions } from "./developerCategories.js";
11
+ export type { AppMenuCategory, AppMenuLink, AppMenuLinkGroup } from "./types.js";
12
+ export { useServiceWorkerUpdate } from "./useServiceWorkerUpdate.js";
@@ -0,0 +1,35 @@
1
+ /** A single entry in the app menu's right hand pane or in the user menu. */
2
+ export type AppMenuLink = {
3
+ label: string;
4
+ /** Renders an anchor. Without an href the entry is rendered as a button. */
5
+ href?: string;
6
+ target?: string;
7
+ rel?: string;
8
+ onClick?: () => void;
9
+ /** Extra attributes, e.g. `{ "data-action": "clear-cache" }` for site scripts. */
10
+ attributes?: Record<string, string>;
11
+ /** Keep the menu open when the entry is activated. */
12
+ keepOpen?: boolean;
13
+ /** Render a divider above this entry (user menu only). */
14
+ separatorBefore?: boolean;
15
+ };
16
+
17
+ /** A titled block of links inside a category. */
18
+ export type AppMenuLinkGroup = {
19
+ title?: string;
20
+ items: AppMenuLink[];
21
+ };
22
+
23
+ /**
24
+ * A category listed in the app menu rail that shows a fixed set of links
25
+ * instead of apps, e.g. the developer tools.
26
+ */
27
+ export type AppMenuCategory = {
28
+ /** Unique key, used for selection. */
29
+ id: string;
30
+ /** Label shown in the rail. */
31
+ label: string;
32
+ /** Sub header in the rail that this category is listed under. */
33
+ section?: string;
34
+ groups: AppMenuLinkGroup[];
35
+ };
@@ -0,0 +1,118 @@
1
+ import { type KeyboardEvent, useEffect, useState } from "react";
2
+
3
+ const NEXT_KEYS = ["ArrowDown", "ArrowRight"];
4
+ const PREV_KEYS = ["ArrowUp", "ArrowLeft"];
5
+ const HORIZONTAL_KEYS = ["ArrowLeft", "ArrowRight"];
6
+ const ARROW_KEYS = [...HORIZONTAL_KEYS, "ArrowUp", "ArrowDown"];
7
+
8
+ /**
9
+ * Find the item closest to `from` in the neighbouring visual row or column.
10
+ *
11
+ * The app list is a grid whose column count depends on the available width, so
12
+ * which row and column an item ends up in is only known after layout. Comparing
13
+ * client rectangles is therefore the only reliable way to move in two
14
+ * dimensions.
15
+ */
16
+ function findAdjacent(items: readonly HTMLElement[], from: number, axis: "x" | "y", direction: 1 | -1) {
17
+ // `main` is the axis stepped along, `cross` the one used to pick the closest
18
+ // candidate within the target row/column.
19
+ let rects = items.map((item) => {
20
+ let rect = item.getBoundingClientRect();
21
+ return axis === "x" ? { main: rect.left, cross: rect.top } : { main: rect.top, cross: rect.left };
22
+ });
23
+
24
+ let origin = rects[from];
25
+ if (!origin) return null;
26
+
27
+ // The nearest row/column edge in the requested direction.
28
+ let target: number | null = null;
29
+ for (let rect of rects) {
30
+ let delta = rect.main - origin.main;
31
+ if (direction > 0 ? delta <= 1 : delta >= -1) continue;
32
+ if (target === null || Math.abs(rect.main - origin.main) < Math.abs(target - origin.main)) {
33
+ target = rect.main;
34
+ }
35
+ }
36
+
37
+ if (target === null) return null;
38
+
39
+ let best: number | null = null;
40
+ let bestDistance = Number.POSITIVE_INFINITY;
41
+ for (let index = 0; index < rects.length; index++) {
42
+ let rect = rects[index];
43
+ if (Math.abs(rect.main - target) > 1) continue;
44
+
45
+ let distance = Math.abs(rect.cross - origin.cross);
46
+ if (distance < bestDistance) {
47
+ bestDistance = distance;
48
+ best = index;
49
+ }
50
+ }
51
+
52
+ return best;
53
+ }
54
+
55
+ export type RovingTabIndexOptions = {
56
+ /**
57
+ * When true, the arrow keys follow the visual layout of a wrapping grid
58
+ * instead of the DOM order: left/right move between columns and up/down
59
+ * between rows.
60
+ */
61
+ columns?: boolean;
62
+ };
63
+
64
+ /**
65
+ * Roving tabindex: the container holds a single tab stop, and the arrow keys
66
+ * (plus Home/End) move focus between the items inside it.
67
+ *
68
+ * Spread `getItemProps(index)` on every focusable item and put `onKeyDown` on
69
+ * their common ancestor.
70
+ */
71
+ export function useRovingTabIndex(itemCount: number, { columns = false }: RovingTabIndexOptions = {}) {
72
+ let [activeIndex, setActiveIndex] = useState(0);
73
+
74
+ // Keep the tab stop within the list when it shrinks (e.g. while searching).
75
+ useEffect(() => {
76
+ setActiveIndex((index) => (index >= itemCount ? 0 : index));
77
+ }, [itemCount]);
78
+
79
+ function onKeyDown(event: KeyboardEvent<HTMLElement>) {
80
+ if (itemCount === 0) return;
81
+
82
+ let items = [...event.currentTarget.querySelectorAll<HTMLElement>("[data-roving-item]")];
83
+ let next: number | null;
84
+
85
+ if (columns && ARROW_KEYS.includes(event.key)) {
86
+ event.preventDefault();
87
+
88
+ let isHorizontal = HORIZONTAL_KEYS.includes(event.key);
89
+ let direction: 1 | -1 = NEXT_KEYS.includes(event.key) ? 1 : -1;
90
+ next = findAdjacent(items, activeIndex, isHorizontal ? "x" : "y", direction);
91
+
92
+ if (next === null) {
93
+ // Stay put at the first/last column, but let up/down continue into the
94
+ // neighbouring item so the whole list stays reachable.
95
+ if (isHorizontal) return;
96
+ next = (activeIndex + direction + itemCount) % itemCount;
97
+ }
98
+ } else if (NEXT_KEYS.includes(event.key)) next = (activeIndex + 1) % itemCount;
99
+ else if (PREV_KEYS.includes(event.key)) next = (activeIndex - 1 + itemCount) % itemCount;
100
+ else if (event.key === "Home") next = 0;
101
+ else if (event.key === "End") next = itemCount - 1;
102
+ else return;
103
+
104
+ event.preventDefault();
105
+ setActiveIndex(next);
106
+ items[next]?.focus();
107
+ }
108
+
109
+ function getItemProps(index: number) {
110
+ return {
111
+ "data-roving-item": "",
112
+ tabIndex: index === activeIndex ? 0 : -1,
113
+ onFocus: () => setActiveIndex(index),
114
+ };
115
+ }
116
+
117
+ return { onKeyDown, getItemProps };
118
+ }
@@ -0,0 +1,68 @@
1
+ import { useCallback, useEffect, useState } from "react";
2
+
3
+ /**
4
+ * Track whether a new version of the site has been downloaded by the service
5
+ * worker and is waiting to take over.
6
+ *
7
+ * A waiting worker means every asset of the new version is already cached, so
8
+ * installing it is just `skipWaiting` followed by a reload. The reload is
9
+ * triggered from the worker's `activated` state change rather than immediately,
10
+ * so the page never reloads into the old version.
11
+ *
12
+ * Replaces the DOM based `[data-update-worker]` wiring in the site bundle, which
13
+ * only works for markup that exists when the page loads.
14
+ */
15
+ export function useServiceWorkerUpdate() {
16
+ let [waitingWorker, setWaitingWorker] = useState<ServiceWorker | null>(null);
17
+
18
+ useEffect(() => {
19
+ if (!("serviceWorker" in navigator)) return;
20
+
21
+ let isCancelled = false;
22
+ let cleanups: (() => void)[] = [];
23
+
24
+ function watch(worker: ServiceWorker) {
25
+ if (isCancelled) return;
26
+ setWaitingWorker(worker);
27
+
28
+ function onStateChange() {
29
+ // The new worker took over, so the page can safely reload into it.
30
+ if (worker.state === "activated") window.location.reload();
31
+ }
32
+
33
+ worker.addEventListener("statechange", onStateChange);
34
+ cleanups.push(() => worker.removeEventListener("statechange", onStateChange));
35
+ }
36
+
37
+ navigator.serviceWorker.ready.then((registration) => {
38
+ if (isCancelled) return;
39
+ if (registration.waiting) watch(registration.waiting);
40
+
41
+ function onUpdateFound() {
42
+ let installing = registration.installing;
43
+ if (!installing) return;
44
+
45
+ function onStateChange() {
46
+ if (installing?.state === "installed") watch(installing);
47
+ }
48
+
49
+ installing.addEventListener("statechange", onStateChange);
50
+ cleanups.push(() => installing.removeEventListener("statechange", onStateChange));
51
+ }
52
+
53
+ registration.addEventListener("updatefound", onUpdateFound);
54
+ cleanups.push(() => registration.removeEventListener("updatefound", onUpdateFound));
55
+ });
56
+
57
+ return () => {
58
+ isCancelled = true;
59
+ for (let cleanup of cleanups) cleanup();
60
+ };
61
+ }, []);
62
+
63
+ let installUpdate = useCallback(() => {
64
+ waitingWorker?.postMessage({ action: "skipWaiting" });
65
+ }, [waitingWorker]);
66
+
67
+ return { isUpdateAvailable: waitingWorker !== null, installUpdate };
68
+ }