@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
@@ -4,15 +4,23 @@ import { addCommandHandler } from '../core/commands.js'
4
4
  import { createBus } from '../core/events.js'
5
5
  import type { Bus } from '../core/events.js'
6
6
  import { createDesk, routeOf } from '../core/desk.js'
7
+ import { connectHost, findDeskHost, THEME_TOPIC } from '../core/hosted.js'
8
+ import type { DeskHostBridge, HostClient } from '../core/hosted.js'
9
+ import { applyTheme, applyThemeBasics } from '../core/theme.js'
10
+ import type { DeskTheme } from '../core/theme.js'
7
11
  import { deviceLook, resolveLook } from '../core/look.js'
12
+ import { watchThemeChanges } from '../core/themeChange.js'
13
+ import { deskDrawsWindows } from '../core/location.js'
8
14
  import { holdAll } from '../core/services.js'
9
15
  import type { Holdable } from '../core/services.js'
10
16
  import type { Look, LookChoice } from '../core/look.js'
11
- import { AppProvider, bindDeskShortcuts, hasSettings, openSettings, SettingsCommand } from './app.js'
12
- import { AppearanceSettings, hasRows, hostThemed, rowsOf, showColorScheme, shownRows, useColorScheme, useLookChoice, useThemeFromHost } from './appearance.js'
17
+ import { AppProvider, bindDeskShortcuts, declareOn, desksWindow, hasSettings, openAppSettings, SettingsCommand } from './app.js'
18
+ import { AppearanceSettings, hasRows, hostThemed, rowsOf, showColorScheme, shownRows, useChosenColorScheme, useDefaultColorScheme, useLookChoice, useThemeFromHost } from './appearance.js'
13
19
  import type { DeskApp, SettingsSection } from './app.js'
14
20
  import type { AppearanceRows } from './appearance.js'
15
21
  import { DragProvider } from './dragContext.js'
22
+ import { HostedApp } from './hostApp.js'
23
+ import { HostContext } from './hosted.js'
16
24
  import { missingProvider } from './missingProvider.js'
17
25
  import type { Desk } from '../core/desk.js'
18
26
  import type { DeskOptions, DeskState, WindowId } from '../core/types.js'
@@ -47,22 +55,70 @@ export interface DeskProviderProps {
47
55
  * standard places. Read on every render, so it may change.
48
56
  */
49
57
  readonly app?: DeskApp
58
+ /**
59
+ * Hosted mode: a host that draws one menu bar and dock for several apps. The app's `MenuBar` and
60
+ * `Dock` then draw nothing and send their contents to the host, and the app wears the theme the
61
+ * host passes on. Left out, the app is hosted when the page has a `globalThis.deskHost` that speaks
62
+ * this protocol; `null` keeps it unhosted whatever the page has. Read once.
63
+ */
64
+ readonly host?: DeskHostBridge | null
65
+ /**
66
+ * How a hosted app wears the theme it is sent, for one that keeps some looks of its own. Light or
67
+ * dark and the platform chrome apply whatever this does; the default, `applyTheme`, takes all of it.
68
+ */
69
+ readonly onTheme?: (theme: DeskTheme) => void
50
70
  readonly children: ReactNode
51
71
  }
52
72
 
53
- export function DeskProvider({ desk, options, look: appLook = 'auto', services, app: declared, children }: DeskProviderProps) {
73
+ /**
74
+ * Connects to the host while mounted, and wears the theme it passes on unless `wears` is false: the
75
+ * primary, whose theme it is, keeps its own. Null client until connected.
76
+ */
77
+ function useHostConnection(bridge: DeskHostBridge | null, wears: boolean, onTheme: ((theme: DeskTheme) => void) | undefined) {
78
+ const [client, setClient] = useState<HostClient | null>(null)
79
+ const [theme, setTheme] = useState<DeskTheme | null>(null)
80
+ const wear = useRef(onTheme)
81
+ wear.current = onTheme
82
+ useEffect(() => {
83
+ if (!bridge) return
84
+ const connected = connectHost(bridge)
85
+ const stop = !wears ? () => {} : connected.subscribe<DeskTheme>('primary', THEME_TOPIC, ({ payload }) => {
86
+ ;(wear.current ?? applyTheme)(payload)
87
+ // After the app's own handler, so light or dark and the look hold whatever it did.
88
+ applyThemeBasics(payload)
89
+ setTheme(payload)
90
+ })
91
+ setClient(connected)
92
+ return () => {
93
+ stop()
94
+ connected.close()
95
+ setClient(null)
96
+ setTheme(null)
97
+ }
98
+ }, [bridge, wears])
99
+ return { client, theme }
100
+ }
101
+
102
+ export function DeskProvider({ desk, options, look: appLook = 'auto', services, app: declared, host, onTheme, children }: DeskProviderProps) {
54
103
  const [value] = useState(() => desk ?? createDesk(options))
55
104
  const [bus] = useState(createBus)
56
105
  const [held] = useState(() => services ?? [])
57
106
  useEffect(() => holdAll(held), [held])
58
- // Appearance: the rows the app asked for, less the theme's when a host chooses it.
59
- const fromHost = useThemeFromHost(declared?.themeFromHost)
107
+ const [bridge] = useState(() => (host === undefined ? findDeskHost() : host))
108
+ // The primary declares `themeFromHost: false`: the theme is its own, so it keeps its Appearance.
109
+ const hosted = useHostConnection(bridge, declared?.themeFromHost !== false, onTheme)
110
+ const hosting = useMemo(() => (bridge ? { client: hosted.client } : null), [bridge, hosted.client])
111
+ // Appearance: the rows the app asked for, less the theme's when a host chooses it. A hosted app's
112
+ // host always does, so it offers no scheme, look or theme of its own.
113
+ const fromHost = useThemeFromHost(declared?.themeFromHost ?? (bridge ? true : undefined))
60
114
  const rows = shownRows(rowsOf(declared?.settings?.appearance), fromHost)
61
- const app = useMemo(() => withAppearance(declared, rows, appLook), [declared, rows.scheme, rows.look, rows.sounds, rows.theme, rows.soundsDescription, appLook])
115
+ const app = useMemo(() => withAppearance(declared, rows, appLook), [declared, rows.scheme, rows.defaultScheme, rows.look, rows.sounds, rows.theme, rows.soundsDescription, appLook])
62
116
  const chosenLook = useLookChoice()
63
- const scheme = useColorScheme()
117
+ const defaultScheme = useDefaultColorScheme(Boolean(rows.scheme), rows.defaultScheme)
118
+ const scheme = useChosenColorScheme() ?? defaultScheme
64
119
  const look = (rows.look && chosenLook) || appLook
65
- const resolved = resolveLook(look)
120
+ // A hosted app wears the look of the theme it was sent, once there is one.
121
+ const resolved = hosted.theme?.look ?? resolveLook(look)
66
122
  useLayoutEffect(() => {
67
123
  if (!rows.scheme) return
68
124
  showColorScheme(scheme)
@@ -73,6 +129,7 @@ export function DeskProvider({ desk, options, look: appLook = 'auto', services,
73
129
  }, [rows.scheme, scheme])
74
130
  // On the root, not the desk: menus and popovers are portalled out of it, and are chrome too.
75
131
  useLayoutEffect(() => {
132
+ watchThemeChanges()
76
133
  document.documentElement.dataset.look = resolved
77
134
  return () => {
78
135
  delete document.documentElement.dataset.look
@@ -81,25 +138,43 @@ export function DeskProvider({ desk, options, look: appLook = 'auto', services,
81
138
  // "Settings…" and ⌘, perform this; it answers at the top of the chain, so a window can still take it.
82
139
  const latestApp = useRef(app ?? null)
83
140
  latestApp.current = app ?? null
141
+ // Outside React, openSettings(desk) and syncWithLocation read the declaration from the desk. Said as the
142
+ // provider renders, so a link read in the app's first effect already knows Settings and About, and again
143
+ // in an effect, which a remount in development runs after the cleanup that forgot it.
144
+ const [declaration] = useState(() => ({ app: () => latestApp.current, draws: (id: WindowId) => desksWindow(latestApp.current, id) !== null }))
145
+ declareOn(value, declaration.app)
146
+ deskDrawsWindows(value, declaration.draws)
147
+ useLayoutEffect(() => {
148
+ const forgetApp = declareOn(value, declaration.app)
149
+ const forgetWindows = deskDrawsWindows(value, declaration.draws)
150
+ return () => {
151
+ forgetApp()
152
+ forgetWindows()
153
+ }
154
+ }, [value, declaration])
84
155
  const hasApp = app !== undefined
85
156
  useEffect(() => {
86
157
  if (!hasApp) return
87
- const remove = addCommandHandler(document, SettingsCommand, (route?: unknown) => openSettings(value, latestApp.current, typeof route === 'string' ? route : undefined), {
158
+ const remove = addCommandHandler(document, SettingsCommand, (route?: unknown) => openAppSettings(value, latestApp.current, typeof route === 'string' ? route : undefined), {
88
159
  enabled: () => hasSettings(latestApp.current),
89
160
  })
90
- // ⌘, here, not only in the menu bar's keymap, so it works in an app that has none.
91
- const unbind = bindDeskShortcuts(value)
161
+ // ⌘, here, not only in the menu bar's keymap, so it works in an app that has none. Not when hosted:
162
+ // the host's frame owns it, menu bar or not, connected yet or not.
163
+ const unbind = bridge ? () => {} : bindDeskShortcuts(value)
92
164
  return () => {
93
165
  remove()
94
166
  unbind()
95
167
  }
96
- }, [value, hasApp])
168
+ }, [value, hasApp, bridge])
97
169
  return (
98
170
  <DeskContext.Provider value={value}>
99
171
  <BusContext.Provider value={bus}>
100
172
  <LookContext.Provider value={resolved}>
101
173
  <AppProvider value={app ?? null}>
102
- <DragProvider>{children}</DragProvider>
174
+ <HostContext.Provider value={hosting}>
175
+ {bridge && <HostedApp />}
176
+ <DragProvider>{children}</DragProvider>
177
+ </HostContext.Provider>
103
178
  </AppProvider>
104
179
  </LookContext.Provider>
105
180
  </BusContext.Provider>
@@ -0,0 +1,42 @@
1
+ import { focusedId, instancesOf, isMinimized, windowType } from '../core/desk.js'
2
+ import type { DeskState, WindowId } from '../core/types.js'
3
+
4
+ /** What a dock item needs to say whether its windows are open: the item's window kind, and its id. */
5
+ export interface DockTarget {
6
+ readonly id: string
7
+ readonly window?: WindowId
8
+ /** Whether its windows are open, said by someone else: an app a host runs reports its own. */
9
+ readonly status?: DockStatus
10
+ }
11
+
12
+ /** Whether a dock item's windows are open, have focus, or are all minimized. */
13
+ export interface DockStatus {
14
+ readonly running: boolean
15
+ readonly focused: boolean
16
+ readonly minimized: boolean
17
+ }
18
+
19
+ /** The window a dock item opens and reports as running: its `window`, or its id. */
20
+ export const windowOf = (item: DockTarget): WindowId => item.window ?? item.id
21
+
22
+ /** Whether any of these items' windows are open, have focus, or are all minimized. */
23
+ export const statusOf = (state: DeskState, items: readonly DockTarget[]): DockStatus => {
24
+ const told = items.flatMap(i => (i.status ? [i.status] : []))
25
+ // Items whose status is reported (a hosted app's, drawn by its host) say it themselves.
26
+ if (told.length) {
27
+ return {
28
+ running: told.some(s => s.running),
29
+ focused: told.some(s => s.focused),
30
+ minimized: told.some(s => s.running) && told.every(s => !s.running || s.minimized),
31
+ }
32
+ }
33
+ const key = focusedId(state)
34
+ const windows = items.flatMap(i => instancesOf(state, windowOf(i)))
35
+ return {
36
+ // Any window of this kind counts: a second query window is still Query, running.
37
+ running: windows.length > 0,
38
+ focused: items.some(i => key !== null && windowType(key) === windowOf(i)),
39
+ // Open, and none of it on the desk. One window of a kind still showing means the item is not.
40
+ minimized: windows.length > 0 && windows.every(w => isMinimized(state, w.id)),
41
+ }
42
+ }
@@ -0,0 +1,100 @@
1
+ import { useEffect } from 'react'
2
+ import { addCommandHandler } from '../core/commands.js'
3
+ import type { CommandId } from '../core/commands.js'
4
+ import { focusedId } from '../core/desk.js'
5
+ import { warnOnce } from '../core/location.js'
6
+ import { parseShortcut } from '../core/shortcuts.js'
7
+ import type { Desk } from '../core/desk.js'
8
+ import type { HostMenuItem } from '../core/hosted.js'
9
+ import { checkChrome } from '../host/checkChrome.js'
10
+ import type { WindowId } from '../core/types.js'
11
+ import type { Menu, MenuItem } from './MenuBar.js'
12
+ import { addWindowMenus } from './windowMenus.js'
13
+
14
+ /*
15
+ * MENUS FROM AN EMBEDDED APP.
16
+ *
17
+ * An app in an `AppFrame` sends its menus as hosted mode's apps do, as data in a `chrome` message, and
18
+ * hears what was chosen as a `command`. It is somebody else's page, so its menus get the check a host
19
+ * gives any app's chrome (`checkChrome`): a bad menu or item is dropped and the rest kept. The frame then
20
+ * turns them into the page's own menus, for the window it is in, so they join the bar while that window is
21
+ * in front. Each item becomes a command of its own, named for this frame, so a shortcut works through the
22
+ * bar like any other and a choice goes back only to the frame that sent it.
23
+ */
24
+
25
+ /** The most menus one frame adds to the bar: room for a menu or two, not a bar of its own. */
26
+ const MAX_MENUS = 4
27
+
28
+ /** One item the frame turned into a command, and the app's own id for it. */
29
+ export interface FrameItem {
30
+ readonly command: CommandId
31
+ readonly id: string
32
+ readonly enabled: boolean
33
+ }
34
+
35
+ /**
36
+ * Whether an embedded app may bind this shortcut: only with ⌘/Ctrl or ⌥ held, or a function key. A bare
37
+ * letter, Enter, Escape or an arrow belongs to whatever has focus, and a page in a frame must not take it
38
+ * from the rest of the desk. Read as `matchesShortcut` reads it, so a modifier it ignores (`meta+k`) does not count.
39
+ */
40
+ const framesMayBind = (shortcut: string) => {
41
+ const s = parseShortcut(shortcut)
42
+ return s.mod || s.ctrl || s.alt || /^f([1-9]|1\d|2[0-4])$/.test(s.key)
43
+ }
44
+
45
+ const converted = (row: HostMenuItem, command: CommandId, menu: string): MenuItem[] => {
46
+ if (row.type === 'separator') return [{ type: 'separator' }]
47
+ if (row.label === undefined) return []
48
+ if (row.type === 'header') return [{ type: 'header', label: row.label }]
49
+ let { shortcut } = row
50
+ if (shortcut !== undefined && !framesMayBind(shortcut)) {
51
+ warnOnce(`desk: "${row.label}" in the ${menu} menu asks for ${shortcut}, which has no modifier. An embedded app's shortcut needs one, so it keeps its label without the key.`)
52
+ shortcut = undefined
53
+ }
54
+ return [{ type: 'command', label: row.label, command, ...(row.detail === undefined ? {} : { detail: row.detail }), ...(shortcut === undefined ? {} : { shortcut }), ...(row.checked === undefined ? {} : { checked: row.checked }) }]
55
+ }
56
+
57
+ /**
58
+ * An app's menus as the page's own, after `checkChrome`, its commands named `prefix`:menu index:row index, and what
59
+ * each stands for. Items without an id or label are left out, and menus past the first few. Null when
60
+ * there is nothing.
61
+ */
62
+ export function frameMenus(raw: unknown, prefix: string): { readonly menus: Menu[]; readonly items: FrameItem[] } | null {
63
+ const checked = checkChrome({ menus: raw, dock: [], settings: [], about: null }, location.origin)
64
+ if (!checked.ok) return null
65
+ const items: FrameItem[] = []
66
+ // Named by place, not by the app's ids, which may repeat or run into each other ("a:b" + "c", "a" + "b:c").
67
+ const menus = checked.chrome.menus.slice(0, MAX_MENUS).map((menu, m) => ({
68
+ id: `${prefix}/${m}`,
69
+ label: menu.label,
70
+ items: menu.items.flatMap((row, r) => {
71
+ if (row.type === 'item' && row.id === undefined) return []
72
+ const command = `${prefix}:${m}:${r}`
73
+ const made = converted(row, command, menu.label)
74
+ if (row.type === 'item' && made.length) items.push({ command, id: row.id as string, enabled: row.enabled !== false })
75
+ return made
76
+ }),
77
+ }))
78
+ return menus.length ? { menus, items } : null
79
+ }
80
+
81
+ /**
82
+ * While the frame has menus and its window is in front, they join the bar, and choosing an item, or
83
+ * pressing its shortcut, calls `choose` with the app's own id for it.
84
+ */
85
+ export function useFrameMenus(
86
+ desk: Desk,
87
+ window: WindowId | null,
88
+ menus: { readonly menus: Menu[]; readonly items: FrameItem[] } | null,
89
+ choose: (id: string) => void,
90
+ ): void {
91
+ useEffect(() => {
92
+ if (!menus || window === null) return undefined
93
+ const front = () => focusedId(desk.getState()) === window
94
+ const stops = menus.items.map(item => addCommandHandler(document, item.command, () => choose(item.id), { enabled: () => item.enabled && front() }))
95
+ stops.push(addWindowMenus(desk, window, menus.menus))
96
+ return () => stops.forEach(stop => stop())
97
+ // choose is read fresh by the caller through a ref; the menus are what change.
98
+ // eslint-disable-next-line react-hooks/exhaustive-deps
99
+ }, [desk, window, menus])
100
+ }
@@ -0,0 +1,89 @@
1
+ import { useEffect, useRef } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import type { HostAbout, HostAboutSection, HostSettingsSection } from '../core/hosted.js'
4
+ import { hasSettings, useDeskApp } from './app.js'
5
+ import type { AboutSection, AppLink, DeskApp } from './app.js'
6
+ import { useOpenSettings } from './appPanels.js'
7
+ import { badgeText } from './hostDock.js'
8
+ import { useHost } from './hosted.js'
9
+
10
+ /*
11
+ * SETTINGS AND ABOUT, WHEN A HOST HAS THEM.
12
+ *
13
+ * A host that runs several apps has one Settings and one About in its own frame, so a hosted app draws
14
+ * no gear and no About item. It sends what it declared instead: its Settings sections by name (their
15
+ * controls are React and stay in the app), and its name, version, links and facts as plain data. When
16
+ * the person picks a section in the host's Settings, the app opens its own Settings there.
17
+ */
18
+
19
+ /** An app without facts has nothing to report. */
20
+ const NO_FACTS = (): readonly AboutSection[] | null => []
21
+
22
+ const linkOf = ({ label, url }: AppLink) => ({ label, url })
23
+
24
+ /** A note as text, when it is text; a note drawn with React cannot cross, and is left out. */
25
+ const noteText = (note: ReactNode): string | undefined => (typeof note === 'string' || typeof note === 'number' ? String(note) : undefined)
26
+
27
+ /**
28
+ * An app's About as data: its note and each fact's link, `copy: false` kept, and facts `[]` for nothing
29
+ * to report as against null while they are read. A fact's own note is React, and stays behind.
30
+ */
31
+ export function hostAbout(app: DeskApp, facts: readonly AboutSection[] | null): HostAbout {
32
+ const sections = facts?.map(
33
+ (section): HostAboutSection => ({
34
+ ...(section.title === undefined ? {} : { title: section.title }),
35
+ facts: section.facts.map(({ name, value, link, copy }) => ({
36
+ name,
37
+ value,
38
+ ...(link === undefined ? {} : { link: linkOf(link) }),
39
+ ...(copy === false ? { copy } : {}),
40
+ })),
41
+ }),
42
+ )
43
+ const note = noteText(app.note)
44
+ return {
45
+ name: app.name,
46
+ ...(app.version === undefined ? {} : { version: app.version }),
47
+ links: (app.links ?? []).map(linkOf),
48
+ ...(note === undefined ? {} : { note }),
49
+ facts: sections ?? null,
50
+ }
51
+ }
52
+
53
+ /**
54
+ * An app's Settings sections as data, in order; none for an app without settings. An app whose Settings
55
+ * is a window of its own, with no sections declared, is listed as one entry with the id `''`.
56
+ */
57
+ export function hostSettings(app: DeskApp | null): HostSettingsSection[] {
58
+ if (!app || !hasSettings(app)) return []
59
+ const sections = app.settings?.sections ?? []
60
+ if (sections.length === 0) return [{ id: '', title: 'Settings' }]
61
+ return sections.map(({ id, title, group, badge }) => {
62
+ const text = badgeText(badge)
63
+ return { id, title, ...(group === undefined ? {} : { group }), ...(text === undefined ? {} : { badge: text }) }
64
+ })
65
+ }
66
+
67
+ /** Sends the host the app's Settings sections and About, and opens Settings where the host says. Draws nothing. */
68
+ export function HostedApp() {
69
+ const host = useHost()
70
+ const app = useDeskApp()
71
+ const openSettings = useOpenSettings()
72
+ // The facts are a hook, read here as the About panel reads them, so they can change.
73
+ const facts = (app?.facts ?? NO_FACTS)()
74
+ const settings = hostSettings(app)
75
+ const about = app ? hostAbout(app, facts) : null
76
+ const key = JSON.stringify([settings, about])
77
+ const open = useRef(openSettings)
78
+ open.current = openSettings
79
+
80
+ useEffect(() => {
81
+ host?.setChrome({ settings, about })
82
+ // key stands for both, which are rebuilt on every render.
83
+ // eslint-disable-next-line react-hooks/exhaustive-deps
84
+ }, [host, key])
85
+
86
+ useEffect(() => host?.onCommand('settings', id => open.current(id === '' ? undefined : id)), [host])
87
+
88
+ return null
89
+ }
@@ -0,0 +1,118 @@
1
+ import { useEffect, useRef } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import type { HostDockEntry, HostDockItem } from '../core/hosted.js'
4
+ import type { DeskState } from '../core/types.js'
5
+ import type { Desk } from '../core/desk.js'
6
+ import { markerOf } from './app.js'
7
+ import { useDesk, useDeskState } from './context.js'
8
+ import type { DockEntry, DockItem } from './Dock.js'
9
+ import { statusOf, windowOf } from './dockStatus.js'
10
+ import { useHost } from './hosted.js'
11
+
12
+ /*
13
+ * A DOCK SOMEBODY ELSE DRAWS.
14
+ *
15
+ * In hosted mode one dock serves several apps, drawn by the host. Each app's dock sends its entries
16
+ * as data — label, image, badge, and whether the item's windows are open — and the host sends back
17
+ * the id of the item chosen, which runs here as a click on the drawn dock would.
18
+ */
19
+
20
+ /** The dock as plain data, and the item each id opens. */
21
+ export interface HostDockModel {
22
+ readonly model: readonly HostDockEntry[]
23
+ readonly run: ReadonlyMap<string, DockItem>
24
+ }
25
+
26
+ /** A badge as text: numbers and strings as they are, anything else drawn as a dot. */
27
+ export const badgeText = (badge: ReactNode): string | undefined =>
28
+ badge == null || typeof badge === 'boolean' ? undefined : typeof badge === 'string' || typeof badge === 'number' ? String(badge) : ''
29
+
30
+ function itemModel(item: DockItem, state: DeskState): HostDockItem {
31
+ const badge = badgeText(item.badge)
32
+ return {
33
+ type: 'item',
34
+ id: item.id,
35
+ label: item.label,
36
+ ...(item.description === undefined ? {} : { description: item.description }),
37
+ ...(item.image === undefined ? {} : { image: item.image }),
38
+ ...(badge === undefined ? {} : { badge }),
39
+ ...(item.disabled ? { disabled: true } : {}),
40
+ ...statusOf(state, [item]),
41
+ }
42
+ }
43
+
44
+ /** Turns dock entries into what a host can draw, as the desk stands now. */
45
+ export function hostDockModel(entries: readonly DockEntry[], state: DeskState): HostDockModel {
46
+ const run = new Map<string, DockItem>()
47
+ const model = entries.flatMap((entry): HostDockEntry[] => {
48
+ switch (entry.type) {
49
+ case 'separator':
50
+ return [{ type: 'separator', id: entry.id }]
51
+ case 'settings':
52
+ case 'about':
53
+ // The host's frame has the one Settings and About: the app's places for them are not drawn.
54
+ return []
55
+ case 'item':
56
+ run.set(entry.id, entry)
57
+ return [itemModel(entry, state)]
58
+ case 'stack': {
59
+ // Settings and About placed in a stack are the host's too: dropped, and the stack with them if it empties.
60
+ const items = entry.items.filter(item => !markerOf(item))
61
+ for (const item of items) run.set(item.id, item)
62
+ if (!items.length) return []
63
+ return [
64
+ {
65
+ type: 'stack',
66
+ id: entry.id,
67
+ label: entry.label,
68
+ ...(entry.image === undefined ? {} : { image: entry.image }),
69
+ items: items.map(item => itemModel(item, state)),
70
+ },
71
+ ]
72
+ }
73
+ }
74
+ })
75
+ return { model, run }
76
+ }
77
+
78
+ /** Opens a dock item's window, or runs its own `onSelect`, as clicking it on a drawn dock does. */
79
+ export function selectDockItem(desk: Desk, item: DockItem): void {
80
+ if (item.disabled) return
81
+ if (item.onSelect) item.onSelect()
82
+ else desk.open(windowOf(item))
83
+ }
84
+
85
+ /**
86
+ * The dock in hosted mode. Draws nothing. Sends the host the entries whenever they or the desk
87
+ * change, and runs the item the host says was chosen. A right-click menu, pinning and dragging
88
+ * stay with the drawn dock: a host offers its own.
89
+ */
90
+ export function HostedDock({ entries }: { readonly entries: readonly DockEntry[] }) {
91
+ const host = useHost()
92
+ const desk = useDesk()
93
+ const state = useDeskState()
94
+ const { model, run } = hostDockModel(entries, state)
95
+ const latest = useRef(run)
96
+ latest.current = run
97
+ const key = JSON.stringify(model)
98
+
99
+ useEffect(() => {
100
+ host?.setChrome({ dock: model })
101
+ // key stands for the model's contents, which is rebuilt on every render.
102
+ // eslint-disable-next-line react-hooks/exhaustive-deps
103
+ }, [host, key])
104
+
105
+ useEffect(() => {
106
+ if (!host) return undefined
107
+ const stop = host.onCommand('dock', id => {
108
+ const item = latest.current.get(id)
109
+ if (item) selectDockItem(desk, item)
110
+ })
111
+ return () => {
112
+ stop()
113
+ host.setChrome({ dock: [] })
114
+ }
115
+ }, [host, desk])
116
+
117
+ return null
118
+ }
@@ -1,7 +1,10 @@
1
1
  import type { CommandId } from '../core/commands.js'
2
+ import type { HostMenu, HostMenuItem } from '../core/hosted.js'
2
3
  import { parseShortcut } from '../core/shortcuts.js'
3
4
  import type { Menu, MenuItem } from './MenuBar.js'
4
5
 
6
+ export type { HostMenu, HostMenuItem }
7
+
5
8
  /*
6
9
  * A MENU BAR SOMEBODY ELSE DRAWS.
7
10
  *
@@ -11,44 +14,6 @@ import type { Menu, MenuItem } from './MenuBar.js'
11
14
  * under an id. When someone picks a row the host sends the id back, and the page runs the item.
12
15
  */
13
16
 
14
- /** One row of a menu a host draws. Plain data, so it can cross a process boundary. */
15
- export interface HostMenuItem {
16
- readonly type: 'item' | 'separator' | 'header'
17
- /**
18
- * Present on 'item'; unique within one publish. Opaque to a host, which only sends it back: it
19
- * names the item's menu, place and label, so a choice from a menu that has since changed runs
20
- * nothing rather than whatever took that place.
21
- */
22
- readonly id?: string
23
- /** Present on 'item' and 'header'. */
24
- readonly label?: string
25
- readonly detail?: string
26
- /** In desk's format: 'mod+k', 'mod+alt+a', 'alt+]'. */
27
- readonly shortcut?: string
28
- /**
29
- * The page handles this item's shortcut itself, so a host draws it beside the item and gives it
30
- * no key (Electron: `registerAccelerator: false`). Set on an action's shortcut, which the drawn
31
- * bar only shows too: binding it as well would fire the action twice.
32
- */
33
- readonly showOnly?: boolean
34
- /** Defaults to true. */
35
- readonly enabled?: boolean
36
- /** Absent means the item is not checkable. */
37
- readonly checked?: boolean
38
- }
39
-
40
- /** A whole menu as a host sees it. */
41
- export interface HostMenu {
42
- readonly id: string
43
- /** The menu's `label`: a host draws text, so a status menu's richer `title` stays behind. */
44
- readonly label: string
45
- /** The app's own menu, which a `Menu` calls `emphasis`. */
46
- readonly primary?: boolean
47
- /** One of the bar's status menus, which a host puts after the others. */
48
- readonly status?: boolean
49
- readonly items: readonly HostMenuItem[]
50
- }
51
-
52
17
  /** What a native shell provides so a `MenuBar` can live in its menu bar. */
53
18
  export interface MenuHost {
54
19
  /** Replaces every menu the page published before. An empty list takes them all away. */
@@ -0,0 +1,65 @@
1
+ import { createContext, useContext, useEffect, useMemo, useRef } from 'react'
2
+ import { THEME_TOPIC } from '../core/hosted.js'
3
+ import type { Broadcast, HostClient, Publisher } from '../core/hosted.js'
4
+ import type { DeskTheme } from '../core/theme.js'
5
+ import type { MenuHost } from './hostMenu.js'
6
+
7
+ /*
8
+ * An app in hosted mode has its host in context: `MenuBar` and `Dock` find it there and send their
9
+ * contents to the host instead of drawing them, and the app's own code reaches it through `useHost`
10
+ * to publish and listen. Outside a host the context is empty and nothing changes.
11
+ *
12
+ * The client connects in an effect, so for the first render an app knows it is hosted before it has
13
+ * a client: `client` is null then, and the chrome draws nothing rather than flash its own.
14
+ */
15
+
16
+ export const HostContext = createContext<{ readonly client: HostClient | null } | null>(null)
17
+
18
+ /** Whether this app runs in a host, connected yet or not. */
19
+ export const useHosted = (): boolean => useContext(HostContext) !== null
20
+
21
+ /** The host this app runs in, or null when it runs on its own (or has not connected yet). */
22
+ export const useHost = (): HostClient | null => useContext(HostContext)?.client ?? null
23
+
24
+ /**
25
+ * The host's menu bar as a `MenuHost`, for a `MenuBar` in hosted mode; null until connected. Shortcuts
26
+ * are shared as with any host's menu bar: the host gives those with `mod` a key and sends the item
27
+ * back, as a native menu's key equivalents do whichever app has focus, and the app binds the rest.
28
+ */
29
+ export function useHostMenu(): MenuHost | null {
30
+ const host = useHost()
31
+ return useMemo(
32
+ () =>
33
+ host && {
34
+ publish: menus => host.setChrome({ menus }),
35
+ onSelect: listener => host.onCommand('menu', listener),
36
+ },
37
+ [host],
38
+ )
39
+ }
40
+
41
+ /**
42
+ * Hears `publisher`'s broadcasts on `topic` while mounted, starting with the last one. `publisher` is
43
+ * an app's id, or `'primary'`. Does nothing when not hosted.
44
+ */
45
+ export function useHostBroadcast<T = unknown>(publisher: Publisher, topic: string, handler: (broadcast: Broadcast<T>) => void): void {
46
+ const host = useHost()
47
+ const latest = useRef(handler)
48
+ latest.current = handler
49
+ useEffect(() => host?.subscribe<T>(publisher, topic, broadcast => latest.current(broadcast)), [host, publisher, topic])
50
+ }
51
+
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()
59
+ const key = theme ? JSON.stringify(theme) : ''
60
+ const latest = useRef(theme)
61
+ latest.current = theme
62
+ useEffect(() => {
63
+ if (host && latest.current) host.publish(THEME_TOPIC, latest.current)
64
+ }, [host, key])
65
+ }