@liberation-data/desk 0.46.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.
package/src/core/index.ts CHANGED
@@ -27,6 +27,8 @@ export {
27
27
  } from './commands.js'
28
28
  export type { ChainOptions, CommandHandler, CommandId, CommandOptions } from './commands.js'
29
29
  export { createService, holdAll } from './services.js'
30
+ export { watchSwipes } from './swipe.js'
31
+ export type { SwipeOptions } from './swipe.js'
30
32
  export type { Holdable, Service, ServiceOptions, ServiceRun } from './services.js'
31
33
  export { attended, attentionOn, becomesNews, watchAttention } from './attention.js'
32
34
  export type { Attention } from './attention.js'
@@ -43,8 +45,9 @@ export { applyTheme, applyThemeBasics, appliedTheme } from './theme.js'
43
45
  export { drawnTheme, THEME_CHANGE, watchThemeChanges } from './themeChange.js'
44
46
  export type { ThemeChange } from './themeChange.js'
45
47
  export type { AppTheme, DeskTheme, ThemeFont } from './theme.js'
46
- export { connectHost, DESK_PROTOCOL, findDeskHost, isAppToHost, isDeskHostBridge, isHostToApp, THEME_TOPIC } from './hosted.js'
48
+ export { connectHost, DESK_PROTOCOL, findDeskHost, isAppGesture, isAppToHost, isDeskHostBridge, isHostToApp, THEME_TOPIC } from './hosted.js'
47
49
  export type {
50
+ AppGesture,
48
51
  AppToHost,
49
52
  Broadcast,
50
53
  BroadcastSender,
@@ -0,0 +1,101 @@
1
+ import { WINDOW_ATTRIBUTE } from './commands.js'
2
+ import type { AppGesture } from './hosted.js'
3
+
4
+ /*
5
+ * A TWO-FINGER SWIPE ON THE DESKTOP BACKGROUND.
6
+ *
7
+ * Chromium hands a page a trackpad's two-finger movement as wheel events, with no begin or end: a
8
+ * swipe is a run of them, mostly sideways, ended by a pause. So a run that starts on the background
9
+ * and goes sideways first is a swipe, and is passed on as begin, moves and end; one that starts in a
10
+ * window, or goes up and down first, is scrolling, and is left alone until it pauses. Three and four
11
+ * fingers never reach a page: the OS keeps them.
12
+ *
13
+ * Wheel steps come in pixels from a trackpad on every platform Chromium runs on, but in lines or
14
+ * pages from some mice and other browsers: all are turned into pixels. Shift with a wheel is a
15
+ * mouse's sideways scroll, not a swipe. On a Mac the trackpad's momentum arrives as more wheel
16
+ * events after the fingers lift; they are taken as part of the swipe, which ends when they stop.
17
+ */
18
+
19
+ export interface SwipeOptions {
20
+ /** Whether a run that starts on this element is the background's; by default, anything outside a window or the widget list. */
21
+ readonly isBackground?: (target: EventTarget | null) => boolean
22
+ /** The pause that ends a swipe, in ms. */
23
+ readonly endAfterMs?: number
24
+ /** For tests: the time, and a delay that returns its cancel. */
25
+ readonly clock?: { readonly now: () => number; readonly later: (run: () => void, ms: number) => () => void }
26
+ }
27
+
28
+ /** How far a run must go before it is a swipe or a scroll, in px, and how much more sideways than up and down. */
29
+ const DECIDE_PX = 6
30
+ const SIDEWAYS = 1.5
31
+ /** A line of a wheel in px, as Chromium scrolls one. */
32
+ const LINE_PX = 40
33
+ /** How far back the lift-off speed is measured, in ms. */
34
+ const VELOCITY_MS = 80
35
+
36
+ const pixels = (delta: number, mode: number, page: number) => (mode === 1 ? delta * LINE_PX : mode === 2 ? delta * page : delta)
37
+
38
+ const outsideWindows = (target: EventTarget | null) =>
39
+ typeof Element !== 'undefined' && target instanceof Element && !target.closest(`[${WINDOW_ATTRIBUTE}], .desk-widget-list`)
40
+
41
+ /** Watches `element` for swipes that start on its background and passes each on. Returns a stop. */
42
+ export function watchSwipes(element: HTMLElement, send: (gesture: AppGesture) => void, options: SwipeOptions = {}): () => void {
43
+ const isBackground = options.isBackground ?? outsideWindows
44
+ const endAfter = options.endAfterMs ?? 120
45
+ const clock = options.clock ?? { now: () => performance.now(), later: (run, ms) => clearTimeout.bind(null, setTimeout(run, ms)) }
46
+ let state: 'idle' | 'deciding' | 'swiping' | 'scrolling' = 'idle'
47
+ let x = 0
48
+ let y = 0
49
+ let samples: { at: number; x: number }[] = []
50
+ let cancelEnd: (() => void) | null = null
51
+
52
+ const velocity = () => {
53
+ const last = samples.at(-1)
54
+ const first = last && samples.find(s => last.at - s.at <= VELOCITY_MS)
55
+ return last && first && last.at > first.at ? ((last.x - first.x) * 1000) / (last.at - first.at) : 0
56
+ }
57
+ const finish = (phase: 'end' | 'cancel') => {
58
+ cancelEnd?.()
59
+ cancelEnd = null
60
+ if (state === 'swiping') send(phase === 'end' ? { type: 'swipe', phase, delta: x, velocity: velocity() } : { type: 'swipe', phase, delta: x })
61
+ state = 'idle'
62
+ x = y = 0
63
+ samples = []
64
+ }
65
+
66
+ const onWheel = (event: WheelEvent) => {
67
+ if (event.ctrlKey || event.shiftKey) return
68
+ cancelEnd?.()
69
+ cancelEnd = clock.later(() => finish('end'), endAfter)
70
+ if (state === 'idle') state = isBackground(event.target) ? 'deciding' : 'scrolling'
71
+ if (state === 'scrolling') return
72
+ x += pixels(event.deltaX, event.deltaMode, element.clientWidth || innerWidth)
73
+ y += pixels(event.deltaY, event.deltaMode, element.clientHeight || innerHeight)
74
+ if (state === 'deciding') {
75
+ if (Math.abs(x) + Math.abs(y) < DECIDE_PX) return
76
+ if (Math.abs(x) <= SIDEWAYS * Math.abs(y)) return void (state = 'scrolling')
77
+ state = 'swiping'
78
+ send({ type: 'swipe', phase: 'begin', delta: 0 })
79
+ // Stopped as the begin was heard: it was cancelled, so no move comes after.
80
+ if (state !== 'swiping') return
81
+ }
82
+ // The background's to move now: not the browser's back and forward.
83
+ event.preventDefault()
84
+ samples.push({ at: clock.now(), x })
85
+ if (samples.length > 32) samples.shift()
86
+ send({ type: 'swipe', phase: 'move', delta: x })
87
+ }
88
+ // Leaving the window mid-swipe leaves it unfinished: the host puts things back.
89
+ const onLeave = () => finish('cancel')
90
+ const onVisibility = () => document.visibilityState === 'hidden' && finish('cancel')
91
+
92
+ element.addEventListener('wheel', onWheel, { passive: false })
93
+ addEventListener('blur', onLeave)
94
+ document.addEventListener('visibilitychange', onVisibility)
95
+ return () => {
96
+ finish('cancel')
97
+ element.removeEventListener('wheel', onWheel)
98
+ removeEventListener('blur', onLeave)
99
+ document.removeEventListener('visibilitychange', onVisibility)
100
+ }
101
+ }
@@ -1,6 +1,6 @@
1
1
  import { topicMatches } from '../core/events.js'
2
2
  import { DESK_PROTOCOL, isAppToHost, THEME_TOPIC } from '../core/hosted.js'
3
- import type { BroadcastSender, CommandTarget, DeskChrome, DeskHostBridge, HostToApp, Publisher } from '../core/hosted.js'
3
+ import type { AppGesture, BroadcastSender, CommandTarget, DeskChrome, DeskHostBridge, HostToApp, Publisher } from '../core/hosted.js'
4
4
  import { checkChrome } from './checkChrome.js'
5
5
  import { checkTheme } from './checkTheme.js'
6
6
 
@@ -42,6 +42,17 @@ export interface BroadcastRouterOptions {
42
42
  * `undefined` to drop it. The theme is always checked as well, whatever this does.
43
43
  */
44
44
  readonly check?: (topic: string, payload: unknown, from: HostedApp) => unknown
45
+ /**
46
+ * A swipe on an app's desktop background: the host's shell moves between apps with it. Only from the
47
+ * app in front (`front`); moves come no faster than the `gesture` rate, the latest held over it,
48
+ * and a begin, end or cancel always goes, after any move held before it. A swipe under way whose app
49
+ * leaves the front, is unregistered or connects again, or that another begin overtakes (its own app's
50
+ * too), gets a cancel here, and a move of it still held is dropped. A move, end or cancel with no swipe
51
+ * of its app under way is not passed on.
52
+ */
53
+ readonly gesture?: (appId: string, gesture: AppGesture) => void
54
+ /** The app in front, whose swipes count. Without it, a gesture from any app does. */
55
+ readonly front?: () => string | null
45
56
  /** The most a payload may take as JSON. Default 64 KiB; larger ones are dropped. */
46
57
  readonly maxPayload?: number
47
58
  /** How fast each publisher may broadcast on each topic: see `RateLimits`. */
@@ -57,7 +68,8 @@ export interface Rate {
57
68
  }
58
69
 
59
70
  /**
60
- * Per publisher and topic, a bucket of broadcasts. Over it, nothing is queued and nothing lost: the
71
+ * Per publisher and topic, a bucket of broadcasts. Gestures have a bucket per app of their own, at
72
+ * `topics.gesture`'s rate or 30 at once then 120 a second: enough to follow fingers frame by frame. Over it, nothing is queued and nothing lost: the
61
73
  * latest payload is held, replacing any held before, and goes out when the bucket allows, so every
62
74
  * subscriber still ends on the last value. Defaults: 20 at once then 10 a second; the theme 2 then 1
63
75
  * a second, since it changes on a person's choice; and 64 topics per publisher at once, past which a
@@ -70,7 +82,7 @@ export interface RateLimits extends Partial<Rate> {
70
82
  }
71
83
 
72
84
  /** Why a message was not acted on, or null when it was. */
73
- export type Refusal = 'unknown app' | 'malformed' | 'not granted' | 'not the primary' | 'refused by check' | 'too large' | 'rate limited' | null
85
+ export type Refusal = 'unknown app' | 'malformed' | 'not in front' | 'not granted' | 'not the primary' | 'refused by check' | 'too large' | 'rate limited' | null
74
86
 
75
87
  /** The rules of a host's broadcasts, kept in one place so every transport keeps them alike. */
76
88
  export interface BroadcastRouter {
@@ -95,6 +107,9 @@ export interface BroadcastRouter {
95
107
  const DEFAULT_MAX_PAYLOAD = 64 * 1024
96
108
  const RATE: Rate = { burst: 20, perSecond: 10 }
97
109
  const THEME_RATE: Rate = { burst: 2, perSecond: 1 }
110
+ const GESTURE_RATE: Rate = { burst: 30, perSecond: 120 }
111
+ /** The key of an app's gesture bucket among its topics': no topic can be empty. */
112
+ const GESTURES = ''
98
113
 
99
114
  interface Bucket {
100
115
  tokens: number
@@ -180,7 +195,8 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
180
195
  if (!bucket) {
181
196
  // A new topic starts with a full burst, so a flood across topics is bounded by how many a
182
197
  // publisher may have at once. A full, idle bucket says nothing a new one would not: it can go.
183
- if (own.size >= (limits.maxTopics ?? 64)) {
198
+ // The gesture bucket is not a topic: it neither counts nor makes room.
199
+ if (own.size - Number(own.has(GESTURES)) >= (limits.maxTopics ?? 64)) {
184
200
  const idle = [...own].find(([t, b]) => !b.held && (refill(b), b.tokens >= b.rate.burst) && t)
185
201
  if (!idle) return count(app.id), 'rate limited'
186
202
  own.delete(idle[0])
@@ -260,6 +276,67 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
260
276
  /** Apps that have said hello, told their role again when it changes. */
261
277
  const greeted = new Set<string>()
262
278
  const tellRole = (app: HostedApp) => options.deliver(app.id, { desk: DESK_PROTOCOL, kind: 'role', primary: Boolean(app.primary) })
279
+ /** The app whose swipe is under way, and how far it had got, to cancel it should the app leave the front or go. */
280
+ let swiping: { appId: string; delta: number } | null = null
281
+ const endSwipe = (appId: string) => {
282
+ if (swiping?.appId !== appId) return
283
+ const delta = swiping.delta
284
+ swiping = null
285
+ options.gesture?.(appId, { type: 'swipe', phase: 'cancel', delta })
286
+ }
287
+ /** Puts back an app's swipe under way, and drops any move of it held over the rate, unsent. */
288
+ const dropSwipe = (appId: string) => {
289
+ const b = buckets.get(appId)?.get(GESTURES)
290
+ if (b?.held) b.held.cancel(), delete b.held
291
+ endSwipe(appId)
292
+ }
293
+ /**
294
+ * A gesture from the app in front. A move over the rate is held, replacing one held before; a
295
+ * begin, end or cancel is never held or dropped, and sends any move held before it first, so the
296
+ * host hears the phases in order.
297
+ */
298
+ const gesture = (app: HostedApp, g: AppGesture): Refusal => {
299
+ const front = options.front?.()
300
+ if (options.front && front !== app.id) return dropSwipe(app.id), 'not in front'
301
+ // A move, end or cancel of a swipe the host never heard begin, or already put back: nothing to go on with.
302
+ if (g.phase !== 'begin' && swiping?.appId !== app.id) return null
303
+ // A swipe still open as another begins (another app's, its app gone from the front without a word,
304
+ // or this app's, never finished): put back first, with any move of it held.
305
+ if (g.phase === 'begin' && swiping) dropSwipe(swiping.appId)
306
+ const own = buckets.get(app.id) ?? new Map<string, Bucket>()
307
+ buckets.set(app.id, own)
308
+ let b = own.get(GESTURES)
309
+ if (!b) {
310
+ const rate = { ...GESTURE_RATE, ...limits.topics?.gesture }
311
+ own.set(GESTURES, (b = { tokens: rate.burst, at: clock.now(), rate }))
312
+ }
313
+ refill(b)
314
+ const out = (next: AppGesture) => {
315
+ if (next.phase === 'begin' || swiping?.appId === app.id) swiping = next.phase === 'begin' || next.phase === 'move' ? { appId: app.id, delta: next.delta } : null
316
+ options.gesture?.(app.id, next)
317
+ }
318
+ if (g.phase !== 'move') {
319
+ const held = b.held
320
+ if (held) held.cancel(), delete b.held, out(held.payload as AppGesture)
321
+ b.tokens = Math.max(0, b.tokens - 1)
322
+ return out(g), null
323
+ }
324
+ if (b.held) return count(app.id), (b.held.payload = g), null
325
+ if (b.tokens >= 1) return b.tokens--, out(g), null
326
+ const bucket = b
327
+ const cancel = clock.later(() => {
328
+ const held = bucket.held
329
+ if (!held) return
330
+ delete bucket.held
331
+ // Its app has left the front meanwhile: the move is not sent, and its swipe is put back.
332
+ if (options.front && options.front() !== app.id) return endSwipe(app.id)
333
+ refill(bucket)
334
+ bucket.tokens = Math.max(0, bucket.tokens - 1)
335
+ out(held.payload as AppGesture)
336
+ }, Math.ceil(((1 - b.tokens) * 1000) / b.rate.perSecond))
337
+ b.held = { from: senderOf(app), payload: g, cancel }
338
+ return null
339
+ }
263
340
 
264
341
  /** Cancels what an app held over its rate. */
265
342
  const dropHeld = (appId: string) => {
@@ -283,8 +360,9 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
283
360
  unregister(appId) {
284
361
  greeted.delete(appId)
285
362
  if (apps.delete(appId)) options.chrome?.(appId, null, [])
286
- // What it had held goes with it, unsent.
363
+ // What it had held goes with it, unsent; a swipe it had under way is put back.
287
364
  dropHeld(appId)
365
+ endSwipe(appId)
288
366
  buckets.delete(appId)
289
367
  subscriptions.delete(appId)
290
368
  const own = kept.get(appId)
@@ -319,8 +397,12 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
319
397
  return null
320
398
  case 'hello':
321
399
  greeted.add(appId)
400
+ // A page connecting afresh (reloaded) has no swipe under way, whatever its last one left open.
401
+ dropSwipe(appId)
322
402
  tellRole(app)
323
403
  return null
404
+ case 'gesture':
405
+ return gesture(app, message.gesture)
324
406
  }
325
407
  },
326
408
 
@@ -351,7 +433,7 @@ export interface MemoryHost {
351
433
  * A host in memory. Messages are copied with `structuredClone` each way, as a real boundary would,
352
434
  * so an app that sends something that cannot cross fails here too.
353
435
  */
354
- export function createMemoryHost(options: Pick<BroadcastRouterOptions, 'check' | 'maxPayload'> = {}): MemoryHost {
436
+ export function createMemoryHost(options: Pick<BroadcastRouterOptions, 'check' | 'maxPayload' | 'gesture' | 'front' | 'limits' | 'clock'> = {}): MemoryHost {
355
437
  const listeners = new Map<string, Set<(message: HostToApp) => void>>()
356
438
  const chromes = new Map<string, DeskChrome>()
357
439
  const log: { appId: string; message: unknown; refusal: Refusal }[] = []
@@ -16,6 +16,8 @@ import type { DeskApp } from './app.js'
16
16
  import { ABOUT_WINDOW, appWindowLimits, appWindowTitle, desksWindow, SETTINGS_WINDOW, useDeskApp } from './app.js'
17
17
  import { AboutContent, SettingsContent } from './appPanels.js'
18
18
  import { WindowBoundary } from './windowBoundary.js'
19
+ import { watchSwipes } from '../core/swipe.js'
20
+ import { useHost } from './hosted.js'
19
21
  import { TitleProgress } from './windowProgress.js'
20
22
  import type { WindowProgress } from './windowProgress.js'
21
23
  import type { WindowFailed, WindowLoading } from './windowBoundary.js'
@@ -116,6 +118,10 @@ export function Desktop({ renderWindow, title, note, info, actions, limits, empt
116
118
  [renderWindow, ownsAbout, ownsSettings],
117
119
  )
118
120
 
121
+ // Hosted: a two-finger swipe on the background moves between the host's apps, so it goes to the host.
122
+ const host = useHost()
123
+ useEffect(() => (host && stage.current ? watchSwipes(stage.current, gesture => host.gesture(gesture)) : undefined), [host])
124
+
119
125
  useLayoutEffect(() => {
120
126
  desk.setStage(() => ({ width: stage.current?.clientWidth ?? 1024, height: stage.current?.clientHeight ?? 768 }))
121
127
  }, [desk])
@@ -27,3 +27,5 @@ export {
27
27
  ZOOM_OUT_MS,
28
28
  } from './zoom.js'
29
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
+ }