@liberation-data/desk 0.45.0 → 0.46.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 (70) hide show
  1. package/README.md +58 -6
  2. package/dist/core/hosted.d.ts +15 -0
  3. package/dist/core/hosted.d.ts.map +1 -1
  4. package/dist/core/hosted.js +28 -0
  5. package/dist/core/hosted.js.map +1 -1
  6. package/dist/core/index.d.ts +1 -1
  7. package/dist/core/index.d.ts.map +1 -1
  8. package/dist/core/index.js +1 -1
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/theme.d.ts +15 -0
  11. package/dist/core/theme.d.ts.map +1 -1
  12. package/dist/core/theme.js +73 -1
  13. package/dist/core/theme.js.map +1 -1
  14. package/dist/css/shell.css +89 -0
  15. package/dist/host/checkTheme.d.ts +2 -7
  16. package/dist/host/checkTheme.d.ts.map +1 -1
  17. package/dist/host/checkTheme.js +3 -27
  18. package/dist/host/checkTheme.js.map +1 -1
  19. package/dist/host/router.d.ts +1 -0
  20. package/dist/host/router.d.ts.map +1 -1
  21. package/dist/host/router.js +11 -0
  22. package/dist/host/router.js.map +1 -1
  23. package/dist/react/context.d.ts +6 -1
  24. package/dist/react/context.d.ts.map +1 -1
  25. package/dist/react/context.js +5 -3
  26. package/dist/react/context.js.map +1 -1
  27. package/dist/react/hostApp.d.ts +3 -1
  28. package/dist/react/hostApp.d.ts.map +1 -1
  29. package/dist/react/hostApp.js +3 -2
  30. package/dist/react/hostApp.js.map +1 -1
  31. package/dist/react/hosted.d.ts +10 -3
  32. package/dist/react/hosted.d.ts.map +1 -1
  33. package/dist/react/hosted.js +68 -8
  34. package/dist/react/hosted.js.map +1 -1
  35. package/dist/react/shell.d.ts +3 -1
  36. package/dist/react/shell.d.ts.map +1 -1
  37. package/dist/react/shell.js +2 -2
  38. package/dist/react/shell.js.map +1 -1
  39. package/dist/shell/HostOverview.d.ts +41 -0
  40. package/dist/shell/HostOverview.d.ts.map +1 -0
  41. package/dist/shell/HostOverview.js +219 -0
  42. package/dist/shell/HostOverview.js.map +1 -0
  43. package/dist/shell/HostShell.d.ts +3 -1
  44. package/dist/shell/HostShell.d.ts.map +1 -1
  45. package/dist/shell/HostShell.js +6 -4
  46. package/dist/shell/HostShell.js.map +1 -1
  47. package/dist/shell/index.d.ts +4 -0
  48. package/dist/shell/index.d.ts.map +1 -1
  49. package/dist/shell/index.js +2 -0
  50. package/dist/shell/index.js.map +1 -1
  51. package/dist/shell/zoom.d.ts +62 -0
  52. package/dist/shell/zoom.d.ts.map +1 -0
  53. package/dist/shell/zoom.js +116 -0
  54. package/dist/shell/zoom.js.map +1 -0
  55. package/llms.txt +9 -4
  56. package/package.json +12 -7
  57. package/src/core/hosted.ts +33 -0
  58. package/src/core/index.ts +1 -1
  59. package/src/core/theme.ts +69 -1
  60. package/src/css/shell.css +89 -0
  61. package/src/host/checkTheme.ts +3 -25
  62. package/src/host/router.ts +12 -0
  63. package/src/react/context.tsx +9 -2
  64. package/src/react/hostApp.tsx +3 -2
  65. package/src/react/hosted.tsx +68 -8
  66. package/src/react/shell.tsx +4 -2
  67. package/src/shell/HostOverview.tsx +317 -0
  68. package/src/shell/HostShell.tsx +8 -5
  69. package/src/shell/index.ts +18 -0
  70. package/src/shell/zoom.ts +151 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liberation-data/desk",
3
- "version": "0.45.0",
3
+ "version": "0.46.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",
@@ -36,23 +36,28 @@
36
36
  "exports": {
37
37
  ".": {
38
38
  "types": "./dist/core/index.d.ts",
39
- "import": "./dist/core/index.js"
39
+ "import": "./dist/core/index.js",
40
+ "default": "./dist/core/index.js"
40
41
  },
41
42
  "./react": {
42
43
  "types": "./dist/react/index.d.ts",
43
- "import": "./dist/react/index.js"
44
+ "import": "./dist/react/index.js",
45
+ "default": "./dist/react/index.js"
44
46
  },
45
47
  "./host": {
46
48
  "types": "./dist/host/index.d.ts",
47
- "import": "./dist/host/index.js"
49
+ "import": "./dist/host/index.js",
50
+ "default": "./dist/host/index.js"
48
51
  },
49
52
  "./shell": {
50
53
  "types": "./dist/shell/index.d.ts",
51
- "import": "./dist/shell/index.js"
54
+ "import": "./dist/shell/index.js",
55
+ "default": "./dist/shell/index.js"
52
56
  },
53
57
  "./fx": {
54
58
  "types": "./dist/fx/index.d.ts",
55
- "import": "./dist/fx/index.js"
59
+ "import": "./dist/fx/index.js",
60
+ "default": "./dist/fx/index.js"
56
61
  },
57
62
  "./desk.css": "./dist/desk.css",
58
63
  "./css/*": "./dist/css/*"
@@ -64,7 +69,7 @@
64
69
  "example": "vite examples/garage",
65
70
  "prepublishOnly": "npm run typecheck && npm test && npm run build",
66
71
  "size": "node scripts/size.mjs",
67
- "check": "npm run typecheck && npm test && npm run build && npm run size",
72
+ "check": "npm run typecheck && npm test && npm run build && npm run size && node scripts/require.mjs",
68
73
  "check:browser": "node scripts/browser-check.mjs",
69
74
  "screenshots": "node scripts/screenshots.mjs"
70
75
  },
@@ -171,12 +171,16 @@ export type AppToHost =
171
171
  | { readonly desk: 1; readonly kind: 'publish'; readonly topic: string; readonly payload: unknown }
172
172
  | { readonly desk: 1; readonly kind: 'subscribe'; readonly publisher: Publisher; readonly topic: string }
173
173
  | { readonly desk: 1; readonly kind: 'unsubscribe'; readonly publisher: Publisher; readonly topic: string }
174
+ /** Sent on connecting: the host answers with the app's `role`. */
175
+ | { readonly desk: 1; readonly kind: 'hello' }
174
176
 
175
177
  /** What a host sends an app: a choice from the chrome it draws, or another app's broadcast, stamped. */
176
178
  export type HostToApp =
177
179
  /** A menu item or dock item chosen by its id, or Settings opened at a section's id (`''` for the first). */
178
180
  | { readonly desk: 1; readonly kind: 'command'; readonly target: CommandTarget; readonly id: string }
179
181
  | { readonly desk: 1; readonly kind: 'broadcast'; readonly from: BroadcastSender; readonly topic: string; readonly payload: unknown }
182
+ /** Whether the app is the primary, whose theme the others wear: the answer to `hello`, and again when it changes. */
183
+ | { readonly desk: 1; readonly kind: 'role'; readonly primary: boolean }
180
184
 
181
185
  /**
182
186
  * The app's end of the connection to its host. The host provides it — an Electron preload through
@@ -219,6 +223,8 @@ export function isAppToHost(value: unknown): value is AppToHost {
219
223
  case 'subscribe':
220
224
  case 'unsubscribe':
221
225
  return isString(value.publisher) && isString(value.topic) && value.topic.length > 0
226
+ case 'hello':
227
+ return true
222
228
  default:
223
229
  return false
224
230
  }
@@ -232,6 +238,8 @@ export function isHostToApp(value: unknown): value is HostToApp {
232
238
  return (value.target === 'menu' || value.target === 'dock' || value.target === 'settings') && isString(value.id)
233
239
  case 'broadcast':
234
240
  return isRecord(value.from) && isString(value.from.id) && isString(value.topic)
241
+ case 'role':
242
+ return typeof value.primary === 'boolean'
235
243
  default:
236
244
  return false
237
245
  }
@@ -258,6 +266,10 @@ export interface HostClient {
258
266
  * one straight away, so an app that starts late still hears the current theme.
259
267
  */
260
268
  subscribe<T = unknown>(publisher: Publisher, topic: string, handler: (broadcast: Broadcast<T>) => void): () => void
269
+ /** Whether the host says this app is the primary; null until it has said. */
270
+ primary(): boolean | null
271
+ /** Calls the listener when the host says whether this app is the primary, now and on any change. */
272
+ onRole(listener: (primary: boolean) => void): () => void
261
273
  /** Stops listening, and takes the chrome away. */
262
274
  close(): void
263
275
  }
@@ -274,9 +286,17 @@ export function connectHost(bridge: DeskHostBridge): HostClient {
274
286
  /** Per subscription, the broadcasts last heard on each topic it covers, for a second handler that joins later. */
275
287
  const subscriptions = new Map<string, { publisher: Publisher; topic: string; handlers: Set<Handler>; last: Map<string, Broadcast> }>()
276
288
  const keyOf = (publisher: string, topic: string) => `${publisher}\u0000${topic}`
289
+ let primary: boolean | null = null
290
+ const roles = new Set<(primary: boolean) => void>()
277
291
 
278
292
  const stop = bridge.onMessage(message => {
279
293
  if (closed || !isHostToApp(message)) return
294
+ if (message.kind === 'role') {
295
+ if (primary === message.primary) return
296
+ primary = message.primary
297
+ for (const listener of [...roles]) if (roles.has(listener)) listener(message.primary)
298
+ return
299
+ }
280
300
  if (message.kind === 'command') {
281
301
  const listeners = commands[message.target]
282
302
  // Copied, and each still checked: a listener may take another away while this one runs.
@@ -293,6 +313,9 @@ export function connectHost(bridge: DeskHostBridge): HostClient {
293
313
  }
294
314
  })
295
315
 
316
+ // Listening first, so a host that answers at once is heard.
317
+ bridge.send({ desk: DESK_PROTOCOL, kind: 'hello' })
318
+
296
319
  return {
297
320
  bridge,
298
321
  setChrome(part) {
@@ -337,8 +360,18 @@ export function connectHost(bridge: DeskHostBridge): HostClient {
337
360
  }
338
361
  }
339
362
  },
363
+ primary: () => primary,
364
+ onRole(listener) {
365
+ roles.add(listener)
366
+ if (primary !== null) listener(primary)
367
+ return () => {
368
+ roles.delete(listener)
369
+ }
370
+ },
340
371
  close() {
341
372
  if (closed) return
373
+ roles.clear()
374
+ primary = null
342
375
  bridge.send({ desk: DESK_PROTOCOL, kind: 'chrome', chrome: EMPTY_CHROME })
343
376
  // So the host stops sending what nobody here hears.
344
377
  for (const { publisher, topic } of subscriptions.values()) bridge.send({ desk: DESK_PROTOCOL, kind: 'unsubscribe', publisher, topic })
package/src/core/index.ts CHANGED
@@ -39,7 +39,7 @@ export { COLOR_SCHEME_KEY, COLOR_SCHEME_SCRIPT, colorSchemeScript, LOOK_KEY } fr
39
39
  export { getPreference, localPreferences, setPreference, setPreferenceStore, subscribePreferences } from './preferences.js'
40
40
  export type { PreferenceStore } from './preferences.js'
41
41
  export type { ColorScheme } from './scheme.js'
42
- export { applyTheme, applyThemeBasics } from './theme.js'
42
+ export { applyTheme, applyThemeBasics, appliedTheme } from './theme.js'
43
43
  export { drawnTheme, THEME_CHANGE, watchThemeChanges } from './themeChange.js'
44
44
  export type { ThemeChange } from './themeChange.js'
45
45
  export type { AppTheme, DeskTheme, ThemeFont } from './theme.js'
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`)
@@ -77,6 +77,7 @@ export interface BroadcastRouter {
77
77
  /**
78
78
  * Adds an app, or updates one. Throws for a second primary: two looks cannot both be worn. An update
79
79
  * drops what the app had held over its rate, unsent: it was vetted under the grants and origin it replaces.
80
+ * One that changes `primary` tells the app its new `role`, if it has said `hello`.
80
81
  */
81
82
  register(app: HostedApp): void
82
83
  /** Forgets an app: its chrome (`chrome` is called with null), its subscriptions, and what it published, except its last theme. */
@@ -256,6 +257,10 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
256
257
  }
257
258
  }
258
259
 
260
+ /** Apps that have said hello, told their role again when it changes. */
261
+ const greeted = new Set<string>()
262
+ const tellRole = (app: HostedApp) => options.deliver(app.id, { desk: DESK_PROTOCOL, kind: 'role', primary: Boolean(app.primary) })
263
+
259
264
  /** Cancels what an app held over its rate. */
260
265
  const dropHeld = (appId: string) => {
261
266
  for (const bucket of buckets.get(appId)?.values() ?? []) bucket.held?.cancel(), delete bucket.held
@@ -265,7 +270,9 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
265
270
  register(app) {
266
271
  if (app.primary && primaryId() !== null && primaryId() !== app.id) throw new Error(`${primaryId()} is already the primary`)
267
272
  dropHeld(app.id)
273
+ const was = apps.get(app.id)
268
274
  apps.set(app.id, app)
275
+ if (was && Boolean(was.primary) !== Boolean(app.primary) && greeted.has(app.id)) tellRole(app)
269
276
  if (app.primary) lastPrimary = app.id
270
277
  else if (lastPrimary === app.id) lastPrimary = null
271
278
  // A primary registered again after it went: what it kept still carries its role.
@@ -274,6 +281,7 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
274
281
  },
275
282
 
276
283
  unregister(appId) {
284
+ greeted.delete(appId)
277
285
  if (apps.delete(appId)) options.chrome?.(appId, null, [])
278
286
  // What it had held goes with it, unsent.
279
287
  dropHeld(appId)
@@ -309,6 +317,10 @@ export function createBroadcastRouter(options: BroadcastRouterOptions): Broadcas
309
317
  case 'unsubscribe':
310
318
  subscriptions.get(appId)?.delete(`${message.publisher}\u0000${message.topic}`)
311
319
  return null
320
+ case 'hello':
321
+ greeted.add(appId)
322
+ tellRole(app)
323
+ return null
312
324
  }
313
325
  },
314
326
 
@@ -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
  }