@liberation-data/desk 0.46.0 → 0.48.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/llms.txt CHANGED
@@ -381,22 +381,26 @@ useWindowMenus(menus: Menu[]) // inside a window: its menus join the bar while
381
381
  // about: { name, version?, links, note? (text only), facts: { title?, facts: { name, value, link?, copy?: false }[] }[] | null } from the app declaration; facts null while read, [] for nothing to report. Hosted implies themeFromHost; the primary declares themeFromHost: false to keep its Appearance and its own theme.
382
382
  interface DeskHostBridge { version: 1; send(m: AppToHost): void; onMessage(l: (m: HostToApp) => void): () => void }
383
383
  connectHost(bridge): HostClient // core, for a page without React; DeskProvider calls it
384
- useHost(): HostClient | null // publish(topic, payload); subscribe(publisher: appId | 'primary', topic, handler); onCommand; setChrome; primary(): boolean | null; onRole(l: (primary) => void)
384
+ useHost(): HostClient | null // publish(topic, payload); subscribe(publisher: appId | 'primary', topic, handler); onCommand; setChrome; primary(): boolean | null; onRole(l: (primary) => void); gesture(AppGesture) (a hosted Desktop calls it)
385
385
  // connectHost sends { kind: 'hello' }; the host answers { kind: 'role', primary: boolean }, again on any change (createBroadcastRouter does; a host without it must). No answer: nothing published by default.
386
386
  // The primary publishes appliedTheme(root?) (scheme, look, --desk-* tokens as worn; url() tokens and fonts left out) by default, again on change; <DeskShell|DeskProvider publishTheme={false}> turns it off
387
387
  useHosted(): boolean; useHostBroadcast(publisher, topic, handler); usePublishTheme(theme: DeskTheme | null) // publishes this theme instead of appliedTheme while mounted
388
388
  interface DeskTheme { mode: 'light'|'dark'; look: Look; tokens: Record<`--${string}`, string>; fonts?: { family; src; weight?; style? }[]; wallpaper?: string }
389
389
  <DeskShell onTheme={theme => …}> // keep some looks of your own; mode and look always apply. Default: applyTheme(theme)
390
390
  hostDockModel(entries, state): { model: HostDockEntry[]; run: Map<id, DockItem> } // the dock as data, as HostedDock sends it
391
- // '@liberation-data/desk/host' (the host's half): createBroadcastRouter({ deliver, chrome?: (appId, chrome, dropped: string[]) => void, check?, maxPayload?, limits?: { burst?, perSecond?, topics?, maxTopics? }, clock? }), router.limited(appId), checkTheme(theme, origin), checkChrome(chrome, origin): { ok: true, chrome, dropped } | { ok: false, reason }, createMemoryHost()
391
+ // '@liberation-data/desk/host' (the host's half): createBroadcastRouter({ deliver, chrome?: (appId, chrome, dropped: string[]) => void, check?, gesture?: (appId, AppGesture) => void, front?: () => appId | null, maxPayload?, limits?: { burst?, perSecond?, topics?, maxTopics? }, clock? }), router.limited(appId), checkTheme(theme, origin), checkChrome(chrome, origin): { ok: true, chrome, dropped } | { ok: false, reason }, createMemoryHost()
392
392
  // '@liberation-data/desk/shell' (the host's page only, with css/shell.css): <HostShell workspaces={{ id, title, accent?, icon?, primary?, state: 'live'|'suspended'|'discarded' }[]} current chrome={Record<appId, DeskChrome|null>} theme? snapshots?={Record<id, imageUrl>} keys?={SwitchKeys|null} clickSwitch?={'zoom'|'slide'} dockSide? onSwitch={(id, how) => …} onOverview?={() => …} onCommand={(appId, 'dock'|'menu'|'settings', itemId) => …} onInsets?={({ top, right, bottom, left }) => …} />
393
393
  // It draws the current app's dock and a switcher (one Tab stop, arrows/Home/End, title announced once on arrival); the host moves the views and passes the new current.
394
394
  // switchKeys(platformOf(process.platform)): mac Ctrl+Opt+←/→/↑, Linux Super+Alt, Windows Ctrl+Alt; switchKeyAction(pageEvent | electronInput, keys): 'previous'|'next'|'overview'|null (key releases ignored); neighbour(workspaces, current, step) | null at the ends
395
395
  // slidePlan(reducedMotion): { kind: 'slide', 350 } | { kind: 'fade', 120 }; spring(ms, from?, velocity?) → t => progress, no overshoot; slideOffsets(progress, 1|-1, width): { leaving, arriving } whole px, no gap: clip views to the desktop area or they cover the dock
396
396
  // animate({ durationMs, step, curve?, clock?: pageClock()|timerClock(), timeoutMs? = 250 }): { done: 'finished'|'jumped'|'stopped', progress(), stop() }; jumps to 1 when frames stop
397
+ // createSwipeController({ count(), current(), width(), reducedMotion?(), clock? = timerClock(), frame: (SlideFrame { from, to, progress, offsets, fade? }) => …, arrive: index => … }): { gesture(AppGesture), slideTo(index), busy(), stop() } // follows 1:1 (rubber band at the ends), goes on past COMMIT_DISTANCE 0.5 or a COMMIT_SPEED 0.5 widths/s flick, else springs back; catches a settling slide, a key's too; arrive once per landing, at rest (a slideTo from it starts afresh); stop() on closing: no more frames or arrive. swipeProgress, swipeDecision
397
398
  // <HostOverview workspaces current snapshots?={Record<id, imageUrl>} request={{ kind: 'open' } | { kind: 'switch', to } | null} theme? insets? visible? reducedMotion? pose? onWantCapture?={id => …} onCover?={() => …} onArrive={id => …} /> // an overlay over the views; capture on onWantCapture into snapshots and return a promise of its URL (an identical picture still counts; waits 100 ms at most), hide views on onCover, swap the view in and clear request on onArrive; each once per move; the host revokes its own snapshot URLs
398
399
  // planZoom(from, to, reducedMotion?): { phases: out 200 / across 250 / in 200 | fade 120, durationMs, to }; poseAt(plan, ms): { zoom, centre, fog, opacity }; overviewTiles(count, pose, width): { x, z, scale, opacity, layer }[]
399
400
  // Rate limits per publisher+topic: 20 then 10/s (theme 2 then 1/s), 64 topics at once; over it the latest is held (never queued), so subscribers end on the last value; order holds within a topic.
401
+ // Swipes: a hosted <Desktop> passes a two-finger sideways wheel run that starts on its background (not in a window or the widget list) to the host: AppGesture { type: 'swipe', phase: 'begin'|'move'|'end'|'cancel', delta: total px since begin (+ toward the next workspace), velocity?: px/s at end }; isAppGesture(value). watchSwipes(element, send, { isBackground?, endAfterMs? = 120 }) → stop, for a page without React: send = g => client.gesture(g). Lines and pages taken as px; Shift and Ctrl wheels ignored; cancel on blur or a hidden page.
402
+ // The router passes gestures from front() only ('not in front' otherwise; a swipe under way is cancelled, its held move dropped, if its app leaves the front, is unregistered or says hello again, or another begin comes, its own app's too; a move, end or cancel with no swipe of its app under way is dropped); moves 30 then 120/s (limits.topics.gesture), the latest held; begin/end/cancel never held, and sent after any held move.
403
+ // Known limit, macOS: momentum wheel events after lift-off count as part of the swipe, which ends when they stop.
400
404
  // register({ id, origin, primary?, publishes? }): the primary's publishes must include 'theme'. A deliver that throws for one app still lets the rest hear; the error is thrown after.
401
405
  // chrome(appId, null) when an app is unregistered: stop drawing its chrome. The primary's last theme is kept while it is down and replayed to subscribers of 'primary'.
402
406
  // The router checks chrome before chrome() sees it: bounded text and lists, links http(s), mailto: or the app's origin, dock images from the app's origin or data: raster (no SVG). A bad part (menu item, dock item, section, link, fact; an image or fact link from its item) is dropped and named in dropped; the rest is drawn. Only the wrong shape (not lists, too large, a stack in a stack) refuses it whole. Open About links in the system browser, rel="noopener noreferrer".
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liberation-data/desk",
3
- "version": "0.46.0",
3
+ "version": "0.48.0",
4
4
  "description": "A desktop environment for React apps: windows, a dock, menus and commands, controls, tours and setup assistants.",
5
5
  "keywords": [
6
6
  "react",
@@ -165,6 +165,22 @@ export type Publisher = 'primary' | (string & {})
165
165
  /** What a host's command is for: the app's menus, its dock, or its Settings. */
166
166
  export type CommandTarget = 'menu' | 'dock' | 'settings'
167
167
 
168
+ /**
169
+ * A two-finger horizontal swipe that started on the app's desktop background, passed to the host,
170
+ * which moves between apps with it. One that starts inside a window is the window's, and never sent.
171
+ */
172
+ export interface AppGesture {
173
+ readonly type: 'swipe'
174
+ readonly phase: 'begin' | 'move' | 'end' | 'cancel'
175
+ /**
176
+ * How far the fingers have gone since `begin`, in CSS pixels, as the page scrolls: positive toward
177
+ * the next workspace. The total, not the step, so a host that drops moves loses nothing.
178
+ */
179
+ readonly delta: number
180
+ /** At `end`: how fast they were going as they lifted, in pixels a second, signed as `delta`. */
181
+ readonly velocity?: number
182
+ }
183
+
168
184
  /** What an app sends its host. Untrusted at the host's end: check it with `isAppToHost`. */
169
185
  export type AppToHost =
170
186
  | { readonly desk: 1; readonly kind: 'chrome'; readonly chrome: DeskChrome }
@@ -173,6 +189,7 @@ export type AppToHost =
173
189
  | { readonly desk: 1; readonly kind: 'unsubscribe'; readonly publisher: Publisher; readonly topic: string }
174
190
  /** Sent on connecting: the host answers with the app's `role`. */
175
191
  | { readonly desk: 1; readonly kind: 'hello' }
192
+ | { readonly desk: 1; readonly kind: 'gesture'; readonly gesture: AppGesture }
176
193
 
177
194
  /** What a host sends an app: a choice from the chrome it draws, or another app's broadcast, stamped. */
178
195
  export type HostToApp =
@@ -225,11 +242,20 @@ export function isAppToHost(value: unknown): value is AppToHost {
225
242
  return isString(value.publisher) && isString(value.topic) && value.topic.length > 0
226
243
  case 'hello':
227
244
  return true
245
+ case 'gesture':
246
+ return isAppGesture(value.gesture)
228
247
  default:
229
248
  return false
230
249
  }
231
250
  }
232
251
 
252
+ const PHASES: readonly unknown[] = ['begin', 'move', 'end', 'cancel']
253
+ const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
254
+
255
+ /** Whether `value` is a gesture as an app sends one: a known phase, and finite numbers. */
256
+ export const isAppGesture = (value: unknown): value is AppGesture =>
257
+ isRecord(value) && value.type === 'swipe' && PHASES.includes(value.phase) && isFiniteNumber(value.delta) && (value.velocity === undefined || isFiniteNumber(value.velocity))
258
+
233
259
  /** Whether a message from a host has the shape of one. */
234
260
  export function isHostToApp(value: unknown): value is HostToApp {
235
261
  if (!isRecord(value) || value.desk !== DESK_PROTOCOL) return false
@@ -270,7 +296,9 @@ export interface HostClient {
270
296
  primary(): boolean | null
271
297
  /** Calls the listener when the host says whether this app is the primary, now and on any change. */
272
298
  onRole(listener: (primary: boolean) => void): () => void
273
- /** Stops listening, and takes the chrome away. */
299
+ /** Passes a swipe on the desktop background to the host. `DeskProvider`'s `Desktop` does this itself. */
300
+ gesture(gesture: AppGesture): void
301
+ /** Stops listening, takes the chrome away, and puts back a swipe under way. */
274
302
  close(): void
275
303
  }
276
304
 
@@ -288,6 +316,8 @@ export function connectHost(bridge: DeskHostBridge): HostClient {
288
316
  const keyOf = (publisher: string, topic: string) => `${publisher}\u0000${topic}`
289
317
  let primary: boolean | null = null
290
318
  const roles = new Set<(primary: boolean) => void>()
319
+ /** How far a swipe under way had got, so closing puts it back: a watcher stopped after the close is not heard. */
320
+ let swipe: number | null = null
291
321
 
292
322
  const stop = bridge.onMessage(message => {
293
323
  if (closed || !isHostToApp(message)) return
@@ -337,6 +367,11 @@ export function connectHost(bridge: DeskHostBridge): HostClient {
337
367
  publish(topic, payload) {
338
368
  if (!closed) bridge.send({ desk: DESK_PROTOCOL, kind: 'publish', topic, payload })
339
369
  },
370
+ gesture(gesture) {
371
+ if (closed) return
372
+ swipe = gesture.phase === 'begin' || gesture.phase === 'move' ? gesture.delta : null
373
+ bridge.send({ desk: DESK_PROTOCOL, kind: 'gesture', gesture })
374
+ },
340
375
  subscribe(publisher, topic, handler) {
341
376
  const key = keyOf(publisher, topic)
342
377
  const existing = subscriptions.get(key)
@@ -373,6 +408,7 @@ export function connectHost(bridge: DeskHostBridge): HostClient {
373
408
  roles.clear()
374
409
  primary = null
375
410
  bridge.send({ desk: DESK_PROTOCOL, kind: 'chrome', chrome: EMPTY_CHROME })
411
+ if (swipe !== null) bridge.send({ desk: DESK_PROTOCOL, kind: 'gesture', gesture: { type: 'swipe', phase: 'cancel', delta: swipe } })
376
412
  // So the host stops sending what nobody here hears.
377
413
  for (const { publisher, topic } of subscriptions.values()) bridge.send({ desk: DESK_PROTOCOL, kind: 'unsubscribe', publisher, topic })
378
414
  closed = true
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
+ }
package/src/css/dock.css CHANGED
@@ -188,9 +188,20 @@
188
188
  height: 46%;
189
189
  }
190
190
 
191
- .desk-dock-icon > svg {
191
+ /* A glyph fills its share of the tile, drawn or a picture: an image (a hosted app's dock entry is a PNG
192
+ * or data: URI) would otherwise draw at its own size and spill out of the dock. As .desk-icon-glyph. */
193
+ .desk-dock-icon > svg,
194
+ .desk-dock-icon > img {
192
195
  width: 100%;
193
196
  height: 100%;
197
+ object-fit: contain;
198
+ }
199
+
200
+ /* Carried while pinning or reordering: the tile's glyph at a fixed size, as .desk-icon-drag, since the
201
+ * drag picture has no size of its own for the glyph's share to be taken of. */
202
+ .desk-drag-preview > .desk-dock-icon {
203
+ width: 40px;
204
+ height: 40px;
194
205
  }
195
206
 
196
207
  .desk-dock-item[data-stack] .desk-dock-icon {
@@ -209,15 +220,19 @@
209
220
  .desk-dock-preview > span {
210
221
  display: grid;
211
222
  place-items: center;
223
+ min-width: 0;
224
+ min-height: 0;
212
225
  padding: 3px;
213
226
  border-radius: 4px;
214
227
  background: color-mix(in srgb, var(--desk-ink) 10%, transparent);
215
228
  color: var(--desk-muted);
216
229
  }
217
230
 
218
- .desk-dock-preview svg {
231
+ .desk-dock-preview svg,
232
+ .desk-dock-preview img {
219
233
  width: 100%;
220
234
  height: 100%;
235
+ object-fit: contain;
221
236
  }
222
237
 
223
238
  /* A dot for "a window is open", brighter when it has focus: a 4px dot 2px off its tile. */
@@ -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'