@liberation-data/desk 0.36.1 → 0.38.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.
@@ -1,4 +1,5 @@
1
- import { useEffect, useId, useRef, useState } from 'react'
1
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
2
+ import { WINDOW_ATTRIBUTE } from '../core/commands.js'
2
3
  import type { KeyboardEvent, ReactNode } from 'react'
3
4
 
4
5
  /*
@@ -27,6 +28,9 @@ export interface PopUpButtonProps<T extends string> {
27
28
  readonly size?: 'regular' | 'small'
28
29
  }
29
30
 
31
+ /** How far the list keeps from its window's edges. */
32
+ const LIST_MARGIN = 8
33
+
30
34
  export function PopUpButton<T extends string>({
31
35
  value,
32
36
  onChange,
@@ -76,6 +80,24 @@ export function PopUpButton<T extends string>({
76
80
  return () => document.removeEventListener('pointerdown', onPointerDown, true)
77
81
  }, [open])
78
82
 
83
+ /*
84
+ * THE LIST IS AS WIDE AS ITS WIDEST OPTION, as a menu is, and not as narrow as the button: a short
85
+ * button over longer options wrapped every label in two. Wider than the button, it can reach past
86
+ * the window's right edge, so it moves left until it fits, never past the window's left edge.
87
+ */
88
+ useLayoutEffect(() => {
89
+ const element = list.current
90
+ const anchor = element?.parentElement
91
+ if (!open || !element || !anchor) return
92
+ element.style.left = ''
93
+ const frame = anchor.closest(`[${WINDOW_ATTRIBUTE}]`)?.getBoundingClientRect()
94
+ const right = (frame?.right ?? innerWidth) - LIST_MARGIN
95
+ const left = (frame?.left ?? 0) + LIST_MARGIN
96
+ const box = element.getBoundingClientRect()
97
+ const over = box.right - right
98
+ if (over > 0) element.style.left = `${-Math.min(over, Math.max(box.left - left, 0))}px`
99
+ }, [open])
100
+
79
101
  const step = (from: number, delta: 1 | -1) => {
80
102
  for (let i = 1; i <= options.length; i++) {
81
103
  const index = (from + delta * i + options.length * 2) % options.length
@@ -163,7 +185,7 @@ export function PopUpButton<T extends string>({
163
185
  >
164
186
  <span className="desk-popup-check" aria-hidden="true">{option.value === value ? '✓' : ''}</span>
165
187
  <span className="desk-popup-text">
166
- <span>{option.label}</span>
188
+ <span className="desk-popup-label">{option.label}</span>
167
189
  {option.description && <span className="desk-help">{option.description}</span>}
168
190
  </span>
169
191
  </li>
@@ -0,0 +1,161 @@
1
+ import { useRef, useState } from 'react'
2
+ import type { CSSProperties, KeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from 'react'
3
+
4
+ /*
5
+ * Two panels in one window, with the edge between them to drag: a list beside its detail, a picker
6
+ * beside the canvas it fills.
7
+ *
8
+ * They are one app, so they are one window: they open, close, minimize and move together, and
9
+ * nothing can pull them apart. Only the edge between them moves, and it is remembered, so the side
10
+ * panel opens at the width it was left at. Dragging things from one panel to the other is the
11
+ * ordinary drag and drop (`useDragSource`, `useDropTarget`), which does not care where its ends are.
12
+ */
13
+
14
+ export interface SplitProps {
15
+ /** The panel at the edge: a list, a picker, an outline. */
16
+ readonly side: ReactNode
17
+ /** The rest of the window: what the side panel chooses for. */
18
+ readonly children: ReactNode
19
+ /** Which edge the side panel stands at. Default `start`. */
20
+ readonly at?: 'start' | 'end'
21
+ /** The side panel's width, in px, until it is dragged. Default 280. */
22
+ readonly size?: number
23
+ /** The narrowest it can be dragged to. Default 200. */
24
+ readonly min?: number
25
+ /**
26
+ * The most of the window it may take, as CSS: `50%` (the default), `420px`. A width remembered from
27
+ * a big screen never leaves a small one without room for the rest.
28
+ */
29
+ readonly max?: string
30
+ /** Remembers the width in this browser under this key, so the panel opens at the width it was left at. */
31
+ readonly remember?: string
32
+ /** What the edge is called to assistive technology. Default "Resize". */
33
+ readonly label?: string
34
+ readonly className?: string
35
+ }
36
+
37
+ /** How far an arrow key moves the edge. */
38
+ const STEP = 16
39
+
40
+ const key = (name: string) => `desk.split.${name}`
41
+
42
+ function recall(name: string | undefined, fallback: number, min: number): number {
43
+ if (!name) return fallback
44
+ try {
45
+ const stored = Number(globalThis.localStorage?.getItem(key(name)))
46
+ // Storage is outside the program: anything that is not a usable width is none.
47
+ return Number.isFinite(stored) && stored >= min ? stored : fallback
48
+ } catch {
49
+ return fallback
50
+ }
51
+ }
52
+
53
+ function keep(name: string | undefined, width: number) {
54
+ if (!name) return
55
+ try {
56
+ globalThis.localStorage?.setItem(key(name), String(width))
57
+ } catch {
58
+ // Private windows and full storage: the panel still resizes, it just opens at its default.
59
+ }
60
+ }
61
+
62
+ export function Split({ side, children, at = 'start', size = 280, min = 200, max = '50%', remember, label = 'Resize', className }: SplitProps) {
63
+ const initial = Math.max(min, size)
64
+ const [width, setWidth] = useState(() => recall(remember, initial, min))
65
+ const root = useRef<HTMLDivElement>(null)
66
+ const panel = useRef<HTMLDivElement>(null)
67
+ const length = (px: number) => `min(${px}px, ${max})`
68
+
69
+ const commit = (next: number) => {
70
+ const clamped = Math.max(min, Math.round(next))
71
+ setWidth(clamped)
72
+ keep(remember, clamped)
73
+ }
74
+
75
+ /*
76
+ * While dragging, only the variable on this element changes, so the panels follow the pointer
77
+ * without re-rendering what is in them; the width is committed once, on release. It starts from
78
+ * the width as drawn, which `max` may have capped, so the edge never lags behind the pointer.
79
+ */
80
+ const startDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
81
+ if (event.button !== 0) return
82
+ event.preventDefault()
83
+ const handle = event.currentTarget
84
+ const element = root.current
85
+ const origin = panel.current?.getBoundingClientRect().width ?? width
86
+ const startX = event.clientX
87
+ let next = origin
88
+ handle.setPointerCapture?.(event.pointerId)
89
+ if (element) element.dataset.dragging = ''
90
+ const onMove = (move: PointerEvent) => {
91
+ // Towards the middle is wider, whichever edge the panel is at.
92
+ const pulled = at === 'start' ? move.clientX - startX : startX - move.clientX
93
+ next = Math.max(min, origin + pulled)
94
+ element?.style.setProperty('--desk-split-size', length(next))
95
+ }
96
+ const onUp = () => {
97
+ handle.removeEventListener('pointermove', onMove)
98
+ handle.removeEventListener('pointerup', onUp)
99
+ handle.removeEventListener('pointercancel', onUp)
100
+ if (element) delete element.dataset.dragging
101
+ // Back to what React drew, so the commit is what draws the new width, and a click draws nothing.
102
+ element?.style.setProperty('--desk-split-size', length(width))
103
+ if (Math.round(next) !== Math.round(origin)) commit(next)
104
+ }
105
+ handle.addEventListener('pointermove', onMove)
106
+ handle.addEventListener('pointerup', onUp)
107
+ handle.addEventListener('pointercancel', onUp)
108
+ }
109
+
110
+ // The edge is a separator that can be focused, so the width can be set without a pointer.
111
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
112
+ const wider = at === 'start' ? 'ArrowRight' : 'ArrowLeft'
113
+ const narrower = at === 'start' ? 'ArrowLeft' : 'ArrowRight'
114
+ const drawn = panel.current?.getBoundingClientRect().width || width
115
+ if (event.key === wider) commit(drawn + STEP)
116
+ else if (event.key === narrower) commit(drawn - STEP)
117
+ else if (event.key === 'Home') commit(min)
118
+ else if (event.key === 'Enter') commit(initial)
119
+ else return
120
+ event.preventDefault()
121
+ }
122
+
123
+ const sidePanel = (
124
+ <div key="side" ref={panel} className="desk-split-panel" data-side="">
125
+ {side}
126
+ </div>
127
+ )
128
+ const edge = (
129
+ <div
130
+ key="edge"
131
+ role="separator"
132
+ aria-orientation="vertical"
133
+ aria-label={label}
134
+ aria-valuenow={width}
135
+ aria-valuemin={min}
136
+ tabIndex={0}
137
+ className="desk-split-edge"
138
+ onPointerDown={startDrag}
139
+ onKeyDown={onKeyDown}
140
+ // Back to the width it started at, as a double-click on a divider does on a Mac.
141
+ onDoubleClick={() => commit(initial)}
142
+ />
143
+ )
144
+ const main = (
145
+ <div key="main" className="desk-split-panel">
146
+ {children}
147
+ </div>
148
+ )
149
+
150
+ return (
151
+ <div
152
+ ref={root}
153
+ className={['desk-split', className].filter(Boolean).join(' ')}
154
+ data-at={at}
155
+ style={{ '--desk-split-size': length(width) } as CSSProperties}
156
+ >
157
+ {/* In reading order, so Tab walks the panels the way they are drawn. */}
158
+ {at === 'start' ? [sidePanel, edge, main] : [main, edge, sidePanel]}
159
+ </div>
160
+ )
161
+ }