@liberation-data/desk 0.41.0 → 0.43.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 (112) hide show
  1. package/README.md +152 -9
  2. package/dist/core/index.d.ts +2 -0
  3. package/dist/core/index.d.ts.map +1 -1
  4. package/dist/core/index.js +1 -0
  5. package/dist/core/index.js.map +1 -1
  6. package/dist/core/scheme.d.ts +12 -0
  7. package/dist/core/scheme.d.ts.map +1 -0
  8. package/dist/core/scheme.js +15 -0
  9. package/dist/core/scheme.js.map +1 -0
  10. package/dist/core/types.d.ts +6 -0
  11. package/dist/core/types.d.ts.map +1 -1
  12. package/dist/css/apps.css +149 -0
  13. package/dist/css/controls.css +21 -2
  14. package/dist/css/dock.css +1 -1
  15. package/dist/css/looks.css +50 -4
  16. package/dist/css/overlays.css +6 -0
  17. package/dist/css/tokens.css +1 -0
  18. package/dist/css/windows.css +173 -5
  19. package/dist/desk.css +401 -12
  20. package/dist/react/Desktop.d.ts +12 -3
  21. package/dist/react/Desktop.d.ts.map +1 -1
  22. package/dist/react/Desktop.js +29 -9
  23. package/dist/react/Desktop.js.map +1 -1
  24. package/dist/react/Dock.d.ts +6 -1
  25. package/dist/react/Dock.d.ts.map +1 -1
  26. package/dist/react/Dock.js +9 -1
  27. package/dist/react/Dock.js.map +1 -1
  28. package/dist/react/MenuBar.d.ts +8 -1
  29. package/dist/react/MenuBar.d.ts.map +1 -1
  30. package/dist/react/MenuBar.js +34 -5
  31. package/dist/react/MenuBar.js.map +1 -1
  32. package/dist/react/app.d.ts +174 -0
  33. package/dist/react/app.d.ts.map +1 -0
  34. package/dist/react/app.js +146 -0
  35. package/dist/react/app.js.map +1 -0
  36. package/dist/react/appPanels.d.ts +22 -0
  37. package/dist/react/appPanels.d.ts.map +1 -0
  38. package/dist/react/appPanels.js +114 -0
  39. package/dist/react/appPanels.js.map +1 -0
  40. package/dist/react/appearance.d.ts +55 -0
  41. package/dist/react/appearance.d.ts.map +1 -0
  42. package/dist/react/appearance.js +140 -0
  43. package/dist/react/appearance.js.map +1 -0
  44. package/dist/react/arrange.d.ts +6 -0
  45. package/dist/react/arrange.d.ts.map +1 -1
  46. package/dist/react/arrange.js +21 -0
  47. package/dist/react/arrange.js.map +1 -1
  48. package/dist/react/codeBlock.d.ts.map +1 -1
  49. package/dist/react/codeBlock.js +6 -60
  50. package/dist/react/codeBlock.js.map +1 -1
  51. package/dist/react/context.d.ts +9 -1
  52. package/dist/react/context.d.ts.map +1 -1
  53. package/dist/react/context.js +47 -3
  54. package/dist/react/context.js.map +1 -1
  55. package/dist/react/copy.d.ts +22 -0
  56. package/dist/react/copy.d.ts.map +1 -0
  57. package/dist/react/copy.js +68 -0
  58. package/dist/react/copy.js.map +1 -0
  59. package/dist/react/documentTitle.d.ts.map +1 -1
  60. package/dist/react/documentTitle.js +4 -1
  61. package/dist/react/documentTitle.js.map +1 -1
  62. package/dist/react/index.d.ts +10 -1
  63. package/dist/react/index.d.ts.map +1 -1
  64. package/dist/react/index.js +7 -1
  65. package/dist/react/index.js.map +1 -1
  66. package/dist/react/layers.d.ts.map +1 -1
  67. package/dist/react/layers.js +7 -2
  68. package/dist/react/layers.js.map +1 -1
  69. package/dist/react/overlays.d.ts.map +1 -1
  70. package/dist/react/overlays.js +29 -12
  71. package/dist/react/overlays.js.map +1 -1
  72. package/dist/react/shell.d.ts +4 -1
  73. package/dist/react/shell.d.ts.map +1 -1
  74. package/dist/react/shell.js +2 -2
  75. package/dist/react/shell.js.map +1 -1
  76. package/dist/react/tabs.d.ts +7 -1
  77. package/dist/react/tabs.d.ts.map +1 -1
  78. package/dist/react/tabs.js +13 -8
  79. package/dist/react/tabs.js.map +1 -1
  80. package/dist/react/widgets.d.ts +33 -0
  81. package/dist/react/widgets.d.ts.map +1 -0
  82. package/dist/react/widgets.js +213 -0
  83. package/dist/react/widgets.js.map +1 -0
  84. package/llms.txt +75 -8
  85. package/package.json +1 -1
  86. package/src/core/index.ts +2 -0
  87. package/src/core/scheme.ts +21 -0
  88. package/src/core/types.ts +6 -0
  89. package/src/css/apps.css +149 -0
  90. package/src/css/controls.css +21 -2
  91. package/src/css/dock.css +1 -1
  92. package/src/css/looks.css +50 -4
  93. package/src/css/overlays.css +6 -0
  94. package/src/css/tokens.css +1 -0
  95. package/src/css/windows.css +173 -5
  96. package/src/react/Desktop.tsx +50 -12
  97. package/src/react/Dock.tsx +11 -1
  98. package/src/react/MenuBar.tsx +38 -5
  99. package/src/react/app.tsx +284 -0
  100. package/src/react/appPanels.tsx +197 -0
  101. package/src/react/appearance.tsx +204 -0
  102. package/src/react/arrange.ts +23 -0
  103. package/src/react/codeBlock.tsx +7 -65
  104. package/src/react/context.tsx +55 -3
  105. package/src/react/copy.ts +81 -0
  106. package/src/react/documentTitle.ts +4 -1
  107. package/src/react/index.ts +30 -1
  108. package/src/react/layers.ts +7 -2
  109. package/src/react/overlays.tsx +30 -12
  110. package/src/react/shell.tsx +5 -2
  111. package/src/react/tabs.tsx +23 -10
  112. package/src/react/widgets.tsx +265 -0
@@ -59,15 +59,25 @@ export function Popover({ open, onOpenChange, label, trigger, placement = 'below
59
59
  if (anchor && element) placePopover(anchor, element, placement, align)
60
60
  }, [placement, align])
61
61
 
62
- // Measured once it exists, then kept beside its control while anything under it scrolls.
62
+ // Measured once it exists, then kept beside its control while anything under it scrolls, and placed again
63
+ // when what it shows changes size: content that grows after opening (a live note) still fits, or scrolls.
63
64
  useLayoutEffect(() => {
64
65
  if (!open) return
65
66
  place()
67
+ // Scrolling under it moves its control, so it follows. Its own scrolling doesn't: placing it again then would
68
+ // lose where it was scrolled to (see placePopover), so a popover that scrolls could never be scrolled.
69
+ const onScroll = (event: Event) => {
70
+ if (!panel.current?.contains(event.target as Node)) place()
71
+ }
66
72
  addEventListener('resize', place)
67
- document.addEventListener('scroll', place, true)
73
+ document.addEventListener('scroll', onScroll, true)
74
+ const content = panel.current?.firstElementChild
75
+ const observer = typeof ResizeObserver === 'undefined' || !content ? null : new ResizeObserver(() => place())
76
+ if (observer && content) observer.observe(content)
68
77
  return () => {
69
78
  removeEventListener('resize', place)
70
- document.removeEventListener('scroll', place, true)
79
+ document.removeEventListener('scroll', onScroll, true)
80
+ observer?.disconnect()
71
81
  }
72
82
  }, [open, place])
73
83
 
@@ -75,8 +85,10 @@ export function Popover({ open, onOpenChange, label, trigger, placement = 'below
75
85
  <span className="desk-popover-anchor">
76
86
  {trigger({ ref: button, 'aria-haspopup': 'dialog', 'aria-expanded': open, onClick: () => onOpenChange(!open) })}
77
87
  {open && typeof document !== 'undefined' && createPortal(
78
- <div ref={panel} role="dialog" aria-label={label} className="desk-popover" data-placement={placement} data-align={align}>
79
- {children}
88
+ // Focusable, so the focus trap can land on it when it holds nothing to tab to, and the arrow and page
89
+ // keys then scroll it.
90
+ <div ref={panel} role="dialog" aria-label={label} className="desk-popover" data-placement={placement} data-align={align} tabIndex={-1}>
91
+ <div className="desk-popover-content">{children}</div>
80
92
  </div>,
81
93
  document.body,
82
94
  )}
@@ -91,18 +103,22 @@ const POPOVER_MARGIN = 8
91
103
  * A popover floats OVER its window rather than inside it. Drawn in the window's content it made that
92
104
  * content taller or wider, so opening an (i) grew a scrollbar or pushed the layout — the window
93
105
  * changed size to make room for a note about it. Here it is fixed to the viewport, kept inside the
94
- * window it belongs to, flipped to the other side when its side has no room, and scrolls within
95
- * itself when neither side has.
106
+ * window it belongs to and inside the viewport (a window can reach past the screen's foot), flipped to
107
+ * the other side when its side has no room, and held to the room its side has: what doesn't fit scrolls
108
+ * within it, never off the screen.
96
109
  */
97
110
  function placePopover(anchor: HTMLElement, element: HTMLElement, placement: 'below' | 'above', align: 'start' | 'end') {
98
111
  const box = anchor.getBoundingClientRect()
99
112
  const frame = anchor.closest(`[${WINDOW_ATTRIBUTE}]`)?.getBoundingClientRect()
100
113
  const bounds = {
101
- left: (frame?.left ?? 0) + POPOVER_MARGIN,
102
- top: (frame?.top ?? 0) + POPOVER_MARGIN,
103
- right: (frame?.right ?? innerWidth) - POPOVER_MARGIN,
104
- bottom: (frame?.bottom ?? innerHeight) - POPOVER_MARGIN,
114
+ left: Math.max(frame?.left ?? 0, 0) + POPOVER_MARGIN,
115
+ top: Math.max(frame?.top ?? 0, 0) + POPOVER_MARGIN,
116
+ right: Math.min(frame?.right ?? innerWidth, innerWidth) - POPOVER_MARGIN,
117
+ bottom: Math.min(frame?.bottom ?? innerHeight, innerHeight) - POPOVER_MARGIN,
105
118
  }
119
+ // Measured at its full height, which means letting go of its limit for a moment: that would reset where it is
120
+ // scrolled to, so that is kept and given back.
121
+ const scrolled = element.scrollTop
106
122
  element.style.maxHeight = ''
107
123
  const { width, height } = element.getBoundingClientRect()
108
124
  const roomBelow = bounds.bottom - box.bottom - POPOVER_GAP
@@ -117,7 +133,9 @@ function placePopover(anchor: HTMLElement, element: HTMLElement, placement: 'bel
117
133
  const left = Math.max(bounds.left, Math.min(preferred, bounds.right - width))
118
134
  element.style.left = `${left}px`
119
135
  element.style.top = `${below ? box.bottom + POPOVER_GAP : box.top - POPOVER_GAP - shown}px`
120
- if (height > room) element.style.maxHeight = `${room}px`
136
+ // Always held to its room, not only when it overflows now: content that grows later scrolls inside it.
137
+ element.style.maxHeight = `${room}px`
138
+ element.scrollTop = scrolled
121
139
  element.dataset.side = side
122
140
  }
123
141
 
@@ -5,6 +5,7 @@ import type { Desk } from '../core/desk.js'
5
5
  import type { Bus } from '../core/events.js'
6
6
  import type { LookChoice } from '../core/look.js'
7
7
  import type { Holdable } from '../core/services.js'
8
+ import type { DeskApp } from './app.js'
8
9
  import type { DeskOptions } from '../core/types.js'
9
10
  import { DeskProvider } from './context.js'
10
11
  import { BusProvider } from './events.js'
@@ -22,12 +23,14 @@ export interface DeskShellProps {
22
23
  readonly look?: LookChoice
23
24
  /** What the desk keeps going while it is on screen. See `DeskProviderProps.services`. */
24
25
  readonly services?: readonly Holdable[]
26
+ /** What the app says about itself, for its About and its Settings. See `DeskProviderProps.app`. */
27
+ readonly app?: DeskApp
25
28
  readonly children: ReactNode
26
29
  }
27
30
 
28
31
  /** Everything an app needs around it, in one component: the desk, its bus, and toasts. */
29
- export function DeskShell({ desk, options, bus, toasts = true, look = 'auto', services = [], children }: DeskShellProps) {
32
+ export function DeskShell({ desk, options, bus, toasts = true, look = 'auto', services = [], app, children }: DeskShellProps) {
30
33
  const [made] = useState(() => desk ?? createDesk(options))
31
34
  const inner = toasts ? <ToastProvider>{children}</ToastProvider> : children
32
- return <DeskProvider desk={made} look={look} services={services}>{bus ? <BusProvider bus={bus}>{inner}</BusProvider> : inner}</DeskProvider>
35
+ return <DeskProvider desk={made} look={look} services={services} {...(app ? { app } : {})}>{bus ? <BusProvider bus={bus}>{inner}</BusProvider> : inner}</DeskProvider>
33
36
  }
@@ -18,7 +18,13 @@ export interface Tab<T extends string> {
18
18
  readonly label: string
19
19
  /** A count or a state beside the label, e.g. the 3 in "Needs review 3". */
20
20
  readonly badge?: ReactNode
21
- readonly disabled?: boolean
21
+ /**
22
+ * True when the view can't be chosen, or a string saying why, e.g. "Waiting for the aerial photo". With a
23
+ * reason the tab stays in the accessibility tree as unavailable (`aria-disabled`) and is described by the
24
+ * reason: the arrow keys stop on it, so a screen reader hears why it is grey, and a pointer sees it on hover.
25
+ * It is never selected. Plain `true` is passed by the arrow keys.
26
+ */
27
+ readonly disabled?: boolean | string
22
28
  }
23
29
 
24
30
  export interface TabsProps<T extends string> {
@@ -48,15 +54,17 @@ export function Tabs<T extends string>({ tabs, value, onChange, label, actions,
48
54
 
49
55
  const move = (event: KeyboardEvent<HTMLDivElement>) => {
50
56
  const key = KEYS[event.key as keyof typeof KEYS]
51
- const usable = tabs.filter(t => !t.disabled)
52
- if (key === undefined || !usable.length) return
57
+ // A tab disabled with a reason is a stop, so the reason is heard; one disabled plainly is passed by.
58
+ const stops = tabs.filter(t => t.disabled !== true)
59
+ if (key === undefined || !stops.length) return
53
60
  event.preventDefault()
54
- const at = usable.findIndex(t => t.value === value)
55
- const next = key === 'first' ? usable[0]
56
- : key === 'last' ? usable[usable.length - 1]
57
- : usable[(at + key + usable.length) % usable.length]
61
+ const focused = (event.target as HTMLElement).closest<HTMLElement>('[role="tab"]')?.dataset.value ?? value
62
+ const at = stops.findIndex(t => t.value === focused)
63
+ const next = key === 'first' ? stops[0]
64
+ : key === 'last' ? stops[stops.length - 1]
65
+ : stops[(at + key + stops.length) % stops.length]
58
66
  if (!next) return
59
- onChange(next.value)
67
+ if (!next.disabled) onChange(next.value)
60
68
  strip.current?.querySelector<HTMLButtonElement>(`[data-value="${CSS.escape(next.value)}"]`)?.focus()
61
69
  }
62
70
 
@@ -66,6 +74,7 @@ export function Tabs<T extends string>({ tabs, value, onChange, label, actions,
66
74
  <div ref={strip} role="tablist" aria-label={label} className="desk-tablist" onKeyDown={move}>
67
75
  {tabs.map(tab => {
68
76
  const selected = tab.value === value
77
+ const why = typeof tab.disabled === 'string' && tab.disabled ? tab.disabled : undefined
69
78
  return (
70
79
  <button
71
80
  key={tab.value}
@@ -77,11 +86,15 @@ export function Tabs<T extends string>({ tabs, value, onChange, label, actions,
77
86
  data-value={tab.value}
78
87
  className="desk-tab"
79
88
  tabIndex={selected ? 0 : -1}
80
- disabled={tab.disabled}
81
- onClick={() => onChange(tab.value)}
89
+ disabled={tab.disabled === true}
90
+ aria-disabled={why ? true : undefined}
91
+ aria-describedby={why ? `${tabId(tab.value)}-why` : undefined}
92
+ title={why}
93
+ onClick={() => { if (!tab.disabled) onChange(tab.value) }}
82
94
  >
83
95
  {tab.label}
84
96
  {tab.badge != null && <span className="desk-tab-badge">{tab.badge}</span>}
97
+ {why && <span id={`${tabId(tab.value)}-why`} className="desk-tab-why" aria-hidden="true">{why}</span>}
85
98
  </button>
86
99
  )
87
100
  })}
@@ -0,0 +1,265 @@
1
+ import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react'
2
+ import type { FocusEvent, KeyboardEvent, ReactNode } from 'react'
3
+ import { STAGE_ATTRIBUTE, WINDOW_ATTRIBUTE, windowElement } from '../core/commands.js'
4
+ import { focusedId } from '../core/desk.js'
5
+ import type { Frame } from '../core/types.js'
6
+ import { useDesk } from './context.js'
7
+
8
+ /** A glance on the desk itself, under the windows: what is loaded, a job's progress, a connection. */
9
+ export interface Widget {
10
+ readonly id: string
11
+ /** What it is, in a word or two: read before the content and not drawn, so the content need not repeat it. Also its name in the Window menu. */
12
+ readonly label: string
13
+ /** What it shows. With `onSelect` the whole widget is a button, so no controls in here. */
14
+ readonly content: ReactNode
15
+ /** What a click does: open the window it is about. Without it the widget only shows. */
16
+ readonly onSelect?: () => void
17
+ /** Said politely when it changes. Nothing is said without it, however often the content changes. */
18
+ readonly announce?: string
19
+ }
20
+
21
+ export type WidgetCorner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
22
+
23
+ /*
24
+ * Which widgets the person keeps in front of the windows: their choice, remembered in this browser under
25
+ * `desk.widgets.<id>`, as a split remembers its size. Behind is the default, so only "front" is written.
26
+ */
27
+ const storageKey = (id: string) => `desk.widgets.${id}`
28
+ const listeners = new Set<() => void>()
29
+ let version = 0
30
+
31
+ const changed = () => {
32
+ version++
33
+ listeners.forEach(listener => listener())
34
+ }
35
+
36
+ /** Whether the person has asked for this widget to stay in front of the windows. */
37
+ export function isWidgetInFront(id: string): boolean {
38
+ try {
39
+ return globalThis.localStorage?.getItem(storageKey(id)) === 'front'
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ /** Keeps a widget in front of the windows, or sends it back behind them, and remembers which. */
46
+ export function setWidgetInFront(id: string, front: boolean): void {
47
+ try {
48
+ if (front) globalThis.localStorage?.setItem(storageKey(id), 'front')
49
+ else globalThis.localStorage?.removeItem(storageKey(id))
50
+ } catch {
51
+ // Private windows and full storage: it still comes forward, just not after a reload.
52
+ }
53
+ changed()
54
+ }
55
+
56
+ // Another tab of the same app ticking one.
57
+ const fromAnotherTab = (event: StorageEvent) => {
58
+ if (event.key === null || event.key.startsWith('desk.widgets.')) changed()
59
+ }
60
+
61
+ function subscribe(listener: () => void) {
62
+ if (listeners.size === 0 && typeof window !== 'undefined') window.addEventListener('storage', fromAnotherTab)
63
+ listeners.add(listener)
64
+ return () => {
65
+ listeners.delete(listener)
66
+ if (listeners.size === 0 && typeof window !== 'undefined') window.removeEventListener('storage', fromAnotherTab)
67
+ }
68
+ }
69
+
70
+ /** Re-renders when a widget is brought in front or sent back, here or in another tab; returns `isWidgetInFront`. */
71
+ export function useWidgetsInFront(): (id: string) => boolean {
72
+ const now = useSyncExternalStore(subscribe, () => version, () => -1)
73
+ // A new function each time the answer may have changed, so it can be a dependency.
74
+ return useCallback((id: string) => now >= 0 && isWidgetInFront(id), [now])
75
+ }
76
+
77
+ export interface WidgetsProps {
78
+ readonly widgets: readonly Widget[]
79
+ readonly corner: WidgetCorner
80
+ }
81
+
82
+ const overlaps = (a: DOMRect, b: DOMRect) =>
83
+ a.width > 0 && a.height > 0 && b.width > 0 && b.height > 0 &&
84
+ a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
85
+
86
+ const sameSet = (a: ReadonlySet<string>, b: ReadonlySet<string>) => a.size === b.size && [...a].every(id => b.has(id))
87
+
88
+ /** Drawn by `Desktop`, inside the stage: that is what keeps them clear of the dock on every side. */
89
+ export function Widgets({ widgets, corner }: WidgetsProps) {
90
+ const desk = useDesk()
91
+ const inFront = useWidgetsInFront()
92
+ const box = useRef<HTMLDivElement>(null)
93
+ const list = useRef<HTMLDivElement>(null)
94
+ /*
95
+ * Behind the windows, a widget a window covers is out of reach: inert, so Tab and a screen reader pass
96
+ * it by as the eye does. One the desk shows, with no window over it, can still be clicked and tabbed to.
97
+ */
98
+ const [covered, setCovered] = useState<ReadonlySet<string>>(() => new Set())
99
+ const reachable = (id: string) => inFront(id) || !covered.has(id)
100
+ // One tab stop: the widget last focused while it is there to press, else the first that can be.
101
+ const [current, setCurrent] = useState<string | null>(null)
102
+ /*
103
+ * Those kept in front stand nearest the corner, the rest beyond them, in the order given otherwise: so
104
+ * the room Arrange leaves the ones in front holds none behind, and a widget behind is never half out
105
+ * from under a window. The document follows the order drawn, so Tab and the arrows do too.
106
+ */
107
+ const top = !corner.startsWith('bottom')
108
+ const ordered = [...widgets.filter(w => inFront(w.id) === top), ...widgets.filter(w => inFront(w.id) !== top)]
109
+ const stops = ordered.filter(w => w.onSelect && reachable(w.id)).map(w => w.id)
110
+ const stop = current !== null && stops.includes(current) ? current : stops[0]
111
+
112
+ const focusWindow = () => {
113
+ const key = focusedId(desk.getState())
114
+ const window = key === null ? null : windowElement(document, key)
115
+ if (window instanceof HTMLElement) window.focus({ preventScroll: true })
116
+ }
117
+ const buttons = () => [...(list.current?.querySelectorAll<HTMLButtonElement>(':scope > button:not([inert])') ?? [])]
118
+
119
+ // Which widgets are under a window: measured after every render, and whenever the desk changes size.
120
+ const measure = () => {
121
+ const element = list.current
122
+ const stage = element?.closest(`[${STAGE_ATTRIBUTE}]`)
123
+ if (!element || !stage) return
124
+ const windows = [...stage.querySelectorAll(`[${WINDOW_ATTRIBUTE}]:not([data-hidden])`)].map(w => w.getBoundingClientRect())
125
+ const next = new Set<string>()
126
+ for (const child of element.querySelectorAll<HTMLElement>(':scope > [data-widget]')) {
127
+ const box = child.getBoundingClientRect()
128
+ if (windows.some(w => overlaps(box, w))) next.add(child.dataset.widget as string)
129
+ }
130
+ // A window came over the widget that had the keyboard: it goes to the key window, not to nowhere.
131
+ const holder = document.activeElement?.closest<HTMLElement>('[data-widget]')?.dataset.widget
132
+ if (holder !== undefined && next.has(holder) && !inFront(holder) && element.contains(document.activeElement)) focusWindow()
133
+ setCovered(was => (sameSet(was, next) ? was : next))
134
+ }
135
+ const latest = useRef(measure)
136
+ latest.current = measure
137
+ useLayoutEffect(() => latest.current())
138
+ const shown = widgets.length > 0
139
+ useLayoutEffect(() => {
140
+ if (!shown || !box.current || typeof ResizeObserver === 'undefined') return undefined
141
+ const observer = new ResizeObserver(() => latest.current())
142
+ observer.observe(box.current)
143
+ return () => observer.disconnect()
144
+ }, [shown])
145
+
146
+ // Taken away while it had the keyboard, a widget hands it to the one after it, the one before, or the key window.
147
+ const held = useRef<string | null>(null)
148
+ const order = ordered.map(w => w.id)
149
+ const before = useRef(order)
150
+ useLayoutEffect(() => {
151
+ const was = before.current
152
+ before.current = order
153
+ const id = held.current
154
+ if (id === null || list.current?.contains(document.activeElement)) return
155
+ held.current = null
156
+ // Something else has taken focus already: a dialog the widget opened.
157
+ if (document.activeElement && document.activeElement !== document.body) return
158
+ const at = was.indexOf(id)
159
+ const next = [...was.slice(at + 1), ...was.slice(0, at).reverse()].find(other => stops.includes(other))
160
+ if (next === undefined) focusWindow()
161
+ else buttons()[stops.indexOf(next)]?.focus({ preventScroll: true })
162
+ })
163
+
164
+ const onKeyDown = (event: KeyboardEvent) => {
165
+ if (event.altKey || event.ctrlKey || event.metaKey) return
166
+ // Escape goes back to the key window, from a control in the content too, though not from something that control opened elsewhere.
167
+ if (event.key === 'Escape' && event.currentTarget.contains(event.target as Node)) return focusWindow()
168
+ const all = buttons()
169
+ const at = all.indexOf(event.target as HTMLButtonElement)
170
+ if (at < 0) return
171
+ const next =
172
+ event.key === 'ArrowDown' ? all[(at + 1) % all.length]
173
+ : event.key === 'ArrowUp' ? all[(at - 1 + all.length) % all.length]
174
+ : event.key === 'Home' ? all[0]
175
+ : event.key === 'End' ? all.at(-1)
176
+ : undefined
177
+ if (!next) return
178
+ event.preventDefault()
179
+ next.focus()
180
+ }
181
+
182
+ const onBlur = ({ target }: FocusEvent) => {
183
+ // Another tab or application came forward: this still has the keyboard when the browser comes back.
184
+ if (document.activeElement === target) return
185
+ held.current = null
186
+ // The desk was made too small to show them.
187
+ if (target.checkVisibility?.() === false) focusWindow()
188
+ }
189
+
190
+ if (!widgets.length) return null
191
+ return (
192
+ <div ref={box} className="desk-widgets" data-corner={corner}>
193
+ <div
194
+ ref={list}
195
+ className="desk-widget-list"
196
+ role={stops.length ? 'toolbar' : 'group'}
197
+ aria-label="Widgets"
198
+ aria-orientation={stops.length ? 'vertical' : undefined}
199
+ onKeyDown={onKeyDown}
200
+ onBlur={onBlur}
201
+ >
202
+ {ordered.map(({ id, label, content, onSelect }) => {
203
+ const shared = {
204
+ 'data-widget': id,
205
+ 'data-front': inFront(id) || undefined,
206
+ inert: !reachable(id) || undefined,
207
+ }
208
+ return onSelect ? (
209
+ <button
210
+ key={id}
211
+ type="button"
212
+ className="desk-widget"
213
+ {...shared}
214
+ tabIndex={id === stop ? 0 : -1}
215
+ onFocus={() => {
216
+ held.current = id
217
+ setCurrent(id)
218
+ }}
219
+ onClick={() => onSelect()}
220
+ >
221
+ {/* Before the content rather than an aria-label, which would hide what the widget is showing. */}
222
+ <span className="desk-widget-unseen">{label}</span>{' '}
223
+ <span className="desk-widget-surface">{content}</span>
224
+ </button>
225
+ ) : (
226
+ <div key={id} className="desk-widget" {...shared} role="group" aria-label={label} onFocus={() => (held.current = id)}>
227
+ <div className="desk-widget-surface">{content}</div>
228
+ </div>
229
+ )
230
+ })}
231
+ </div>
232
+ {/* Apart from what is drawn, which changes too often to be read out. Always there, as a region that arrives with its words is not heard. */}
233
+ <div className="desk-widget-unseen" aria-live="polite">
234
+ {widgets.map(({ id, announce }) => announce && <p key={id}>{announce}</p>)}
235
+ </div>
236
+ </div>
237
+ )
238
+ }
239
+
240
+ /**
241
+ * The corner of the stage that Arrange leaves to the widgets kept in front, in stage coordinates: from the
242
+ * stage's corner to the far side of the last one, and a gap beyond. `null` when none is in front, or shown.
243
+ */
244
+ export function widgetsKeptClear(stage: HTMLElement, gap: number): Frame | null {
245
+ const box = stage.querySelector<HTMLElement>(':scope > .desk-widgets')
246
+ const drawn = (selector: string) =>
247
+ [...(box?.querySelectorAll<HTMLElement>(selector) ?? [])].map(w => w.getBoundingClientRect()).filter(r => r.width > 0 && r.height > 0)
248
+ const front = drawn('.desk-widget[data-front]')
249
+ const behind = drawn('.desk-widget:not([data-front])')
250
+ if (!box || !front.length) return null
251
+ const origin = stage.getBoundingClientRect()
252
+ const corner = box.dataset.corner ?? 'top-right'
253
+ const left = Math.min(...front.map(r => r.left)) - origin.left - gap
254
+ const right = Math.max(...front.map(r => r.right)) - origin.left + gap
255
+ const [first, last] = [Math.min(...front.map(r => r.top)), Math.max(...front.map(r => r.bottom))]
256
+ // No further than the widgets behind, which stand beyond them: the windows then cover those whole.
257
+ const top = Math.max(first - gap, ...behind.map(r => r.bottom).filter(edge => edge <= first)) - origin.top
258
+ const bottom = Math.min(last + gap, ...behind.map(r => r.top).filter(edge => edge >= last)) - origin.top
259
+ const [vertical, horizontal] = corner.split('-')
260
+ const x = horizontal === 'left' ? 0 : Math.max(0, left)
261
+ const y = vertical === 'top' ? 0 : Math.max(0, top)
262
+ const width = horizontal === 'left' ? right : stage.clientWidth - x
263
+ const height = vertical === 'top' ? bottom : stage.clientHeight - y
264
+ return { x, y, width, height }
265
+ }