@liberation-data/desk 0.42.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 (200) hide show
  1. package/README.md +312 -5
  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 +10 -0
  7. package/dist/core/index.d.ts.map +1 -1
  8. package/dist/core/index.js +5 -0
  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 +18 -0
  19. package/dist/core/scheme.d.ts.map +1 -0
  20. package/dist/core/scheme.js +24 -0
  21. package/dist/core/scheme.js.map +1 -0
  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/core/types.d.ts +6 -0
  31. package/dist/core/types.d.ts.map +1 -1
  32. package/dist/css/apps.css +183 -0
  33. package/dist/css/overlays.css +6 -0
  34. package/dist/css/shell.css +100 -0
  35. package/dist/css/tokens.css +10 -0
  36. package/dist/css/windows.css +21 -0
  37. package/dist/desk.css +220 -0
  38. package/dist/fx/fx.d.ts.map +1 -1
  39. package/dist/fx/fx.js +7 -31
  40. package/dist/fx/fx.js.map +1 -1
  41. package/dist/host/checkChrome.d.ts +20 -0
  42. package/dist/host/checkChrome.d.ts.map +1 -0
  43. package/dist/host/checkChrome.js +219 -0
  44. package/dist/host/checkChrome.js.map +1 -0
  45. package/dist/host/checkTheme.d.ts +35 -0
  46. package/dist/host/checkTheme.d.ts.map +1 -0
  47. package/dist/host/checkTheme.js +128 -0
  48. package/dist/host/checkTheme.js.map +1 -0
  49. package/dist/host/index.d.ts +7 -0
  50. package/dist/host/index.d.ts.map +1 -0
  51. package/dist/host/index.js +8 -0
  52. package/dist/host/index.js.map +1 -0
  53. package/dist/host/router.d.ts +99 -0
  54. package/dist/host/router.d.ts.map +1 -0
  55. package/dist/host/router.js +279 -0
  56. package/dist/host/router.js.map +1 -0
  57. package/dist/react/Desktop.d.ts.map +1 -1
  58. package/dist/react/Desktop.js +13 -2
  59. package/dist/react/Desktop.js.map +1 -1
  60. package/dist/react/Dock.d.ts +26 -2
  61. package/dist/react/Dock.d.ts.map +1 -1
  62. package/dist/react/Dock.js +23 -27
  63. package/dist/react/Dock.js.map +1 -1
  64. package/dist/react/MenuBar.d.ts +1 -1
  65. package/dist/react/MenuBar.d.ts.map +1 -1
  66. package/dist/react/MenuBar.js +36 -6
  67. package/dist/react/MenuBar.js.map +1 -1
  68. package/dist/react/app.d.ts +215 -0
  69. package/dist/react/app.d.ts.map +1 -0
  70. package/dist/react/app.js +192 -0
  71. package/dist/react/app.js.map +1 -0
  72. package/dist/react/appFrame.d.ts +11 -7
  73. package/dist/react/appFrame.d.ts.map +1 -1
  74. package/dist/react/appFrame.js +24 -6
  75. package/dist/react/appFrame.js.map +1 -1
  76. package/dist/react/appPanels.d.ts +25 -0
  77. package/dist/react/appPanels.d.ts.map +1 -0
  78. package/dist/react/appPanels.js +123 -0
  79. package/dist/react/appPanels.js.map +1 -0
  80. package/dist/react/appearance.d.ts +61 -0
  81. package/dist/react/appearance.d.ts.map +1 -0
  82. package/dist/react/appearance.js +119 -0
  83. package/dist/react/appearance.js.map +1 -0
  84. package/dist/react/codeBlock.d.ts.map +1 -1
  85. package/dist/react/codeBlock.js +6 -60
  86. package/dist/react/codeBlock.js.map +1 -1
  87. package/dist/react/context.d.ts +23 -1
  88. package/dist/react/context.d.ts.map +1 -1
  89. package/dist/react/context.js +108 -5
  90. package/dist/react/context.js.map +1 -1
  91. package/dist/react/copy.d.ts +22 -0
  92. package/dist/react/copy.d.ts.map +1 -0
  93. package/dist/react/copy.js +68 -0
  94. package/dist/react/copy.js.map +1 -0
  95. package/dist/react/dockStatus.d.ts +19 -0
  96. package/dist/react/dockStatus.d.ts.map +1 -0
  97. package/dist/react/dockStatus.js +25 -0
  98. package/dist/react/dockStatus.js.map +1 -0
  99. package/dist/react/documentTitle.d.ts.map +1 -1
  100. package/dist/react/documentTitle.js +4 -1
  101. package/dist/react/documentTitle.js.map +1 -1
  102. package/dist/react/frameMenus.d.ts +28 -0
  103. package/dist/react/frameMenus.d.ts.map +1 -0
  104. package/dist/react/frameMenus.js +85 -0
  105. package/dist/react/frameMenus.js.map +1 -0
  106. package/dist/react/hostApp.d.ts +15 -0
  107. package/dist/react/hostApp.d.ts.map +1 -0
  108. package/dist/react/hostApp.js +77 -0
  109. package/dist/react/hostApp.js.map +1 -0
  110. package/dist/react/hostDock.d.ts +25 -0
  111. package/dist/react/hostDock.d.ts.map +1 -0
  112. package/dist/react/hostDock.js +98 -0
  113. package/dist/react/hostDock.js.map +1 -0
  114. package/dist/react/hostMenu.d.ts +2 -36
  115. package/dist/react/hostMenu.d.ts.map +1 -1
  116. package/dist/react/hostMenu.js.map +1 -1
  117. package/dist/react/hosted.d.ts +28 -0
  118. package/dist/react/hosted.d.ts.map +1 -0
  119. package/dist/react/hosted.js +53 -0
  120. package/dist/react/hosted.js.map +1 -0
  121. package/dist/react/index.d.ts +12 -0
  122. package/dist/react/index.d.ts.map +1 -1
  123. package/dist/react/index.js +8 -0
  124. package/dist/react/index.js.map +1 -1
  125. package/dist/react/layers.d.ts.map +1 -1
  126. package/dist/react/layers.js +7 -2
  127. package/dist/react/layers.js.map +1 -1
  128. package/dist/react/overlays.d.ts.map +1 -1
  129. package/dist/react/overlays.js +29 -12
  130. package/dist/react/overlays.js.map +1 -1
  131. package/dist/react/shell.d.ts +16 -1
  132. package/dist/react/shell.d.ts.map +1 -1
  133. package/dist/react/shell.js +19 -3
  134. package/dist/react/shell.js.map +1 -1
  135. package/dist/react/windowMenus.d.ts +19 -0
  136. package/dist/react/windowMenus.d.ts.map +1 -0
  137. package/dist/react/windowMenus.js +88 -0
  138. package/dist/react/windowMenus.js.map +1 -0
  139. package/dist/shell/HostShell.d.ts +53 -0
  140. package/dist/shell/HostShell.d.ts.map +1 -0
  141. package/dist/shell/HostShell.js +116 -0
  142. package/dist/shell/HostShell.js.map +1 -0
  143. package/dist/shell/index.d.ts +7 -0
  144. package/dist/shell/index.d.ts.map +1 -0
  145. package/dist/shell/index.js +9 -0
  146. package/dist/shell/index.js.map +1 -0
  147. package/dist/shell/keys.d.ts +47 -0
  148. package/dist/shell/keys.d.ts.map +1 -0
  149. package/dist/shell/keys.js +68 -0
  150. package/dist/shell/keys.js.map +1 -0
  151. package/dist/shell/motion.d.ts +72 -0
  152. package/dist/shell/motion.d.ts.map +1 -0
  153. package/dist/shell/motion.js +118 -0
  154. package/dist/shell/motion.js.map +1 -0
  155. package/llms.txt +84 -9
  156. package/package.json +10 -1
  157. package/src/core/hosted.ts +351 -0
  158. package/src/core/index.ts +29 -0
  159. package/src/core/location.ts +23 -3
  160. package/src/core/preferences.ts +132 -0
  161. package/src/core/scheme.ts +32 -0
  162. package/src/core/theme.ts +91 -0
  163. package/src/core/themeChange.ts +59 -0
  164. package/src/core/types.ts +6 -0
  165. package/src/css/apps.css +183 -0
  166. package/src/css/overlays.css +6 -0
  167. package/src/css/shell.css +99 -0
  168. package/src/css/tokens.css +10 -0
  169. package/src/css/windows.css +21 -0
  170. package/src/fx/fx.ts +7 -25
  171. package/src/host/checkChrome.ts +257 -0
  172. package/src/host/checkTheme.ts +134 -0
  173. package/src/host/index.ts +10 -0
  174. package/src/host/router.ts +374 -0
  175. package/src/react/Desktop.tsx +21 -3
  176. package/src/react/Dock.tsx +40 -24
  177. package/src/react/MenuBar.tsx +39 -6
  178. package/src/react/app.tsx +354 -0
  179. package/src/react/appFrame.tsx +39 -14
  180. package/src/react/appPanels.tsx +210 -0
  181. package/src/react/appearance.tsx +195 -0
  182. package/src/react/codeBlock.tsx +7 -65
  183. package/src/react/context.tsx +131 -4
  184. package/src/react/copy.ts +81 -0
  185. package/src/react/dockStatus.ts +42 -0
  186. package/src/react/documentTitle.ts +4 -1
  187. package/src/react/frameMenus.ts +100 -0
  188. package/src/react/hostApp.tsx +89 -0
  189. package/src/react/hostDock.tsx +118 -0
  190. package/src/react/hostMenu.ts +3 -38
  191. package/src/react/hosted.tsx +65 -0
  192. package/src/react/index.ts +34 -0
  193. package/src/react/layers.ts +7 -2
  194. package/src/react/overlays.tsx +30 -12
  195. package/src/react/shell.tsx +33 -3
  196. package/src/react/windowMenus.ts +107 -0
  197. package/src/shell/HostShell.tsx +220 -0
  198. package/src/shell/index.ts +11 -0
  199. package/src/shell/keys.ts +101 -0
  200. package/src/shell/motion.ts +163 -0
@@ -0,0 +1,374 @@
1
+ import { topicMatches } from '../core/events.js'
2
+ import { DESK_PROTOCOL, isAppToHost, THEME_TOPIC } from '../core/hosted.js'
3
+ import type { BroadcastSender, CommandTarget, DeskChrome, DeskHostBridge, HostToApp, Publisher } from '../core/hosted.js'
4
+ import { checkChrome } from './checkChrome.js'
5
+ import { checkTheme } from './checkTheme.js'
6
+
7
+ /*
8
+ * THE HOST'S HALF: WHO MAY SAY WHAT, AND WHO HEARS IT.
9
+ *
10
+ * A host passes every broadcast between its apps, so it is where the rules hold. It stamps each
11
+ * broadcast with the app it really came from; it passes on only topics that app was granted, and
12
+ * the theme only from the primary, checked; and it keeps the last broadcast of each publisher on each
13
+ * topic, so an app that starts late, or one listening while the publisher is down, hears the latest
14
+ * at once. A host builds its transport around this and hands it every message an app sends.
15
+ */
16
+
17
+ /** An app as its host registers it. */
18
+ export interface HostedApp {
19
+ /** Stable across runs. */
20
+ readonly id: string
21
+ /** Where the app is served: its theme's fonts and images, and its dock's images, must come from here. */
22
+ readonly origin: string
23
+ /** The app whose theme every app wears. At most one. */
24
+ readonly primary?: boolean
25
+ /** Topics it may publish (`ride.*` grants a branch). Granted by the host, never by the app. The primary needs `theme` among them. */
26
+ readonly publishes?: readonly string[]
27
+ }
28
+
29
+ /** What a router needs from its host: a way to reach each app, and the host's own rules. */
30
+ export interface BroadcastRouterOptions {
31
+ /** Sends a message to an app, through the host's transport. One that throws keeps no other app from hearing: the first error is thrown once all have. */
32
+ readonly deliver: (appId: string, message: HostToApp) => void
33
+ /**
34
+ * An app's menus and dock changed: the host draws them. Checked first (`checkChrome`): a part that
35
+ * fails is dropped and named in `dropped`, for the host to log; chrome of the wrong shape is not
36
+ * passed on, and the app keeps what it last sent. Null when the app is unregistered: the host stops
37
+ * drawing its chrome.
38
+ */
39
+ readonly chrome?: (appId: string, chrome: DeskChrome | null, dropped: readonly string[]) => void
40
+ /**
41
+ * Checks a broadcast's payload on topics the host knows: return the payload to pass on, or
42
+ * `undefined` to drop it. The theme is always checked as well, whatever this does.
43
+ */
44
+ readonly check?: (topic: string, payload: unknown, from: HostedApp) => unknown
45
+ /** The most a payload may take as JSON. Default 64 KiB; larger ones are dropped. */
46
+ readonly maxPayload?: number
47
+ /** How fast each publisher may broadcast on each topic: see `RateLimits`. */
48
+ readonly limits?: RateLimits
49
+ /** The time, for tests: `now` in milliseconds, and `later` to run something after a delay, returning a canceller. */
50
+ readonly clock?: { readonly now: () => number; readonly later: (run: () => void, ms: number) => () => void }
51
+ }
52
+
53
+ /** A token bucket: `burst` broadcasts at once, then `perSecond`. */
54
+ export interface Rate {
55
+ readonly burst: number
56
+ readonly perSecond: number
57
+ }
58
+
59
+ /**
60
+ * Per publisher and topic, a bucket of broadcasts. Over it, nothing is queued and nothing lost: the
61
+ * latest payload is held, replacing any held before, and goes out when the bucket allows, so every
62
+ * subscriber still ends on the last value. Defaults: 20 at once then 10 a second; the theme 2 then 1
63
+ * a second, since it changes on a person's choice; and 64 topics per publisher at once, past which a
64
+ * broadcast on yet another topic is refused (`'rate limited'`) unless one of them is idle and full.
65
+ */
66
+ export interface RateLimits extends Partial<Rate> {
67
+ /** Rates for particular topics, by exact name. The theme keeps its own unless named here. */
68
+ readonly topics?: Readonly<Record<string, Partial<Rate>>>
69
+ readonly maxTopics?: number
70
+ }
71
+
72
+ /** 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
74
+
75
+ /** The rules of a host's broadcasts, kept in one place so every transport keeps them alike. */
76
+ export interface BroadcastRouter {
77
+ /**
78
+ * Adds an app, or updates one. Throws for a second primary: two looks cannot both be worn. An update
79
+ * drops what the app had held over its rate, unsent: it was vetted under the grants and origin it replaces.
80
+ */
81
+ register(app: HostedApp): void
82
+ /** Forgets an app: its chrome (`chrome` is called with null), its subscriptions, and what it published, except its last theme. */
83
+ unregister(appId: string): void
84
+ /** Acts on a message an app sent. The app is identified by the transport, never by the message. */
85
+ receive(appId: string, message: unknown): Refusal
86
+ /** The primary's id, or null while none is registered. */
87
+ primary(): string | null
88
+ /** The last broadcast `publisher` made on `topic` that went out, if it is kept. */
89
+ kept(publisher: string, topic: string): unknown
90
+ /** How many of an app's broadcasts were held and replaced by a newer one, or refused for its rate. */
91
+ limited(appId: string): number
92
+ }
93
+
94
+ const DEFAULT_MAX_PAYLOAD = 64 * 1024
95
+ const RATE: Rate = { burst: 20, perSecond: 10 }
96
+ const THEME_RATE: Rate = { burst: 2, perSecond: 1 }
97
+
98
+ interface Bucket {
99
+ tokens: number
100
+ at: number
101
+ readonly rate: Rate
102
+ /** The latest payload over the limit, and the cancel of the timer that sends it. */
103
+ held?: { from: BroadcastSender; payload: unknown; readonly cancel: () => void }
104
+ }
105
+
106
+ /** A router for a host to put behind its transport: see `BroadcastRouter`. */
107
+ export function createBroadcastRouter(options: BroadcastRouterOptions): BroadcastRouter {
108
+ const apps = new Map<string, HostedApp>()
109
+ const subscriptions = new Map<string, Map<string, { publisher: Publisher; topic: string }>>()
110
+ /** Per publisher, its last broadcast on each topic. */
111
+ const kept = new Map<string, Map<string, { from: BroadcastSender; payload: unknown }>>()
112
+ const maxPayload = options.maxPayload ?? DEFAULT_MAX_PAYLOAD
113
+ /** Fan-outs waiting their turn; the first is the one being delivered. */
114
+ const pending: (() => void)[] = []
115
+ /** What deliveries threw while they went out. */
116
+ const failures: unknown[] = []
117
+ /** The primary last registered, kept while it is down so its theme still reaches apps that start meanwhile. */
118
+ let lastPrimary: string | null = null
119
+ const limits = options.limits ?? {}
120
+ // setTimeout runs a delay past 2^31 - 1 ms at once, which would let a very slow rate send every held value.
121
+ const clock = options.clock ?? { now: Date.now, later: (run: () => void, ms: number) => clearTimeout.bind(null, setTimeout(run, Math.min(ms, 2 ** 31 - 1))) }
122
+ // A rate that cannot refill (0, negative, NaN) would hold a value for ever or, through setTimeout, not at all.
123
+ for (const rate of [limits, ...Object.values(limits.topics ?? {})]) {
124
+ if (!((rate.burst ?? 0) >= 0 && (rate.perSecond ?? 1) > 0 && (limits.maxTopics ?? 0) >= 0)) throw new RangeError('limits: burst and maxTopics >= 0, perSecond > 0')
125
+ }
126
+ /** Per publisher, a bucket per topic; and how many of its broadcasts the limits held or refused. */
127
+ const buckets = new Map<string, Map<string, Bucket>>()
128
+ const overLimit = new Map<string, number>()
129
+ const count = (appId: string) => overLimit.set(appId, (overLimit.get(appId) ?? 0) + 1)
130
+ /** Refills a bucket at its own topic's rate; a clock that goes back counts as no time passing. */
131
+ const refill = (b: Bucket) => {
132
+ const now = clock.now()
133
+ if (now > b.at) b.tokens = Math.min(b.rate.burst, b.tokens + ((now - b.at) * b.rate.perSecond) / 1000)
134
+ b.at = Math.max(now, b.at)
135
+ }
136
+
137
+ const primaryId = () => [...apps.values()].find(app => app.primary)?.id ?? null
138
+ const senderOf = (app: HostedApp): BroadcastSender => (app.primary ? { id: app.id, role: 'primary' } : { id: app.id })
139
+ const hears = (publisher: Publisher, from: BroadcastSender) => (publisher === 'primary' ? from.role === 'primary' : publisher === from.id)
140
+
141
+ const deliver = (appId: string, from: BroadcastSender, topic: string, payload: unknown) =>
142
+ options.deliver(appId, { desk: DESK_PROTOCOL, kind: 'broadcast', from, topic, payload })
143
+
144
+ const sizeOf = (payload: unknown) => {
145
+ try {
146
+ return JSON.stringify(payload ?? null).length
147
+ } catch {
148
+ return Infinity
149
+ }
150
+ }
151
+
152
+ const publish = (app: HostedApp, topic: string, raw: unknown): Refusal => {
153
+ if (!(app.publishes ?? []).some(pattern => topicMatches(pattern, topic))) return 'not granted'
154
+ if (sizeOf(raw) > maxPayload) return 'too large'
155
+ let payload = raw
156
+ if (topic === THEME_TOPIC) {
157
+ if (!app.primary) return 'not the primary'
158
+ const checked = checkTheme(payload, app.origin)
159
+ if (!checked.ok) return 'refused by check'
160
+ payload = checked.theme
161
+ }
162
+ if (options.check) {
163
+ payload = options.check(topic, payload, app)
164
+ if (payload === undefined) return 'refused by check'
165
+ }
166
+ return limit(app, topic, senderOf(app), payload)
167
+ }
168
+
169
+ /**
170
+ * Sends now if the topic's bucket has a token; else holds the payload, replacing one held before,
171
+ * until it has. A held topic's latest can so go out after a later broadcast on another topic: order
172
+ * holds within a topic, and across topics only while under the limits.
173
+ */
174
+ const limit = (app: HostedApp, topic: string, from: BroadcastSender, payload: unknown): Refusal => {
175
+ const rate = { ...(topic === THEME_TOPIC ? THEME_RATE : { ...RATE, ...limits }), ...limits.topics?.[topic] }
176
+ const own = buckets.get(app.id) ?? new Map<string, Bucket>()
177
+ buckets.set(app.id, own)
178
+ let bucket = own.get(topic)
179
+ if (!bucket) {
180
+ // A new topic starts with a full burst, so a flood across topics is bounded by how many a
181
+ // 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)) {
183
+ const idle = [...own].find(([t, b]) => !b.held && (refill(b), b.tokens >= b.rate.burst) && t)
184
+ if (!idle) return count(app.id), 'rate limited'
185
+ own.delete(idle[0])
186
+ }
187
+ own.set(topic, (bucket = { tokens: rate.burst, at: clock.now(), rate }))
188
+ }
189
+ refill(bucket)
190
+ if (bucket.held) {
191
+ count(app.id)
192
+ bucket.held.from = from
193
+ bucket.held.payload = payload
194
+ return null
195
+ }
196
+ if (bucket.tokens >= 1) {
197
+ bucket.tokens--
198
+ return send(app.id, topic, from, payload)
199
+ }
200
+ const b = bucket
201
+ const cancel = clock.later(() => {
202
+ const held = b.held
203
+ if (!held) return
204
+ delete b.held
205
+ refill(b)
206
+ b.tokens = Math.max(0, b.tokens - 1)
207
+ try {
208
+ send(app.id, topic, held.from, held.payload)
209
+ } catch (error) {
210
+ // No caller to throw to here: reported as any uncaught error is, after the others have heard.
211
+ queueMicrotask(() => {
212
+ throw error
213
+ })
214
+ }
215
+ }, Math.ceil(((1 - b.tokens) * 1000) / rate.perSecond))
216
+ b.held = { from, payload, cancel }
217
+ return null
218
+ }
219
+
220
+ /** Keeps `payload` as the publisher's last on `topic` and passes it to every app that subscribed. */
221
+ const send = (appId: string, topic: string, from: BroadcastSender, payload: unknown): Refusal => {
222
+ const own = kept.get(appId) ?? new Map()
223
+ own.set(topic, { from, payload })
224
+ kept.set(appId, own)
225
+ // One broadcast reaches everyone before the next goes out, even one published by a handler while
226
+ // this one is delivered in-process; otherwise an app could hear the newer first and end on the older.
227
+ // A transport that throws for one app (a window already gone) does not keep the rest from hearing:
228
+ // the first failure is thrown once every broadcast has gone out.
229
+ pending.push(() => {
230
+ for (const [appId, subs] of subscriptions) {
231
+ if ([...subs.values()].some(s => hears(s.publisher, from) && topicMatches(s.topic, topic))) {
232
+ try {
233
+ deliver(appId, from, topic, payload)
234
+ } catch (error) {
235
+ failures.push(error)
236
+ }
237
+ }
238
+ }
239
+ })
240
+ if (pending.length > 1) return null
241
+ failures.length = 0
242
+ for (let next = pending[0]; next; next = pending[0]) {
243
+ next()
244
+ pending.shift()
245
+ }
246
+ if (failures.length > 0) throw failures[0]
247
+ return null
248
+ }
249
+
250
+ /** Replays to a new subscription what it would have heard: the last broadcast on each topic it covers. */
251
+ const replay = (appId: string, publisher: Publisher, pattern: string) => {
252
+ const source = publisher === 'primary' ? (primaryId() ?? lastPrimary) : publisher
253
+ if (source === null) return
254
+ for (const [topic, { from, payload }] of kept.get(source) ?? []) {
255
+ if (topicMatches(pattern, topic)) deliver(appId, from, topic, payload)
256
+ }
257
+ }
258
+
259
+ /** Cancels what an app held over its rate. */
260
+ const dropHeld = (appId: string) => {
261
+ for (const bucket of buckets.get(appId)?.values() ?? []) bucket.held?.cancel(), delete bucket.held
262
+ }
263
+
264
+ return {
265
+ register(app) {
266
+ if (app.primary && primaryId() !== null && primaryId() !== app.id) throw new Error(`${primaryId()} is already the primary`)
267
+ dropHeld(app.id)
268
+ apps.set(app.id, app)
269
+ if (app.primary) lastPrimary = app.id
270
+ else if (lastPrimary === app.id) lastPrimary = null
271
+ // A primary registered again after it went: what it kept still carries its role.
272
+ const own = kept.get(app.id)
273
+ if (own) for (const [topic, entry] of own) own.set(topic, { ...entry, from: senderOf(app) })
274
+ },
275
+
276
+ unregister(appId) {
277
+ if (apps.delete(appId)) options.chrome?.(appId, null, [])
278
+ // What it had held goes with it, unsent.
279
+ dropHeld(appId)
280
+ buckets.delete(appId)
281
+ subscriptions.delete(appId)
282
+ const own = kept.get(appId)
283
+ if (!own) return
284
+ for (const topic of [...own.keys()]) if (topic !== THEME_TOPIC) own.delete(topic)
285
+ if (own.size === 0) kept.delete(appId)
286
+ },
287
+
288
+ receive(appId, message) {
289
+ const app = apps.get(appId)
290
+ if (!app) return 'unknown app'
291
+ if (!isAppToHost(message)) return 'malformed'
292
+ switch (message.kind) {
293
+ case 'chrome': {
294
+ // Drawn in the host's own frame, so checked as a theme is, and only the checked copy drawn.
295
+ const checked = checkChrome(message.chrome, app.origin)
296
+ if (!checked.ok) return 'refused by check'
297
+ options.chrome?.(appId, checked.chrome, checked.dropped)
298
+ return null
299
+ }
300
+ case 'publish':
301
+ return publish(app, message.topic, message.payload)
302
+ case 'subscribe': {
303
+ const subs = subscriptions.get(appId) ?? new Map()
304
+ subs.set(`${message.publisher}\u0000${message.topic}`, { publisher: message.publisher, topic: message.topic })
305
+ subscriptions.set(appId, subs)
306
+ replay(appId, message.publisher, message.topic)
307
+ return null
308
+ }
309
+ case 'unsubscribe':
310
+ subscriptions.get(appId)?.delete(`${message.publisher}\u0000${message.topic}`)
311
+ return null
312
+ }
313
+ },
314
+
315
+ primary: primaryId,
316
+
317
+ kept(publisher, topic) {
318
+ return kept.get(publisher)?.get(topic)?.payload
319
+ },
320
+
321
+ limited: appId => overLimit.get(appId) ?? 0,
322
+ }
323
+ }
324
+
325
+ /** A host that lives in one page: for tests, examples, and apps that host others in-process. */
326
+ export interface MemoryHost {
327
+ readonly router: BroadcastRouter
328
+ /** Registers an app and gives it a bridge to this host. */
329
+ connect(app: HostedApp): DeskHostBridge
330
+ /** The chrome each app last sent. */
331
+ chrome(appId: string): DeskChrome | undefined
332
+ /** Sends an app a choice from its menus, its dock or its Settings, as a host's frame would. */
333
+ command(appId: string, target: CommandTarget, id: string): void
334
+ /** Every message an app sent and how it went, newest last. */
335
+ readonly log: readonly { readonly appId: string; readonly message: unknown; readonly refusal: Refusal }[]
336
+ }
337
+
338
+ /**
339
+ * A host in memory. Messages are copied with `structuredClone` each way, as a real boundary would,
340
+ * so an app that sends something that cannot cross fails here too.
341
+ */
342
+ export function createMemoryHost(options: Pick<BroadcastRouterOptions, 'check' | 'maxPayload'> = {}): MemoryHost {
343
+ const listeners = new Map<string, Set<(message: HostToApp) => void>>()
344
+ const chromes = new Map<string, DeskChrome>()
345
+ const log: { appId: string; message: unknown; refusal: Refusal }[] = []
346
+ const send = (appId: string, message: HostToApp) => {
347
+ for (const listener of [...(listeners.get(appId) ?? [])]) listener(structuredClone(message))
348
+ }
349
+ const router = createBroadcastRouter({ ...options, deliver: send, chrome: (appId, chrome) => (chrome ? chromes.set(appId, chrome) : chromes.delete(appId)) })
350
+ return {
351
+ router,
352
+ connect(app) {
353
+ router.register(app)
354
+ return {
355
+ version: DESK_PROTOCOL,
356
+ send(message) {
357
+ const copy: unknown = structuredClone(message)
358
+ log.push({ appId: app.id, message: copy, refusal: router.receive(app.id, copy) })
359
+ },
360
+ onMessage(listener) {
361
+ const set = listeners.get(app.id) ?? new Set()
362
+ set.add(listener)
363
+ listeners.set(app.id, set)
364
+ return () => {
365
+ set.delete(listener)
366
+ }
367
+ },
368
+ }
369
+ },
370
+ chrome: appId => chromes.get(appId),
371
+ command: (appId, target, id) => send(appId, { desk: DESK_PROTOCOL, kind: 'command', target, id }),
372
+ log,
373
+ }
374
+ }
@@ -10,6 +10,9 @@ import type { Widget, WidgetCorner } from './widgets.js'
10
10
  import { arrangement, areaAround } from './arrange.js'
11
11
  import { InfoTip } from './infoTip.js'
12
12
  import { useDesk, useDeskState, useLook, WindowContext } from './context.js'
13
+ import type { DeskApp } from './app.js'
14
+ import { ABOUT_WINDOW, appWindowLimits, appWindowTitle, desksWindow, SETTINGS_WINDOW, useDeskApp } from './app.js'
15
+ import { AboutContent, SettingsContent } from './appPanels.js'
13
16
  import { WindowBoundary } from './windowBoundary.js'
14
17
  import { TitleProgress } from './windowProgress.js'
15
18
  import type { WindowProgress } from './windowProgress.js'
@@ -100,6 +103,11 @@ function arrangementArea(stage: HTMLElement) {
100
103
  return { x: left, y: top, width: stage.clientWidth - left - right, height: stage.clientHeight - top - bottom, gap }
101
104
  }
102
105
 
106
+ const systemLimits = (app: DeskApp | null, id: WindowId): WindowLimits | null => {
107
+ const which = desksWindow(app, id)
108
+ return which ? appWindowLimits(app, which) : null
109
+ }
110
+
103
111
  const halfFrame = (stage: HTMLElement, side: 'start' | 'end'): Frame => {
104
112
  const area = arrangementArea(stage)
105
113
  const width = (area.width - area.gap) / 2
@@ -112,6 +120,15 @@ export function Desktop({ renderWindow, title, note, info, actions, limits, empt
112
120
  const stage = useRef<HTMLDivElement>(null)
113
121
  const touch = useMediaQuery(TOUCH)
114
122
  const mode: DeskLayout = layout === 'auto' ? (touch ? 'fullscreen' : 'desktop') : layout
123
+ // About and Settings, when the app has declared itself: Desk draws them, unless the app's Settings is its own.
124
+ const app = useDeskApp()
125
+ const ownsAbout = app !== null
126
+ const ownsSettings = desksWindow(app, SETTINGS_WINDOW) !== null
127
+ const render = useCallback(
128
+ (id: WindowId): ReactNode =>
129
+ ownsAbout && id === ABOUT_WINDOW ? <AboutContent /> : ownsSettings && id === SETTINGS_WINDOW ? <SettingsContent /> : renderWindow(id),
130
+ [renderWindow, ownsAbout, ownsSettings],
131
+ )
115
132
 
116
133
  useLayoutEffect(() => {
117
134
  desk.setStage(() => ({ width: stage.current?.clientWidth ?? 1024, height: stage.current?.clientHeight ?? 768 }))
@@ -215,15 +232,15 @@ export function Desktop({ renderWindow, title, note, info, actions, limits, empt
215
232
  // touch, and minimizing, are the same thing to everything below this line.
216
233
  hidden={(mode === 'fullscreen' && window.id !== focused) || isMinimized(state, window.id)}
217
234
  minimized={isMinimized(state, window.id)}
218
- title={title(window.id)}
235
+ title={appWindowTitle(app, window.id) ?? title(window.id)}
219
236
  note={note?.(window.id)}
220
237
  info={info?.(window.id)}
221
- limits={limits?.(window.id) ?? null}
238
+ limits={limits?.(window.id) ?? systemLimits(app, window.id)}
222
239
  actions={actions?.(window.id)}
223
240
  >
224
241
  {/* Memoised on the id and the render function: moving or focusing a window
225
242
  re-renders its chrome, never the app's content inside it. */}
226
- <WindowContent id={window.id} render={renderWindow} loading={loading} failed={failed} />
243
+ <WindowContent id={window.id} render={render} loading={loading} failed={failed} />
227
244
  </WindowView>
228
245
  ))}
229
246
  </div>
@@ -531,6 +548,7 @@ function WindowView({ window, layout, hidden, minimized, depth, focused, title,
531
548
  className="desk-window"
532
549
  data-mode={layout === 'fullscreen' ? 'fullscreen' : live ? 'floating' : window.mode}
533
550
  data-centred={centred || undefined}
551
+ data-fit={(centred && limits?.fitContent) || undefined}
534
552
  data-hidden={hidden || undefined}
535
553
  data-minimized={minimized || undefined}
536
554
  inert={hidden || undefined}
@@ -1,7 +1,11 @@
1
1
  import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
2
2
  import type { KeyboardEvent, ReactNode } from 'react'
3
- import { focusedId, instancesOf, isMinimized, windowType } from '../core/desk.js'
4
- import type { DeskState, WindowId } from '../core/types.js'
3
+ import type { WindowId } from '../core/types.js'
4
+ import { ABOUT_WINDOW, openAppSettings, openPanel, placeAppDockItems, useDeskApp } from './app.js'
5
+ import { statusOf, windowOf } from './dockStatus.js'
6
+ import type { DockStatus } from './dockStatus.js'
7
+ import { useHosted } from './hosted.js'
8
+ import { HostedDock, selectDockItem } from './hostDock.js'
5
9
  import { useDesk, useDeskState } from './context.js'
6
10
  import { useContextMenu } from './contextMenu.js'
7
11
  import { useDragSource, useDropTarget } from './dnd.js'
@@ -13,6 +17,12 @@ export interface DockItem {
13
17
  readonly id: string
14
18
  readonly label: string
15
19
  readonly icon: ReactNode
20
+ /**
21
+ * The icon as an image URL or `data:` URI, for a host that draws the dock in hosted mode: `icon`
22
+ * is a React node and cannot cross to it. Without one a host draws the label. It must be on the
23
+ * app's origin, or a `data:` PNG, JPEG, WebP or GIF: a host drops an SVG or another origin's image and draws the label.
24
+ */
25
+ readonly image?: string
16
26
  /** The window this item opens and reports as running. Defaults to the item's id. */
17
27
  readonly window?: WindowId
18
28
  /** One line under the label inside a stack. */
@@ -25,6 +35,11 @@ export interface DockItem {
25
35
  readonly contextMenu?: () => readonly MenuItem[]
26
36
  /** Can be dragged along the dock to a new place, when the dock has `pins.onMove`. */
27
37
  readonly movable?: boolean
38
+ /**
39
+ * Whether its windows are open, said by someone else rather than read from this desk: a host's
40
+ * dock, drawing an item for an app it runs, shows what the app reported.
41
+ */
42
+ readonly status?: DockStatus
28
43
  }
29
44
 
30
45
  /** The drag type of an item carried along the dock; its payload is the item's id. */
@@ -49,6 +64,8 @@ export interface DockStack {
49
64
  readonly items: readonly DockItem[]
50
65
  /** Defaults to the first four item icons, the way a folder previews its contents. */
51
66
  readonly icon?: ReactNode
67
+ /** The icon as an image, for a host that draws the dock. See `DockItem.image`. */
68
+ readonly image?: string
52
69
  /** What a right-click (or the Menu key) offers for the stack itself: Remove from Dock. */
53
70
  readonly contextMenu?: () => readonly MenuItem[]
54
71
  /** A kept stack: it takes drops and can be carried along the dock, as a `movable` item can. */
@@ -59,6 +76,8 @@ export type DockEntry =
59
76
  | ({ readonly type: 'item' } & DockItem)
60
77
  | ({ readonly type: 'stack' } & DockStack)
61
78
  | { readonly type: 'separator'; readonly id: string }
79
+ /** Where the app wants its Settings or About item: see `dockSettings()` and `dockAbout()`. */
80
+ | { readonly type: 'settings' | 'about'; readonly id: string }
62
81
 
63
82
  export const dockItem = (item: DockItem): DockEntry => ({ type: 'item', ...item })
64
83
  export const dockStack = (stack: DockStack): DockEntry => ({ type: 'stack', ...stack })
@@ -84,22 +103,9 @@ export interface DockProps {
84
103
  readonly pins?: DockPins
85
104
  }
86
105
 
87
- const windowOf = (item: DockItem) => item.window ?? item.id
88
-
89
- const statusOf = (state: DeskState, items: readonly DockItem[]) => {
90
- const key = focusedId(state)
91
- const windows = items.flatMap(i => instancesOf(state, windowOf(i)))
92
- return {
93
- // Any window of this kind counts: a second query window is still Query, running.
94
- running: windows.length > 0,
95
- focused: items.some(i => key !== null && windowType(key) === windowOf(i)),
96
- // Open, and none of it on the desk. One window of a kind still showing means the item is not.
97
- minimized: windows.length > 0 && windows.every(w => isMinimized(state, w.id)),
98
- }
99
- }
100
106
 
101
107
  /** Moves focus among the buttons in a container with arrow keys, Home and End. */
102
- function roveFocus(event: KeyboardEvent<HTMLElement>, keys: { next: string[]; previous: string[] }) {
108
+ export function roveFocus(event: KeyboardEvent<HTMLElement>, keys: { next: string[]; previous: string[] }) {
103
109
  // Only this container's own buttons: the dock must not rove into an open stack, nor a stack back out.
104
110
  const container = event.currentTarget
105
111
  const buttons = [...container.querySelectorAll<HTMLButtonElement>('[data-rove]:not(:disabled)')].filter(
@@ -119,9 +125,24 @@ function roveFocus(event: KeyboardEvent<HTMLElement>, keys: { next: string[]; pr
119
125
  target.focus()
120
126
  }
121
127
 
122
- export function Dock({ entries, label = 'Dock', placement = 'overlay', side = 'left', className, pins }: DockProps) {
128
+ export function Dock(props: DockProps) {
129
+ // In hosted mode the host draws one dock for every app, with its own Settings and About: this one
130
+ // sends it the app's entries instead.
131
+ return useHosted() ? <HostedDock entries={props.entries} /> : <DrawnDock {...props} />
132
+ }
133
+
134
+ function DrawnDock({ entries: given, label = 'Dock', placement = 'overlay', side = 'left', className, pins }: DockProps) {
123
135
  const vertical = side !== 'bottom'
136
+ const desk = useDesk()
137
+ const app = useDeskApp()
138
+ // Settings and About, where every Desk app has them, when the app has declared itself.
139
+ const entries = placeAppDockItems(given, app, {
140
+ settings: () => openAppSettings(desk, app),
141
+ about: () => openPanel(desk, ABOUT_WINDOW),
142
+ })
124
143
  const [openStack, setOpenStack] = useState<string | null>(null)
144
+ // A stack that went while open, as one Settings left empty, comes back closed.
145
+ if (openStack && !entries.some(e => e.id === openStack)) setOpenStack(null)
125
146
  const firstFocusable = entries.find(e => e.type !== 'separator')?.id
126
147
  const { dropProps } = useDropTarget({
127
148
  accepts: pinAccepts(pins),
@@ -209,11 +230,7 @@ function DockButton({ item, tabIndex, pins }: DockButtonProps) {
209
230
  aria-disabled={(item.disabled && item.contextMenu && true) || undefined}
210
231
  {...dropProps}
211
232
  {...drag}
212
- onClick={() => {
213
- if (item.disabled) return
214
- if (item.onSelect) item.onSelect()
215
- else desk.open(windowOf(item))
216
- }}
233
+ onClick={() => selectDockItem(desk, item)}
217
234
  onContextMenu={context.target.onContextMenu}
218
235
  onKeyDown={context.target.onKeyDown}
219
236
  >
@@ -304,8 +321,7 @@ function StackButton({ stack, tabIndex, open, setOpenStack, pins }: StackButtonP
304
321
  }
305
322
 
306
323
  const select = (item: DockItem) => {
307
- if (item.onSelect) item.onSelect()
308
- else desk.open(windowOf(item))
324
+ selectDockItem(desk, item)
309
325
  onOpenChange(false)
310
326
  }
311
327
 
@@ -7,11 +7,14 @@ import { bindShortcuts, formatShortcut, isApplePlatform } from '../core/shortcut
7
7
  import type { Keymap } from '../core/shortcuts.js'
8
8
  import type { Desk } from '../core/desk.js'
9
9
  import type { DeskState, WindowId } from '../core/types.js'
10
+ import { ABOUT_WINDOW, boundByDesk, hostOwnsShortcuts, openPanel, placeAppMenuItems, useDeskApp } from './app.js'
10
11
  import { useDesk, useDeskState } from './context.js'
11
12
  import { hasModKey, hostMenuModel, sameHostModel } from './hostMenu.js'
12
13
  import { isWidgetInFront, setWidgetInFront, useWidgetsInFront } from './widgets.js'
13
14
  import type { Widget } from './widgets.js'
14
15
  import type { HostMenu, MenuHost } from './hostMenu.js'
16
+ import { useHosted, useHostMenu } from './hosted.js'
17
+ import { joinFrontMenus, useFrontMenus } from './windowMenus.js'
15
18
 
16
19
  /*
17
20
  * A menu bar in the AppKit manner. Menus never take keyboard focus from the
@@ -177,16 +180,39 @@ export const typeAhead = (items: readonly Resolved[], from: number, letter: stri
177
180
  return -1
178
181
  }
179
182
 
180
- /** The shortcut of every command item in these menus, as `bindShortcuts` takes them; `keep` leaves some out. */
183
+ /**
184
+ * The shortcut of every command item in these menus, as `bindShortcuts` takes them; `keep` leaves some out.
185
+ * So do those Desk binds on the command itself (⌘, for Settings): the item shows it, and binding it here too would be twice.
186
+ */
181
187
  const menuKeymap = (menus: readonly Menu[], keep: (shortcut: string) => boolean = () => true): Keymap =>
182
188
  Object.fromEntries(
183
189
  menus
184
190
  .flatMap(m => (typeof m.items === 'function' ? m.items() : m.items))
185
- .flatMap(i => (i.type === 'command' && i.shortcut && keep(i.shortcut) ? [[i.shortcut, i.command] as const] : [])),
191
+ .flatMap(i => (i.type === 'command' && i.shortcut && !boundByDesk(i.shortcut, i.command) && keep(i.shortcut) ? [[i.shortcut, i.command] as const] : [])),
186
192
  )
187
193
 
188
- export function MenuBar(props: MenuBarProps) {
189
- return props.host ? <HostedMenuBar {...props} host={props.host} /> : <DrawnMenuBar {...props} />
194
+ /** Whether a host gives this shortcut a key of its own: those it says, or else every one with `mod` in it. */
195
+ const ownedBy = (host: MenuHost) => (shortcut: string) => (host.ownsShortcut ? host.ownsShortcut(shortcut) : hasModKey(shortcut))
196
+
197
+ export function MenuBar(given: MenuBarProps) {
198
+ const desk = useDesk()
199
+ const app = useDeskApp()
200
+ const hosted = useHosted()
201
+ const hostMenu = useHostMenu()
202
+ // About and Settings at the top of the app menu, before either bar sees the menus: drawn or in a host's
203
+ // menu bar, they are there once. The item shows ⌘,; Desk binds it on the command, or the host owns it. In
204
+ // hosted mode they are the host's, which has one About and one Settings for every app it runs.
205
+ // The window in front adds its menus, after the app's own and before Window and Help, in either bar.
206
+ const front = useFrontMenus(desk)
207
+ const menus = useMemo(
208
+ () => joinFrontMenus(hosted ? given.menus : placeAppMenuItems(given.menus, app, () => openPanel(desk, ABOUT_WINDOW)), front, given.status),
209
+ [given.menus, given.status, app, desk, hosted, front],
210
+ )
211
+ const props = menus === given.menus ? given : { ...given, menus }
212
+ // In hosted mode the host's menu bar is the default `host`: one given here still wins.
213
+ const host = props.host ?? hostMenu
214
+ if (host) return <HostedMenuBar {...props} host={host} />
215
+ return hosted ? null : <DrawnMenuBar {...props} />
190
216
  }
191
217
 
192
218
  /**
@@ -260,10 +286,12 @@ function HostedMenuBar({ menus, status = [], host, shortcuts = true }: MenuBarPr
260
286
  }
261
287
  }, [desk, host, publish, refresh])
262
288
 
263
- // The host gives its own shortcuts a key; the page binds the rest, read at each key press.
289
+ // The host gives its own shortcuts a key; the page binds the rest, read at each key press. Desk's own
290
+ // shortcuts (⌘,) step aside for the host's too, while it is up.
291
+ useEffect(() => hostOwnsShortcuts(desk, ownedBy(host)), [desk, host])
264
292
  useEffect(() => {
265
293
  if (!shortcuts) return undefined
266
- const owns = (shortcut: string) => (host.ownsShortcut ? host.ownsShortcut(shortcut) : hasModKey(shortcut))
294
+ const owns = ownedBy(host)
267
295
  return bindShortcuts(desk, () => menuKeymap([...latest.current.menus, ...latest.current.status], shortcut => !owns(shortcut)), { apple })
268
296
  }, [desk, host, shortcuts, apple])
269
297
 
@@ -323,6 +351,11 @@ function DrawnMenuBar({ menus, status = [], leading, trailing, label = 'Menu bar
323
351
  useEffect(() => {
324
352
  if (!open) return
325
353
  const menuIndex = all.findIndex(m => m.id === open.id)
354
+ // Its menu left the bar while open (its window left the front): close it, or it takes keys unseen.
355
+ if (menuIndex < 0) {
356
+ setOpen(null)
357
+ return
358
+ }
326
359
  const move = (active: number) => {
327
360
  setOpen({ ...open, active })
328
361
  revealMenuItem(`${baseId}-menu-${open.id}-${active}`)