@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
package/src/core/theme.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Look } from './look.js'
2
- import { themeChanged, watchThemeChanges } from './themeChange.js'
2
+ import { drawnTheme, themeChanged, watchThemeChanges } from './themeChange.js'
3
3
 
4
4
  /*
5
5
  * A LOOK ONE APP LENDS TO OTHERS.
@@ -44,6 +44,30 @@ export interface DeskTheme extends AppTheme {
44
44
  */
45
45
  export const isImageRef = (wallpaper: string): boolean => /^(data:|[a-z][\w+.-]*:\/\/|\/)/i.test(wallpaper)
46
46
 
47
+ /** The CSS functions a token may use: colours, maths, gradients and other custom properties. Nothing that loads. */
48
+ const FUNCTIONS = new Set([
49
+ 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color', 'color-mix', 'light-dark',
50
+ 'var', 'calc', 'min', 'max', 'clamp',
51
+ 'linear-gradient', 'radial-gradient', 'conic-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient',
52
+ ])
53
+
54
+ const MAX_VALUE = 300
55
+
56
+ /**
57
+ * Whether a custom property's value is plain: a colour, a length, a number, a font list or a gradient.
58
+ * Only letters, digits, spaces and `#.,%/'"+-()*` may appear, every function is one of `FUNCTIONS`, and
59
+ * nothing may escape, end the declaration or open a block. So `url(…)`, `image-set(…)`, `\75rl(` and
60
+ * `red; background: …` are all refused.
61
+ */
62
+ export function isPlainValue(value: string): boolean {
63
+ if (value.length > MAX_VALUE) return false
64
+ if (!/^[\w\s#.,%/'"+*()-]*$/.test(value)) return false
65
+ for (const match of value.matchAll(/([\w-]*)\s*\(/g)) {
66
+ if (!FUNCTIONS.has((match[1] ?? '').toLowerCase())) return false
67
+ }
68
+ return true
69
+ }
70
+
47
71
  /**
48
72
  * The part of a theme every hosted app wears whatever else it does: light or dark, and the
49
73
  * platform chrome. One desktop light and the next dark would look broken as they slide past each
@@ -89,3 +113,47 @@ export function applyTheme(theme: DeskTheme, root: HTMLElement = document.docume
89
113
  applied.set(root, { tokens: Object.keys(theme.tokens), fonts: faces })
90
114
  if (root.style.cssText !== was) themeChanged(root.ownerDocument)
91
115
  }
116
+
117
+ /** The most tokens a theme may carry: `checkTheme` refuses more, and `appliedTheme` takes no more. */
118
+ export const MAX_THEME_TOKENS = 400
119
+
120
+ /** Desk's custom properties the page sets on its root: in rules on the root, and in the root's own style. */
121
+ function rootTokens(root: HTMLElement): Set<string> {
122
+ const names = new Set<string>()
123
+ const take = (style: CSSStyleDeclaration) => {
124
+ for (let i = 0; i < style.length; i++) if (style[i]!.startsWith('--desk-')) names.add(style[i]!)
125
+ }
126
+ const walk = (sheet: { readonly cssRules: CSSRuleList } | null) => {
127
+ let rules: CSSRule[]
128
+ try {
129
+ rules = Array.from(sheet?.cssRules ?? [])
130
+ } catch {
131
+ // Another origin's stylesheet can't be read, and sets none of Desk's tokens.
132
+ return
133
+ }
134
+ for (const rule of rules) {
135
+ if ('selectorText' in rule && /:root|html|\[data-(theme|look)/.test((rule as CSSStyleRule).selectorText)) take((rule as CSSStyleRule).style)
136
+ // A block (@media, @layer, @supports) or an @import's sheet, such as desk.css imported by the app's own.
137
+ else if ('cssRules' in rule || 'styleSheet' in rule) walk('styleSheet' in rule ? (rule as CSSImportRule).styleSheet : (rule as CSSGroupingRule))
138
+ }
139
+ }
140
+ for (const sheet of Array.from(root.ownerDocument.styleSheets)) walk(sheet)
141
+ take(root.style)
142
+ return names
143
+ }
144
+
145
+ /**
146
+ * The theme this page wears now, as data another page can wear: light or dark and the look as drawn,
147
+ * and Desk's tokens as they apply on the root. Only what `checkTheme` would pass is taken: a token that
148
+ * loads something (`url(…)`) is left out, and so are fonts, which the page loads its own way.
149
+ */
150
+ export function appliedTheme(root: HTMLElement = document.documentElement): DeskTheme {
151
+ const drawn = drawnTheme(root.ownerDocument)
152
+ const computed = getComputedStyle(root)
153
+ const tokens: Record<string, string> = {}
154
+ for (const name of [...rootTokens(root)].sort()) {
155
+ const value = computed.getPropertyValue(name).trim()
156
+ if (value && isPlainValue(value) && Object.keys(tokens).length < MAX_THEME_TOKENS) tokens[name] = value
157
+ }
158
+ return { mode: drawn.scheme, look: drawn.look, tokens }
159
+ }
package/src/css/shell.css CHANGED
@@ -97,3 +97,92 @@
97
97
  clip-path: inset(50%);
98
98
  white-space: nowrap;
99
99
  }
100
+
101
+ /* ── The overview: tiles floating in a fog, drawn on an overlay over the apps' views ── */
102
+
103
+ .desk-overview {
104
+ position: fixed;
105
+ overflow: hidden;
106
+ perspective: 1600px;
107
+ font-family: var(--desk-font);
108
+ color: var(--desk-ink);
109
+ }
110
+
111
+ .desk-overview-fog {
112
+ position: absolute;
113
+ inset: 0;
114
+ opacity: 0;
115
+ background: radial-gradient(ellipse at center, var(--desk-overview-fog), var(--desk-overview-fog-far));
116
+ }
117
+
118
+ /* Each tile is the desktop area's full size, moved and scaled by transform alone, so the compositor does it. */
119
+ .desk-overview-tile {
120
+ position: absolute;
121
+ inset: 0;
122
+ padding: 0;
123
+ border: 0;
124
+ border-radius: 14px;
125
+ background: var(--desk-ground);
126
+ color: inherit;
127
+ font: inherit;
128
+ opacity: 0;
129
+ transform-origin: center;
130
+ will-change: transform, opacity;
131
+ cursor: default;
132
+ }
133
+
134
+ .desk-overview-tile img {
135
+ position: absolute;
136
+ inset: 0;
137
+ width: 100%;
138
+ height: 100%;
139
+ object-fit: cover;
140
+ border-radius: inherit;
141
+ }
142
+
143
+ /*
144
+ * The shadow is a small blurred picture, sliced in nine and tinted with the shadow token, not a
145
+ * box-shadow on a layer the size of a desktop. It grows in as the tile goes back.
146
+ */
147
+ .desk-overview-shadow {
148
+ position: absolute;
149
+ inset: -40px;
150
+ background: var(--desk-overview-shadow);
151
+ -webkit-mask-box-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='b' x='-1' y='-1' width='3' height='3'%3E%3CfeGaussianBlur stdDeviation='14'/%3E%3C/filter%3E%3Crect x='40' y='46' width='80' height='80' rx='14' filter='url(%23b)'/%3E%3C/svg%3E") 60 fill / 60px;
152
+ opacity: var(--desk-overview-depth, 0);
153
+ pointer-events: none;
154
+ }
155
+
156
+ .desk-overview-note {
157
+ position: absolute;
158
+ inset: 0;
159
+ display: grid;
160
+ place-content: center;
161
+ gap: var(--desk-space-2);
162
+ text-align: center;
163
+ border-radius: inherit;
164
+ background: var(--desk-surface);
165
+ color: var(--desk-muted);
166
+ font-size: var(--desk-text-hero);
167
+ }
168
+
169
+ .desk-overview-note strong {
170
+ color: var(--desk-ink);
171
+ }
172
+
173
+ /* The title under each tile, at a size that reads once the tile is small. */
174
+ .desk-overview-title {
175
+ position: absolute;
176
+ top: calc(100% + 24px);
177
+ left: 0;
178
+ right: 0;
179
+ text-align: center;
180
+ font-size: var(--desk-text-hero);
181
+ font-weight: 600;
182
+ opacity: var(--desk-overview-depth, 0);
183
+ }
184
+
185
+ .desk-overview-tile:focus-visible {
186
+ outline: 5px solid var(--desk-accent);
187
+ outline-offset: 6px;
188
+ }
@@ -1,4 +1,4 @@
1
- import { isImageRef } from '../core/theme.js'
1
+ import { isImageRef, isPlainValue, MAX_THEME_TOKENS } from '../core/theme.js'
2
2
  import type { DeskTheme, ThemeFont } from '../core/theme.js'
3
3
  import type { Look } from '../core/look.js'
4
4
 
@@ -16,32 +16,10 @@ export type ThemeCheck = { readonly ok: true; readonly theme: DeskTheme } | { re
16
16
 
17
17
  const LOOKS: readonly string[] = ['mac', 'gnome', 'windows']
18
18
 
19
- /** The CSS functions a token may use: colours, maths, gradients and other custom properties. Nothing that loads. */
20
- const FUNCTIONS = new Set([
21
- 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color', 'color-mix', 'light-dark',
22
- 'var', 'calc', 'min', 'max', 'clamp',
23
- 'linear-gradient', 'radial-gradient', 'conic-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient',
24
- ])
19
+ export { isPlainValue }
25
20
 
26
- const MAX_VALUE = 300
27
- const MAX_TOKENS = 400
28
21
  const MAX_FONTS = 16
29
22
 
30
- /**
31
- * Whether a custom property's value is plain: a colour, a length, a number, a font list or a gradient.
32
- * Only letters, digits, spaces and `#.,%/'"+-()*` may appear, every function is one of `FUNCTIONS`, and
33
- * nothing may escape, end the declaration or open a block. So `url(…)`, `image-set(…)`, `\75rl(` and
34
- * `red; background: …` are all refused.
35
- */
36
- export function isPlainValue(value: string): boolean {
37
- if (value.length > MAX_VALUE) return false
38
- if (!/^[\w\s#.,%/'"+*()-]*$/.test(value)) return false
39
- for (const match of value.matchAll(/([\w-]*)\s*\(/g)) {
40
- if (!FUNCTIONS.has((match[1] ?? '').toLowerCase())) return false
41
- }
42
- return true
43
- }
44
-
45
23
  /**
46
24
  * Whether `url` is on `origin`: the same scheme and host. Compared by hand rather than by `URL.origin`,
47
25
  * which is `'null'` for every scheme a browser does not know (an Electron app's `app://` among them,
@@ -84,7 +62,7 @@ export function checkTheme(value: unknown, origin: string): ThemeCheck {
84
62
  if (typeof theme.look !== 'string' || !LOOKS.includes(theme.look)) return fail('look must be mac, gnome or windows')
85
63
  if (typeof theme.tokens !== 'object' || theme.tokens === null) return fail('tokens must be an object')
86
64
  const entries = Object.entries(theme.tokens as Record<string, unknown>)
87
- if (entries.length > MAX_TOKENS) return fail('too many tokens')
65
+ if (entries.length > MAX_THEME_TOKENS) return fail('too many tokens')
88
66
  const tokens: Record<string, string> = {}
89
67
  for (const [name, token] of entries) {
90
68
  if (!/^--[\w-]+$/.test(name)) return fail(`${name} is not a custom property`)
@@ -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,13 +82,14 @@ 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 {
77
89
  /**
78
90
  * Adds an app, or updates one. Throws for a second primary: two looks cannot both be worn. An update
79
91
  * drops what the app had held over its rate, unsent: it was vetted under the grants and origin it replaces.
92
+ * One that changes `primary` tells the app its new `role`, if it has said `hello`.
80
93
  */
81
94
  register(app: HostedApp): void
82
95
  /** Forgets an app: its chrome (`chrome` is called with null), its subscriptions, and what it published, except its last theme. */
@@ -94,6 +107,9 @@ export interface BroadcastRouter {
94
107
  const DEFAULT_MAX_PAYLOAD = 64 * 1024
95
108
  const RATE: Rate = { burst: 20, perSecond: 10 }
96
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 = ''
97
113
 
98
114
  interface Bucket {
99
115
  tokens: number
@@ -179,7 +195,8 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
179
195
  if (!bucket) {
180
196
  // A new topic starts with a full burst, so a flood across topics is bounded by how many a
181
197
  // publisher may have at once. A full, idle bucket says nothing a new one would not: it can go.
182
- 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)) {
183
200
  const idle = [...own].find(([t, b]) => !b.held && (refill(b), b.tokens >= b.rate.burst) && t)
184
201
  if (!idle) return count(app.id), 'rate limited'
185
202
  own.delete(idle[0])
@@ -256,6 +273,71 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
256
273
  }
257
274
  }
258
275
 
276
+ /** Apps that have said hello, told their role again when it changes. */
277
+ const greeted = new Set<string>()
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
+ }
340
+
259
341
  /** Cancels what an app held over its rate. */
260
342
  const dropHeld = (appId: string) => {
261
343
  for (const bucket of buckets.get(appId)?.values() ?? []) bucket.held?.cancel(), delete bucket.held
@@ -265,7 +347,9 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
265
347
  register(app) {
266
348
  if (app.primary && primaryId() !== null && primaryId() !== app.id) throw new Error(`${primaryId()} is already the primary`)
267
349
  dropHeld(app.id)
350
+ const was = apps.get(app.id)
268
351
  apps.set(app.id, app)
352
+ if (was && Boolean(was.primary) !== Boolean(app.primary) && greeted.has(app.id)) tellRole(app)
269
353
  if (app.primary) lastPrimary = app.id
270
354
  else if (lastPrimary === app.id) lastPrimary = null
271
355
  // A primary registered again after it went: what it kept still carries its role.
@@ -274,9 +358,11 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
274
358
  },
275
359
 
276
360
  unregister(appId) {
361
+ greeted.delete(appId)
277
362
  if (apps.delete(appId)) options.chrome?.(appId, null, [])
278
- // 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.
279
364
  dropHeld(appId)
365
+ endSwipe(appId)
280
366
  buckets.delete(appId)
281
367
  subscriptions.delete(appId)
282
368
  const own = kept.get(appId)
@@ -309,6 +395,14 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
309
395
  case 'unsubscribe':
310
396
  subscriptions.get(appId)?.delete(`${message.publisher}\u0000${message.topic}`)
311
397
  return null
398
+ case 'hello':
399
+ greeted.add(appId)
400
+ // A page connecting afresh (reloaded) has no swipe under way, whatever its last one left open.
401
+ dropSwipe(appId)
402
+ tellRole(app)
403
+ return null
404
+ case 'gesture':
405
+ return gesture(app, message.gesture)
312
406
  }
313
407
  },
314
408
 
@@ -339,7 +433,7 @@ export interface MemoryHost {
339
433
  * A host in memory. Messages are copied with `structuredClone` each way, as a real boundary would,
340
434
  * so an app that sends something that cannot cross fails here too.
341
435
  */
342
- export function createMemoryHost(options: Pick<BroadcastRouterOptions, 'check' | 'maxPayload'> = {}): MemoryHost {
436
+ export function createMemoryHost(options: Pick<BroadcastRouterOptions, 'check' | 'maxPayload' | 'gesture' | 'front' | 'limits' | 'clock'> = {}): MemoryHost {
343
437
  const listeners = new Map<string, Set<(message: HostToApp) => void>>()
344
438
  const chromes = new Map<string, DeskChrome>()
345
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])
@@ -67,6 +67,11 @@ export interface DeskProviderProps {
67
67
  * dark and the platform chrome apply whatever this does; the default, `applyTheme`, takes all of it.
68
68
  */
69
69
  readonly onTheme?: (theme: DeskTheme) => void
70
+ /**
71
+ * Hosted, the primary publishes the theme it wears (`appliedTheme`) for the other apps, at once and
72
+ * on every change. False publishes nothing; `usePublishTheme` publishes another theme instead.
73
+ */
74
+ readonly publishTheme?: boolean
70
75
  readonly children: ReactNode
71
76
  }
72
77
 
@@ -83,6 +88,8 @@ function useHostConnection(bridge: DeskHostBridge | null, wears: boolean, onThem
83
88
  if (!bridge) return
84
89
  const connected = connectHost(bridge)
85
90
  const stop = !wears ? () => {} : connected.subscribe<DeskTheme>('primary', THEME_TOPIC, ({ payload }) => {
91
+ // The primary hears its own theme back: it is already wearing it.
92
+ if (connected.primary()) return
86
93
  ;(wear.current ?? applyTheme)(payload)
87
94
  // After the app's own handler, so light or dark and the look hold whatever it did.
88
95
  applyThemeBasics(payload)
@@ -99,7 +106,7 @@ function useHostConnection(bridge: DeskHostBridge | null, wears: boolean, onThem
99
106
  return { client, theme }
100
107
  }
101
108
 
102
- export function DeskProvider({ desk, options, look: appLook = 'auto', services, app: declared, host, onTheme, children }: DeskProviderProps) {
109
+ export function DeskProvider({ desk, options, look: appLook = 'auto', services, app: declared, host, onTheme, publishTheme = true, children }: DeskProviderProps) {
103
110
  const [value] = useState(() => desk ?? createDesk(options))
104
111
  const [bus] = useState(createBus)
105
112
  const [held] = useState(() => services ?? [])
@@ -172,7 +179,7 @@ export function DeskProvider({ desk, options, look: appLook = 'auto', services,
172
179
  <LookContext.Provider value={resolved}>
173
180
  <AppProvider value={app ?? null}>
174
181
  <HostContext.Provider value={hosting}>
175
- {bridge && <HostedApp />}
182
+ {bridge && <HostedApp publishTheme={publishTheme} />}
176
183
  <DragProvider>{children}</DragProvider>
177
184
  </HostContext.Provider>
178
185
  </AppProvider>
@@ -5,7 +5,7 @@ import { hasSettings, useDeskApp } from './app.js'
5
5
  import type { AboutSection, AppLink, DeskApp } from './app.js'
6
6
  import { useOpenSettings } from './appPanels.js'
7
7
  import { badgeText } from './hostDock.js'
8
- import { useHost } from './hosted.js'
8
+ import { useHost, usePublishAppliedTheme } from './hosted.js'
9
9
 
10
10
  /*
11
11
  * SETTINGS AND ABOUT, WHEN A HOST HAS THEM.
@@ -65,8 +65,9 @@ export function hostSettings(app: DeskApp | null): HostSettingsSection[] {
65
65
  }
66
66
 
67
67
  /** Sends the host the app's Settings sections and About, and opens Settings where the host says. Draws nothing. */
68
- export function HostedApp() {
68
+ export function HostedApp({ publishTheme = true }: { readonly publishTheme?: boolean }) {
69
69
  const host = useHost()
70
+ usePublishAppliedTheme(publishTheme)
70
71
  const app = useDeskApp()
71
72
  const openSettings = useOpenSettings()
72
73
  // The facts are a hook, read here as the About panel reads them, so they can change.
@@ -1,7 +1,9 @@
1
- import { createContext, useContext, useEffect, useMemo, useRef } from 'react'
1
+ import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react'
2
2
  import { THEME_TOPIC } from '../core/hosted.js'
3
3
  import type { Broadcast, HostClient, Publisher } from '../core/hosted.js'
4
+ import { appliedTheme } from '../core/theme.js'
4
5
  import type { DeskTheme } from '../core/theme.js'
6
+ import { THEME_CHANGE } from '../core/themeChange.js'
5
7
  import type { MenuHost } from './hostMenu.js'
6
8
 
7
9
  /*
@@ -49,13 +51,16 @@ export function useHostBroadcast<T = unknown>(publisher: Publisher, topic: strin
49
51
  useEffect(() => host?.subscribe<T>(publisher, topic, broadcast => latest.current(broadcast)), [host, publisher, topic])
50
52
  }
51
53
 
52
- /**
53
- * Publishes this app's theme to the host, again whenever it changes: what the primary does so that
54
- * every other app wears its look. The host passes it on only from the primary. Does nothing when not
55
- * hosted, or while `theme` is null.
56
- */
57
- export function usePublishTheme(theme: DeskTheme | null): void {
58
- const host = useHost()
54
+ /** Per connection, how many `usePublishTheme`s are mounted, and who to tell when that changes. */
55
+ const themeOwners = new WeakMap<HostClient, { count: number; readonly changed: Set<() => void> }>()
56
+ const ownersOf = (host: HostClient) => {
57
+ let owners = themeOwners.get(host)
58
+ if (!owners) themeOwners.set(host, (owners = { count: 0, changed: new Set() }))
59
+ return owners
60
+ }
61
+
62
+ /** Sends `theme` when it is set and differs from what this hook last sent. The one path a theme takes. */
63
+ function useThemeSender(host: HostClient | null, theme: DeskTheme | null): void {
59
64
  const key = theme ? JSON.stringify(theme) : ''
60
65
  const latest = useRef(theme)
61
66
  latest.current = theme
@@ -63,3 +68,58 @@ export function usePublishTheme(theme: DeskTheme | null): void {
63
68
  if (host && latest.current) host.publish(THEME_TOPIC, latest.current)
64
69
  }, [host, key])
65
70
  }
71
+
72
+ /**
73
+ * Publishes this app's theme to the host, again whenever it changes: for a primary whose theme for the
74
+ * others is not the one it wears. While mounted, it is published instead of `appliedTheme`. The host
75
+ * passes it on only from the primary. Does nothing when not hosted; while `theme` is null it publishes
76
+ * nothing, and holds back `appliedTheme` too.
77
+ */
78
+ export function usePublishTheme(theme: DeskTheme | null): void {
79
+ const host = useHost()
80
+ useEffect(() => {
81
+ if (!host) return
82
+ const owners = ownersOf(host)
83
+ owners.count++
84
+ owners.changed.forEach(tell => tell())
85
+ return () => {
86
+ owners.count--
87
+ owners.changed.forEach(tell => tell())
88
+ }
89
+ }, [host])
90
+ useThemeSender(host, theme)
91
+ }
92
+
93
+ /**
94
+ * The primary's default: the theme it wears, at once and on every change of scheme, look or tokens,
95
+ * unless `enabled` is false or a `usePublishTheme` publishes another. An app that isn't the primary
96
+ * (the host says, through `role`) publishes nothing, so the host has nothing to refuse.
97
+ */
98
+ export function usePublishAppliedTheme(enabled: boolean): void {
99
+ const host = useHost()
100
+ const [theme, setTheme] = useState<DeskTheme | null>(null)
101
+ useEffect(() => {
102
+ if (!host || !enabled || typeof document === 'undefined') return
103
+ const owners = ownersOf(host)
104
+ let primary = false
105
+ const read = () => setTheme(primary && owners.count === 0 ? appliedTheme() : null)
106
+ const stopRole = host.onRole(is => {
107
+ primary = is
108
+ read()
109
+ })
110
+ owners.changed.add(read)
111
+ // Every way the worn theme changes ends on the root: the scheme and look as attributes, tokens in
112
+ // its style or a class, and a host's or the app's applyTheme says so with desk-themechange.
113
+ const observer = new MutationObserver(read)
114
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'data-look', 'style', 'class'] })
115
+ document.addEventListener(THEME_CHANGE, read)
116
+ return () => {
117
+ stopRole()
118
+ owners.changed.delete(read)
119
+ observer.disconnect()
120
+ document.removeEventListener(THEME_CHANGE, read)
121
+ setTheme(null)
122
+ }
123
+ }, [host, enabled])
124
+ useThemeSender(host, theme)
125
+ }
@@ -33,6 +33,8 @@ export interface DeskShellProps {
33
33
  readonly host?: DeskHostBridge | null
34
34
  /** How a hosted app wears the theme it is sent. See `DeskProviderProps.onTheme`. */
35
35
  readonly onTheme?: (theme: DeskTheme) => void
36
+ /** Hosted, whether the primary publishes the theme it wears. See `DeskProviderProps.publishTheme`. */
37
+ readonly publishTheme?: boolean
36
38
  /**
37
39
  * Where every choice Desk remembers is kept: scheme, look, sounds. This browser's localStorage when left
38
40
  * out. Desk copies the store's values to localStorage too, for the head script's first paint.
@@ -45,7 +47,7 @@ export interface DeskShellProps {
45
47
  const givenStores: PreferenceStore[] = []
46
48
 
47
49
  /** Everything an app needs around it, in one component: the desk, its bus, and toasts. */
48
- export function DeskShell({ desk, options, bus, toasts = true, look = 'auto', services = [], app, host, onTheme, preferences, children }: DeskShellProps) {
50
+ export function DeskShell({ desk, options, bus, toasts = true, look = 'auto', services = [], app, host, onTheme, publishTheme, preferences, children }: DeskShellProps) {
49
51
  const [made] = useState(() => desk ?? createDesk(options))
50
52
  useLayoutEffect(() => {
51
53
  if (!preferences) return
@@ -58,6 +60,6 @@ export function DeskShell({ desk, options, bus, toasts = true, look = 'auto', se
58
60
  }
59
61
  }, [preferences])
60
62
  const inner = toasts ? <ToastProvider>{children}</ToastProvider> : children
61
- const given = { ...(app ? { app } : {}), ...(host === undefined ? {} : { host }), ...(onTheme === undefined ? {} : { onTheme }) }
63
+ const given = { ...(app ? { app } : {}), ...(host === undefined ? {} : { host }), ...(onTheme === undefined ? {} : { onTheme }), ...(publishTheme === undefined ? {} : { publishTheme }) }
62
64
  return <DeskProvider desk={made} look={look} services={services} {...given}>{bus ? <BusProvider bus={bus}>{inner}</BusProvider> : inner}</DeskProvider>
63
65
  }