@liberation-data/desk 0.43.0 → 0.44.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 (168) hide show
  1. package/README.md +225 -8
  2. package/dist/core/hosted.d.ts +222 -0
  3. package/dist/core/hosted.d.ts.map +1 -0
  4. package/dist/core/hosted.js +166 -0
  5. package/dist/core/hosted.js.map +1 -0
  6. package/dist/core/index.d.ts +9 -1
  7. package/dist/core/index.d.ts.map +1 -1
  8. package/dist/core/index.js +5 -1
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/location.d.ts +8 -1
  11. package/dist/core/location.d.ts.map +1 -1
  12. package/dist/core/location.js +18 -2
  13. package/dist/core/location.js.map +1 -1
  14. package/dist/core/preferences.d.ts +27 -0
  15. package/dist/core/preferences.d.ts.map +1 -0
  16. package/dist/core/preferences.js +121 -0
  17. package/dist/core/preferences.js.map +1 -0
  18. package/dist/core/scheme.d.ts +9 -3
  19. package/dist/core/scheme.d.ts.map +1 -1
  20. package/dist/core/scheme.js +13 -4
  21. package/dist/core/scheme.js.map +1 -1
  22. package/dist/core/theme.d.ts +41 -0
  23. package/dist/core/theme.d.ts.map +1 -0
  24. package/dist/core/theme.js +56 -0
  25. package/dist/core/theme.js.map +1 -0
  26. package/dist/core/themeChange.d.ts +25 -0
  27. package/dist/core/themeChange.d.ts.map +1 -0
  28. package/dist/core/themeChange.js +49 -0
  29. package/dist/core/themeChange.js.map +1 -0
  30. package/dist/css/apps.css +35 -1
  31. package/dist/css/shell.css +100 -0
  32. package/dist/css/tokens.css +10 -0
  33. package/dist/desk.css +45 -1
  34. package/dist/fx/fx.d.ts.map +1 -1
  35. package/dist/fx/fx.js +7 -31
  36. package/dist/fx/fx.js.map +1 -1
  37. package/dist/host/checkChrome.d.ts +20 -0
  38. package/dist/host/checkChrome.d.ts.map +1 -0
  39. package/dist/host/checkChrome.js +219 -0
  40. package/dist/host/checkChrome.js.map +1 -0
  41. package/dist/host/checkTheme.d.ts +35 -0
  42. package/dist/host/checkTheme.d.ts.map +1 -0
  43. package/dist/host/checkTheme.js +128 -0
  44. package/dist/host/checkTheme.js.map +1 -0
  45. package/dist/host/index.d.ts +7 -0
  46. package/dist/host/index.d.ts.map +1 -0
  47. package/dist/host/index.js +8 -0
  48. package/dist/host/index.js.map +1 -0
  49. package/dist/host/router.d.ts +99 -0
  50. package/dist/host/router.d.ts.map +1 -0
  51. package/dist/host/router.js +279 -0
  52. package/dist/host/router.js.map +1 -0
  53. package/dist/react/Dock.d.ts +23 -4
  54. package/dist/react/Dock.d.ts.map +1 -1
  55. package/dist/react/Dock.js +17 -29
  56. package/dist/react/Dock.js.map +1 -1
  57. package/dist/react/MenuBar.d.ts +1 -1
  58. package/dist/react/MenuBar.d.ts.map +1 -1
  59. package/dist/react/MenuBar.js +20 -4
  60. package/dist/react/MenuBar.js.map +1 -1
  61. package/dist/react/app.d.ts +50 -9
  62. package/dist/react/app.d.ts.map +1 -1
  63. package/dist/react/app.js +59 -13
  64. package/dist/react/app.js.map +1 -1
  65. package/dist/react/appFrame.d.ts +11 -7
  66. package/dist/react/appFrame.d.ts.map +1 -1
  67. package/dist/react/appFrame.js +24 -6
  68. package/dist/react/appFrame.js.map +1 -1
  69. package/dist/react/appPanels.d.ts +4 -1
  70. package/dist/react/appPanels.d.ts.map +1 -1
  71. package/dist/react/appPanels.js +32 -23
  72. package/dist/react/appPanels.js.map +1 -1
  73. package/dist/react/appearance.d.ts +7 -1
  74. package/dist/react/appearance.d.ts.map +1 -1
  75. package/dist/react/appearance.js +32 -53
  76. package/dist/react/appearance.js.map +1 -1
  77. package/dist/react/context.d.ts +15 -1
  78. package/dist/react/context.d.ts.map +1 -1
  79. package/dist/react/context.js +73 -14
  80. package/dist/react/context.js.map +1 -1
  81. package/dist/react/dockStatus.d.ts +19 -0
  82. package/dist/react/dockStatus.d.ts.map +1 -0
  83. package/dist/react/dockStatus.js +25 -0
  84. package/dist/react/dockStatus.js.map +1 -0
  85. package/dist/react/frameMenus.d.ts +28 -0
  86. package/dist/react/frameMenus.d.ts.map +1 -0
  87. package/dist/react/frameMenus.js +85 -0
  88. package/dist/react/frameMenus.js.map +1 -0
  89. package/dist/react/hostApp.d.ts +15 -0
  90. package/dist/react/hostApp.d.ts.map +1 -0
  91. package/dist/react/hostApp.js +77 -0
  92. package/dist/react/hostApp.js.map +1 -0
  93. package/dist/react/hostDock.d.ts +25 -0
  94. package/dist/react/hostDock.d.ts.map +1 -0
  95. package/dist/react/hostDock.js +98 -0
  96. package/dist/react/hostDock.js.map +1 -0
  97. package/dist/react/hostMenu.d.ts +2 -36
  98. package/dist/react/hostMenu.d.ts.map +1 -1
  99. package/dist/react/hostMenu.js.map +1 -1
  100. package/dist/react/hosted.d.ts +28 -0
  101. package/dist/react/hosted.d.ts.map +1 -0
  102. package/dist/react/hosted.js +53 -0
  103. package/dist/react/hosted.js.map +1 -0
  104. package/dist/react/index.d.ts +8 -3
  105. package/dist/react/index.d.ts.map +1 -1
  106. package/dist/react/index.js +5 -2
  107. package/dist/react/index.js.map +1 -1
  108. package/dist/react/shell.d.ts +13 -1
  109. package/dist/react/shell.d.ts.map +1 -1
  110. package/dist/react/shell.js +19 -3
  111. package/dist/react/shell.js.map +1 -1
  112. package/dist/react/windowMenus.d.ts +19 -0
  113. package/dist/react/windowMenus.d.ts.map +1 -0
  114. package/dist/react/windowMenus.js +88 -0
  115. package/dist/react/windowMenus.js.map +1 -0
  116. package/dist/shell/HostShell.d.ts +53 -0
  117. package/dist/shell/HostShell.d.ts.map +1 -0
  118. package/dist/shell/HostShell.js +116 -0
  119. package/dist/shell/HostShell.js.map +1 -0
  120. package/dist/shell/index.d.ts +7 -0
  121. package/dist/shell/index.d.ts.map +1 -0
  122. package/dist/shell/index.js +9 -0
  123. package/dist/shell/index.js.map +1 -0
  124. package/dist/shell/keys.d.ts +47 -0
  125. package/dist/shell/keys.d.ts.map +1 -0
  126. package/dist/shell/keys.js +68 -0
  127. package/dist/shell/keys.js.map +1 -0
  128. package/dist/shell/motion.d.ts +72 -0
  129. package/dist/shell/motion.d.ts.map +1 -0
  130. package/dist/shell/motion.js +118 -0
  131. package/dist/shell/motion.js.map +1 -0
  132. package/llms.txt +48 -14
  133. package/package.json +10 -1
  134. package/src/core/hosted.ts +351 -0
  135. package/src/core/index.ts +28 -1
  136. package/src/core/location.ts +23 -3
  137. package/src/core/preferences.ts +132 -0
  138. package/src/core/scheme.ts +16 -5
  139. package/src/core/theme.ts +91 -0
  140. package/src/core/themeChange.ts +59 -0
  141. package/src/css/apps.css +35 -1
  142. package/src/css/shell.css +99 -0
  143. package/src/css/tokens.css +10 -0
  144. package/src/fx/fx.ts +7 -25
  145. package/src/host/checkChrome.ts +257 -0
  146. package/src/host/checkTheme.ts +134 -0
  147. package/src/host/index.ts +10 -0
  148. package/src/host/router.ts +374 -0
  149. package/src/react/Dock.tsx +34 -28
  150. package/src/react/MenuBar.tsx +22 -4
  151. package/src/react/app.tsx +84 -14
  152. package/src/react/appFrame.tsx +39 -14
  153. package/src/react/appPanels.tsx +38 -25
  154. package/src/react/appearance.tsx +36 -45
  155. package/src/react/context.tsx +88 -13
  156. package/src/react/dockStatus.ts +42 -0
  157. package/src/react/frameMenus.ts +100 -0
  158. package/src/react/hostApp.tsx +89 -0
  159. package/src/react/hostDock.tsx +118 -0
  160. package/src/react/hostMenu.ts +3 -38
  161. package/src/react/hosted.tsx +65 -0
  162. package/src/react/index.ts +9 -2
  163. package/src/react/shell.tsx +30 -3
  164. package/src/react/windowMenus.ts +107 -0
  165. package/src/shell/HostShell.tsx +220 -0
  166. package/src/shell/index.ts +11 -0
  167. package/src/shell/keys.ts +101 -0
  168. package/src/shell/motion.ts +163 -0
@@ -0,0 +1,351 @@
1
+ import { topicMatches } from './events.js'
2
+
3
+ /*
4
+ * HOSTED MODE: SEVERAL DESK APPS UNDER ONE MENU BAR AND DOCK.
5
+ *
6
+ * A host — a native shell such as Electron, or a web page framing several apps — can run more than
7
+ * one Desk app side by side and draw one menu bar and one dock above all of them, so moving between
8
+ * apps changes only what fills the desktop. Each app then draws no chrome of its own: it sends its
9
+ * menus and dock to the host as plain data, and the host sends back what the person chose.
10
+ *
11
+ * Apps never talk to each other directly. Everything goes through the host, which knows which app
12
+ * each message came from and stamps it on what it passes on: an app cannot speak as another. An app
13
+ * publishes on a topic, and apps that asked for that publisher's topic hear it. The first topic is
14
+ * the theme: one app, the primary, sets the look every app wears.
15
+ *
16
+ * The transport is the host's: an Electron preload, or `postMessage` between frames. Either way it
17
+ * is a `DeskHostBridge`, found on `globalThis.deskHost`, and every message carries the protocol
18
+ * number, so a mismatch is ignored rather than misread.
19
+ */
20
+
21
+ /** The protocol version. Every message carries it as `desk`, framed apps' messages included. */
22
+ export const DESK_PROTOCOL = 1
23
+
24
+ /** The topic of the look every app wears: a `DeskTheme`. Only the primary may publish it. */
25
+ export const THEME_TOPIC = 'theme'
26
+
27
+ /** One row of a menu a host draws. Plain data, so it can cross a process boundary. */
28
+ export interface HostMenuItem {
29
+ readonly type: 'item' | 'separator' | 'header'
30
+ /**
31
+ * Present on 'item'; unique within one publish. Opaque to a host, which only sends it back: it
32
+ * names the item's menu, place and label, so a choice from a menu that has since changed runs
33
+ * nothing rather than whatever took that place.
34
+ */
35
+ readonly id?: string
36
+ /** Present on 'item' and 'header'. */
37
+ readonly label?: string
38
+ readonly detail?: string
39
+ /** In desk's format: 'mod+k', 'mod+alt+a', 'alt+]'. */
40
+ readonly shortcut?: string
41
+ /**
42
+ * The page handles this item's shortcut itself, so a host draws it beside the item and gives it
43
+ * no key (Electron: `registerAccelerator: false`). Set on an action's shortcut, which the drawn
44
+ * bar only shows too: binding it as well would fire the action twice.
45
+ */
46
+ readonly showOnly?: boolean
47
+ /** Defaults to true. */
48
+ readonly enabled?: boolean
49
+ /** Absent means the item is not checkable. */
50
+ readonly checked?: boolean
51
+ }
52
+
53
+ /** A whole menu as a host sees it. */
54
+ export interface HostMenu {
55
+ readonly id: string
56
+ /** The menu's `label`: a host draws text, so a status menu's richer `title` stays behind. */
57
+ readonly label: string
58
+ /** The app's own menu, which a `Menu` calls `emphasis`. */
59
+ readonly primary?: boolean
60
+ /** One of the bar's status menus, which a host puts after the others. */
61
+ readonly status?: boolean
62
+ readonly items: readonly HostMenuItem[]
63
+ }
64
+
65
+ /** One dock item as a host draws it: what the app's dock would show, as data. */
66
+ export interface HostDockItem {
67
+ readonly type: 'item'
68
+ /** Sent back in a `command` when the item is chosen. */
69
+ readonly id: string
70
+ readonly label: string
71
+ readonly description?: string
72
+ /** An image URL or `data:` URI from the item's `image`; a host without one draws the label. */
73
+ readonly image?: string
74
+ /** The badge as text; `''` for a badge that is not text, which a host draws as a dot. */
75
+ readonly badge?: string
76
+ readonly disabled?: boolean
77
+ readonly running: boolean
78
+ readonly focused: boolean
79
+ readonly minimized: boolean
80
+ }
81
+
82
+ /** A dock stack as a host draws it: a folder of items that opens on the host's dock. */
83
+ export interface HostDockStack {
84
+ readonly type: 'stack'
85
+ readonly id: string
86
+ readonly label: string
87
+ readonly image?: string
88
+ readonly items: readonly HostDockItem[]
89
+ }
90
+
91
+ /** One place on the dock a host draws. */
92
+ export type HostDockEntry = HostDockItem | HostDockStack | { readonly type: 'separator'; readonly id: string }
93
+
94
+ /**
95
+ * A section of the app's Settings, for the host's one Settings, which lists each app's sections. Its
96
+ * controls are the app's and stay in the app: choosing one sends a `settings` command with its id, and
97
+ * the app opens its own Settings there.
98
+ */
99
+ export interface HostSettingsSection {
100
+ readonly id: string
101
+ readonly title: string
102
+ /** The heading it is listed under, as in a sidebar of sections. */
103
+ readonly group?: string
104
+ /** As text; `''` for a badge that is not text. */
105
+ readonly badge?: string
106
+ }
107
+
108
+ /** One fact of the app's About: what something is, and its value. */
109
+ export interface HostAboutFact {
110
+ readonly name: string
111
+ readonly value: string
112
+ /** Where to read more, shown with the fact as a link. Never copied. */
113
+ readonly link?: { readonly label: string; readonly url: string }
114
+ /** `false` keeps it out of what the host copies for a bug report. It is still shown. */
115
+ readonly copy?: false
116
+ }
117
+
118
+ export interface HostAboutSection {
119
+ readonly title?: string
120
+ readonly facts: readonly HostAboutFact[]
121
+ }
122
+
123
+ /**
124
+ * What the app says about itself, for its section of the host's one About. Its links, and its facts',
125
+ * are http(s), `mailto:` or on the app's origin (`checkChrome`); a host opens them in the system
126
+ * browser or mail app, or in a new window with `rel="noopener noreferrer"`, never in its own frame.
127
+ */
128
+ export interface HostAbout {
129
+ readonly name: string
130
+ readonly version?: string
131
+ readonly links: readonly { readonly label: string; readonly url: string }[]
132
+ /** A short line under the links, never copied: what this build can and cannot say. Text only. */
133
+ readonly note?: string
134
+ /** Null while the app is still reading them; `[]` when there is nothing to report, and nothing to copy. */
135
+ readonly facts: readonly HostAboutSection[] | null
136
+ }
137
+
138
+ /**
139
+ * Everything an app would draw around its desktop, for the host to draw instead. The host's frame has
140
+ * the one Settings and About: an app sends its sections and facts, and draws no gear and no About item
141
+ * of its own. Widgets are not in it: they stay on the app's desktop.
142
+ */
143
+ export interface DeskChrome {
144
+ readonly menus: readonly HostMenu[]
145
+ readonly dock: readonly HostDockEntry[]
146
+ /** Empty for an app with no settings; one entry with the id `''` for one whose Settings is a window of its own. */
147
+ readonly settings: readonly HostSettingsSection[]
148
+ /** Null for an app that declared nothing about itself. */
149
+ readonly about: HostAbout | null
150
+ }
151
+
152
+ /** Who sent a broadcast, as the host stamped it. */
153
+ export interface BroadcastSender {
154
+ readonly id: string
155
+ /** Present when the sender is the app whose theme every app wears. */
156
+ readonly role?: 'primary'
157
+ }
158
+
159
+ /**
160
+ * Whose broadcasts a subscription is for: an app's id, or `'primary'` for whichever app is the
161
+ * primary, so a subscriber need not change when the host makes another app primary.
162
+ */
163
+ export type Publisher = 'primary' | (string & {})
164
+
165
+ /** What a host's command is for: the app's menus, its dock, or its Settings. */
166
+ export type CommandTarget = 'menu' | 'dock' | 'settings'
167
+
168
+ /** What an app sends its host. Untrusted at the host's end: check it with `isAppToHost`. */
169
+ export type AppToHost =
170
+ | { readonly desk: 1; readonly kind: 'chrome'; readonly chrome: DeskChrome }
171
+ | { readonly desk: 1; readonly kind: 'publish'; readonly topic: string; readonly payload: unknown }
172
+ | { readonly desk: 1; readonly kind: 'subscribe'; readonly publisher: Publisher; readonly topic: string }
173
+ | { readonly desk: 1; readonly kind: 'unsubscribe'; readonly publisher: Publisher; readonly topic: string }
174
+
175
+ /** What a host sends an app: a choice from the chrome it draws, or another app's broadcast, stamped. */
176
+ export type HostToApp =
177
+ /** A menu item or dock item chosen by its id, or Settings opened at a section's id (`''` for the first). */
178
+ | { readonly desk: 1; readonly kind: 'command'; readonly target: CommandTarget; readonly id: string }
179
+ | { readonly desk: 1; readonly kind: 'broadcast'; readonly from: BroadcastSender; readonly topic: string; readonly payload: unknown }
180
+
181
+ /**
182
+ * The app's end of the connection to its host. The host provides it — an Electron preload through
183
+ * `contextBridge`, a framed page through `postMessage` — as `globalThis.deskHost`.
184
+ */
185
+ export interface DeskHostBridge {
186
+ /** The protocol the host speaks. An app that does not speak it runs unhosted. */
187
+ readonly version: number
188
+ send(message: AppToHost): void
189
+ /** Calls the listener with each message from the host; returns an unsubscribe. */
190
+ onMessage(listener: (message: HostToApp) => void): () => void
191
+ }
192
+
193
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
194
+
195
+ /** Whether `value` has a bridge's shape: `globalThis.deskHost` is set by code this page does not own. */
196
+ export function isDeskHostBridge(value: unknown): value is DeskHostBridge {
197
+ return isRecord(value) && typeof value.version === 'number' && typeof value.send === 'function' && typeof value.onMessage === 'function'
198
+ }
199
+
200
+ /** The host this page runs in, when one put a bridge that speaks this protocol on `globalThis.deskHost`; null otherwise. */
201
+ export function findDeskHost(): DeskHostBridge | null {
202
+ const candidate = (globalThis as { deskHost?: unknown }).deskHost
203
+ return isDeskHostBridge(candidate) && candidate.version === DESK_PROTOCOL ? candidate : null
204
+ }
205
+
206
+ const isString = (value: unknown): value is string => typeof value === 'string'
207
+ const isList = (value: unknown): value is unknown[] => Array.isArray(value)
208
+
209
+ /** Whether a message from an app has the shape of one. A host checks before acting on it: the app is not trusted. */
210
+ export function isAppToHost(value: unknown): value is AppToHost {
211
+ if (!isRecord(value) || value.desk !== DESK_PROTOCOL) return false
212
+ switch (value.kind) {
213
+ case 'chrome': {
214
+ const chrome = value.chrome
215
+ return isRecord(chrome) && isList(chrome.menus) && isList(chrome.dock) && isList(chrome.settings) && (chrome.about === null || isRecord(chrome.about))
216
+ }
217
+ case 'publish':
218
+ return isString(value.topic) && value.topic.length > 0
219
+ case 'subscribe':
220
+ case 'unsubscribe':
221
+ return isString(value.publisher) && isString(value.topic) && value.topic.length > 0
222
+ default:
223
+ return false
224
+ }
225
+ }
226
+
227
+ /** Whether a message from a host has the shape of one. */
228
+ export function isHostToApp(value: unknown): value is HostToApp {
229
+ if (!isRecord(value) || value.desk !== DESK_PROTOCOL) return false
230
+ switch (value.kind) {
231
+ case 'command':
232
+ return (value.target === 'menu' || value.target === 'dock' || value.target === 'settings') && isString(value.id)
233
+ case 'broadcast':
234
+ return isRecord(value.from) && isString(value.from.id) && isString(value.topic)
235
+ default:
236
+ return false
237
+ }
238
+ }
239
+
240
+ /** A broadcast as an app hears it. */
241
+ export interface Broadcast<T = unknown> {
242
+ readonly from: BroadcastSender
243
+ readonly topic: string
244
+ readonly payload: T
245
+ }
246
+
247
+ /** The app's side of hosted mode, over a bridge: what it sends the host, and what it hears back. */
248
+ export interface HostClient {
249
+ readonly bridge: DeskHostBridge
250
+ /** Replaces part of the chrome. Changes made in one task go to the host as one message. */
251
+ setChrome(part: Partial<DeskChrome>): void
252
+ /** Calls the listener with the id of each menu item, dock item or Settings section the host says was chosen. */
253
+ onCommand(target: CommandTarget, listener: (id: string) => void): () => void
254
+ /** Says something on a topic. The host passes it on only if this app may publish it. */
255
+ publish(topic: string, payload: unknown): void
256
+ /**
257
+ * Hears `publisher`'s broadcasts on `topic` (`ride.*` takes a branch). The host replays the last
258
+ * one straight away, so an app that starts late still hears the current theme.
259
+ */
260
+ subscribe<T = unknown>(publisher: Publisher, topic: string, handler: (broadcast: Broadcast<T>) => void): () => void
261
+ /** Stops listening, and takes the chrome away. */
262
+ close(): void
263
+ }
264
+
265
+ const EMPTY_CHROME: DeskChrome = { menus: [], dock: [], settings: [], about: null }
266
+
267
+ /** Connects an app to its host over `bridge`. `DeskProvider` does this for a React app; a page without React calls it itself. */
268
+ export function connectHost(bridge: DeskHostBridge): HostClient {
269
+ let chrome = EMPTY_CHROME
270
+ let queued = false
271
+ let closed = false
272
+ const commands: Record<CommandTarget, Set<(id: string) => void>> = { menu: new Set(), dock: new Set(), settings: new Set() }
273
+ type Handler = (broadcast: Broadcast<never>) => void
274
+ /** Per subscription, the broadcasts last heard on each topic it covers, for a second handler that joins later. */
275
+ const subscriptions = new Map<string, { publisher: Publisher; topic: string; handlers: Set<Handler>; last: Map<string, Broadcast> }>()
276
+ const keyOf = (publisher: string, topic: string) => `${publisher}\u0000${topic}`
277
+
278
+ const stop = bridge.onMessage(message => {
279
+ if (closed || !isHostToApp(message)) return
280
+ if (message.kind === 'command') {
281
+ const listeners = commands[message.target]
282
+ // Copied, and each still checked: a listener may take another away while this one runs.
283
+ for (const listener of [...listeners]) if (listeners.has(listener)) listener(message.id)
284
+ return
285
+ }
286
+ const { from, topic, payload } = message
287
+ for (const { publisher, topic: pattern, handlers, last } of [...subscriptions.values()]) {
288
+ const fromThem = publisher === 'primary' ? from.role === 'primary' : publisher === from.id
289
+ if (!fromThem || !topicMatches(pattern, topic)) continue
290
+ const broadcast: Broadcast = { from, topic, payload }
291
+ last.set(topic, broadcast)
292
+ for (const handler of [...handlers]) if (handlers.has(handler)) (handler as (b: Broadcast) => void)(broadcast)
293
+ }
294
+ })
295
+
296
+ return {
297
+ bridge,
298
+ setChrome(part) {
299
+ if (closed) return
300
+ chrome = { ...chrome, ...part }
301
+ if (queued) return
302
+ queued = true
303
+ queueMicrotask(() => {
304
+ queued = false
305
+ if (!closed) bridge.send({ desk: DESK_PROTOCOL, kind: 'chrome', chrome })
306
+ })
307
+ },
308
+ onCommand(target, listener) {
309
+ commands[target].add(listener)
310
+ return () => {
311
+ commands[target].delete(listener)
312
+ }
313
+ },
314
+ publish(topic, payload) {
315
+ if (!closed) bridge.send({ desk: DESK_PROTOCOL, kind: 'publish', topic, payload })
316
+ },
317
+ subscribe(publisher, topic, handler) {
318
+ const key = keyOf(publisher, topic)
319
+ const existing = subscriptions.get(key)
320
+ const own = handler as Handler
321
+ if (existing) {
322
+ // The host replayed to the first handler only: this one gets what was heard since, here.
323
+ existing.handlers.add(own)
324
+ for (const broadcast of existing.last.values()) (handler as (b: Broadcast) => void)(broadcast)
325
+ } else if (!closed) {
326
+ // Added before the subscribe goes out, so a host that replays at once reaches it.
327
+ subscriptions.set(key, { publisher, topic, handlers: new Set([own]), last: new Map() })
328
+ bridge.send({ desk: DESK_PROTOCOL, kind: 'subscribe', publisher, topic })
329
+ }
330
+ const handlers = subscriptions.get(key)?.handlers
331
+ return () => {
332
+ if (!handlers) return
333
+ handlers.delete(own)
334
+ if (handlers.size === 0 && subscriptions.get(key)?.handlers === handlers) {
335
+ subscriptions.delete(key)
336
+ if (!closed) bridge.send({ desk: DESK_PROTOCOL, kind: 'unsubscribe', publisher, topic })
337
+ }
338
+ }
339
+ },
340
+ close() {
341
+ if (closed) return
342
+ bridge.send({ desk: DESK_PROTOCOL, kind: 'chrome', chrome: EMPTY_CHROME })
343
+ // So the host stops sending what nobody here hears.
344
+ for (const { publisher, topic } of subscriptions.values()) bridge.send({ desk: DESK_PROTOCOL, kind: 'unsubscribe', publisher, topic })
345
+ closed = true
346
+ stop()
347
+ subscriptions.clear()
348
+ for (const listeners of Object.values(commands)) listeners.clear()
349
+ },
350
+ }
351
+ }
package/src/core/index.ts CHANGED
@@ -35,8 +35,35 @@ export type { Bus, DeskEvent, EventHandler, InputDescription, SubscribeOptions }
35
35
  export { bindShortcuts, formatShortcut, isApplePlatform, isInstalledApp, matchesShortcut, parseShortcut } from './shortcuts.js'
36
36
  export type { Keymap, Shortcut, ShortcutOptions } from './shortcuts.js'
37
37
  export { deviceLook, lookFor, resolveLook } from './look.js'
38
- export { COLOR_SCHEME_KEY, COLOR_SCHEME_SCRIPT, LOOK_KEY } from './scheme.js'
38
+ export { COLOR_SCHEME_KEY, COLOR_SCHEME_SCRIPT, colorSchemeScript, LOOK_KEY } from './scheme.js'
39
+ export { getPreference, localPreferences, setPreference, setPreferenceStore, subscribePreferences } from './preferences.js'
40
+ export type { PreferenceStore } from './preferences.js'
39
41
  export type { ColorScheme } from './scheme.js'
42
+ export { applyTheme, applyThemeBasics } from './theme.js'
43
+ export { drawnTheme, THEME_CHANGE, watchThemeChanges } from './themeChange.js'
44
+ export type { ThemeChange } from './themeChange.js'
45
+ export type { AppTheme, DeskTheme, ThemeFont } from './theme.js'
46
+ export { connectHost, DESK_PROTOCOL, findDeskHost, isAppToHost, isDeskHostBridge, isHostToApp, THEME_TOPIC } from './hosted.js'
47
+ export type {
48
+ AppToHost,
49
+ Broadcast,
50
+ BroadcastSender,
51
+ CommandTarget,
52
+ DeskChrome,
53
+ DeskHostBridge,
54
+ HostAbout,
55
+ HostAboutFact,
56
+ HostAboutSection,
57
+ HostClient,
58
+ HostDockEntry,
59
+ HostDockItem,
60
+ HostDockStack,
61
+ HostMenu,
62
+ HostMenuItem,
63
+ HostSettingsSection,
64
+ HostToApp,
65
+ Publisher,
66
+ } from './hosted.js'
40
67
  export type { Look, LookChoice } from './look.js'
41
68
  export { parse, serialize, syncWithLocation } from './location.js'
42
69
  export { isTitleCase, titleCase } from './titles.js'
@@ -40,18 +40,35 @@ const decodeRoute = (route: string) => {
40
40
 
41
41
  const warned = new Set<string>()
42
42
  /** Said once per message: a warning on every parse would be noise, not help. */
43
- const warnOnce = (message: string) => {
43
+ export const warnOnce = (message: string) => {
44
44
  if (warned.has(message)) return
45
45
  warned.add(message)
46
46
  console.warn(message)
47
47
  }
48
48
 
49
+ /*
50
+ * Windows a desk draws for itself, such as Settings and About for an app that declared itself. The React
51
+ * provider says which; the core reads only the answer, so it needs no React and no app declaration.
52
+ */
53
+ const deskWindows = new WeakMap<Desk, (id: WindowId) => boolean>()
54
+
55
+ /** Says which windows this desk draws itself, so a link to them is kept. Returns a function that forgets it. */
56
+ export function deskDrawsWindows(desk: Desk, draws: (id: WindowId) => boolean): () => void {
57
+ deskWindows.set(desk, draws)
58
+ return () => {
59
+ if (deskWindows.get(desk) === draws) deskWindows.delete(desk)
60
+ }
61
+ }
62
+
49
63
  export interface LocationOptions {
50
64
  /** Hash parameter that holds the windows. Default `w`. */
51
65
  readonly key?: string
52
66
  /** Hash parameter that holds the focused window. Default `f`. */
53
67
  readonly focusKey?: string
54
- /** Ids the app can render. Anything else in a URL is dropped. */
68
+ /**
69
+ * Ids the app can render. Anything else in a URL is dropped. With `syncWithLocation`, the windows the desk
70
+ * draws itself (Settings and About, for an app declared on its provider) are known too, unlisted.
71
+ */
55
72
  readonly isKnown?: (id: WindowId) => boolean
56
73
  }
57
74
 
@@ -131,7 +148,10 @@ export function syncWithLocation(desk: Desk, stage: () => Size, options: Locatio
131
148
  const keys = [options.key ?? 'w', options.focusKey ?? 'f']
132
149
  const read = () => new URLSearchParams(target.location.hash.replace(/^#/, ''))
133
150
 
134
- const fromUrl = () => desk.restore(parse(read(), stage(), options))
151
+ // The desk's own windows are known as well as the app's, asked at each read, so a declaration made later counts.
152
+ const given = options.isKnown
153
+ const reading: LocationOptions = given ? { ...options, isKnown: id => (deskWindows.get(desk)?.(id) ?? false) || given(id) } : options
154
+ const fromUrl = () => desk.restore(parse(read(), stage(), reading))
135
155
 
136
156
  const toUrl = (state: DeskState, previous: DeskState) => {
137
157
  const params = read()
@@ -0,0 +1,132 @@
1
+ /*
2
+ * Where Desk keeps what a person chooses: the colour scheme, the look, the sounds. This browser's
3
+ * localStorage unless the app gives a store of its own, such as one kept with the person's account.
4
+ *
5
+ * The head script (`colorSchemeScript`) runs before any app code, so it can only read localStorage. With
6
+ * an app's store, Desk writes each value it reads or is told of through to localStorage under the same
7
+ * key: the app's store is the truth, and localStorage a copy for the first paint.
8
+ */
9
+ import { COLOR_SCHEME_KEY, LOOK_KEY } from './scheme.js'
10
+
11
+ export interface PreferenceStore {
12
+ /**
13
+ * The value kept under the key, or null when there is none. `undefined` while the store does not know yet,
14
+ * as a remote store before its values arrive: Desk uses this browser's copy meanwhile.
15
+ */
16
+ get(key: string): string | null | undefined
17
+ /** Keeps a value, or forgets it for null. */
18
+ set(key: string, value: string | null): void
19
+ /** Calls back when values change other than through `set`: arrived from a server, or set in another tab. Null: any key. */
20
+ subscribe?(listener: (key: string | null) => void): () => void
21
+ }
22
+
23
+ /* What storage refused, as a private window or a full one does: it applies until the page is closed. */
24
+ const unstored = new Map<string, string | null>()
25
+
26
+ const storage = () => globalThis.localStorage
27
+
28
+ function readLocal(key: string): string | null {
29
+ let kept: string | null | undefined
30
+ try {
31
+ kept = storage()?.getItem(key)
32
+ } catch {
33
+ // Unreadable: what was kept in memory, if anything.
34
+ }
35
+ return kept ?? unstored.get(key) ?? null
36
+ }
37
+
38
+ function writeLocal(key: string, value: string | null): void {
39
+ try {
40
+ if (value === null) storage()?.removeItem(key)
41
+ else storage()?.setItem(key, value)
42
+ unstored.delete(key)
43
+ } catch {
44
+ // What storage still holds is the old choice, read before this one, so it goes.
45
+ unstored.set(key, value)
46
+ try {
47
+ storage()?.removeItem(key)
48
+ } catch {
49
+ // Unreadable too: then it is never read.
50
+ }
51
+ }
52
+ }
53
+
54
+ /** The default: this browser's localStorage, following changes made in its other tabs. */
55
+ export const localPreferences: PreferenceStore = {
56
+ get: readLocal,
57
+ set: writeLocal,
58
+ subscribe(listener) {
59
+ if (typeof window === 'undefined') return () => {}
60
+ const fromAnotherTab = (event: StorageEvent) => listener(event.key)
61
+ window.addEventListener('storage', fromAnotherTab)
62
+ return () => window.removeEventListener('storage', fromAnotherTab)
63
+ },
64
+ }
65
+
66
+ let store = localPreferences
67
+ const listeners = new Set<(key: string | null) => void>()
68
+ let unsubscribe: (() => void) | undefined
69
+ /* Every key Desk has asked for, so a change to "any key" brings all their copies up to date, the sounds' too. */
70
+ const keys = new Set([COLOR_SCHEME_KEY, LOOK_KEY])
71
+
72
+ /** A store's value, or undefined when it does not know yet or fails. */
73
+ function fromStore(key: string): string | null | undefined {
74
+ try {
75
+ return store.get(key)
76
+ } catch {
77
+ return undefined
78
+ }
79
+ }
80
+
81
+ /* Brings this browser's copy up to the app's store, for the head script's next first paint. */
82
+ function copy(key: string): void {
83
+ const value = fromStore(key)
84
+ if (store !== localPreferences && value !== undefined && value !== readLocal(key)) writeLocal(key, value)
85
+ }
86
+
87
+ /** Tells everything that shows a choice that it may have changed. Null: any of them. */
88
+ export function preferenceChanged(key: string | null): void {
89
+ ;(key === null ? [...keys] : [key]).forEach(copy)
90
+ listeners.forEach(listener => listener(key))
91
+ }
92
+
93
+ /** A remembered choice: the store's, or this browser's copy while the store does not know yet. */
94
+ export function getPreference(key: string): string | null {
95
+ keys.add(key)
96
+ const value = fromStore(key)
97
+ return value === undefined ? readLocal(key) : value
98
+ }
99
+
100
+ /** Remembers a choice in the store, and in this browser's copy, and tells everything that shows it. */
101
+ export function setPreference(key: string, value: string | null): void {
102
+ try {
103
+ store.set(key, value)
104
+ } catch {
105
+ // The store refused: this browser's copy still has it.
106
+ }
107
+ if (store !== localPreferences) writeLocal(key, value)
108
+ preferenceChanged(key)
109
+ }
110
+
111
+ /** Called with the key when a remembered choice changes, here, in the store, or in another tab. */
112
+ export function subscribePreferences(listener: (key: string | null) => void): () => void {
113
+ if (!listeners.size) unsubscribe = store.subscribe?.(preferenceChanged)
114
+ listeners.add(listener)
115
+ return () => {
116
+ listeners.delete(listener)
117
+ if (listeners.size) return
118
+ unsubscribe?.()
119
+ unsubscribe = undefined
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Keeps every choice Desk remembers in this store from now on; none puts localStorage back. `DeskShell`'s
125
+ * `preferences` calls it. Its keys: `COLOR_SCHEME_KEY`, `LOOK_KEY` and `createFx`'s `storageKey`.
126
+ */
127
+ export function setPreferenceStore(next: PreferenceStore = localPreferences): void {
128
+ unsubscribe?.()
129
+ store = next
130
+ unsubscribe = listeners.size ? next.subscribe?.(preferenceChanged) : undefined
131
+ preferenceChanged(null)
132
+ }
@@ -7,15 +7,26 @@
7
7
  /** Light, dark, or the system's, which the stylesheet follows through `prefers-color-scheme`. */
8
8
  export type ColorScheme = 'system' | 'light' | 'dark'
9
9
 
10
- /** Where the chosen colour scheme is kept in localStorage: `light` or `dark`; absent for the system's. */
10
+ /**
11
+ * Where the chosen colour scheme is kept in localStorage: `light`, `dark` or `system`. Absent while the app's
12
+ * own default stands (`appearance.defaultScheme`, the system's unless it says otherwise).
13
+ */
11
14
  export const COLOR_SCHEME_KEY = 'desk.scheme'
12
15
 
13
16
  /** Where the chosen look is kept in localStorage: `auto`, `mac`, `gnome` or `windows`; absent while the app's own stands. */
14
17
  export const LOOK_KEY = 'desk.look'
15
18
 
16
19
  /**
17
- * For the page's `<head>`, before anything paints: the remembered scheme on the root as `data-theme`, so a dark
18
- * choice does not open light for a moment while the app loads.
20
+ * For the page's `<head>`, before anything paints: the remembered scheme on the root as `data-theme`, or the
21
+ * app's default when none is remembered, so a dark choice does not open light for a moment while the app
22
+ * loads. Give it the same `defaultScheme` as Appearance.
19
23
  */
20
- export const COLOR_SCHEME_SCRIPT =
21
- `try{var s=localStorage.getItem(${JSON.stringify(COLOR_SCHEME_KEY)});if(s=="light"||s=="dark")document.documentElement.setAttribute("data-theme",s)}catch(e){}`
24
+ export function colorSchemeScript(defaultScheme: ColorScheme = 'system'): string {
25
+ return (
26
+ `try{var s=localStorage.getItem(${JSON.stringify(COLOR_SCHEME_KEY)});if(s!="light"&&s!="dark"&&s!="system")s=${JSON.stringify(defaultScheme)};` +
27
+ `var r=document.documentElement;if(s=="light"||s=="dark")r.setAttribute("data-theme",s);else r.removeAttribute("data-theme")}catch(e){}`
28
+ )
29
+ }
30
+
31
+ /** The head script for an app whose default is the system's scheme: `colorSchemeScript()`. */
32
+ export const COLOR_SCHEME_SCRIPT = colorSchemeScript()