@tearleads/windowing 0.2.26 → 0.2.28

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.
package/README.md CHANGED
@@ -9,7 +9,7 @@ switch, and a launcher that runs a set of mini-apps in windows or in the routed
9
9
 
10
10
  The package knows nothing about the applications that run inside its windows.
11
11
  It depends only on React, react-dom, and Phosphor icons, which draw the
12
- chrome's own icons unless a host passes its own (see [Icons](#icons)).
12
+ chrome's own icons unless a host passes its own (see [Icons](./docs/windows.md#icons)).
13
13
 
14
14
  ## Composing a desktop
15
15
 
@@ -53,503 +53,23 @@ function OpenNotes() {
53
53
  Windows are absolutely positioned and clamp to their parent element, so the
54
54
  desktop surface must be a positioned container.
55
55
 
56
- ## Geometry and input
57
-
58
- Windows move by their title bar and resize by any side or corner with pointer
59
- events, so mouse, touch, and pen all work. The resize targets reach a few
60
- pixels past the window's border, so an edge can be taken from just outside the
61
- window, and a hovered corner lights up over the window's own rounded border.
62
-
63
- While a gesture runs the geometry stays local to that window; when it ends, the
64
- window commits its `position` and `size` (surface-relative) to its
65
- `WindowEntry`. The first layout commits too, so `position` always reflects
66
- where the window sits. Without `size` a window takes its stylesheet's default
67
- size.
68
-
69
- To save a layout, read `position` and `size` from `useWindowStateData()`. To
70
- restore one, pass them back as `create` options, which take precedence over
71
- `create`'s viewport `x`/`y`. `setGeometry(id, { position, size })` moves or
72
- resizes a window programmatically.
73
-
74
- Content with a natural size, such as a document page, passes it in CSS pixels
75
- to `useWindowContentSize({ width, height })` while it is mounted. Its window
76
- then offers **Fit to Content** in the View menu, which restores the window if
77
- maximized and sizes it so the scroll pane's content area shows that size. The
78
- fit measures the chrome as rendered (bars, sidebar, the pane's padding and
79
- scrollbars) and stays within the surface. Content the surface cannot hold
80
- scrolls. The width always leaves room for a vertical scrollbar, so the
81
- content keeps its width even when a status message briefly takes height from
82
- the body. Last, the window moves as far as it must to stay on the surface.
83
- `undefined` withdraws the item.
84
-
85
- To open a window already fitted, pass `fitToContent: true` to `create`. The
86
- window fits once, as Fit to Content would, when its content has loaded and
87
- reported its size. Content reports its load by calling
88
- `useCurrentWindow()?.markContentLoaded?.()`, for example once a page has
89
- rendered. A later call does nothing. A window that is maximized when its
90
- content loads, as a host might open it on a narrow screen, stays maximized,
91
- and a window on a hidden surface fits once the surface shows.
92
-
93
- ## Slots
94
-
95
- - **`ContentBoundary`** — `Window` renders a window's component inside this
96
- optional wrapper, which receives the `WindowEntry`. Hosts use it to give
97
- content app-specific context (a route provider, an error boundary) without the
98
- window layer knowing about apps. `MiniAppWindow` fills it for launcher apps
99
- (see [Launching mini-apps](#launching-mini-apps)).
100
- - **`appId`** — an opaque string a host attaches when creating a window. The
101
- window layer only stores and compares it; the host interprets it.
102
-
103
- Windows register their own menu items, title-bar actions, a Back action, a
104
- sidebar, a background, and a natural size through the `useWindow*` hooks, from
105
- inside the window's content.
106
-
107
- ## Toolbar
108
-
109
- The toolbar row sits between the menu bar and the body. Content registers icon
110
- buttons in it with `useWindowTitleBarAction`; give an action `pressed` to make
111
- it a toggle, announced as `aria-pressed` and drawn pressed while true:
112
-
113
- ```tsx
114
- const icon = useMemo(() => <HashIcon aria-hidden size={18} />, []);
115
- useWindowTitleBarAction(
116
- useMemo(
117
- () => ({ icon, id: "ascii", label: "ASCII", onClick: toggle, pressed }),
118
- [icon, pressed, toggle],
119
- ),
120
- );
121
- ```
122
-
123
- Memoized `buttonProps` forwards `ref`, `aria-expanded`, and `onMouseDown` to
124
- popup triggers. Both toolbars place Refresh last; it also remains in View.
125
-
126
- Windows with an `appId` reserve the toolbar and offer route-history Back.
127
- With `historyBack={false}`, the row appears when actions register, then stays.
128
-
129
- ## Icons
130
-
131
- Icons are components, from any icon set. `MenuItem`, `StartMenu` items, and the
132
- chrome take a `WindowingIcon`: a component that accepts `WindowingIconProps`
133
- (`aria-hidden`, `className`, `focusable`, and `size`), as Phosphor and Lucide
134
- icons do. A menu item renders its icon at 16 pixels:
135
-
136
- ```tsx
137
- import { NotePencilIcon } from "@phosphor-icons/react";
138
-
139
- <MenuItem icon={NotePencilIcon} label="Notes" onClick={openNotes} />;
140
- ```
141
-
142
- Toolbar actions take a rendered `icon` element instead, as shown above.
143
-
144
- The chrome draws three icons of its own, from Phosphor: the toolbar's Back
145
- caret and the title bar menu's Move Forward and Move Backward arrows.
146
- `WindowingIconsProvider` replaces them for the chrome inside it. An icon it
147
- leaves out keeps the one from the nearest provider above, or the default:
148
-
149
- ```tsx
150
- import { ArrowDown, ArrowUp, ChevronLeft } from "lucide-react";
151
-
152
- <WindowingIconsProvider
153
- icons={{ back: ChevronLeft, moveBackward: ArrowDown, moveForward: ArrowUp }}
154
- >
155
- <Desktop />
156
- </WindowingIconsProvider>;
157
- ```
158
-
159
- ## Start menu
160
-
161
- `StartMenu` is a taskbar's start button: place it at the bar's leading edge,
162
- give it an `icon` to show (a logo or an icon element), and the menu opens above
163
- the button's top-left corner. Its `items` each take an `id`, `label`, optional
164
- `icon` and `disabled`, and `onSelect`, which runs after the menu closes and
165
- receives where the menu opened, for placing a new window near it:
166
-
167
- ```tsx
168
- <StartMenu
169
- icon={<Logo />}
170
- items={[
171
- {
172
- icon: NotePencilIcon,
173
- id: "notes",
174
- label: "Notes",
175
- onSelect: ({ x }) => create("Notes", x, 80, NotesApp),
176
- },
177
- ]}
178
- />
179
- ```
180
-
181
- The button is named "Menu" unless `label` says otherwise, and announces its
182
- menu with `aria-haspopup` and `aria-expanded`. By default it is a square,
183
- borderless control the height of the bar's controls, lit while hovered,
184
- focused, or open (`StartMenu.css`). A `className` replaces that styling, so a
185
- host's own button styles apply alone. A menu that needs more than a list passes
186
- `renderMenu`, which renders the open menu itself and receives its `position`
187
- and a `close` callback. Tearleads' footer does this in
188
- `packages/app/src/shell/pane/footer/PaneFooter.tsx`.
189
-
190
- ## Launching mini-apps
191
-
192
- A launcher application is a set of mini-apps, defined once and shown either in
193
- windows on a desktop or one at a time in the routed shell. A
194
- `LauncherDefinition` lists the apps by id, the order the launchers show them in,
195
- and the app the routed shell shows at the root route:
196
-
197
- ```tsx
198
- import type { LauncherDefinition } from "@tearleads/windowing";
199
-
200
- const LAUNCHER: LauncherDefinition<"notes" | "contacts"> = {
201
- apps: {
202
- contacts: {
203
- createComponent: () => ContactsApp,
204
- icon: AddressBookIcon,
205
- title: "Contacts",
206
- },
207
- notes: {
208
- createComponent: () => NotesApp,
209
- icon: NoteIcon,
210
- initialShowSidebar: false,
211
- title: "Notes",
212
- },
213
- },
214
- defaultWindowAppId: "notes",
215
- homeAppId: "notes",
216
- order: ["notes", "contacts"],
217
- };
218
- ```
219
-
220
- `LauncherNavigationProvider` takes the definition and a `NavigationMode`, and
221
- goes inside a `WindowStateProvider`. In `windowed` mode
222
- `useLauncherNavigationActions().openMiniApp({ appId })` opens the app's window,
223
- or raises the one already open; in `routed` mode it pushes the app's route,
224
- `/app/<app id>/…`, onto browser history, and Back and Forward walk it. Render
225
- each window with `MiniAppWindow`, whose `AppBoundary` slot wraps the app (for
226
- example in an error boundary).
227
-
228
- Optional `defaultWindowAppId` opens on entering an empty windowed desktop,
229
- including mount. Minimized windows count as open. Closing the last window
230
- leaves it empty until the next mode entry. The provider's `defaultWindowEnabled`
231
- defers that entry while false (e.g. hidden workspaces). Hiding and showing an
232
- already initialized desktop preserves it, even if empty. Omit the app id to
233
- manage startup yourself; `homeAppId` only sets the routed home.
234
-
235
- A mini-app reads and sets its own route with `useMiniAppRouteSegments(appId)`,
236
- or `useMiniAppRouteState` for a parsed route: the browser route in the routed
237
- shell, its window's own route and Back stack in a window. It registers its
238
- sidebar and toolbar actions with the window hooks, and both shells show them.
239
-
240
- `useNavigationMode` picks the mode: the user's choice from
241
- `NavigationModeOverrideProvider` (which persists it under a `storageKey`)
242
- first, while that choice suits the screen; then a host's `forcedMode`; then
243
- `preferredMode`, which defaults to `routed`.
244
- `NavigationModeSwitch`, for a taskbar's corner, records that choice: given the
245
- layout showing it, it offers the other ("Switch to iPad / mobile layout"). Windowed
246
- applies only where windows suit the screen: at least 1024px wide, with a fine
247
- pointer, and not an iPad. Pass the mode to
248
- `useNavigationModeDocumentAttribute`, which stamps
249
- `<html data-navigation-mode>`; the routed touch sizes key off it (see
250
- [Styles](#styles)), and `useRoutedLayoutActive` reads it back.
251
-
252
- ## Desktop icons
253
-
254
- `DesktopIcons` shows launcher apps as icons on the windowed desktop, beneath
255
- its windows. Render it inside `LauncherNavigationProvider`, as the first child
256
- of the positioned surface the windows lay out on, and name the apps it shows:
257
-
258
- ```tsx
259
- const storage = createOpfsDesktopStateStorage({ fileName: "desktop.json" });
260
-
261
- <div className="desktop-surface">
262
- <DesktopIcons appIds={["notes", "contacts"]} storage={storage} />
263
- {windows.map((entry) => (
264
- <MiniAppWindow key={entry.id} windowId={entry.id} />
265
- ))}
266
- </div>;
267
- ```
268
-
269
- The icons are options of a listbox named "Desktop" (`label` renames it). A
270
- press selects an icon and a drag moves it; double-click or Enter opens its app
271
- with `openMiniApp`, or with `onOpen` when given; arrow keys, Home, and End move
272
- the selection. Right-click or the context-menu key offers Open, then any items
273
- `menuItems(appId)` returns. Icons without a saved position fill the free cells
274
- of a grid from the top-left corner, down then across.
275
-
276
- Positions persist through a `DesktopStateStorage` adapter, which reads and
277
- writes one JSON string, so the host chooses where it lives:
278
- `createOpfsDesktopStateStorage` keeps a file in the origin private file system,
279
- `createMemoryDesktopStateStorage` keeps it in memory (the default), and a host
280
- can wrap its own store, as Tearleads wraps each identity's encrypted blob store
281
- in `packages/app/src/shell/pane/shell/usePaneDesktopStateStorage.ts`. Keep the
282
- adapter stable: a new adapter reloads the layout from what it holds. Moves made
283
- before the load finishes win and are saved with the stored layout; when the
284
- read fails, moves stay in memory and nothing is written.
285
-
286
- ## Routed shell
287
-
288
- `RoutedPane` is the routed shell, the iPad / phone layout: one mini-app at a
289
- time, chosen by the route, under an app bar with Back, Forward, the app's
290
- sidebar toggle, its title, and its toolbar actions, above a taskbar. Below 760px
291
- (`ROUTED_TABLET_BREAKPOINT_PX`) it is a phone layout whose launcher is a bottom
292
- sheet of app tiles; at or above it, a tablet layout whose launcher is a left
293
- rail or, at the user's choice, the same sheet. Mini-apps put their actions in
294
- the toolbar: the routed shell has no menu bar.
295
-
296
- ```tsx
297
- <WindowStateProvider>
298
- <LauncherNavigationProvider definition={LAUNCHER} mode="routed">
299
- <RoutedPane
300
- AppBoundary={AppErrorBoundary}
301
- menuIcon={<Logo />}
302
- taskbarTray={<ModeSwitch />}
303
- />
304
- </LauncherNavigationProvider>
305
- </WindowStateProvider>
306
- ```
307
-
308
- The host fills its chrome: `menuIcon` is the taskbar's centered launcher
309
- button, `taskbarTray` its end-aligned tray, `contentTop` rides above the active
310
- app, and `renderAboveTaskbar` draws a strip above the taskbar, told whether the
311
- phone's software keyboard is open. `appIds` narrows the apps the launcher
312
- offers, such as to those the session may see, and
313
- `subscribeKeyboardVisibility` reports a native keyboard a WebView hides.
314
- Overlays that should fill the content pane rather than the screen portal into
315
- `useRoutedPaneOverlayHost().host`. The shell sizes to the box its host gives
316
- `.routed-pane`, as a grid item or a block with a height. Tearleads dresses it in
317
- `packages/app/src/shell/layout/routed/AppRoutedPane.tsx`.
318
-
319
- ## Themes
320
-
321
- A host offers its own color themes. `ThemeProvider` takes them as a list of
322
- `{ id, label, scheme }`, the scheme `light` or `dark`, and stamps the active one
323
- as `<html data-theme>` and `<html data-theme-scheme>`. The host styles each
324
- theme with a block of the design tokens (see [Styles](#styles)):
325
-
326
- ```tsx
327
- const THEMES: readonly ThemeDefinition<"paper" | "ink">[] = [
328
- { id: "paper", label: "Paper", scheme: "light" },
329
- { id: "ink", label: "Ink", scheme: "dark" },
330
- ];
331
-
332
- <ThemeProvider
333
- defaultTheme={{ dark: "ink", light: "paper" }}
334
- storageKey="notes.theme"
335
- themes={THEMES}
336
- >
337
- <Desktop />
338
- <ThemeSwitch />
339
- </ThemeProvider>;
340
- ```
341
-
342
- ```css
343
- :root[data-theme="ink"] {
344
- --color-dark: #e5e5e5;
345
- --color-light: #161616;
346
- }
347
- ```
348
-
349
- `defaultTheme`, the theme until the user picks one, is an id or an id per OS
350
- color scheme, followed live. The choice persists under `storageKey`; a stored
351
- id the host no longer offers counts as none, and a default it does not offer
352
- falls back to its first theme. Define the list once, outside render.
353
-
354
- `ThemeSwitch`, for a taskbar's corner, moves to the next theme in order,
355
- wrapping, and names it ("Switch to Ink theme"). It renders nothing outside a
356
- provider or for a single theme. It draws a half-filled square unless given an
357
- `icon`, and is styled as `NavigationModeSwitch` unless given a `className`.
358
- `useTheme` reads the active and next themes and the list, and sets a theme by
359
- id; `useOptionalTheme` returns `null` outside a provider.
360
-
361
- Mount one provider above everything themed. It stamps the attributes before
362
- the browser paints and removes them on unmount; under a dark scheme,
363
- `tokens.css` sets `color-scheme: dark`. Tearleads sets its themes per host
364
- profile in `packages/app/src/host/AppHostConfig.ts`.
365
-
366
- ## Wallpapers and Display Properties
367
-
368
- A host offers its own desktop wallpapers. A `WallpaperDefinition` is
369
- `{ id, label, tile?, base?, ink? }`: `tile` is one cell of a repeating
370
- pattern, as SVG markup with its `width` and `height` in CSS pixels. The tile's
371
- SVG is a mask rather than a picture: opaque shapes paint the ink, translucent
372
- ones (`fill-opacity`) a share of it, and the base shows elsewhere. Unless a
373
- wallpaper names its colors, they come from the theme, resolved on the
374
- wallpaper's own element: the `--desktop-wallpaper-base` and
375
- `--desktop-wallpaper-ink` tokens where a host sets them, else the desk color
376
- (`--desktop-background`, then `--color-light`) under a faint wash of
377
- `--color-dark`. So one tile suits every theme.
378
- A wallpaper without a tile is its base alone.
379
-
380
- The package ships quiet tessellations to choose from: `BLOCKS_WALLPAPER`,
381
- `HONEYCOMB_WALLPAPER`, `TRIANGLES_WALLPAPER`, `HARLEQUIN_WALLPAPER`,
382
- `CHEVRON_WALLPAPER`, and `PLAIN_WALLPAPER` (no pattern). List them with the
383
- host's own in a `WallpaperProvider`, and render `DesktopWallpaper` as the
384
- first child of the desktop surface, before `DesktopIcons`:
385
-
386
- ```tsx
387
- const BRICKS: WallpaperDefinition<"bricks"> = {
388
- id: "bricks",
389
- label: "Bricks",
390
- tile: {
391
- height: 24,
392
- svg: `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="24">…</svg>`,
393
- width: 48,
394
- },
395
- };
396
- const WALLPAPERS = [BRICKS, HONEYCOMB_WALLPAPER, PLAIN_WALLPAPER];
397
-
398
- <WallpaperProvider
399
- defaultWallpaper="bricks"
400
- storageKey="notes.wallpaper"
401
- wallpapers={WALLPAPERS}
402
- >
403
- <div style={{ position: "relative", isolation: "isolate", height: "100%" }}>
404
- <DesktopWallpaper />
405
- <DesktopIcons appIds={APP_IDS} />
406
- {windows}
407
- </div>
408
- </WallpaperProvider>;
409
- ```
410
-
411
- The wallpaper paints on a layer below everything on the surface, including
412
- content laid out in flow, so the surface must be a stacking context: give it
413
- `isolation: isolate` beside its `position`. The wallpaper takes no pointer
414
- input, so a right-click on it reaches the surface, where a host opens its
415
- desktop menu. The choice persists under
416
- `storageKey` like a theme's; `useWallpaper` and `useOptionalWallpaper` read
417
- and set it. `DesktopWallpaper` paints its `wallpaper` prop instead when given
418
- one, and nothing without a provider.
419
-
420
- `DisplayProperties` is the content of a host's Display Properties mini-app: a
421
- Background section listing the provider's wallpapers as previews, and a Theme
422
- section listing the theme provider's themes. Each choice applies at once; a
423
- section whose provider is missing, or a theme list of one, is left out. Both
424
- Tearleads and a2f0.net open it from their desktop's context menu.
425
-
426
- ## Styles
427
-
428
- Each component imports its own stylesheet, so a bundler that handles CSS imports
429
- picks them up. Stylesheets are also exported by path (for example
430
- `@tearleads/windowing/window/WindowTitleBar.css`) for surfaces that reuse the
431
- chrome's look without rendering a window.
432
-
433
- The stylesheets read design tokens (colors, spacing, radii, shadows, and the
434
- `--window-bar-*` and `--tearleads-window-titlebar-*` chrome tokens). The package
435
- entry imports `tokens.css`, which defines every one of them under
436
- `:where(:root)`, so a page that defines none still renders a complete light
437
- window. That rule has zero specificity: any `:root` rule, theme, or scoped block
438
- the host writes overrides it. Tearleads overrides them with its own themes in
439
- `packages/ui/src/styles.css` and `packages/app/src/shell/layout/AppChrome.css`.
440
- The routed shell also reads the screen's safe areas (`--safe-area-*`) and, under
441
- `:root[data-navigation-mode="routed"]`, a 44px `--control-height` and 24px
442
- `--control-icon-size`, which `tokens.css` defines the same way.
443
-
444
- Several defaults derive from `--color-dark`, the foreground: the window edge
445
- (`--border-strong-color`), the hover and selection chip (`--emphasis-surface`
446
- and `--emphasis-text`), and `--color-hairline`. A dark theme that sets only the
447
- `--color-*` primitives gets near-white edges and chips, so set these too, as
448
- Tearleads' dark theme does.
449
-
450
- The window, menus, and routed shell draw thin scrollbars in `--scrollbar-thumb`
451
- over `--scrollbar-track`. `tokens.css` leaves both unset, so the thumb falls
452
- back to `--color-dark` at 32%, mixed on each surface so it follows the theme
453
- there, including a scoped one, and the track to transparent. They use the
454
- standard `scrollbar-width` and
455
- `scrollbar-color` properties, which Firefox, Chromium 121, and Safari 26.2
456
- read; older Safari keeps its own scrollbars. Content in a window or the shell
457
- scrolls the same way: `scrollbar-color` inherits from the surface, and
458
- `scrollbar-width` is set on every element in it. Both rules have zero
459
- specificity, so any host rule wins.
460
-
461
- The window paints its background, behind its body and sidebar, with
462
- `--window-background`. `tokens.css` leaves it unset, so it falls back to
463
- `--color-light` wherever that is set, including a scoped theme. Content sets
464
- its own window's background with `useWindowBackground`, while it is mounted;
465
- `undefined` keeps the default. A document viewer can use it to set its page
466
- apart from the window around it:
467
-
468
- ```tsx
469
- useWindowBackground(`color-mix(in srgb, ${foreground} 10%, ${page})`);
470
- ```
471
-
472
- The window rounds its corners but does not clip its content, since its resize
473
- handles and menus reach past its edges. While no visible status bar sits below
474
- it, the window body rounds its own bottom corners to the window's inner radius
475
- and clips its content there, so content painted edge to edge stays inside the
476
- border.
477
-
478
- Windows and menus lay out `border-box`, the box model their sizes assume. Since
479
- `box-sizing` does not inherit, a zero-specificity rule sets it on the window or
480
- menu and everything inside, including window content; any host rule overrides
481
- it.
482
-
483
- ## Publishing
484
-
485
- Inside this workspace the package exports its TypeScript source. The npm
486
- package is built separately, into `dist/`, with its own generated manifest:
487
-
488
- ```sh
489
- bun run --cwd packages/windowing package # build dist/
490
- bun run --cwd packages/windowing package:smoke # pack, install, render, typecheck, and bundle outside the workspace
491
- ```
492
-
493
- The built package is ES modules with declarations and source maps, plus every
494
- stylesheet. React and react-dom are peer dependencies from 19.2, the first
495
- release with `useEffectEvent`; Phosphor icons is its one dependency. The
496
- stylesheets and the entry module (which imports `tokens.css`) are declared side
497
- effects, so bundlers that trust `sideEffects` keep the token defaults.
498
- `src/publishedPackage.test.ts` checks the built manifest and that no module
499
- reaches outside the package, so a new workspace import fails the package's tests
500
- rather than the publish. The declarations drop the stylesheet imports tsc keeps
501
- in them, which a consumer's typecheck could not resolve. The smoke script
502
- installs the lowest React the peer range admits, typechecks against the
503
- declarations with TypeScript's defaults, and bundles a named import with webpack.
504
-
505
- Merging to `main` publishes. When `packages/windowing` changes there,
506
- `.github/workflows/windowing-publish.yml` publishes the version in
507
- `package.json` if it is a stable `x.y.z` newer than npm's `latest`; a merge that
508
- leaves the version alone, a re-run, or a run that finishes after a newer release
509
- succeeds without publishing, as decided by `agent-tool release plan`.
510
- The workflow authenticates with
511
- [npm trusted publishing](https://docs.npmjs.com/trusted-publishers): npm accepts
512
- the job's GitHub OIDC token instead of an npm token, and attaches provenance to
513
- each version. On npmjs.com the package's trusted publisher names the `a2f0`
514
- owner, the `tearleads` repository, the `windowing-publish.yml` workflow, and
515
- the `npm` environment, which the repository restricts to `main`. Renaming the
516
- workflow or the environment breaks publishing until that setting matches.
517
-
518
- To publish by hand instead, run from the repository root with an account that
519
- owns the `@tearleads` npm scope:
520
-
521
- ```sh
522
- npm login --registry https://registry.npmjs.org
523
- bun run publish:npm:dry-run windowing
524
- bun run publish:npm windowing
525
- ```
526
-
527
- Windowing has no workspace dependencies, and its React peers and Phosphor
528
- dependency already exist on npm, so it publishes on its own.
529
- `scripts/release/publishNpmPackage.sh` publishes each npm package by its
530
- directory name; `bun run --cwd packages/windowing publish:npm` runs it for
531
- windowing, and the workflow runs it too.
532
-
533
- The command rebuilds into a fresh temporary directory, publishes its generated
534
- consumer manifest with public access to `https://registry.npmjs.org`, and
535
- removes the directory on success or failure. A temporary `.npmrc` overrides any
536
- scope-specific registry without changing your npm configuration. A dry run
537
- builds and previews the same package without uploading. It accepts
538
- `--dry-run`, `--tag <tag>` (default `latest`), and `--otp <code>`; for example:
539
-
540
- ```sh
541
- bun run publish:npm windowing --dry-run --tag next
542
- bun run publish:npm windowing --tag next --otp 123456
543
- ```
544
-
545
- Run `package:smoke` separately before a release to verify the packed package in
546
- an external consumer. It needs the network to install the consumer dependencies.
547
-
548
- `ship-pr` bumps changed workspace packages before review and merge; the generated
549
- manifest copies `version` from `package.json`. For a release outside that flow,
550
- bump the version yourself before publishing. The manifest names this repository,
551
- which npm requires of a version with provenance, and declares
552
- `"license": "UNLICENSED"`.
56
+ ## Guides
57
+
58
+ - [Windows and chrome](./docs/windows.md)
59
+ - [Geometry and input](./docs/windows.md#geometry-and-input)
60
+ - [Slots](./docs/windows.md#slots)
61
+ - [Toolbar](./docs/windows.md#toolbar)
62
+ - [Icons](./docs/windows.md#icons)
63
+ - [Start menu and launcher](./docs/launcher.md)
64
+ - [Start menu](./docs/launcher.md#start-menu)
65
+ - [Launching mini-apps](./docs/launcher.md#launching-mini-apps)
66
+ - [Desktop icons](./docs/launcher.md#desktop-icons)
67
+ - [Routed shell](./docs/launcher.md#routed-shell)
68
+ - [Themes, wallpapers, and styles](./docs/appearance.md)
69
+ - [Themes](./docs/appearance.md#themes)
70
+ - [Wallpapers and Display Properties](./docs/appearance.md#wallpapers-and-display-properties)
71
+ - [Styles](./docs/appearance.md#styles)
72
+ - [Publishing](./docs/publishing.md)
553
73
 
554
74
  ## Dependency compatibility
555
75
 
@@ -0,0 +1,167 @@
1
+ # Themes, Wallpapers, And Styles
2
+
3
+ Part of the [@tearleads/windowing](../README.md).
4
+
5
+ ## Themes
6
+
7
+ A host offers its own color themes. `ThemeProvider` takes them as a list of
8
+ `{ id, label, scheme }`, the scheme `light` or `dark`, and stamps the active one
9
+ as `<html data-theme>` and `<html data-theme-scheme>`. The host styles each
10
+ theme with a block of the design tokens (see [Styles](#styles)):
11
+
12
+ ```tsx
13
+ const THEMES: readonly ThemeDefinition<"paper" | "ink">[] = [
14
+ { id: "paper", label: "Paper", scheme: "light" },
15
+ { id: "ink", label: "Ink", scheme: "dark" },
16
+ ];
17
+
18
+ <ThemeProvider
19
+ defaultTheme={{ dark: "ink", light: "paper" }}
20
+ storageKey="notes.theme"
21
+ themes={THEMES}
22
+ >
23
+ <Desktop />
24
+ <ThemeSwitch />
25
+ </ThemeProvider>;
26
+ ```
27
+
28
+ ```css
29
+ :root[data-theme="ink"] {
30
+ --color-dark: #e5e5e5;
31
+ --color-light: #161616;
32
+ }
33
+ ```
34
+
35
+ `defaultTheme`, the theme until the user picks one, is an id or an id per OS
36
+ color scheme, followed live. The choice persists under `storageKey`; a stored
37
+ id the host no longer offers counts as none, and a default it does not offer
38
+ falls back to its first theme. Define the list once, outside render.
39
+
40
+ `ThemeSwitch`, for a taskbar's corner, moves to the next theme in order,
41
+ wrapping, and names it ("Switch to Ink theme"). It renders nothing outside a
42
+ provider or for a single theme. It draws a half-filled square unless given an
43
+ `icon`, and is styled as `NavigationModeSwitch` unless given a `className`.
44
+ `useTheme` reads the active and next themes and the list, and sets a theme by
45
+ id; `useOptionalTheme` returns `null` outside a provider.
46
+
47
+ Mount one provider above everything themed. It stamps the attributes before
48
+ the browser paints and removes them on unmount; under a dark scheme,
49
+ `tokens.css` sets `color-scheme: dark`. Tearleads sets its themes per host
50
+ profile in `packages/app/src/host/AppHostConfig.ts`.
51
+
52
+ ## Wallpapers and Display Properties
53
+
54
+ A host offers its own desktop wallpapers. A `WallpaperDefinition` is
55
+ `{ id, label, tile?, base?, ink? }`: `tile` is one cell of a repeating
56
+ pattern, as SVG markup with its `width` and `height` in CSS pixels. The tile's
57
+ SVG is a mask rather than a picture: opaque shapes paint the ink, translucent
58
+ ones (`fill-opacity`) a share of it, and the base shows elsewhere. Unless a
59
+ wallpaper names its colors, they come from the theme, resolved on the
60
+ wallpaper's own element: the `--desktop-wallpaper-base` and
61
+ `--desktop-wallpaper-ink` tokens where a host sets them, else the desk color
62
+ (`--desktop-background`, then `--color-light`) under a faint wash of
63
+ `--color-dark`. So one tile suits every theme.
64
+ A wallpaper without a tile is its base alone.
65
+
66
+ The package ships quiet tessellations to choose from: `BLOCKS_WALLPAPER`,
67
+ `HONEYCOMB_WALLPAPER`, `TRIANGLES_WALLPAPER`, `HARLEQUIN_WALLPAPER`,
68
+ `CHEVRON_WALLPAPER`, and `PLAIN_WALLPAPER` (no pattern). List them with the
69
+ host's own in a `WallpaperProvider`, and render `DesktopWallpaper` as the
70
+ first child of the desktop surface, before `DesktopIcons`:
71
+
72
+ ```tsx
73
+ const BRICKS: WallpaperDefinition<"bricks"> = {
74
+ id: "bricks",
75
+ label: "Bricks",
76
+ tile: {
77
+ height: 24,
78
+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="24">…</svg>`,
79
+ width: 48,
80
+ },
81
+ };
82
+ const WALLPAPERS = [BRICKS, HONEYCOMB_WALLPAPER, PLAIN_WALLPAPER];
83
+
84
+ <WallpaperProvider
85
+ defaultWallpaper="bricks"
86
+ storageKey="notes.wallpaper"
87
+ wallpapers={WALLPAPERS}
88
+ >
89
+ <div style={{ position: "relative", isolation: "isolate", height: "100%" }}>
90
+ <DesktopWallpaper />
91
+ <DesktopIcons appIds={APP_IDS} />
92
+ {windows}
93
+ </div>
94
+ </WallpaperProvider>;
95
+ ```
96
+
97
+ The wallpaper paints on a layer below everything on the surface, including
98
+ content laid out in flow, so the surface must be a stacking context: give it
99
+ `isolation: isolate` beside its `position`. The wallpaper takes no pointer
100
+ input, so a right-click on it reaches the surface, where a host opens its
101
+ desktop menu. The choice persists under
102
+ `storageKey` like a theme's; `useWallpaper` and `useOptionalWallpaper` read
103
+ and set it. `DesktopWallpaper` paints its `wallpaper` prop instead when given
104
+ one, and nothing without a provider.
105
+
106
+ `DisplayProperties` is the content of a host's Display Properties mini-app: a
107
+ Background section listing the provider's wallpapers as previews, and a Theme
108
+ section listing the theme provider's themes. Each choice applies at once; a
109
+ section whose provider is missing, or a theme list of one, is left out. Both
110
+ Tearleads and a2f0.net open it from their desktop's context menu.
111
+
112
+ ## Styles
113
+
114
+ Each component imports its own stylesheet, so a bundler that handles CSS imports
115
+ picks them up. Stylesheets are also exported by path (for example
116
+ `@tearleads/windowing/window/WindowTitleBar.css`) for surfaces that reuse the
117
+ chrome's look without rendering a window.
118
+
119
+ The stylesheets read design tokens (colors, spacing, radii, shadows, and the
120
+ `--window-bar-*` and `--tearleads-window-titlebar-*` chrome tokens). The package
121
+ entry imports `tokens.css`, which defines every one of them under
122
+ `:where(:root)`, so a page that defines none still renders a complete light
123
+ window. That rule has zero specificity: any `:root` rule, theme, or scoped block
124
+ the host writes overrides it. Tearleads overrides them with its own themes in
125
+ `packages/ui/src/styles.css` and `packages/app/src/shell/layout/AppChrome.css`.
126
+ The routed shell also reads the screen's safe areas (`--safe-area-*`) and, under
127
+ `:root[data-navigation-mode="routed"]`, a 44px `--control-height` and 24px
128
+ `--control-icon-size`, which `tokens.css` defines the same way.
129
+
130
+ Several defaults derive from `--color-dark`, the foreground: the window edge
131
+ (`--border-strong-color`), the hover and selection chip (`--emphasis-surface`
132
+ and `--emphasis-text`), and `--color-hairline`. A dark theme that sets only the
133
+ `--color-*` primitives gets near-white edges and chips, so set these too, as
134
+ Tearleads' dark theme does.
135
+
136
+ The window, menus, and routed shell draw thin scrollbars in `--scrollbar-thumb`
137
+ over `--scrollbar-track`. `tokens.css` leaves both unset, so the thumb falls
138
+ back to `--color-dark` at 32%, mixed on each surface so it follows the theme
139
+ there, including a scoped one, and the track to transparent. They use the
140
+ standard `scrollbar-width` and
141
+ `scrollbar-color` properties, which Firefox, Chromium 121, and Safari 26.2
142
+ read; older Safari keeps its own scrollbars. Content in a window or the shell
143
+ scrolls the same way: `scrollbar-color` inherits from the surface, and
144
+ `scrollbar-width` is set on every element in it. Both rules have zero
145
+ specificity, so any host rule wins.
146
+
147
+ The window paints its background, behind its body and sidebar, with
148
+ `--window-background`. `tokens.css` leaves it unset, so it falls back to
149
+ `--color-light` wherever that is set, including a scoped theme. Content sets
150
+ its own window's background with `useWindowBackground`, while it is mounted;
151
+ `undefined` keeps the default. A document viewer can use it to set its page
152
+ apart from the window around it:
153
+
154
+ ```tsx
155
+ useWindowBackground(`color-mix(in srgb, ${foreground} 10%, ${page})`);
156
+ ```
157
+
158
+ The window rounds its corners but does not clip its content, since its resize
159
+ handles and menus reach past its edges. While no visible status bar sits below
160
+ it, the window body rounds its own bottom corners to the window's inner radius
161
+ and clips its content there, so content painted edge to edge stays inside the
162
+ border.
163
+
164
+ Windows and menus lay out `border-box`, the box model their sizes assume. Since
165
+ `box-sizing` does not inherit, a zero-specificity rule sets it on the window or
166
+ menu and everything inside, including window content; any host rule overrides
167
+ it.
@@ -0,0 +1,163 @@
1
+ # Start Menu And Launcher
2
+
3
+ Part of the [@tearleads/windowing](../README.md).
4
+
5
+ ## Start menu
6
+
7
+ `StartMenu` is a taskbar's start button: place it at the bar's leading edge,
8
+ give it an `icon` to show (a logo or an icon element), and the menu opens above
9
+ the button's top-left corner. Its `items` each take an `id`, `label`, optional
10
+ `icon` and `disabled`, and `onSelect`, which runs after the menu closes and
11
+ receives where the menu opened, for placing a new window near it:
12
+
13
+ ```tsx
14
+ <StartMenu
15
+ icon={<Logo />}
16
+ items={[
17
+ {
18
+ icon: NotePencilIcon,
19
+ id: "notes",
20
+ label: "Notes",
21
+ onSelect: ({ x }) => create("Notes", x, 80, NotesApp),
22
+ },
23
+ ]}
24
+ />
25
+ ```
26
+
27
+ The button is named "Menu" unless `label` says otherwise, and announces its
28
+ menu with `aria-haspopup` and `aria-expanded`. By default it is a square,
29
+ borderless control the height of the bar's controls, lit while hovered,
30
+ focused, or open (`StartMenu.css`). A `className` replaces that styling, so a
31
+ host's own button styles apply alone. A menu that needs more than a list passes
32
+ `renderMenu`, which renders the open menu itself and receives its `position`
33
+ and a `close` callback. Tearleads' footer does this in
34
+ `packages/app/src/shell/pane/footer/PaneFooter.tsx`.
35
+
36
+ ## Launching mini-apps
37
+
38
+ A launcher application is a set of mini-apps, defined once and shown either in
39
+ windows on a desktop or one at a time in the routed shell. A
40
+ `LauncherDefinition` lists the apps by id, the order the launchers show them in,
41
+ and the app the routed shell shows at the root route:
42
+
43
+ ```tsx
44
+ import type { LauncherDefinition } from "@tearleads/windowing";
45
+
46
+ const LAUNCHER: LauncherDefinition<"notes" | "contacts"> = {
47
+ apps: {
48
+ contacts: {
49
+ createComponent: () => ContactsApp,
50
+ icon: AddressBookIcon,
51
+ title: "Contacts",
52
+ },
53
+ notes: {
54
+ createComponent: () => NotesApp,
55
+ icon: NoteIcon,
56
+ initialShowSidebar: false,
57
+ title: "Notes",
58
+ },
59
+ },
60
+ defaultWindowAppId: "notes",
61
+ homeAppId: "notes",
62
+ order: ["notes", "contacts"],
63
+ };
64
+ ```
65
+
66
+ `LauncherNavigationProvider` takes the definition and a `NavigationMode`, and
67
+ goes inside a `WindowStateProvider`. In `windowed` mode
68
+ `useLauncherNavigationActions().openMiniApp({ appId })` opens the app's window,
69
+ or raises the one already open; in `routed` mode it pushes the app's route,
70
+ `/app/<app id>/…`, onto browser history, and Back and Forward walk it. Render
71
+ each window with `MiniAppWindow`, whose `AppBoundary` slot wraps the app (for
72
+ example in an error boundary).
73
+
74
+ Optional `defaultWindowAppId` opens on entering an empty windowed desktop,
75
+ including mount. Minimized windows count as open. Closing the last window
76
+ leaves it empty until the next mode entry. The provider's `defaultWindowEnabled`
77
+ defers that entry while false (e.g. hidden workspaces). Hiding and showing an
78
+ already initialized desktop preserves it, even if empty. Omit the app id to
79
+ manage startup yourself; `homeAppId` only sets the routed home.
80
+
81
+ A mini-app reads and sets its own route with `useMiniAppRouteSegments(appId)`,
82
+ or `useMiniAppRouteState` for a parsed route: the browser route in the routed
83
+ shell, its window's own route and Back stack in a window. It registers its
84
+ sidebar and toolbar actions with the window hooks, and both shells show them.
85
+
86
+ `useNavigationMode` picks the mode: the user's choice from
87
+ `NavigationModeOverrideProvider` (which persists it under a `storageKey`)
88
+ first, while that choice suits the screen; then a host's `forcedMode`; then
89
+ `preferredMode`, which defaults to `routed`.
90
+ `NavigationModeSwitch`, for a taskbar's corner, records that choice: given the
91
+ layout showing it, it offers the other ("Switch to iPad / mobile layout"). Windowed
92
+ applies only where windows suit the screen: at least 1024px wide, with a fine
93
+ pointer, and not an iPad. Pass the mode to
94
+ `useNavigationModeDocumentAttribute`, which stamps
95
+ `<html data-navigation-mode>`; the routed touch sizes key off it (see
96
+ [Styles](./appearance.md#styles)), and `useRoutedLayoutActive` reads it back.
97
+
98
+ ## Desktop icons
99
+
100
+ `DesktopIcons` shows launcher apps as icons on the windowed desktop, beneath
101
+ its windows. Render it inside `LauncherNavigationProvider`, as the first child
102
+ of the positioned surface the windows lay out on, and name the apps it shows:
103
+
104
+ ```tsx
105
+ const storage = createOpfsDesktopStateStorage({ fileName: "desktop.json" });
106
+
107
+ <div className="desktop-surface">
108
+ <DesktopIcons appIds={["notes", "contacts"]} storage={storage} />
109
+ {windows.map((entry) => (
110
+ <MiniAppWindow key={entry.id} windowId={entry.id} />
111
+ ))}
112
+ </div>;
113
+ ```
114
+
115
+ The icons are options of a listbox named "Desktop" (`label` renames it). A
116
+ press selects an icon and a drag moves it; double-click or Enter opens its app
117
+ with `openMiniApp`, or with `onOpen` when given; arrow keys, Home, and End move
118
+ the selection. Right-click or the context-menu key offers Open, then any items
119
+ `menuItems(appId)` returns. Icons without a saved position fill the free cells
120
+ of a grid from the top-left corner, down then across.
121
+
122
+ Positions persist through a `DesktopStateStorage` adapter, which reads and
123
+ writes one JSON string, so the host chooses where it lives:
124
+ `createOpfsDesktopStateStorage` keeps a file in the origin private file system,
125
+ `createMemoryDesktopStateStorage` keeps it in memory (the default), and a host
126
+ can wrap its own store, as Tearleads wraps each identity's encrypted blob store
127
+ in `packages/app/src/shell/pane/shell/usePaneDesktopStateStorage.ts`. Keep the
128
+ adapter stable: a new adapter reloads the layout from what it holds. Moves made
129
+ before the load finishes win and are saved with the stored layout; when the
130
+ read fails, moves stay in memory and nothing is written.
131
+
132
+ ## Routed shell
133
+
134
+ `RoutedPane` is the routed shell, the iPad / phone layout: one mini-app at a
135
+ time, chosen by the route, under an app bar with Back, Forward, the app's
136
+ sidebar toggle, its title, and its toolbar actions, above a taskbar. Below 760px
137
+ (`ROUTED_TABLET_BREAKPOINT_PX`) it is a phone layout whose launcher is a bottom
138
+ sheet of app tiles; at or above it, a tablet layout whose launcher is a left
139
+ rail or, at the user's choice, the same sheet. Mini-apps put their actions in
140
+ the toolbar: the routed shell has no menu bar.
141
+
142
+ ```tsx
143
+ <WindowStateProvider>
144
+ <LauncherNavigationProvider definition={LAUNCHER} mode="routed">
145
+ <RoutedPane
146
+ AppBoundary={AppErrorBoundary}
147
+ menuIcon={<Logo />}
148
+ taskbarTray={<ModeSwitch />}
149
+ />
150
+ </LauncherNavigationProvider>
151
+ </WindowStateProvider>
152
+ ```
153
+
154
+ The host fills its chrome: `menuIcon` is the taskbar's centered launcher
155
+ button, `taskbarTray` its end-aligned tray, `contentTop` rides above the active
156
+ app, and `renderAboveTaskbar` draws a strip above the taskbar, told whether the
157
+ phone's software keyboard is open. `appIds` narrows the apps the launcher
158
+ offers, such as to those the session may see, and
159
+ `subscribeKeyboardVisibility` reports a native keyboard a WebView hides.
160
+ Overlays that should fill the content pane rather than the screen portal into
161
+ `useRoutedPaneOverlayHost().host`. The shell sizes to the box its host gives
162
+ `.routed-pane`, as a grid item or a block with a height. Tearleads dresses it in
163
+ `packages/app/src/shell/layout/routed/AppRoutedPane.tsx`.
@@ -0,0 +1,74 @@
1
+ # Publishing @tearleads/windowing
2
+
3
+ Part of the [@tearleads/windowing](../README.md).
4
+
5
+ ## Publishing
6
+
7
+ Inside this workspace the package exports its TypeScript source. The npm
8
+ package is built separately, into `dist/`, with its own generated manifest:
9
+
10
+ ```sh
11
+ bun run --cwd packages/windowing package # build dist/
12
+ bun run --cwd packages/windowing package:smoke # pack, install, render, typecheck, and bundle outside the workspace
13
+ ```
14
+
15
+ The built package is ES modules with declarations and source maps, plus every
16
+ stylesheet. React and react-dom are peer dependencies from 19.2, the first
17
+ release with `useEffectEvent`; Phosphor icons is its one dependency. The
18
+ stylesheets and the entry module (which imports `tokens.css`) are declared side
19
+ effects, so bundlers that trust `sideEffects` keep the token defaults.
20
+ `src/publishedPackage.test.ts` checks the built manifest and that no module
21
+ reaches outside the package, so a new workspace import fails the package's tests
22
+ rather than the publish. The declarations drop the stylesheet imports tsc keeps
23
+ in them, which a consumer's typecheck could not resolve. The smoke script
24
+ installs the lowest React the peer range admits, typechecks against the
25
+ declarations with TypeScript's defaults, and bundles a named import with webpack.
26
+
27
+ Merging to `main` publishes. When `packages/windowing` changes there,
28
+ `.github/workflows/windowing-publish.yml` publishes the version in
29
+ `package.json` if it is a stable `x.y.z` newer than npm's `latest`; a merge that
30
+ leaves the version alone, a re-run, or a run that finishes after a newer release
31
+ succeeds without publishing, as decided by `agent-tool release plan`.
32
+ The workflow authenticates with
33
+ [npm trusted publishing](https://docs.npmjs.com/trusted-publishers): npm accepts
34
+ the job's GitHub OIDC token instead of an npm token, and attaches provenance to
35
+ each version. On npmjs.com the package's trusted publisher names the `a2f0`
36
+ owner, the `tearleads` repository, the `windowing-publish.yml` workflow, and
37
+ the `npm` environment, which the repository restricts to `main`. Renaming the
38
+ workflow or the environment breaks publishing until that setting matches.
39
+
40
+ To publish by hand instead, run from the repository root with an account that
41
+ owns the `@tearleads` npm scope:
42
+
43
+ ```sh
44
+ npm login --registry https://registry.npmjs.org
45
+ bun run publish:npm:dry-run windowing
46
+ bun run publish:npm windowing
47
+ ```
48
+
49
+ Windowing has no workspace dependencies, and its React peers and Phosphor
50
+ dependency already exist on npm, so it publishes on its own.
51
+ `scripts/release/publishNpmPackage.sh` publishes each npm package by its
52
+ directory name; `bun run --cwd packages/windowing publish:npm` runs it for
53
+ windowing, and the workflow runs it too.
54
+
55
+ The command rebuilds into a fresh temporary directory, publishes its generated
56
+ consumer manifest with public access to `https://registry.npmjs.org`, and
57
+ removes the directory on success or failure. A temporary `.npmrc` overrides any
58
+ scope-specific registry without changing your npm configuration. A dry run
59
+ builds and previews the same package without uploading. It accepts
60
+ `--dry-run`, `--tag <tag>` (default `latest`), and `--otp <code>`; for example:
61
+
62
+ ```sh
63
+ bun run publish:npm windowing --dry-run --tag next
64
+ bun run publish:npm windowing --tag next --otp 123456
65
+ ```
66
+
67
+ Run `package:smoke` separately before a release to verify the packed package in
68
+ an external consumer. It needs the network to install the consumer dependencies.
69
+
70
+ `ship-pr` bumps changed workspace packages before review and merge; the generated
71
+ manifest copies `version` from `package.json`. For a release outside that flow,
72
+ bump the version yourself before publishing. The manifest names this repository,
73
+ which npm requires of a version with provenance, and declares
74
+ `"license": "UNLICENSED"`.
@@ -0,0 +1,106 @@
1
+ # Windows And Chrome
2
+
3
+ Part of the [@tearleads/windowing](../README.md).
4
+
5
+ ## Geometry and input
6
+
7
+ Windows move by their title bar and resize by any side or corner with pointer
8
+ events, so mouse, touch, and pen all work. The resize targets reach a few
9
+ pixels past the window's border, so an edge can be taken from just outside the
10
+ window, and a hovered corner lights up over the window's own rounded border.
11
+
12
+ While a gesture runs the geometry stays local to that window; when it ends, the
13
+ window commits its `position` and `size` (surface-relative) to its
14
+ `WindowEntry`. The first layout commits too, so `position` always reflects
15
+ where the window sits. Without `size` a window takes its stylesheet's default
16
+ size.
17
+
18
+ To save a layout, read `position` and `size` from `useWindowStateData()`. To
19
+ restore one, pass them back as `create` options, which take precedence over
20
+ `create`'s viewport `x`/`y`. `setGeometry(id, { position, size })` moves or
21
+ resizes a window programmatically.
22
+
23
+ Content with a natural size, such as a document page, passes it in CSS pixels
24
+ to `useWindowContentSize({ width, height })` while it is mounted. Its window
25
+ then offers **Fit to Content** in the View menu, which restores the window if
26
+ maximized and sizes it so the scroll pane's content area shows that size. The
27
+ fit measures the chrome as rendered (bars, sidebar, the pane's padding and
28
+ scrollbars) and stays within the surface. Content the surface cannot hold
29
+ scrolls. The width always leaves room for a vertical scrollbar, so the
30
+ content keeps its width even when a status message briefly takes height from
31
+ the body. Last, the window moves as far as it must to stay on the surface.
32
+ `undefined` withdraws the item.
33
+
34
+ To open a window already fitted, pass `fitToContent: true` to `create`. The
35
+ window fits once, as Fit to Content would, when its content has loaded and
36
+ reported its size. Content reports its load by calling
37
+ `useCurrentWindow()?.markContentLoaded?.()`, for example once a page has
38
+ rendered. A later call does nothing. A window that is maximized when its
39
+ content loads, as a host might open it on a narrow screen, stays maximized,
40
+ and a window on a hidden surface fits once the surface shows.
41
+
42
+ ## Slots
43
+
44
+ - **`ContentBoundary`** — `Window` renders a window's component inside this
45
+ optional wrapper, which receives the `WindowEntry`. Hosts use it to give
46
+ content app-specific context (a route provider, an error boundary) without the
47
+ window layer knowing about apps. `MiniAppWindow` fills it for launcher apps
48
+ (see [Launching mini-apps](./launcher.md#launching-mini-apps)).
49
+ - **`appId`** — an opaque string a host attaches when creating a window. The
50
+ window layer only stores and compares it; the host interprets it.
51
+
52
+ Windows register their own menu items, title-bar actions, a Back action, a
53
+ sidebar, a background, and a natural size through the `useWindow*` hooks, from
54
+ inside the window's content.
55
+
56
+ ## Toolbar
57
+
58
+ The toolbar row sits between the menu bar and the body. Content registers icon
59
+ buttons in it with `useWindowTitleBarAction`; give an action `pressed` to make
60
+ it a toggle, announced as `aria-pressed` and drawn pressed while true:
61
+
62
+ ```tsx
63
+ const icon = useMemo(() => <HashIcon aria-hidden size={18} />, []);
64
+ useWindowTitleBarAction(
65
+ useMemo(
66
+ () => ({ icon, id: "ascii", label: "ASCII", onClick: toggle, pressed }),
67
+ [icon, pressed, toggle],
68
+ ),
69
+ );
70
+ ```
71
+
72
+ Memoized `buttonProps` forwards `ref`, `aria-expanded`, and `onMouseDown` to
73
+ popup triggers. Both toolbars place Refresh last; it also remains in View.
74
+
75
+ Windows with an `appId` reserve the toolbar and offer route-history Back.
76
+ With `historyBack={false}`, the row appears when actions register, then stays.
77
+
78
+ ## Icons
79
+
80
+ Icons are components, from any icon set. `MenuItem`, `StartMenu` items, and the
81
+ chrome take a `WindowingIcon`: a component that accepts `WindowingIconProps`
82
+ (`aria-hidden`, `className`, `focusable`, and `size`), as Phosphor and Lucide
83
+ icons do. A menu item renders its icon at 16 pixels:
84
+
85
+ ```tsx
86
+ import { NotePencilIcon } from "@phosphor-icons/react";
87
+
88
+ <MenuItem icon={NotePencilIcon} label="Notes" onClick={openNotes} />;
89
+ ```
90
+
91
+ Toolbar actions take a rendered `icon` element instead, as shown above.
92
+
93
+ The chrome draws three icons of its own, from Phosphor: the toolbar's Back
94
+ caret and the title bar menu's Move Forward and Move Backward arrows.
95
+ `WindowingIconsProvider` replaces them for the chrome inside it. An icon it
96
+ leaves out keeps the one from the nearest provider above, or the default:
97
+
98
+ ```tsx
99
+ import { ArrowDown, ArrowUp, ChevronLeft } from "lucide-react";
100
+
101
+ <WindowingIconsProvider
102
+ icons={{ back: ChevronLeft, moveBackward: ArrowDown, moveForward: ArrowUp }}
103
+ >
104
+ <Desktop />
105
+ </WindowingIconsProvider>;
106
+ ```
@@ -49,17 +49,8 @@ export function useMenuKeyboard(menuRef, ready, onClose) {
49
49
  return;
50
50
  if (!menu?.contains(document.activeElement))
51
51
  return;
52
- if (event.key === "Escape") {
53
- event.preventDefault();
54
- event.stopPropagation();
55
- restoreFocus();
56
- close();
57
- return;
58
- }
59
- if (event.key === "Tab") {
60
- if (!restoreFocus())
61
- event.preventDefault();
62
- close();
52
+ if (event.key === "Escape" || event.key === "Tab") {
53
+ leaveMenu(event);
63
54
  return;
64
55
  }
65
56
  const next = nextControl(items(), document.activeElement, event.key);
@@ -69,6 +60,19 @@ export function useMenuKeyboard(menuRef, ready, onClose) {
69
60
  next.focus();
70
61
  }
71
62
  }
63
+ // Escape returns focus to the trigger; Tab moves on from it natively
64
+ // unless focus could not return there.
65
+ function leaveMenu(event) {
66
+ if (event.key === "Escape") {
67
+ event.preventDefault();
68
+ event.stopPropagation();
69
+ restoreFocus();
70
+ }
71
+ else if (!restoreFocus()) {
72
+ event.preventDefault();
73
+ }
74
+ close();
75
+ }
72
76
  function handleMouseDown(event) {
73
77
  dismissedByPointer =
74
78
  event.target instanceof Node && !menu?.contains(event.target);
@@ -1 +1 @@
1
- {"version":3,"file":"useMenuKeyboard.js","sourceRoot":"","sources":["../../../home/runner/work/tearleads/tearleads/packages/windowing/src/menu/useMenuKeyboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,SAAS,EAAE,cAAc,EAAE,MAAM,OAAO,CAAC;AAElE,SAAS,WAAW,CAClB,QAAuB,EACvB,OAAuB,EACvB,GAAW;IAEX,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5C,MAAM,KAAK,GAAG,OAAO,YAAY,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,QAAQ,GAAG,EAAE,CAAC;QACZ,KAAK,WAAW;YACd,OAAO,QAAQ,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;QACjD,KAAK,SAAS;YACZ,OAAO,QAAQ,CACb,KAAK,GAAG,CAAC;gBACP,CAAC,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;gBACrB,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CACpD,CAAC;QACJ,KAAK,MAAM;YACT,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;QACrB,KAAK,KAAK;YACR,OAAO,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACzB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IAAI,CAAC,CAAC;QAC1D,OAAO,GAAG,EAAE;YACV,QAAQ,CAAC,UAAU,EAAE,CAAC;YACtB,QAAQ,CAAC,mBAAmB,CAAC,WAAW,EAAE,eAAe,EAAE,IAAI,CAAC,CAAC;YACjE,QAAQ,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,EAAE,IAAI,CAAC,CAAC;YAC7D,IACE,CAAC,kBAAkB;gBACnB,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC;oBACpC,QAAQ,CAAC,aAAa,KAAK,QAAQ,CAAC,IAAI,CAAC,EAC3C,CAAC;gBACD,YAAY,EAAE,CAAC;YACjB,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import { type RefObject, useEffect, useEffectEvent } from \"react\";\n\nfunction nextControl(\n controls: HTMLElement[],\n focused: Element | null,\n key: string,\n) {\n if (controls.length === 0) return undefined;\n const index = focused instanceof HTMLElement ? controls.indexOf(focused) : -1;\n switch (key) {\n case \"ArrowDown\":\n return controls[(index + 1) % controls.length];\n case \"ArrowUp\":\n return controls[\n index < 0\n ? controls.length - 1\n : (index - 1 + controls.length) % controls.length\n ];\n case \"Home\":\n return controls[0];\n case \"End\":\n return controls.at(-1);\n default:\n return undefined;\n }\n}\n\nexport function useMenuKeyboard(\n menuRef: RefObject<HTMLDivElement | null>,\n ready: boolean,\n onClose: () => void,\n) {\n const close = useEffectEvent(onClose);\n\n useEffect(() => {\n const menu = menuRef.current;\n if (!ready || !menu) return;\n\n const trigger = document.activeElement;\n let dismissedByPointer = false;\n const items = () =>\n Array.from(\n menu.querySelectorAll<HTMLElement>(\n \":is(button, input[type=checkbox]):not(:disabled):not([hidden])\",\n ),\n );\n const focusFirst = () =>\n (items()[0] ?? menu).focus({ preventScroll: true });\n focusFirst();\n // Startup and sync can replace an action while its menu is open. Recover\n // focus only when that replacement dropped it onto the document body.\n const observer = new MutationObserver(() => {\n if (!dismissedByPointer && document.activeElement === document.body) {\n focusFirst();\n }\n });\n observer.observe(menu, { childList: true, subtree: true });\n\n function restoreFocus() {\n if (trigger instanceof HTMLElement && trigger.isConnected) {\n trigger.focus({ preventScroll: true });\n return document.activeElement === trigger && trigger !== document.body;\n }\n return false;\n }\n\n function handleKeyDown(event: KeyboardEvent) {\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n if (!menu?.contains(document.activeElement)) return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n restoreFocus();\n close();\n return;\n }\n if (event.key === \"Tab\") {\n if (!restoreFocus()) event.preventDefault();\n close();\n return;\n }\n const next = nextControl(items(), document.activeElement, event.key);\n if (next) {\n event.preventDefault();\n event.stopPropagation();\n next.focus();\n }\n }\n\n function handleMouseDown(event: MouseEvent) {\n dismissedByPointer =\n event.target instanceof Node && !menu?.contains(event.target);\n }\n\n document.addEventListener(\"mousedown\", handleMouseDown, true);\n document.addEventListener(\"keydown\", handleKeyDown, true);\n return () => {\n observer.disconnect();\n document.removeEventListener(\"mousedown\", handleMouseDown, true);\n document.removeEventListener(\"keydown\", handleKeyDown, true);\n if (\n !dismissedByPointer &&\n (menu.contains(document.activeElement) ||\n document.activeElement === document.body)\n ) {\n restoreFocus();\n }\n };\n }, [menuRef, ready]);\n}\n"]}
1
+ {"version":3,"file":"useMenuKeyboard.js","sourceRoot":"","sources":["../../../home/runner/work/tearleads/tearleads/packages/windowing/src/menu/useMenuKeyboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,SAAS,EAAE,cAAc,EAAE,MAAM,OAAO,CAAC;AAElE,SAAS,WAAW,CAClB,QAAuB,EACvB,OAAuB,EACvB,GAAW;IAEX,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5C,MAAM,KAAK,GAAG,OAAO,YAAY,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,C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ffect, useEffectEvent } from \"react\";\n\nfunction nextControl(\n controls: HTMLElement[],\n focused: Element | null,\n key: string,\n) {\n if (controls.length === 0) return undefined;\n const index = focused instanceof HTMLElement ? controls.indexOf(focused) : -1;\n switch (key) {\n case \"ArrowDown\":\n return controls[(index + 1) % controls.length];\n case \"ArrowUp\":\n return controls[\n index < 0\n ? controls.length - 1\n : (index - 1 + controls.length) % controls.length\n ];\n case \"Home\":\n return controls[0];\n case \"End\":\n return controls.at(-1);\n default:\n return undefined;\n }\n}\n\nexport function useMenuKeyboard(\n menuRef: RefObject<HTMLDivElement | null>,\n ready: boolean,\n onClose: () => void,\n) {\n const close = useEffectEvent(onClose);\n\n useEffect(() => {\n const menu = menuRef.current;\n if (!ready || !menu) return;\n\n const trigger = document.activeElement;\n let dismissedByPointer = false;\n const items = () =>\n Array.from(\n menu.querySelectorAll<HTMLElement>(\n \":is(button, input[type=checkbox]):not(:disabled):not([hidden])\",\n ),\n );\n const focusFirst = () =>\n (items()[0] ?? menu).focus({ preventScroll: true });\n focusFirst();\n // Startup and sync can replace an action while its menu is open. Recover\n // focus only when that replacement dropped it onto the document body.\n const observer = new MutationObserver(() => {\n if (!dismissedByPointer && document.activeElement === document.body) {\n focusFirst();\n }\n });\n observer.observe(menu, { childList: true, subtree: true });\n\n function restoreFocus() {\n if (trigger instanceof HTMLElement && trigger.isConnected) {\n trigger.focus({ preventScroll: true });\n return document.activeElement === trigger && trigger !== document.body;\n }\n return false;\n }\n\n function handleKeyDown(event: KeyboardEvent) {\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n if (!menu?.contains(document.activeElement)) return;\n if (event.key === \"Escape\" || event.key === \"Tab\") {\n leaveMenu(event);\n return;\n }\n const next = nextControl(items(), document.activeElement, event.key);\n if (next) {\n event.preventDefault();\n event.stopPropagation();\n next.focus();\n }\n }\n\n // Escape returns focus to the trigger; Tab moves on from it natively\n // unless focus could not return there.\n function leaveMenu(event: KeyboardEvent) {\n if (event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n restoreFocus();\n } else if (!restoreFocus()) {\n event.preventDefault();\n }\n close();\n }\n\n function handleMouseDown(event: MouseEvent) {\n dismissedByPointer =\n event.target instanceof Node && !menu?.contains(event.target);\n }\n\n document.addEventListener(\"mousedown\", handleMouseDown, true);\n document.addEventListener(\"keydown\", handleKeyDown, true);\n return () => {\n observer.disconnect();\n document.removeEventListener(\"mousedown\", handleMouseDown, true);\n document.removeEventListener(\"keydown\", handleKeyDown, true);\n if (\n !dismissedByPointer &&\n (menu.contains(document.activeElement) ||\n document.activeElement === document.body)\n ) {\n restoreFocus();\n }\n };\n }, [menuRef, ready]);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/windowing",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
4
4
  "description": "App-agnostic window management for React: window state, window chrome, and the menu and sidebar primitives it renders with.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {