@liberation-data/desk 0.45.0 → 0.47.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 (84) hide show
  1. package/README.md +73 -7
  2. package/dist/core/hosted.d.ts +39 -1
  3. package/dist/core/hosted.d.ts.map +1 -1
  4. package/dist/core/hosted.js +44 -0
  5. package/dist/core/hosted.js.map +1 -1
  6. package/dist/core/index.d.ts +5 -3
  7. package/dist/core/index.d.ts.map +1 -1
  8. package/dist/core/index.js +3 -2
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/swipe.d.ts +15 -0
  11. package/dist/core/swipe.d.ts.map +1 -0
  12. package/dist/core/swipe.js +77 -0
  13. package/dist/core/swipe.js.map +1 -0
  14. package/dist/core/theme.d.ts +15 -0
  15. package/dist/core/theme.d.ts.map +1 -1
  16. package/dist/core/theme.js +73 -1
  17. package/dist/core/theme.js.map +1 -1
  18. package/dist/css/shell.css +89 -0
  19. package/dist/host/checkTheme.d.ts +2 -7
  20. package/dist/host/checkTheme.d.ts.map +1 -1
  21. package/dist/host/checkTheme.js +3 -27
  22. package/dist/host/checkTheme.js.map +1 -1
  23. package/dist/host/router.d.ts +17 -4
  24. package/dist/host/router.d.ts.map +1 -1
  25. package/dist/host/router.js +94 -2
  26. package/dist/host/router.js.map +1 -1
  27. package/dist/react/Desktop.d.ts.map +1 -1
  28. package/dist/react/Desktop.js +5 -0
  29. package/dist/react/Desktop.js.map +1 -1
  30. package/dist/react/context.d.ts +6 -1
  31. package/dist/react/context.d.ts.map +1 -1
  32. package/dist/react/context.js +5 -3
  33. package/dist/react/context.js.map +1 -1
  34. package/dist/react/hostApp.d.ts +3 -1
  35. package/dist/react/hostApp.d.ts.map +1 -1
  36. package/dist/react/hostApp.js +3 -2
  37. package/dist/react/hostApp.js.map +1 -1
  38. package/dist/react/hosted.d.ts +10 -3
  39. package/dist/react/hosted.d.ts.map +1 -1
  40. package/dist/react/hosted.js +68 -8
  41. package/dist/react/hosted.js.map +1 -1
  42. package/dist/react/shell.d.ts +3 -1
  43. package/dist/react/shell.d.ts.map +1 -1
  44. package/dist/react/shell.js +2 -2
  45. package/dist/react/shell.js.map +1 -1
  46. package/dist/shell/HostOverview.d.ts +41 -0
  47. package/dist/shell/HostOverview.d.ts.map +1 -0
  48. package/dist/shell/HostOverview.js +219 -0
  49. package/dist/shell/HostOverview.js.map +1 -0
  50. package/dist/shell/HostShell.d.ts +3 -1
  51. package/dist/shell/HostShell.d.ts.map +1 -1
  52. package/dist/shell/HostShell.js +6 -4
  53. package/dist/shell/HostShell.js.map +1 -1
  54. package/dist/shell/index.d.ts +6 -0
  55. package/dist/shell/index.d.ts.map +1 -1
  56. package/dist/shell/index.js +3 -0
  57. package/dist/shell/index.js.map +1 -1
  58. package/dist/shell/swipe.d.ts +60 -0
  59. package/dist/shell/swipe.d.ts.map +1 -0
  60. package/dist/shell/swipe.js +158 -0
  61. package/dist/shell/swipe.js.map +1 -0
  62. package/dist/shell/zoom.d.ts +62 -0
  63. package/dist/shell/zoom.d.ts.map +1 -0
  64. package/dist/shell/zoom.js +116 -0
  65. package/dist/shell/zoom.js.map +1 -0
  66. package/llms.txt +14 -5
  67. package/package.json +12 -7
  68. package/src/core/hosted.ts +70 -1
  69. package/src/core/index.ts +5 -2
  70. package/src/core/swipe.ts +101 -0
  71. package/src/core/theme.ts +69 -1
  72. package/src/css/shell.css +89 -0
  73. package/src/host/checkTheme.ts +3 -25
  74. package/src/host/router.ts +100 -6
  75. package/src/react/Desktop.tsx +6 -0
  76. package/src/react/context.tsx +9 -2
  77. package/src/react/hostApp.tsx +3 -2
  78. package/src/react/hosted.tsx +68 -8
  79. package/src/react/shell.tsx +4 -2
  80. package/src/shell/HostOverview.tsx +317 -0
  81. package/src/shell/HostShell.tsx +8 -5
  82. package/src/shell/index.ts +20 -0
  83. package/src/shell/swipe.ts +202 -0
  84. package/src/shell/zoom.ts +151 -0
@@ -0,0 +1,317 @@
1
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
2
+ import type { KeyboardEvent } from 'react'
3
+ import { applyTheme } from '../core/theme.js'
4
+ import type { DeskTheme } from '../core/theme.js'
5
+ import type { ShellInsets, ShellWorkspace } from './HostShell.js'
6
+ import { animate, linear, pageClock } from './motion.js'
7
+ import type { Animation } from './motion.js'
8
+ import { CAPTURE_WAIT_MS, overviewTiles, planZoom, poseAt } from './zoom.js'
9
+ import type { OverviewPose } from './zoom.js'
10
+
11
+ /*
12
+ * THE OVERVIEW, AND SWITCHING THROUGH IT.
13
+ *
14
+ * Drawn on an overlay over the apps' live views: in an app host, its own transparent view on top
15
+ * (the window's page under the views gets no frames while they cover it); in a page, a layer over the
16
+ * desktop area. The host asks for a move with `request` and does what the overlay says:
17
+ *
18
+ * onWantCapture(id) capture this workspace's view now and pass the picture back in `snapshots`;
19
+ * return a promise of it too, and it counts even when it is the same picture
20
+ * as last time (a still workspace captures byte for byte the same)
21
+ * onCover() the overlay now covers the desktop: the live views under it may be hidden
22
+ * onArrive(id) a full-size picture of this workspace is showing: swap its live view in, then
23
+ * clear `request`
24
+ *
25
+ * Input to first motion is kept short: the fog starts fading in at once, the tiles already held are
26
+ * used, and only the current workspace is captured, waited for at most CAPTURE_WAIT_MS.
27
+ */
28
+
29
+ export type OverviewRequest = { readonly kind: 'open' } | { readonly kind: 'switch'; readonly to: string }
30
+
31
+ export interface HostOverviewProps {
32
+ /** In the switcher's order. */
33
+ readonly workspaces: readonly ShellWorkspace[]
34
+ readonly current: string
35
+ /** A picture of each workspace, by id: URLs or `data:` URIs. A live one without one shows a note. */
36
+ readonly snapshots?: Readonly<Record<string, string>>
37
+ /** What to do; a new object starts a new move, null clears the overlay. */
38
+ readonly request: OverviewRequest | null
39
+ readonly theme?: DeskTheme | null
40
+ /** Where the desktop area is, when the overlay shares the page with the chrome. */
41
+ readonly insets?: ShellInsets
42
+ /** False when the window can't be seen (covered, minimised, another desktop): moves jump. */
43
+ readonly visible?: boolean
44
+ /** Less motion: every move a short fade in place. Read from the system when left out. */
45
+ readonly reducedMotion?: boolean
46
+ /**
47
+ * A pose to hold instead of moving: what a gesture that drives the overview by hand draws each frame,
48
+ * or a still for a picture. `request` is ignored while it is set.
49
+ */
50
+ readonly pose?: OverviewPose
51
+ /**
52
+ * Capture this workspace now and pass the picture in `snapshots`, which the tiles draw. Return a promise
53
+ * of its URL as well to say when it is ready: a picture identical to the last one is still fresh, and a
54
+ * rejected one goes on with the picture held. Returning nothing, the overlay watches `snapshots` for a
55
+ * changed picture instead, which an unchanged workspace never gives, so it waits out CAPTURE_WAIT_MS.
56
+ */
57
+ readonly onWantCapture?: (id: string) => void | PromiseLike<string | void>
58
+ readonly onCover?: () => void
59
+ readonly onArrive: (id: string) => void
60
+ }
61
+
62
+ const CLOSED: OverviewPose = { zoom: 0, centre: 0, fog: 0, opacity: 1 }
63
+ const NONE: ShellInsets = { top: 0, right: 0, bottom: 0, left: 0 }
64
+
65
+ const prefersLessMotion = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
66
+ const pageHidden = () => typeof document !== 'undefined' && document.visibilityState === 'hidden'
67
+
68
+ /** Resolves once a picture is decoded and ready to draw without a blank frame, or after `ms` regardless. */
69
+ function decoded(url: string | undefined, ms: number): Promise<void> {
70
+ if (!url || typeof Image === 'undefined') return Promise.resolve()
71
+ const image = new Image()
72
+ image.src = url
73
+ const decode = typeof image.decode === 'function' ? image.decode().catch(() => {}) : Promise.resolve()
74
+ let timer: ReturnType<typeof setTimeout> | undefined
75
+ return Promise.race([decode, new Promise<void>(resolve => (timer = setTimeout(resolve, ms)))]).finally(() => clearTimeout(timer))
76
+ }
77
+
78
+ export function HostOverview(props: HostOverviewProps) {
79
+ const { workspaces, current, snapshots = {}, request, theme, insets = NONE } = props
80
+ useLayoutEffect(() => {
81
+ if (theme) applyTheme(theme)
82
+ }, [theme])
83
+
84
+ const indexOf = (id: string) => Math.max(0, workspaces.findIndex(w => w.id === id))
85
+ const latest = useRef(props)
86
+ latest.current = props
87
+
88
+ const layer = useRef<HTMLDivElement>(null)
89
+ const fog = useRef<HTMLDivElement>(null)
90
+ const tiles = useRef<(HTMLButtonElement | null)[]>([])
91
+ const pose = useRef<OverviewPose>({ ...CLOSED, centre: indexOf(current) })
92
+ const running = useRef<Animation | null>(null)
93
+ const [open, setOpen] = useState(false)
94
+ const [said, setSaid] = useState('')
95
+ const captured = useRef<(() => void) | null>(null)
96
+ // Whether onCover has been said since the overlay last cleared: a move asked for mid-flight carries on.
97
+ const covered = useRef(false)
98
+ // Where the focus was before the overlay, to give it back when it clears.
99
+ const returnTo = useRef<HTMLElement | null>(null)
100
+
101
+ /** Draws a pose: writes transforms and opacities straight to the tiles, which the compositor moves. */
102
+ const paint = (at: OverviewPose) => {
103
+ pose.current = at
104
+ const width = layer.current?.clientWidth || 1
105
+ if (fog.current) fog.current.style.opacity = String(at.fog)
106
+ overviewTiles(workspaces.length, at, width).forEach((place, i) => {
107
+ const tile = tiles.current[i]
108
+ if (!tile) return
109
+ tile.style.transform = `translate3d(${place.x}px, 0, ${place.z}px) scale(${place.scale})`
110
+ tile.style.opacity = String(place.opacity * at.opacity)
111
+ tile.style.zIndex = String(place.layer)
112
+ tile.style.setProperty('--desk-overview-depth', String(at.zoom))
113
+ })
114
+ }
115
+
116
+ /** Runs a move to a pose, from where things stand. */
117
+ const move = (to: OverviewPose, reduced: boolean): Promise<'finished' | 'jumped' | 'stopped'> => {
118
+ running.current?.stop()
119
+ const plan = planZoom(pose.current, to, reduced)
120
+ if (!plan.phases.length || pageHidden() || latest.current.visible === false) {
121
+ paint(to)
122
+ return Promise.resolve('jumped')
123
+ }
124
+ const run = animate({ durationMs: plan.durationMs, curve: linear(plan.durationMs), step: p => paint(poseAt(plan, p * plan.durationMs)), clock: pageClock() })
125
+ running.current = run
126
+ return run.done
127
+ }
128
+
129
+ useLayoutEffect(() => {
130
+ if (props.pose) paint(props.pose)
131
+ })
132
+
133
+ // A fresh capture of the current workspace has come in.
134
+ useEffect(() => {
135
+ captured.current?.()
136
+ }, [snapshots[current]])
137
+
138
+ useLayoutEffect(() => {
139
+ if (!request || props.pose) {
140
+ running.current?.stop()
141
+ covered.current = false
142
+ setOpen(false)
143
+ setSaid('')
144
+ pose.current = { ...CLOSED, centre: indexOf(current) }
145
+ if (document.activeElement === document.body) returnTo.current?.focus()
146
+ returnTo.current = null
147
+ return
148
+ }
149
+ returnTo.current ??= document.activeElement as HTMLElement | null
150
+ // A move asked for while the overview is open: the tiles take no clicks on the way.
151
+ setOpen(false)
152
+ let cancelled = false
153
+ const cover = () => {
154
+ if (covered.current) return
155
+ covered.current = true
156
+ latest.current.onCover?.()
157
+ }
158
+ const reduced = latest.current.reducedMotion ?? prefersLessMotion()
159
+ const jump = pageHidden() || latest.current.visible === false
160
+ const here = indexOf(current)
161
+ const target = request.kind === 'switch' ? indexOf(request.to) : here
162
+
163
+ // A switch with nothing to see, or a reduced-motion switch, needs no capture of where we are.
164
+ if (request.kind === 'switch' && (jump || reduced)) {
165
+ // A jump waits a microtask too, after any cleanup, so StrictMode's rerun arrives once.
166
+ if (!jump) paint({ zoom: 0, centre: target, fog: 0, opacity: 0 })
167
+ void (jump ? Promise.resolve() : move({ zoom: 0, centre: target, fog: 0, opacity: 1 }, true)).then(() => {
168
+ if (cancelled) return
169
+ cover()
170
+ latest.current.onArrive(request.to)
171
+ })
172
+ return () => void (cancelled = true)
173
+ }
174
+
175
+ // Asked mid-flight, the views are already covered: carry on from where the tiles are, no capture.
176
+ const already = covered.current
177
+ // First motion at once: the fog starts coming in while the current workspace is captured.
178
+ if (!already) paint({ zoom: 0, centre: here, fog: 0, opacity: 0 })
179
+ const haze = jump || reduced || already ? null : animate({ durationMs: CAPTURE_WAIT_MS, curve: linear(CAPTURE_WAIT_MS), step: p => paint({ ...pose.current, fog: p * 0.6 }) })
180
+ const before = latest.current.snapshots?.[current]
181
+ let waiting: ReturnType<typeof setTimeout> | undefined
182
+ let given: string | undefined
183
+ const fresh = already
184
+ ? Promise.resolve()
185
+ : new Promise<void>(resolve => {
186
+ captured.current = () => {
187
+ if (latest.current.snapshots?.[current] !== before) resolve()
188
+ }
189
+ waiting = setTimeout(resolve, CAPTURE_WAIT_MS)
190
+ const answer = latest.current.onWantCapture?.(current)
191
+ if (answer && typeof answer.then === 'function') {
192
+ answer.then(
193
+ url => {
194
+ if (typeof url === 'string') given = url
195
+ resolve()
196
+ },
197
+ () => resolve(),
198
+ )
199
+ }
200
+ })
201
+
202
+ void fresh
203
+ .then(() => (already ? undefined : decoded(given ?? latest.current.snapshots?.[current], CAPTURE_WAIT_MS)))
204
+ .then(async () => {
205
+ if (cancelled) return
206
+ haze?.stop()
207
+ captured.current = null
208
+ if (!reduced && !already) {
209
+ // The picture exactly over the live view: nothing changes on screen, and the views can go.
210
+ paint({ ...pose.current, opacity: 1 })
211
+ cover()
212
+ }
213
+ if (request.kind === 'switch') {
214
+ await move({ zoom: 0, centre: target, fog: 1, opacity: 1 }, false)
215
+ if (!cancelled) latest.current.onArrive(request.to)
216
+ return
217
+ }
218
+ await move({ zoom: 1, centre: here, fog: 1, opacity: 1 }, reduced)
219
+ if (cancelled) return
220
+ cover()
221
+ setOpen(true)
222
+ setSaid(`Overview, ${workspaces.length} workspaces`)
223
+ })
224
+ return () => {
225
+ cancelled = true
226
+ haze?.stop()
227
+ running.current?.stop()
228
+ clearTimeout(waiting)
229
+ captured.current = null
230
+ }
231
+ // A new request object is a new move; the rest is read when it starts.
232
+ }, [request, Boolean(props.pose)])
233
+
234
+ // Once the tiles can take it, the focus goes to the current one.
235
+ useEffect(() => {
236
+ if (open) tiles.current[indexOf(latest.current.current)]?.focus()
237
+ }, [open])
238
+
239
+ const reduced = () => latest.current.reducedMotion ?? prefersLessMotion()
240
+ const choose = (i: number) => {
241
+ if (!open) return
242
+ setOpen(false)
243
+ const id = workspaces[i]!.id
244
+ // Cleared or replaced on the way (the move stopped): the host has moved on, so no arrival.
245
+ void move({ zoom: 0, centre: i, fog: 1, opacity: 1 }, reduced()).then(how => how !== 'stopped' && latest.current.onArrive(id))
246
+ }
247
+
248
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
249
+ if (!open) return
250
+ const index = tiles.current.indexOf(document.activeElement as HTMLButtonElement)
251
+ if (event.key === 'Escape') {
252
+ event.preventDefault()
253
+ return choose(indexOf(current))
254
+ }
255
+ const next =
256
+ event.key === 'ArrowRight' ? Math.min(index + 1, workspaces.length - 1)
257
+ : event.key === 'ArrowLeft' ? Math.max(index - 1, 0)
258
+ : event.key === 'Home' ? 0
259
+ : event.key === 'End' ? workspaces.length - 1
260
+ : null
261
+ if (next === null || index < 0) return
262
+ event.preventDefault()
263
+ // The one Tab stop goes with the focus, as in the switcher.
264
+ tiles.current.forEach((tile, i) => tile && (tile.tabIndex = i === next ? 0 : -1))
265
+ tiles.current[next]?.focus()
266
+ // The row follows the focus, so the chosen tile comes to the centre.
267
+ void move({ ...pose.current, zoom: 1, centre: next }, false)
268
+ }
269
+
270
+ if (!request && !props.pose) return null
271
+ return (
272
+ <div
273
+ ref={layer}
274
+ className="desk-overview"
275
+ style={{ top: insets.top, right: insets.right, bottom: insets.bottom, left: insets.left }}
276
+ role="dialog"
277
+ aria-label="Overview"
278
+ aria-modal={open || undefined}
279
+ onKeyDown={onKeyDown}
280
+ >
281
+ <div ref={fog} className="desk-overview-fog" />
282
+ {workspaces.map((w, i) => {
283
+ const picture = snapshots[w.id]
284
+ return (
285
+ <button
286
+ key={w.id}
287
+ ref={el => void (tiles.current[i] = el)}
288
+ type="button"
289
+ className="desk-overview-tile"
290
+ tabIndex={open && i === indexOf(current) ? 0 : -1}
291
+ aria-current={w.id === current ? 'true' : undefined}
292
+ aria-label={w.title}
293
+ disabled={!open}
294
+ data-state={w.state}
295
+ onClick={() => choose(i)}
296
+ >
297
+ <span className="desk-overview-shadow" aria-hidden="true" />
298
+ {picture ? (
299
+ <img src={picture} alt="" draggable={false} />
300
+ ) : (
301
+ <span className="desk-overview-note" aria-hidden="true">
302
+ <strong>{w.title}</strong>
303
+ {w.state === 'live' ? 'Live' : null}
304
+ </span>
305
+ )}
306
+ <span className="desk-overview-title" aria-hidden="true">
307
+ {w.title}
308
+ </span>
309
+ </button>
310
+ )
311
+ })}
312
+ <div className="desk-shell-announce" role="status" aria-live="polite">
313
+ {said}
314
+ </div>
315
+ </div>
316
+ )
317
+ }
@@ -66,8 +66,10 @@ export interface HostShellProps {
66
66
  readonly onInsets?: (insets: ShellInsets) => void
67
67
  /** The switching keys; the platform's defaults if left out, none at all with null. */
68
68
  readonly keys?: SwitchKeys | null
69
- /** How a click in the switcher switches. */
69
+ /** How a click in the switcher switches: through the overview by default; the keys always slide. */
70
70
  readonly clickSwitch?: SwitchHow
71
+ /** The overview key was pressed on this page; a host catches it first when an app has focus. */
72
+ readonly onOverview?: () => void
71
73
  readonly dockSide?: DockSide
72
74
  }
73
75
 
@@ -104,7 +106,7 @@ export function HostShell(props: HostShellProps) {
104
106
  )
105
107
  }
106
108
 
107
- function Shell({ workspaces, current, chrome, theme, onSwitch, onCommand, onInsets, keys, clickSwitch = 'slide', dockSide = 'left' }: HostShellProps) {
109
+ function Shell({ workspaces, current, chrome, theme, onSwitch, onCommand, onInsets, onOverview, keys, clickSwitch = 'zoom', dockSide = 'left' }: HostShellProps) {
108
110
  useLayoutEffect(() => {
109
111
  if (theme) applyTheme(theme)
110
112
  }, [theme])
@@ -129,14 +131,15 @@ function Shell({ workspaces, current, chrome, theme, onSwitch, onCommand, onInse
129
131
  if (!bound) return
130
132
  const onKey = (event: globalThis.KeyboardEvent) => {
131
133
  const action = switchKeyAction(event, bound)
132
- if (action !== 'previous' && action !== 'next') return
133
- const to = neighbour(workspaces, current, action)
134
+ if (!action) return
134
135
  event.preventDefault()
136
+ if (action === 'overview') return onOverview?.()
137
+ const to = neighbour(workspaces, current, action)
135
138
  if (to) onSwitch(to.id, 'slide')
136
139
  }
137
140
  window.addEventListener('keydown', onKey)
138
141
  return () => window.removeEventListener('keydown', onKey)
139
- }, [bound, workspaces, current, onSwitch])
142
+ }, [bound, workspaces, current, onSwitch, onOverview])
140
143
 
141
144
  const root = useRef<HTMLDivElement>(null)
142
145
  useInsets(root, dockSide, onInsets)
@@ -4,8 +4,28 @@
4
4
  * app does, and nothing in core or react imports it.
5
5
  */
6
6
  export { dockFromHost, HostShell } from './HostShell.js'
7
+ export { HostOverview } from './HostOverview.js'
8
+ export type { HostOverviewProps, OverviewRequest } from './HostOverview.js'
7
9
  export type { HostShellProps, ShellInsets, ShellWorkspace, SwitchHow } from './HostShell.js'
8
10
  export { neighbour, platformOf, switchKeyAction, switchKeys } from './keys.js'
9
11
  export type { KeyInput, ShellPlatform, SwitchKey, SwitchKeys } from './keys.js'
10
12
  export { animate, FADE_MS, linear, pageClock, SLIDE_MS, slideOffsets, slidePlan, spring, timerClock } from './motion.js'
11
13
  export type { Animation, AnimateOptions, FrameClock, SlideOffsets, SlidePlan } from './motion.js'
14
+ export {
15
+ CAPTURE_WAIT_MS,
16
+ cubicBezier,
17
+ easeIn,
18
+ easeInOut,
19
+ easeOut,
20
+ OVERVIEW_SCALE,
21
+ overviewTiles,
22
+ planZoom,
23
+ poseAt,
24
+ ZOOM_ACROSS_MS,
25
+ ZOOM_FADE_MS,
26
+ ZOOM_IN_MS,
27
+ ZOOM_OUT_MS,
28
+ } from './zoom.js'
29
+ export type { OverviewPose, TilePlace, ZoomPhase, ZoomPlan } from './zoom.js'
30
+ export { COMMIT_DISTANCE, COMMIT_SPEED, createSwipeController, swipeDecision, swipeProgress } from './swipe.js'
31
+ export type { SlideFrame, SwipeController, SwipeControllerOptions } from './swipe.js'
@@ -0,0 +1,202 @@
1
+ import type { AppGesture } from '../core/hosted.js'
2
+ import { animate, FADE_MS, linear, SLIDE_MS, slideOffsets, spring, timerClock } from './motion.js'
3
+ import type { Animation, FrameClock, SlideOffsets } from './motion.js'
4
+
5
+ /*
6
+ * THE SWIPE: FINGERS MOVE THE DESKTOPS, ONE TO ONE.
7
+ *
8
+ * The app in front passes on a two-finger swipe that started on its background; the host's router
9
+ * passes it here. While the fingers move, the desktops follow them exactly. When they lift, the
10
+ * swipe goes on to the next workspace if it went far enough or fast enough that way, or springs back
11
+ * if not, on part 1's spring, from where it is and as fast as it was going. A new swipe, or a key,
12
+ * catches a slide still settling and carries on from there.
13
+ *
14
+ * No DOM: a host's main process runs this and moves its views' bounds from each frame.
15
+ */
16
+
17
+ /** Past half the width, a released swipe goes on; short of it, it goes back. */
18
+ export const COMMIT_DISTANCE = 0.5
19
+ /** Faster than this, in widths a second, a flick goes on (or back) whatever the distance. */
20
+ export const COMMIT_SPEED = 0.5
21
+
22
+ /** Progress past the last workspace, or before the first, as a rubber band gives it: a little, and less the further. */
23
+ const rubber = (over: number) => (over * 0.15) / (over + 0.15)
24
+
25
+ /**
26
+ * Where the desktops are, as a signed progress (positive toward the next workspace), after `delta` px
27
+ * of a swipe that started at `start`. One to one, up to a whole workspace either way; where there is
28
+ * no workspace to go to, it gives only a little.
29
+ */
30
+ export function swipeProgress(start: number, delta: number, width: number, canPrevious: boolean, canNext: boolean): number {
31
+ const p = Math.max(-1, Math.min(1, start + delta / Math.max(1, width)))
32
+ if (p > 0 && !canNext) return rubber(p)
33
+ if (p < 0 && !canPrevious) return -rubber(-p)
34
+ return p
35
+ }
36
+
37
+ /**
38
+ * Where a released swipe settles: 1 for the next workspace, -1 the previous, 0 back where it started.
39
+ * A flick decides by its direction (one back toward the start goes back); a slow release by distance.
40
+ */
41
+ export function swipeDecision(progress: number, velocity: number, canPrevious: boolean, canNext: boolean): -1 | 0 | 1 {
42
+ const way = Math.abs(velocity) >= COMMIT_SPEED ? (progress === 0 || Math.sign(velocity) === Math.sign(progress) ? Math.sign(velocity) : 0) : Math.abs(progress) >= COMMIT_DISTANCE ? Math.sign(progress) : 0
43
+ if ((way > 0 && !canNext) || (way < 0 && !canPrevious)) return 0
44
+ return way as -1 | 0 | 1
45
+ }
46
+
47
+ /** One frame of a slide, as the host draws it. */
48
+ export interface SlideFrame {
49
+ /** The workspace the slide started from. */
50
+ readonly from: number
51
+ /** The one coming in beside it; `from` while nothing is: at rest, or a rubber band past the first or last. */
52
+ readonly to: number
53
+ /** From 0 (`from` fills the desktop) toward 1 (`to` does). */
54
+ readonly progress: number
55
+ /** Where each desktop sits, in px from the desktop area's left edge. */
56
+ readonly offsets: SlideOffsets
57
+ /** Reduced motion: `to` fades in at its place over `from`, which stays put; this is its opacity. */
58
+ readonly fade?: number
59
+ }
60
+
61
+ export interface SwipeControllerOptions {
62
+ /** How many workspaces, and which is on screen, in the switcher's order. */
63
+ readonly count: () => number
64
+ readonly current: () => number
65
+ /** The desktop area's width, in px. */
66
+ readonly width: () => number
67
+ readonly reducedMotion?: () => boolean
68
+ /** Frames: a page's (`pageClock`), or a timer's in a main process (the default). */
69
+ readonly clock?: FrameClock
70
+ /** Draw this frame: move the views to its offsets. */
71
+ readonly frame: (frame: SlideFrame) => void
72
+ /** The slide has landed on this workspace: it is the current one now. */
73
+ readonly arrive: (index: number) => void
74
+ }
75
+
76
+ export interface SwipeController {
77
+ /** A gesture from the app in front, as the router passed it. */
78
+ gesture(gesture: AppGesture): void
79
+ /** Slides to a workspace, as the keys do: on the same spring, and as catchable. */
80
+ slideTo(index: number): void
81
+ /** Whether a swipe is under the fingers or a slide is settling. */
82
+ busy(): boolean
83
+ /**
84
+ * Stops a swipe or slide where it is, with no more frames and no `arrive`: for a host closing, or
85
+ * putting its views back itself. The rest of the swipe is ignored; the next starts from `current`.
86
+ */
87
+ stop(): void
88
+ }
89
+
90
+ /** Follows swipes and settles them; see the file's note. */
91
+ export function createSwipeController(options: SwipeControllerOptions): SwipeController {
92
+ const clock = options.clock ?? timerClock()
93
+ let anchor = -1
94
+ /** Signed progress from `anchor`, and the workspace on the other side while one is chosen. */
95
+ let p = 0
96
+ let other: number | null = null
97
+ let start = 0
98
+ let tracking = false
99
+ let running: Animation | null = null
100
+
101
+ const draw = (fade?: number) => {
102
+ // A rubber band past the first or last workspace has nothing beside it: `from` moves alone.
103
+ const next = anchor + Math.sign(p)
104
+ const to = other ?? (next >= 0 && next < options.count() ? next : anchor)
105
+ const way = to > anchor || (to === anchor && p >= 0) ? 1 : -1
106
+ const progress = Math.abs(p)
107
+ const offsets = slideOffsets(progress, way, options.width())
108
+ // Fading in, the arriving desktop is at its own place already.
109
+ options.frame({ from: anchor, to, progress, offsets: fade === undefined ? offsets : { ...offsets, arriving: 0 }, ...(fade === undefined ? {} : { fade }) })
110
+ }
111
+
112
+ /** Stops a settle where it is, so whatever comes next starts from there. */
113
+ const catchIt = () => {
114
+ if (running) running.stop(), (running = null)
115
+ if (anchor < 0) anchor = options.current()
116
+ }
117
+
118
+ const settle = (target: number, velocity: number, to: number | null) => {
119
+ const from = p
120
+ const goal = target === 0 ? 0 : Math.sign(target)
121
+ // Going on, the arriving desktop is chosen now: a flick from no distance has no side to draw it on yet.
122
+ other = to ?? (goal === 0 ? null : anchor + goal)
123
+ if (goal !== 0 && options.reducedMotion?.()) {
124
+ // Less motion: the arriving desktop fades in at its place; nothing slides on.
125
+ const run = animate({ durationMs: FADE_MS, curve: linear(FADE_MS), step: o => draw(o), clock })
126
+ running = run
127
+ return void run.done.then(how => how !== 'stopped' && running === run && land(goal))
128
+ }
129
+ const span = goal - from
130
+ if (Math.abs(span) < 1e-4) return land(goal)
131
+ // The spring runs from 0 to 1 along the span, starting as fast as the fingers were going.
132
+ const curve = spring(SLIDE_MS, 0, Math.max(-30, Math.min(30, velocity / span)))
133
+ const run = animate({ durationMs: SLIDE_MS, curve, step: u => ((p = from + span * u), draw()), clock })
134
+ running = run
135
+ // Stopped or caught as its last frame was drawn, it has ended, but it lands no more.
136
+ void run.done.then(how => how !== 'stopped' && running === run && land(goal))
137
+ }
138
+
139
+ const land = (goal: number) => {
140
+ running = null
141
+ const index = other ?? anchor + goal
142
+ // Home exactly, from however near it was let go.
143
+ if (goal === 0) (p = 0), draw()
144
+ // At rest before the host hears, so a slide it starts from `arrive` starts afresh.
145
+ rest()
146
+ if (goal !== 0) options.arrive(index)
147
+ }
148
+
149
+ const rest = () => {
150
+ anchor = -1
151
+ p = 0
152
+ other = null
153
+ }
154
+
155
+ return {
156
+ gesture(g) {
157
+ const count = options.count()
158
+ if (g.phase === 'begin') {
159
+ // A slide still settling stops where it is, and the fingers take it up from there, toward
160
+ // the workspace it was going to if they keep going that way.
161
+ catchIt()
162
+ start = p
163
+ tracking = true
164
+ return
165
+ }
166
+ if (!tracking) return
167
+ const width = options.width()
168
+ const towardOther = other !== null && Math.sign(other - anchor)
169
+ p = swipeProgress(start, g.delta, width, anchor > 0, anchor < count - 1)
170
+ // Back past where it started: whatever was beside it before is not the one beside it now.
171
+ if (towardOther !== false && Math.sign(p) !== towardOther) other = null
172
+ if (g.phase === 'move') return draw()
173
+ tracking = false
174
+ if (g.phase === 'cancel') return settle(0, 0, other)
175
+ const v = (g.velocity ?? 0) / Math.max(1, width)
176
+ const goal = swipeDecision(p, v, anchor > 0, anchor < count - 1)
177
+ settle(goal, v, goal === 0 ? other : other !== null && Math.sign(other - anchor) === goal ? other : null)
178
+ },
179
+
180
+ slideTo(index) {
181
+ if (tracking) return
182
+ const moving = running !== null
183
+ catchIt()
184
+ // Back to where it started, from wherever a caught slide had got to; with nothing moving, nothing
185
+ // to do, and the next swipe or key starts from whatever is current then.
186
+ if (index === anchor) return void (moving || p !== 0 ? settle(0, 0, other) : (anchor = -1))
187
+ // Toward the workspace asked for: from wherever a caught slide had got to, if it was going that way.
188
+ const way = Math.sign(index - anchor)
189
+ if (Math.sign(p) !== way) p = 0
190
+ settle(way, 0, index)
191
+ },
192
+
193
+ busy: () => tracking || running !== null,
194
+
195
+ stop() {
196
+ running?.stop()
197
+ running = null
198
+ tracking = false
199
+ rest()
200
+ },
201
+ }
202
+ }