@liberation-data/desk 0.40.1 → 0.42.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 (49) hide show
  1. package/README.md +61 -8
  2. package/dist/css/controls.css +21 -2
  3. package/dist/css/dock.css +1 -1
  4. package/dist/css/looks.css +50 -4
  5. package/dist/css/tokens.css +1 -0
  6. package/dist/css/windows.css +165 -6
  7. package/dist/desk.css +238 -13
  8. package/dist/react/Desktop.d.ts +12 -3
  9. package/dist/react/Desktop.d.ts.map +1 -1
  10. package/dist/react/Desktop.js +20 -10
  11. package/dist/react/Desktop.js.map +1 -1
  12. package/dist/react/MenuBar.d.ts +9 -2
  13. package/dist/react/MenuBar.d.ts.map +1 -1
  14. package/dist/react/MenuBar.js +15 -0
  15. package/dist/react/MenuBar.js.map +1 -1
  16. package/dist/react/arrange.d.ts +6 -0
  17. package/dist/react/arrange.d.ts.map +1 -1
  18. package/dist/react/arrange.js +21 -0
  19. package/dist/react/arrange.js.map +1 -1
  20. package/dist/react/hostMenu.d.ts +6 -0
  21. package/dist/react/hostMenu.d.ts.map +1 -1
  22. package/dist/react/hostMenu.js +1 -0
  23. package/dist/react/hostMenu.js.map +1 -1
  24. package/dist/react/index.d.ts +3 -1
  25. package/dist/react/index.d.ts.map +1 -1
  26. package/dist/react/index.js +2 -1
  27. package/dist/react/index.js.map +1 -1
  28. package/dist/react/tabs.d.ts +7 -1
  29. package/dist/react/tabs.d.ts.map +1 -1
  30. package/dist/react/tabs.js +13 -8
  31. package/dist/react/tabs.js.map +1 -1
  32. package/dist/react/widgets.d.ts +33 -0
  33. package/dist/react/widgets.d.ts.map +1 -0
  34. package/dist/react/widgets.js +213 -0
  35. package/dist/react/widgets.js.map +1 -0
  36. package/llms.txt +33 -7
  37. package/package.json +2 -2
  38. package/src/css/controls.css +21 -2
  39. package/src/css/dock.css +1 -1
  40. package/src/css/looks.css +50 -4
  41. package/src/css/tokens.css +1 -0
  42. package/src/css/windows.css +165 -6
  43. package/src/react/Desktop.tsx +33 -11
  44. package/src/react/MenuBar.tsx +20 -2
  45. package/src/react/arrange.ts +23 -0
  46. package/src/react/hostMenu.ts +7 -0
  47. package/src/react/index.ts +3 -1
  48. package/src/react/tabs.tsx +23 -10
  49. package/src/react/widgets.tsx +265 -0
@@ -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
+ }