release-2.9.0 (#1532)

* fix(macos): skip single-instance lock in Mac App Store builds (#1454)

fix(macos): skip single-instance lock in Mac App Store builds

* Fix/backend optional sharp (#1455)

Fix/backend optional sharp

* feat: issue #1218 (#1218)

https://github.com/Termix-SSH/Support/issues/1218

* feat: Add option to use saved global custom theme under Connection Defaults (#1209)

https://github.com/Termix-SSH/Support/issues/1209

* feat: Add Fleet Sharing functionality to the UI (#1228)

https://github.com/Termix-SSH/Support/issues/1228

* feat: Add a list view to the Docker management page (#1237)

https://github.com/Termix-SSH/Support/issues/1237

* feat: issue #1264 (#1264)

https://github.com/Termix-SSH/Support/issues/1264

* feat: 2FA With FortiToken (#1288)

https://github.com/Termix-SSH/Support/issues/1288

* feat: Allow to disable showing paths to folders (#1274)

https://github.com/Termix-SSH/Support/issues/1274

* feat: Sync Network Graph between Desktop and Remote Server (#1245)

https://github.com/Termix-SSH/Support/issues/1245

* feat: Version Number on offline servers (#1291)

https://github.com/Termix-SSH/Support/issues/1291

* feat: Support OrbStack Docker socket path on macOS / Fix "Docker is not installed" on mac... (#1302)

https://github.com/Termix-SSH/Support/issues/1302

* feat: Sidebar host click should focus existing tab instead of opening a new connection (#1289)

https://github.com/Termix-SSH/Support/issues/1289

* fix: Search in side bar shows overlapping hosts when grouped by tags (#1303)

https://github.com/Termix-SSH/Support/issues/1303

* fix: I can't send a file on its own. (#1304)

https://github.com/Termix-SSH/Support/issues/1304

* fix: sudo password not autofilling (#1248)

https://github.com/Termix-SSH/Support/issues/1248

* fix: node-MainThread (#1300)

https://github.com/Termix-SSH/Support/issues/1300

* fix: Tunnel authentication with shared credentials (#1295)

https://github.com/Termix-SSH/Support/issues/1295

* fix: host key updates not syncing, metrics 404 race on first connect

Host key writes never bumped updatedAt so sync never picked them up.
Also retry the first metrics fetch briefly instead of failing right away.

* chore: increment ver

* feat: add category and icon fields to plugin manifest schema

* ci(deps): bump the github-actions group with 2 updates (#1458)

Bumps the github-actions group with 2 updates: [crowdin/github-action](https://github.com/crowdin/github-action) and [actions/github-script](https://github.com/actions/github-script).


Updates `crowdin/github-action` from 2 to 3
- [Release notes](https://github.com/crowdin/github-action/releases)
- [Commits](https://github.com/crowdin/github-action/compare/v2...v3)

Updates `actions/github-script` from 7 to 9
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v9)

---
updated-dependencies:
- dependency-name: crowdin/github-action
  dependency-version: '3'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/github-script
  dependency-version: '9'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-patch-updates group with 13 updates (#1459)

Bumps the dev-patch-updates group with 13 updates:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.11.0` | `6.11.1` |
| [@codemirror/search](https://github.com/codemirror/search) | `6.7.1` | `6.7.2` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.9` | `6.43.12` |
| [@testing-library/dom](https://github.com/testing-library/dom-testing-library) | `10.4.1` | `10.4.2` |
| [@testing-library/react](https://github.com/testing-library/react-testing-library) | `16.3.2` | `16.3.3` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.5` | `14.6.7` |
| [@types/ssh2](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ssh2) | `1.15.5` | `1.15.6` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.1.0` | `6.1.1` |
| [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.1` | `3.34.3` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.4` | `0.5.7` |
| [i18next](https://github.com/i18next/i18next) | `26.4.0` | `26.4.2` |
| [prettier](https://github.com/prettier/prettier) | `3.9.6` | `3.9.8` |
| [react-i18next](https://github.com/i18next/react-i18next) | `17.0.12` | `17.0.14` |


Updates `@codemirror/commands` from 6.11.0 to 6.11.1
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@codemirror/search` from 6.7.1 to 6.7.2
- [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/search/commits)

Updates `@codemirror/view` from 6.43.9 to 6.43.12
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)

Updates `@testing-library/dom` from 10.4.1 to 10.4.2
- [Release notes](https://github.com/testing-library/dom-testing-library/releases)
- [Changelog](https://github.com/testing-library/dom-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/dom-testing-library/compare/v10.4.1...v10.4.2)

Updates `@testing-library/react` from 16.3.2 to 16.3.3
- [Release notes](https://github.com/testing-library/react-testing-library/releases)
- [Changelog](https://github.com/testing-library/react-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/react-testing-library/compare/v16.3.2...v16.3.3)

Updates `@testing-library/user-event` from 14.6.5 to 14.6.7
- [Release notes](https://github.com/testing-library/user-event/releases)
- [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/user-event/compare/v14.6.5...v14.6.7)

Updates `@types/ssh2` from 1.15.5 to 1.15.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ssh2)

Updates `@vitejs/plugin-react` from 6.1.0 to 6.1.1
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.1/packages/plugin-react)

Updates `cytoscape` from 3.34.1 to 3.34.3
- [Release notes](https://github.com/cytoscape/cytoscape.js/releases)
- [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.1...v3.34.3)

Updates `eslint-plugin-react-refresh` from 0.5.4 to 0.5.7
- [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases)
- [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.4...v0.5.7)

Updates `i18next` from 26.4.0 to 26.4.2
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.4.0...v26.4.2)

Updates `prettier` from 3.9.6 to 3.9.8
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.6...3.9.8)

Updates `react-i18next` from 17.0.12 to 17.0.14
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.0.12...v17.0.14)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/search"
  dependency-version: 6.7.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.12
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/dom"
  dependency-version: 10.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/react"
  dependency-version: 16.3.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/user-event"
  dependency-version: 14.6.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@types/ssh2"
  dependency-version: 1.15.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: cytoscape
  dependency-version: 3.34.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: eslint-plugin-react-refresh
  dependency-version: 0.5.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: i18next
  dependency-version: 26.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: prettier
  dependency-version: 3.9.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: react-i18next
  dependency-version: 17.0.14
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump the prod-patch-updates group with 6 updates (#1461)

Bumps the prod-patch-updates group with 6 updates:

| Package | From | To |
| --- | --- | --- |
| [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.10` | `3.14.13` |
| [compression](https://github.com/expressjs/compression) | `1.8.1` | `1.8.2` |
| [jose](https://github.com/panva/jose) | `6.2.9` | `6.2.12` |
| [jszip](https://github.com/Stuk/jszip) | `3.10.1` | `3.10.2` |
| [socks](https://github.com/JoshGlazebrook/socks) | `2.8.9` | `2.8.10` |
| [undici](https://github.com/nodejs/undici) | `8.10.0` | `8.10.2` |


Updates `@tanstack/react-virtual` from 3.14.10 to 3.14.13
- [Release notes](https://github.com/TanStack/virtual/releases)
- [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md)
- [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.13/packages/react-virtual)

Updates `compression` from 1.8.1 to 1.8.2
- [Release notes](https://github.com/expressjs/compression/releases)
- [Changelog](https://github.com/expressjs/compression/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/compression/compare/v1.8.1...v1.8.2)

Updates `jose` from 6.2.9 to 6.2.12
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.9...v6.2.12)

Updates `jszip` from 3.10.1 to 3.10.2
- [Changelog](https://github.com/Stuk/jszip/blob/main/CHANGES.md)
- [Commits](https://github.com/Stuk/jszip/compare/v3.10.1...v3.10.2)

Updates `socks` from 2.8.9 to 2.8.10
- [Release notes](https://github.com/JoshGlazebrook/socks/releases)
- [Commits](https://github.com/JoshGlazebrook/socks/compare/2.8.9...2.8.10)

Updates `undici` from 8.10.0 to 8.10.2
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.10.0...v8.10.2)

---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
  dependency-version: 3.14.13
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: compression
  dependency-version: 1.8.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: jose
  dependency-version: 6.2.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: jszip
  dependency-version: 3.10.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: socks
  dependency-version: 2.8.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: undici
  dependency-version: 8.10.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* feat: add plugin worker protocol, bootstrap and plugin_storage table

Worker-side ctx proxy plus the message envelope it talks over, and the
per-plugin key/value table behind ctx.storage with migrations for all
three dialects. Rows cascade with the plugin so uninstalling leaves
nothing behind.

* feat: add allowlisted host view for plugins

An allowlist rather than a list of fields to strip. A blocklist rots:
the moment a new secret-bearing column lands on SSHHost it starts
leaking silently. With an allowlist a new field stays invisible to
plugins until someone adds it here on purpose.

* feat: add plugin loader with manifest validation and crash restart

Validates an unpacked plugin, spawns a worker_threads worker and manages
activate/deactivate/crash-restart with backoff, disabling after three
tries.

The crash counter clears only after a plugin stays up past a stability
window, not on activation. Clearing it on activation let a plugin that
activates cleanly and then dies restart forever, because every attempt
looked like the first.

loader.ts documents what the worker boundary does and does not buy you.
Node's permission model is process-wide, not per-worker, so it cannot be
enabled for plugin workers alone and is not claimed here.

* feat: route internal events through a shared plugin event bus

Formalises three ad-hoc publish paths that already existed:
automation-events.ts, metrics/automation-bridge.ts and the
hostSessionStatus singleton, now the host.session.status topic.

Both invariants the old code relied on are preserved. Publishing stays
fire-and-forget, so a failing subscriber cannot disturb a metrics poll or
a host delete. The automations engine subscribes to the bus at scheduler
start instead of being imported ad hoc, which keeps the edge
one-directional: automations may import repositories, hosts modules must
not import automations.

* feat: add plugin ctx broker with permission gate and audit

Every ctx call a plugin makes is checked against its granted
capabilities, performed by the main thread, then audited. A capability
must be both declared in the manifest and granted in the database, so
widening a plugin's reach always needs a new manifest the user can see,
never just a database row.

Audit attribution is set by the broker, not the plugin. The plugin
supplies only the details, so it cannot forge the actor.

fix: stop plugin workers seeing plaintext credentials in error messages

A failing ctx.ssh.connect handed the worker the raw error from deep in
the SSH stack, which embeds the connect config. The worker received, in
full:

  Authentication failed for root using password <SECRET>

where <SECRET> was the host's real plaintext password. Any plugin with
ssh.exec could read it by catching the error, defeating the whole point
of the handle-based ssh API.

Errors crossing the boundary are now sanitised. Only PluginFacingError
and PluginPermissionError, both authored here, reach a plugin verbatim;
anything else becomes a generic message and the real one goes to the
log. This uses a marker class rather than matching on message text,
because matching would start leaking again the moment an upstream error
happened to contain a familiar phrase.

Covered by credential-isolation.test.ts, which plants a sentinel in
every secret-bearing field and asserts it appears in no message the
worker ever receives.

* feat: dispatch plugin HTTP routes and wire the runtime into startup

ctx.http.route now registers a real router on the /plugin-api/:pluginId
dispatcher, replacing its stub 404. A plugin never touches the Express
req/res: it gets a plain summary and returns a plain object, so sockets
and session cookies stay on this side of the boundary. Authorization and
cookie headers are not forwarded.

Plugins load last in the start-up sequence, after the server is fully
wired, and are terminated before the database on shutdown so none can
outlive it. A plugin that fails to load cannot stop the backend.

fix: correct the nginx plugin-api location regex

The pattern was ^/plugin-api/(/.*)?$, which needs a double slash and so
never matched /plugin-api/<id>/<route>. Every other block in the file
uses ^/prefix(/.*)?$. Left alone, plugin routes would work in dev and
404 only behind Docker.

* fix: update stale SFTP transfer test for single file destination paths

The test still asserted transferToHost was called with the destination
directory "/srv". Commit 7727fa09 (#1304) deliberately changed a single
file transfer to send the full destination path including the filename,
so the correct expectation is "/srv/remote-1.txt". The code was right
and the test was left behind.

* feat: ship the ssh terminal as a first-party in-process plugin

Adds a hardcoded process:transport-owner tier so the terminal can own its
WebSocket server and ssh2 clients, which cannot cross the worker boundary.

* feat: ship docker as a first-party in-process plugin

Moves docker backend and frontend into plugins/docker/, alongside
ssh-terminal. Adds a host editor tab seam, a dashboard card registry,
and a build step to compile plugin backends into dist.

* feat: ship host metrics as a first-party in-process plugin

* fix: harden plugin auth and add per-request identity for ctx calls

Require auth on /plugin-api, gate plugin enable/grant/revoke routes
behind admin.plugins.manage, and thread the calling user through
worker ctx.hosts/ctx.ssh calls instead of always using the install
owner. Also adds the plugin permissions grant/revoke UI.

* feat: ship the AI assistant as a first-party in-process plugin

Moves src/backend/ai and its routes into plugins/ai, mounted through a
small /ai dispatcher instead of its own port. Moves the ai-enabled and
ai-private-endpoints settings routes out of user-settings-routes.ts
into the plugin too, so it has no leftover core dependents.

* fix: remove compiled plugin JS left behind in plugins/ after build

copy-bundled-plugins.cjs compiled and rewrote plugin backend TS in
place, copied it to dist/plugins, but never deleted the .js it had
just emitted next to the .ts sources. Those files shadowed the real
source for vitest/tsx and had import paths rewritten for the dist
layout, so tests failed with "Cannot find module" once a local build
had run. Affects docker, host-metrics and ai, not just this one.

* feat: add a permission-gated backend service registry for plugins

* feat: add a permission-gated UI action registry and action slots for plugins

Moves the terminal toolbar's hardwired AI button into a slot the ssh-terminal
plugin offers and the ai plugin fills, gated on ai.services.use.

* feat: add cross-plugin secret references gated by the provider's RBAC permission

* feat: move proxmox discovery/import/sync into a first-party plugin

* feat: move remote desktop (RDP/VNC/Telnet) into a first-party plugin

Relocates guacamole backend/frontend source and tests into
plugins/remote-desktop, following the ssh-terminal/docker pattern.

* feat: wire remote-desktop plugin into core and rename i18n keys

Repoints core consumers (dispatcher, collab, session-sharing, tab
utils) at the plugin, adds isTabTypeAvailable gating for rdp/vnc/
telnet, widens hostCapability to accept an array, and renames the
guacamole i18n namespace to remoteDesktop.

* feat: move fleets into a first-party plugin

* feat: move automations into a first-party plugin

* feat: remove legacy alert rules, superseded by automations

Alert rules already auto-migrate into automations on boot and the old
engine stands down after. Deletes the rule/firing tables, routes, UI,
and AI tools; keeps notification channels since automations still use
them. Also fixes automations' notify step, which still called the
deleted repository.

* feat: move network topology into a first-party plugin

* feat: move tailscale device discovery and settings into a plugin

Adds plugins/tailscale/ with a devices sidebar tab, admin settings
section, and re-auth dialog. Host Metrics tailscale manager card and
SSH re-auth banner parsing stay in core.

* feat: move workspaces into a first-party plugin

* feat: move web endpoint into a first-party plugin

* feat: collapse plugin runtime to one tier behind a plugin SDK

* feat: make each plugin an npm workspace built by a termix-plugin CLI

* feat: give plugins their own tables, migrations and sync entities

* feat: serve plugin http and websockets from one mount instead of ports

* feat: namespace plugin permissions and keep them valid when a plugin is off

* feat: give plugins their own settings and one settings screen

* feat: load plugin frontends at runtime and remove plugin ids from the shell

* fix: mock the ai status fetch in its activate test

* feat: add auth extension points and one ssh connect pipeline

* feat: rebuild workspaces as the reference plugin

* fix: gate second factors after SSO/LDAP behind an admin setting

* feat: convert network-topology to a full plugin (B1)

* feat: move snippets backend and tables into a plugin (B2)

* feat: point core frontend snippets pickers at the plugin (B2)

* feat: add the snippets plugin (B2)

* feat: wire ai, automations, fleets and ssh-terminal to snippets (B2)

* feat: finish the tailscale plugin, including SSH auth (B3)

* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)

* chore: update proxmox and host-metrics locale files for B5

* chore: regenerate drizzle migration journals for B5

* feat: add ctx.hosts create/update to the SDK, host-metrics drops proxmox

* feat: move proxmox node stats and collectors into the proxmox plugin

* feat: drop proxmox host columns, use plugin settings instead

* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)

* feat: convert file manager into a plugin

* feat: convert ssh tunnels into a plugin

* feat: finish the web-endpoint plugin, add ctx.desktop (B8)

* feat: move the terminal fully into the ssh-terminal plugin (B9)

* feat: convert tmux monitoring into a plugin (B10)

* feat: convert serial console into the serial plugin

* feat: move session sharing and collab rooms into a plugin (B12)

* feat: turn session recording into a plugin (B13)

* feat: finish the remote-desktop plugin (B14)

* feat: finish the host-metrics plugin, move host status into core (B16)

* feat: finish the docker plugin (B15)

* feat: finish the automations plugin (B17)

* feat: finish the ai plugin (B18)

* feat: finish the homepage plugin, move service links and canvas out of core (B19)

* feat: convert wake-on-lan into a plugin (B20)

* feat: convert secret-sources into a plugin (B20)

* feat: move totp and passkeys into plugins (C1)

* feat: move sso and ldap logins into plugins (C2)

* feat: move opkssh and warpgate into plugins (C3)

* feat: move step-ca into a plugin (C4)

* feat: move vault ssh signing into a plugin (C5)

* feat: move termix identity into a plugin (C6)

* feat: move acme certificate automation into a plugin (C7)

* fix: finish 2.9.0 plugin moves and get every check green

* chore: lock the plugin boundary and remove 2.9.0 leftovers

* fix: harden the plugin runtime after the 2.9.0 security review

* feat: add plugin packing, signing, pinned trust and tmxplug bundling

* test: prove 2.8 to 2.9.0 upgrade is lossless and fix what it caught

* fix: give bundled plugin backends a real require for CJS deps

* feat: improve UI loading time and jitter

* feat: show credential sharing inline in the sidebar like host sharing

* feat: tailscale add host and copy ip, fix outbound fetch hang and plugin ESM warning

* feat: unify alerts into one plugin, channels, rules and inbox

* feat: rebuild desktop sync as linked server accounts, fix packaged plugin bundles and UI scaling

* fix: set blacksmith builder cache-key to stop broken gha cache fallback

* fix: link plugin-sdk workspace before npm ci in docker deps stage

* fix: link every plugin workspace before npm ci in docker deps stage

* fix(host-metrics): exclude image and firmware filesystems (#1469)

* fix(host-metrics): exclude image and firmware filesystems

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(hosts): normalize imported jump host references (#1470)

* fix(hosts): normalize imported jump host references

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(ci): build plugin SDK and repair MySQL settings migration (#1471)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): keep inline rename consistent (#1476)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): keep inline rename consistent

* fix(dashboard): reuse translated host status labels (#1475)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(dashboard): reuse translated host status labels

* docs(api): clarify local and remote version fields (#1474)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* docs(api): clarify local and remote version fields

* fix(file-manager): preserve selected backgrounds on hover (#1473)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): preserve selection feedback on hover

* test(ui): await dialog focus cleanup before teardown

* fix(file-manager): restore Ctrl/Cmd+F file search (#1472)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): focus file search with Ctrl or Cmd F

* fix: keep rounded-full circular in production builds

* fix(file-manager): cancel uploads and stop remote writes (#1477)

* fix(file-manager): cancel uploads and stop remote writes

* test(css): exercise the configured PostCSS plugin chain

* fix(file-manager): apply compact density to directory tree (#1478)

* fix(file-manager): apply compact density to directory tree

* test(css): exercise the configured PostCSS plugin chain

* fix(file-manager): preserve font sizes in compact mode (#1480)

* fix(file-manager): preserve font sizes in compact mode

* test(css): exercise the configured PostCSS plugin chain

* fix(file-manager): prioritize file names in narrow lists (#1483)

* fix(file-manager): prioritize file names in narrow lists

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* test(remote-desktop): always mutate ciphertext in tamper test

* fix(remote-desktop): probe the saved host guacd endpoint (#1481)

* fix(remote-desktop): probe the saved host guacd endpoint

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* fix(homepage): check allowlisted private service reachability (#1479)

* fix(homepage): check allowlisted private service reachability

* test(css): exercise the configured PostCSS plugin chain

* fix(remote-desktop): stop unsolicited clipboard read prompts (#1482)

* fix(remote-desktop): read clipboard only on explicit paste

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* test(remote-desktop): always mutate ciphertext in tamper test

* chore: simplify plugin readmes, changelogs and manifest descriptions

* fix: keep plugins loaded after signing in from the login screen

* fix(file-manager): accept OS file drops over existing rows (#1484)

* fix(file-manager): accept OS file drops over existing rows

* test(file-manager): target the file label in drop tests

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* test(remote-desktop): always mutate ciphertext in tamper test

* fix(file-manager): pipeline SFTP download reads (#1485)

* feat: add plugin sdk build to beta release

* fix: make link-store secret check immune to random base64 matches

* fix(ldap): preserve the directory-provided bind DN (#1486)

* fix: compute beta changes across dev branches and move the beta tag

* chore: untrack plugin sdk ARCHITECTURE.md

* chore: remove references to plugin sdk ARCHITECTURE.md

* feat: merge host editor terminal tabs into one owned by ssh-terminal

* feat: add descriptions to plugin host enable toggles

* fix(file-manager): show download progress in file viewers (#1487)

* fix(electron): signal backend readiness over IPC (#1488)

* fix(split-screen): allow layout creation without randomUUID (#1490)

* fix(split-screen): allow layout creation without randomUUID

* test(credentials): avoid flaky Ed25519 key generation

* fix(sidebar): remeasure visible rows after density changes (#1489)

* fix(sidebar): remeasure visible rows after density changes

* test(credentials): avoid flaky Ed25519 key generation

* feat(split-screen): redesign split screen with free-form panes and pane picker

* feat(sidebar): add host click behavior setting, default to always opening a new tab

* feat(snippets): redesign panel to match the host list

* fix(session-recording): stop session logs panel from refetching in a loop

* feat(snippets): bring back sharing, target hosts and drag reorder

* feat(ssh-terminal): add toolbar position, start state, display and fade host settings

* feat(ssh-terminal): add host setting to turn off password prompt auto-fill

* fix(ai): stop streams getting cut off and keep tool steps across messages

* feat: improve quick connect system using plugin api

* fix: proxmox guest sync, startup snippet sync, drop dead cloudflare ssh transport

* feat: move terminal settings, look and ssh tools into ssh-terminal plugin

* feat: move snippets, keybinding actions and macros out of core into plugins

* feat: store rdp, vnc and telnet logins in a generic per-protocol table

* feat: type the plugin host record, move plugin strings out of core and add lint checks

* feat: replace core homepage widget registry with generic extension points

* feat: plugins only see their own host settings in the browser

* feat: harden plugin api for separate repos, signed updates and generic external login

* fix: keep plugin css below core utilities and version plugin assets by their css

* fix: load and save plugin host settings in the editor and tighten settings row spacing

* feat: redesign user host defaults system

* fix(remote-desktop): release held keys on focus loss (#1498)

* fix(session-sharing): replace local presentation after takeover (#1500)

* fix(file-manager): refresh disk usage with directory listing (#1503)

* fix(ssh-terminal): preserve input order during local echo reconciliation (#1505)

* feat(remote-desktop): expose display zoom controls for RDP (#1514)

* fix(file-manager): restore text selection and copying in Markdown previews (#1518)

* fix(sidebar): keep compact host addresses visible (#1524)

* fix(hosts): preserve plugin settings when reopening the editor (#1499)

* fix(ssh-terminal): close owner sockets when presentations unmount (#1501)

* fix(session-sharing): synchronize shared SSH terminal dimensions (#1502)

* fix(session-sharing): show participant presence in member terminals (#1504)

* fix(ai): sync provider configuration and keys across linked devices (#1506)

* feat(ssh-terminal): add a duplicate tab action (#1510)

* feat(file-manager): allow disabling move-to-trash confirmation (#1511)

* feat(file-manager): default to the remote login directory (#1512)

* feat(homepage): synchronize canvas layouts across devices (#1515)

* fix(shortcuts): prevent accidental double-Shift palette activation (#1519)

* feat(tmux-monitor): add a unified multi-host view (#1520)

* fix(electron): allow explicit quit with active connections (#1522)

* feat: reconnect all disconnected terminal tabs (#1523)

* fix(hosts): preserve recording and sharing settings in the dev editor (#1509)

* fix(database): preserve RDP domain during startup backfill (#1497)

* feat(sidebar): add keyboard type-ahead search for hosts (#1516)

* feat(automations): add per-host maintenance mode and recurring schedules (#1521)

* feat(tmux): add a per-host mouse toggle and preserve remote configuration (#1513)

* fix(session-sharing): use the linked server for desktop meetings and links (#1507)

* fix(tunnels): support TOTP for client tunnels and jump hosts (#1508)

* fix: type errors and lint failures from merged plugin prs

* feat(installer): make the Windows desktop shortcut optional (#1517)

* fix: ship the plugin sdk and serialport in desktop builds

* fix: prefer ipv4 when resolving ssh host names (#1365)

* fix: readable terminal selection with the light theme (#1319)

* fix: build desktop session share links on the linked server (#1350)

* fix: show meeting guests to members and hide the roster from guests (#1353)

* fix: reliable file manager saves with sudo prompt and no base64 guessing (#1335)

* fix: show disk usage for the mount being browsed (#1347)

* fix: load the linux tray icon reliably and log tray failures (#1332)

* fix: cover the gnome close path in the desktop quit test (#1332)

* fix: prompt for jump host TOTP in terminal, file manager and metrics (#1312)

* feat: optional auto reconnect for dropped ssh sessions (#1321)

* feat: tighter compact host rows with inline tags (#1325)

* feat: bring back the alert feed homepage widget

* feat: pick target terminals for snippets again

* feat: share button on connection tabs again

* feat: recent servers list when linking the desktop app

* feat: list the fixed app shortcuts in keyboard shortcuts

* fix: translate hardcoded toasts and drop em dashes from ui text

* fix: translate leftover hardcoded ui text

* fix: toolbar files button opens at the shell directory again

* fix: show the remote desktop note under connection origin again

* chore: openapi docs for host metrics manager routes

* chore: openapi docs for undocumented routes and fix two broken doc blocks

* fix: declare terminal.listSessions use for snippet targets

* revert: drop the alert feed widget, the notification center replaces it

* feat: restore the alert feed homepage widget

* fix: quick connect fills the host address from plugin auth editors like tailscale

* fix: docker container logs use the base background color

* chore: fix dependabot alerts and apply safe npm upgrades

* fix: proxmox stats tab reads its switch from plugin host settings

* fix: count plugin ssh logins toward host status and stop showing reachable as a warning

* fix: hide the built-in source pill in the host editor

* fix: host status shows online when the port answers and only warns on a failed login

* fix: drop the top border on the split layout menu

* fix: host defaults tabs sit where the host editor puts them and skip plugins with nothing to default

* fix: remote desktop auth method labels and notes for vnc and telnet

* fix: add description to the web endpoint enable switch

* fix: crowdin sync and pretranslate for plugin locales, run plugin tests on release

* feat: move telemetry out of core into a usage statistics plugin

* fix: recent activity card no longer cuts off host names early

* fix: remove duplicate top border on split screen menu

* fix: redesign session log player controls, fix tooltip overlap and drop dot separators

* fix: file manager and sftp text showing raw i18n keys

* fix: onboarding rerunning for existing users after upgrading

* fix: fleet detail buttons overflowing the sidebar

* fix: session log player scrolling off screen horizontally

* fix: network graph lag when adding hosts and on every render

* fix: maintenance index name, shared host read only view and badge polling

* fix: meeting tabs, workspace tab merging, rail panels as tabs and general ui lag

* chore: update release notes

* fix: remote desktop tabs reconnecting on every tab switch

* fix: build plugin sdk before linting in release workflow

* chore: lint, format, and bump version to 2.9.0

* chore: skip crowdin pre-translate in release for now

* chore: sync Crowdin translations for 2.9.0

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Koi <38512047+datlt4@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-10-01 16:20:16 -05:00
1 parent 49fa488093
commit 3643e7af97
4405 files changed
+1341026 -289722

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Search, X } from "lucide-react";
import { Input } from "@/components/input";
import { Button } from "@/components/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/dropdown-menu";
import { tabIcon } from "@/shell/tabUtils";
import {
hostActionsFor,
useHostActions,
type HostActionDef,
} from "@/sidebar/host-contributions";
import type { Host, Tab } from "@/types/ui-types";
/** Hosts listed before a search narrows them down. */
const HOST_LIMIT = 60;
export interface NewTabOption {
type: string;
label: string;
icon?: React.ComponentType<{ className?: string }>;
}
export type PickHostTarget =
| { action: HostActionDef }
| { action: HostActionDef; item: { id: string; label: string } };
function HostActionButton({
host,
action,
onPick,
}: {
host: Host;
action: HostActionDef;
onPick: (target: PickHostTarget) => void;
}) {
const { t } = useTranslation();
const Icon = action.icon;
const title = action.label?.(host) ?? t(action.titleKey);
const items = action.items?.(host) ?? [];
const button = (
<button
type="button"
title={title}
aria-label={`${host.name}: ${title}`}
className="flex size-6 shrink-0 items-center justify-center text-muted-foreground hover:bg-accent-brand/10 hover:text-accent-brand"
onClick={items.length > 1 ? undefined : () => onPick({ action })}
>
<Icon className="size-3.5" />
</button>
);
if (items.length <= 1) return button;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
{items.map((item) => (
<DropdownMenuItem
key={item.id}
onSelect={() => onPick({ action, item })}
>
{item.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
/**
* What an empty pane shows: the tabs that could move in, new tabs to start,
* and every host with the ways to open it. Picking anything fills this pane.
*/
export function EmptyPanePicker({
paneIndex,
freeTabs,
hosts,
newTabOptions,
onPickTab,
onPickHost,
onOpenType,
onClosePane,
}: {
paneIndex: number;
freeTabs: Tab[];
hosts: Host[];
newTabOptions: NewTabOption[];
onPickTab: (tabId: string) => void;
onPickHost: (host: Host, target: PickHostTarget) => void;
onOpenType: (type: string) => void;
onClosePane: () => void;
}) {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const allActions = useHostActions();
const shownHosts = useMemo(() => {
const q = query.trim().toLowerCase();
const matches = q
? hosts.filter((host) =>
[host.name, host.ip, host.username, host.folder]
.filter(Boolean)
.some((field) => String(field).toLowerCase().includes(q)),
)
: hosts;
return [...matches]
.sort((a, b) => a.name.localeCompare(b.name))
.slice(0, HOST_LIMIT);
}, [hosts, query]);
return (
<div
className="flex size-full justify-center overflow-y-auto bg-background p-4"
data-split-empty-pane
>
<div className="flex w-full max-w-md flex-col gap-4 self-start">
<div className="flex flex-col gap-1">
<span className="text-sm font-semibold text-foreground">
{t("splitScreen.emptyTitle")}
<span className="ml-2 text-xs font-normal text-muted-foreground">
{t("splitScreen.paneNumber", { index: paneIndex })}
</span>
</span>
<span className="text-xs text-muted-foreground">
{t("splitScreen.emptyHint")}
</span>
</div>
<section className="flex flex-col gap-1.5">
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{t("splitScreen.openTabs")}
</span>
{freeTabs.length === 0 ? (
<span className="text-xs text-muted-foreground/70">
{t("splitScreen.noOpenTabs")}
</span>
) : (
<div className="flex flex-col border border-border">
{freeTabs.map((tab) => (
<button
key={tab.id}
type="button"
className="flex items-center gap-2 border-b border-border px-2.5 py-1.5 text-left text-xs last:border-b-0 hover:bg-accent-brand/10 hover:text-accent-brand"
onClick={() => onPickTab(tab.id)}
>
<span className="shrink-0 text-muted-foreground">
{tabIcon(tab.type)}
</span>
<span className="truncate">{tab.label}</span>
</button>
))}
</div>
)}
</section>
{newTabOptions.length > 0 && (
<section className="flex flex-col gap-1.5">
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{t("splitScreen.newSession")}
</span>
<div className="flex flex-wrap gap-1.5">
{newTabOptions.map((option) => {
const Icon = option.icon;
return (
<button
key={option.type}
type="button"
className="flex items-center gap-1.5 border border-border px-2.5 py-1.5 text-xs hover:border-accent-brand/40 hover:bg-accent-brand/10 hover:text-accent-brand"
onClick={() => onOpenType(option.type)}
>
{Icon && <Icon className="size-3.5" />}
{option.label}
</button>
);
})}
</div>
</section>
)}
<section className="flex flex-col gap-1.5">
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{t("splitScreen.hosts")}
</span>
<div className="relative">
<Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("splitScreen.searchHosts")}
aria-label={t("splitScreen.searchHosts")}
className="h-8 rounded-none pl-7 text-xs"
/>
</div>
{shownHosts.length === 0 ? (
<span className="text-xs text-muted-foreground/70">
{t("splitScreen.noHosts")}
</span>
) : (
<div className="flex flex-col border border-border">
{shownHosts.map((host) => {
const actions = hostActionsFor(allActions, host);
const connect = actions
.filter((action) => action.kind === "connect")
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
const open = actions.filter((action) => action.kind === "open");
const primary = connect[0];
return (
<div
key={host.id}
className="flex items-center gap-2 border-b border-border px-2.5 py-1 last:border-b-0"
>
<button
type="button"
disabled={!primary}
className="flex min-w-0 flex-1 flex-col items-start text-left text-xs enabled:hover:text-accent-brand disabled:opacity-60"
onClick={() =>
primary && onPickHost(host, { action: primary })
}
>
<span className="w-full truncate font-medium">
{host.name}
</span>
<span className="w-full truncate text-[10px] text-muted-foreground">
{host.username ? `${host.username}@` : ""}
{host.ip}
</span>
</button>
<div className="flex shrink-0 items-center">
{[...connect, ...open].map((action) => (
<HostActionButton
key={action.id}
host={host}
action={action}
onPick={(target) => onPickHost(host, target)}
/>
))}
</div>
</div>
);
})}
</div>
)}
</section>
<Button
variant="ghost"
size="sm"
className="self-start rounded-none text-xs text-muted-foreground"
onClick={onClosePane}
>
<X className="size-3" />
{t("splitScreen.closePane")}
</Button>
</div>
</div>
);
}
+100
View File
@@ -0,0 +1,100 @@
import { useEffect, type RefObject } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
dropTargetAt,
dropTargetRect,
setSplitDropHitTest,
useSplitDrag,
} from "./split-drag";
/**
* Drop zones over the main area while a tab or pane is dragged. Over a
* split, each pane offers its four edges (split there) and its center (show
* it there). Over a plain tab only the edges count, to start a new split.
*/
export function SplitDropOverlay({
containerRef,
}: {
containerRef: RefObject<HTMLElement | null>;
}) {
const { t } = useTranslation();
const drag = useSplitDrag();
useEffect(
() =>
setSplitDropHitTest((x, y, source) => {
const container = containerRef.current;
if (!container) return null;
const bounds = container.getBoundingClientRect();
if (
x < bounds.left ||
x > bounds.right ||
y < bounds.top ||
y > bounds.bottom
) {
return null;
}
const panes = Array.from(
container.querySelectorAll<HTMLElement>("[data-split-pane-id]"),
).filter((el) => el.getClientRects().length > 0);
if (panes.length === 0) {
if (source.kind !== "tab") return null;
const target = dropTargetAt(bounds, x, y);
if (target === "center") return null;
return { paneId: null, target, rect: dropTargetRect(bounds, target) };
}
for (const el of panes) {
const rect = el.getBoundingClientRect();
if (
x < rect.left ||
x > rect.right ||
y < rect.top ||
y > rect.bottom
) {
continue;
}
const paneId = el.dataset.splitPaneId ?? null;
if (source.kind === "pane" && source.paneId === paneId) return null;
const target = dropTargetAt(rect, x, y);
return { paneId, target, rect: dropTargetRect(rect, target) };
}
return null;
}),
[containerRef],
);
if (!drag) return null;
const { hover } = drag;
return createPortal(
<div className="pointer-events-none fixed inset-0 z-[9998]">
{hover && (
<div
className="absolute flex items-center justify-center border-2 border-dashed border-accent-brand bg-accent-brand/15 transition-[left,top,width,height] duration-100"
style={{
left: hover.rect.left,
top: hover.rect.top,
width: hover.rect.width,
height: hover.rect.height,
}}
>
<span className="bg-background/90 px-2 py-1 text-xs font-medium text-accent-brand">
{hover.target === "center"
? t("splitScreen.dropHere")
: t("splitScreen.dropSplit")}
</span>
</div>
)}
<div
className="absolute max-w-48 truncate border border-border bg-popover px-2 py-1 text-xs text-foreground shadow-lg"
style={{ left: drag.x + 12, top: drag.y + 12 }}
>
{drag.source.label}
</div>
</div>,
document.body,
);
}
+142
View File
@@ -0,0 +1,142 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Columns2, LayoutPanelLeft, Rows2 } from "lucide-react";
import { Button } from "@/components/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "@/components/dropdown-menu";
import type { LayoutNode } from "@/types/ui-types";
import {
buildPreset,
SPLIT_PRESETS,
type SplitPresetId,
} from "./split-presets";
import { MAX_PANES, type PaneEdge } from "./split-tree";
function NodeThumb({ node }: { node: LayoutNode }) {
if (node.kind === "pane") {
return <div className="size-full border border-current" />;
}
return (
<div
className={`flex size-full gap-0.5 ${node.direction === "row" ? "flex-row" : "flex-col"}`}
>
{node.children.map((child, index) => (
<div
key={child.id}
className="min-w-0 min-h-0"
style={{ flex: `${node.sizes[index]} 1 0px` }}
>
<NodeThumb node={child} />
</div>
))}
</div>
);
}
/** A small drawing of a preset's panes. */
export function PresetThumb({ id }: { id: SplitPresetId }) {
const node = useMemo(() => buildPreset(id), [id]);
return <NodeThumb node={node} />;
}
/**
* The tab bar's split button: split the active tab right or down, or lay it
* out as one of the presets.
*/
export function SplitLayoutMenu({
activeIsSplit,
canAddPane,
onSplit,
onPreset,
}: {
activeIsSplit: boolean;
canAddPane: boolean;
onSplit: (edge: Extract<PaneEdge, "right" | "bottom">) => void;
onPreset: (id: SplitPresetId) => void;
}) {
const { t } = useTranslation();
const fullTitle = canAddPane
? undefined
: t("splitScreen.maxPanes", { count: MAX_PANES });
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className={`h-full w-12.5 rounded-none border-y-0 border-border ${activeIsSplit ? "text-accent-brand" : "text-muted-foreground hover:text-foreground"}`}
title={t("splitScreen.title")}
aria-label={t("splitScreen.title")}
>
<LayoutPanelLeft className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
sideOffset={1}
className="w-64 border-t-0 [clip-path:inset(0px_-4px_-4px_-4px)] p-1"
>
<DropdownMenuItem
disabled={!canAddPane}
title={fullTitle}
onSelect={() => onSplit("right")}
>
<Columns2 className="size-3.5" />
{t("splitScreen.splitRight")}
<DropdownMenuShortcut>Ctrl+Shift+\</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem
disabled={!canAddPane}
title={fullTitle}
onSelect={() => onSplit("bottom")}
>
<Rows2 className="size-3.5" />
{t("splitScreen.splitDown")}
<DropdownMenuShortcut>Ctrl+Shift+-</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{activeIsSplit
? t("splitScreen.applyLayout")
: t("splitScreen.layouts")}
</DropdownMenuLabel>
<div className="grid grid-cols-4 gap-1 p-1">
{SPLIT_PRESETS.map((preset) => (
<DropdownMenuItem
key={preset.id}
className="flex h-12 items-center justify-center p-1.5 text-muted-foreground focus:text-accent-brand"
title={t(preset.titleKey)}
aria-label={t(preset.titleKey)}
onSelect={() => onPreset(preset.id)}
>
<div className="h-8 w-11">
<PresetThumb id={preset.id} />
</div>
</DropdownMenuItem>
))}
</div>
<DropdownMenuSeparator />
<DropdownMenuLabel className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{t("splitScreen.shortcuts")}
</DropdownMenuLabel>
<div className="flex flex-col gap-1 px-2 pb-1.5 text-xs text-muted-foreground">
<div className="flex items-center justify-between gap-2">
<span>{t("splitScreen.shortcutNavigate")}</span>
<kbd className="font-mono text-[10px]">Alt+Arrows</kbd>
</div>
<div className="flex items-center justify-between gap-2">
<span>{t("splitScreen.zoom")}</span>
<kbd className="font-mono text-[10px]">Ctrl+Shift+Enter</kbd>
</div>
</div>
</DropdownMenuContent>
</DropdownMenu>
);
}
+606
View File
@@ -0,0 +1,606 @@
import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
ChevronDown,
Columns2,
Maximize2,
Minimize2,
MoreHorizontal,
Rows2,
} from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/dropdown-menu";
import { tabIcon } from "@/shell/tabUtils";
import type { LayoutNode, PaneNode, SplitNode, Tab } from "@/types/ui-types";
import type { SplitTab } from "./split-tabs";
import {
listPanes,
MAX_PANES,
moveDivider,
shownPanes,
type PaneEdge,
} from "./split-tree";
import { beginSplitDrag, endSplitDrag, moveSplitDrag } from "./split-drag";
export interface SplitViewActions {
focusPane: (paneId: string) => void;
resize: (nodeId: string, sizes: number[]) => void;
equalize: (nodeId: string) => void;
splitPane: (
paneId: string,
edge: Extract<PaneEdge, "right" | "bottom">,
) => void;
closePane: (paneId: string) => void;
closeSession: (tabId: string) => void;
moveToTab: (paneId: string) => void;
showInPane: (paneId: string, tabId: string | null) => void;
swapPanes: (firstId: string, secondId: string) => void;
toggleZoom: (paneId: string) => void;
/** A divider drag finished, so sessions can fit their new size. */
resizeEnd: () => void;
}
interface PaneContext {
splitTab: SplitTab;
tabsById: Map<string, Tab>;
/** Tabs outside any split, offered in each pane's switcher. */
freeTabs: Tab[];
paneIndexById: Map<string, number>;
paneCount: number;
isMobile: boolean;
resizing: boolean;
actions: SplitViewActions;
onPaneContentRef: (paneId: string, el: HTMLDivElement | null) => void;
renderEmptyPane: (paneId: string, paneIndex: number) => React.ReactNode;
setResizing: (resizing: boolean) => void;
}
const DRAG_THRESHOLD = 5;
function tabLabel(tab: Tab): string {
return tab.customLabel || tab.label;
}
function PaneHeader({
pane,
tab,
focused,
ctx,
}: {
pane: PaneNode;
tab: Tab | null;
focused: boolean;
ctx: PaneContext;
}) {
const { t } = useTranslation();
const { actions, splitTab, paneIndexById, tabsById } = ctx;
const index = paneIndexById.get(pane.id) ?? 0;
const panes = listPanes(splitTab.split.root);
const otherPanes = panes.filter((other) => other.id !== pane.id);
const full = panes.length >= MAX_PANES;
const zoomed = splitTab.split.zoomedPaneId === pane.id;
const fullTitle = full
? t("splitScreen.maxPanes", { count: MAX_PANES })
: undefined;
const drag = useRef<{ x: number; y: number; started: boolean } | null>(null);
const label = tab ? tabLabel(tab) : t("splitScreen.emptyTitle");
function onPointerDown(event: React.PointerEvent<HTMLDivElement>) {
if (event.button !== 0 || ctx.isMobile || !tab) return;
// The header's menus render in portals, and React still bubbles their
// events up to here. Only presses on the header itself start a drag.
const target = event.target as HTMLElement;
if (!event.currentTarget.contains(target)) return;
if (target.closest("button")) return;
drag.current = { x: event.clientX, y: event.clientY, started: false };
}
function onPointerMove(event: React.PointerEvent<HTMLDivElement>) {
const state = drag.current;
if (!state || !tab) return;
// Released outside the header before it became a drag.
if (!state.started && event.buttons === 0) {
drag.current = null;
return;
}
if (!state.started) {
const moved = Math.hypot(
event.clientX - state.x,
event.clientY - state.y,
);
if (moved < DRAG_THRESHOLD) return;
state.started = true;
// Captured only once it is really a drag, so a plain click stays a click.
event.currentTarget.setPointerCapture(event.pointerId);
beginSplitDrag(
{
kind: "pane",
splitTabId: splitTab.id,
paneId: pane.id,
label: tabLabel(tab),
},
event.clientX,
event.clientY,
);
return;
}
moveSplitDrag(event.clientX, event.clientY);
}
function finishDrag(commit: boolean) {
const started = drag.current?.started;
drag.current = null;
if (started) endSplitDrag(commit);
}
const buttonClass =
"flex size-6 shrink-0 items-center justify-center text-muted-foreground hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40";
return (
<div
data-split-pane-header
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={() => finishDrag(true)}
onPointerCancel={() => finishDrag(false)}
onLostPointerCapture={() => finishDrag(false)}
className={`flex h-7 shrink-0 items-center gap-1 border-b pl-1 pr-0.5 text-xs select-none ${
focused
? "border-accent-brand/40 bg-accent-brand/10"
: "border-border bg-sidebar"
} ${tab && !ctx.isMobile ? "cursor-grab active:cursor-grabbing" : ""}`}
>
<span
className={`flex h-4 min-w-4 shrink-0 items-center justify-center px-1 font-mono text-[10px] ${
focused
? "bg-accent-brand text-background"
: "bg-muted text-muted-foreground"
}`}
>
{index}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className={`flex min-w-0 items-center gap-1.5 px-1 py-0.5 hover:bg-muted ${
focused ? "text-accent-brand" : "text-foreground"
}`}
title={t("splitScreen.showHere")}
>
{tab && (
<span className={focused ? "" : "text-muted-foreground"}>
{tabIcon(tab.type)}
</span>
)}
<span
className={`truncate ${tab ? "font-medium" : "text-muted-foreground"}`}
>
{label}
</span>
<ChevronDown className="size-3 shrink-0 opacity-60" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-60">
<DropdownMenuLabel className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{t("splitScreen.showHere")}
</DropdownMenuLabel>
{ctx.freeTabs.length === 0 && (
<DropdownMenuItem disabled>
{t("splitScreen.noOpenTabs")}
</DropdownMenuItem>
)}
{ctx.freeTabs.map((free) => (
<DropdownMenuItem
key={free.id}
onSelect={() => actions.showInPane(pane.id, free.id)}
>
{tabIcon(free.type)}
<span className="truncate">{tabLabel(free)}</span>
</DropdownMenuItem>
))}
{tab && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => actions.showInPane(pane.id, null)}
>
{t("splitScreen.clearPane")}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
<div className="ml-auto flex shrink-0 items-center">
{!ctx.isMobile && (
<>
<button
type="button"
className={buttonClass}
disabled={full}
title={fullTitle ?? t("splitScreen.splitRight")}
aria-label={t("splitScreen.splitRight")}
onClick={() => actions.splitPane(pane.id, "right")}
>
<Columns2 className="size-3.5" />
</button>
<button
type="button"
className={buttonClass}
disabled={full}
title={fullTitle ?? t("splitScreen.splitDown")}
aria-label={t("splitScreen.splitDown")}
onClick={() => actions.splitPane(pane.id, "bottom")}
>
<Rows2 className="size-3.5" />
</button>
{panes.length > 1 && (
<button
type="button"
className={`${buttonClass} ${zoomed ? "text-accent-brand" : ""}`}
title={zoomed ? t("splitScreen.unzoom") : t("splitScreen.zoom")}
aria-label={
zoomed ? t("splitScreen.unzoom") : t("splitScreen.zoom")
}
aria-pressed={zoomed}
onClick={() => actions.toggleZoom(pane.id)}
>
{zoomed ? (
<Minimize2 className="size-3.5" />
) : (
<Maximize2 className="size-3.5" />
)}
</button>
)}
</>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className={buttonClass}
title={t("splitScreen.paneActions")}
aria-label={t("splitScreen.paneActions")}
>
<MoreHorizontal className="size-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52">
{tab && (
<>
<DropdownMenuItem onSelect={() => actions.moveToTab(pane.id)}>
{t("splitScreen.moveToTab")}
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => actions.closeSession(tab.id)}>
{t("splitScreen.closeSession")}
</DropdownMenuItem>
</>
)}
{otherPanes.length > 0 && (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
{t("splitScreen.swapWith")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-56">
{otherPanes.map((other) => {
const otherTab = other.tabId
? tabsById.get(other.tabId)
: undefined;
const otherIndex = paneIndexById.get(other.id) ?? 0;
return (
<DropdownMenuItem
key={other.id}
onSelect={() => actions.swapPanes(pane.id, other.id)}
>
<span className="truncate">
{otherTab
? t("splitScreen.paneItem", {
index: otherIndex,
label: tabLabel(otherTab),
})
: t("splitScreen.paneEmptyItem", {
index: otherIndex,
})}
</span>
</DropdownMenuItem>
);
})}
</DropdownMenuSubContent>
</DropdownMenuSub>
)}
{(tab || otherPanes.length > 0) && <DropdownMenuSeparator />}
<DropdownMenuItem
variant="destructive"
onSelect={() => actions.closePane(pane.id)}
>
{t("splitScreen.closePane")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
}
const PaneView = memo(function PaneView({
pane,
ctx,
}: {
pane: PaneNode;
ctx: PaneContext;
}) {
const tab = pane.tabId ? (ctx.tabsById.get(pane.tabId) ?? null) : null;
const focused = ctx.splitTab.split.focusedPaneId === pane.id;
const { onPaneContentRef, actions } = ctx;
const paneId = pane.id;
const contentRef = useCallback(
(el: HTMLDivElement | null) => onPaneContentRef(paneId, el),
[paneId, onPaneContentRef],
);
const paneRef = useRef<HTMLDivElement>(null);
const focusRef = useRef(actions.focusPane);
focusRef.current = actions.focusPane;
// Native listeners, not React props: a tab's content is a portal that the
// shell moves in here by hand, so React sends its events elsewhere.
useEffect(() => {
const el = paneRef.current;
if (!el) return;
const focus = () => focusRef.current(paneId);
el.addEventListener("pointerdown", focus, true);
el.addEventListener("focusin", focus);
return () => {
el.removeEventListener("pointerdown", focus, true);
el.removeEventListener("focusin", focus);
};
}, [paneId]);
return (
<div
ref={paneRef}
data-split-pane-id={pane.id}
className="relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-background"
>
<PaneHeader pane={pane} tab={tab} focused={focused} ctx={ctx} />
<div className="relative min-h-0 flex-1 overflow-hidden">
{tab ? (
<div ref={contentRef} className="absolute inset-0" />
) : (
ctx.renderEmptyPane(pane.id, ctx.paneIndexById.get(pane.id) ?? 0)
)}
{ctx.resizing && <div className="absolute inset-0 z-10" />}
</div>
{/* Drawn over the content, which would otherwise cover an inset ring. */}
{focused && ctx.paneCount > 1 && (
<div className="pointer-events-none absolute inset-0 z-30 border border-accent-brand/70" />
)}
</div>
);
});
function Divider({
node,
index,
ctx,
}: {
node: SplitNode;
index: number;
ctx: PaneContext;
}) {
const { t } = useTranslation();
const row = node.direction === "row";
const drag = useRef<{
start: number;
total: number;
sizes: number[];
} | null>(null);
function onPointerDown(event: React.PointerEvent<HTMLDivElement>) {
if (event.button !== 0) return;
const parent = event.currentTarget.parentElement?.parentElement;
if (!parent) return;
event.preventDefault();
const rect = parent.getBoundingClientRect();
drag.current = {
start: row ? event.clientX : event.clientY,
total: row ? rect.width : rect.height,
sizes: node.sizes,
};
event.currentTarget.setPointerCapture(event.pointerId);
ctx.setResizing(true);
}
function onPointerMove(event: React.PointerEvent<HTMLDivElement>) {
const state = drag.current;
if (!state || state.total <= 0) return;
const position = row ? event.clientX : event.clientY;
const delta = ((position - state.start) / state.total) * 100;
ctx.actions.resize(node.id, moveDivider(state.sizes, index, delta));
}
function finish() {
if (!drag.current) return;
drag.current = null;
ctx.setResizing(false);
ctx.actions.resizeEnd();
}
return (
<div
className={`relative z-20 shrink-0 bg-border ${row ? "w-px" : "h-px"}`}
>
<div
role="separator"
aria-orientation={row ? "vertical" : "horizontal"}
title={t("splitScreen.dividerHint")}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={finish}
onPointerCancel={finish}
onDoubleClick={() => {
ctx.actions.equalize(node.id);
ctx.actions.resizeEnd();
}}
className={`group absolute flex touch-none items-center justify-center ${
row
? "inset-y-0 -left-1.5 -right-1.5 cursor-col-resize"
: "inset-x-0 -top-1.5 -bottom-1.5 cursor-row-resize"
}`}
>
<div
className={`pointer-events-none bg-transparent transition-colors group-hover:bg-accent-brand/60 ${
row ? "h-full w-0.5" : "h-0.5 w-full"
}`}
/>
</div>
</div>
);
}
function NodeView({ node, ctx }: { node: LayoutNode; ctx: PaneContext }) {
if (node.kind === "pane") return <PaneView pane={node} ctx={ctx} />;
const row = node.direction === "row";
return (
<div
className={`flex size-full min-h-0 min-w-0 ${row ? "flex-row" : "flex-col"}`}
>
{node.children.map((child, index) => (
<React.Fragment key={child.id}>
<div
className="relative min-h-0 min-w-0 overflow-hidden"
style={{ flex: `${node.sizes[index]} 1 0px` }}
>
<NodeView node={child} ctx={ctx} />
</div>
{index < node.children.length - 1 && (
<Divider node={node} index={index} ctx={ctx} />
)}
</React.Fragment>
))}
</div>
);
}
function MobilePaneStrip({ ctx }: { ctx: PaneContext }) {
const { t } = useTranslation();
const panes = listPanes(ctx.splitTab.split.root);
return (
<div className="flex h-9 shrink-0 items-stretch overflow-x-auto border-b border-border bg-sidebar">
{panes.map((pane) => {
const tab = pane.tabId ? ctx.tabsById.get(pane.tabId) : undefined;
const active = ctx.splitTab.split.focusedPaneId === pane.id;
const index = ctx.paneIndexById.get(pane.id) ?? 0;
return (
<button
key={pane.id}
type="button"
onClick={() => ctx.actions.focusPane(pane.id)}
className={`flex min-w-0 max-w-40 shrink-0 items-center gap-1.5 border-r border-border px-3 text-xs ${
active
? "bg-accent-brand/10 text-accent-brand"
: "text-muted-foreground"
}`}
>
<span className="font-mono text-[10px]">{index}</span>
<span className="truncate">
{tab ? tabLabel(tab) : t("splitScreen.emptyTitle")}
</span>
</button>
);
})}
</div>
);
}
/**
* A split tab's panes. Each pane with a tab renders an empty host element;
* the shell moves the tab's own DOM node into it, so switching panes never
* remounts a session.
*/
export function SplitView({
splitTab,
tabs,
isMobile,
actions,
onPaneContentRef,
renderEmptyPane,
}: {
splitTab: SplitTab;
tabs: Tab[];
isMobile: boolean;
actions: SplitViewActions;
onPaneContentRef: (paneId: string, el: HTMLDivElement | null) => void;
renderEmptyPane: (paneId: string, paneIndex: number) => React.ReactNode;
}) {
const [resizing, setResizing] = useState(false);
const focusRef = useRef(actions.focusPane);
focusRef.current = actions.focusPane;
// A click into an iframe (a web page tab) sends no pointer event to this
// document, only a blur on the window. The focused iframe says which pane.
useEffect(() => {
const onBlur = () =>
setTimeout(() => {
const active = document.activeElement;
if (!(active instanceof HTMLIFrameElement)) return;
const pane = active.closest<HTMLElement>("[data-split-pane-id]");
const paneId = pane?.dataset.splitPaneId;
if (paneId) focusRef.current(paneId);
}, 0);
window.addEventListener("blur", onBlur);
return () => window.removeEventListener("blur", onBlur);
}, []);
const panes = listPanes(splitTab.split.root);
const paneIndexById = new Map(panes.map((pane, i) => [pane.id, i + 1]));
const tabsById = new Map(tabs.map((tab) => [tab.id, tab]));
const freeTabs = tabs.filter(
(tab) =>
!tab.parentSplitTabId &&
tab.type !== "dashboard" &&
tab.type !== splitTab.type,
);
const ctx: PaneContext = {
splitTab,
tabsById,
freeTabs,
paneIndexById,
paneCount: panes.length,
isMobile,
resizing,
actions,
onPaneContentRef,
renderEmptyPane,
setResizing,
};
const shown = shownPanes(splitTab.split, isMobile);
const single = shown.length === 1 && panes.length > 1 ? shown[0] : null;
return (
<div
className={`flex size-full min-h-0 flex-col overflow-hidden ${resizing ? "select-none" : ""}`}
data-split-view={splitTab.id}
>
{isMobile && panes.length > 1 && <MobilePaneStrip ctx={ctx} />}
<div className="relative min-h-0 flex-1">
{single ? (
<PaneView key={single.id} pane={single} ctx={ctx} />
) : (
<NodeView node={splitTab.split.root} ctx={ctx} />
)}
</div>
</div>
);
}
+136
View File
@@ -0,0 +1,136 @@
import { useSyncExternalStore } from "react";
import type { DropTarget } from "./split-tree";
/**
* Dragging a tab or a pane onto the main area to split it. The tab bar and
* pane headers start a drag, the drop overlay over the main area answers
* where the pointer is, and the shell's handler acts on the drop.
*/
export type SplitDragSource =
| { kind: "tab"; tabId: string; label: string }
| { kind: "pane"; splitTabId: string; paneId: string; label: string };
export interface SplitDropHover {
/** The pane under the pointer, or null over a view that is not split. */
paneId: string | null;
target: DropTarget;
rect: { left: number; top: number; width: number; height: number };
}
export interface SplitDragState {
source: SplitDragSource;
x: number;
y: number;
hover: SplitDropHover | null;
}
type HitTest = (
x: number,
y: number,
source: SplitDragSource,
) => SplitDropHover | null;
type DropHandler = (source: SplitDragSource, hover: SplitDropHover) => void;
let state: SplitDragState | null = null;
let hitTest: HitTest | null = null;
let dropHandler: DropHandler | null = null;
const listeners = new Set<() => void>();
function emit() {
for (const listener of listeners) listener();
}
export function beginSplitDrag(source: SplitDragSource, x: number, y: number) {
state = { source, x, y, hover: hitTest?.(x, y, source) ?? null };
emit();
}
export function moveSplitDrag(x: number, y: number) {
if (!state) return;
state = { ...state, x, y, hover: hitTest?.(x, y, state.source) ?? null };
emit();
}
/** Ends the drag, dropping it where it is when `commit` is true. */
export function endSplitDrag(commit: boolean) {
const ended = state;
if (!ended) return;
state = null;
emit();
if (commit && ended.hover) dropHandler?.(ended.source, ended.hover);
}
export function isSplitDragging(): boolean {
return state !== null;
}
export function setSplitDropHitTest(next: HitTest): () => void {
hitTest = next;
return () => {
if (hitTest === next) hitTest = null;
};
}
export function setSplitDropHandler(next: DropHandler): () => void {
dropHandler = next;
return () => {
if (dropHandler === next) dropHandler = null;
};
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function useSplitDrag(): SplitDragState | null {
return useSyncExternalStore(
subscribe,
() => state,
() => null,
);
}
/** Share of a pane's width or height, from each edge, that splits on drop. */
const EDGE_SHARE = 0.25;
/** Which zone of a rect a point falls in: an edge band, else the center. */
export function dropTargetAt(
rect: { left: number; top: number; width: number; height: number },
x: number,
y: number,
): DropTarget {
const fx = (x - rect.left) / rect.width;
const fy = (y - rect.top) / rect.height;
const distances: [DropTarget, number][] = [
["left", fx],
["right", 1 - fx],
["top", fy],
["bottom", 1 - fy],
];
const [edge, distance] = distances.reduce((best, entry) =>
entry[1] < best[1] ? entry : best,
);
return distance < EDGE_SHARE ? edge : "center";
}
/** The part of a rect a drop target covers, for drawing the highlight. */
export function dropTargetRect(
rect: { left: number; top: number; width: number; height: number },
target: DropTarget,
): SplitDropHover["rect"] {
const { left, top, width, height } = rect;
switch (target) {
case "left":
return { left, top, width: width / 2, height };
case "right":
return { left: left + width / 2, top, width: width / 2, height };
case "top":
return { left, top, width, height: height / 2 };
case "bottom":
return { left, top: top + height / 2, width, height: height / 2 };
default:
return { left, top, width, height };
}
}
+162
View File
@@ -0,0 +1,162 @@
import {
createPane,
createSplitNode,
createSplitState,
listPanes,
type LayoutNode,
type SplitState,
} from "./split-tree";
/** Starting layouts offered in the layout picker. Any pane can be split further. */
export type SplitPresetId =
| "columns-2"
| "rows-2"
| "columns-3"
| "main-left-3"
| "main-bottom-3"
| "grid-4"
| "grid-5"
| "grid-6";
export interface SplitPreset {
id: SplitPresetId;
titleKey: string;
panes: number;
}
export const SPLIT_PRESETS: SplitPreset[] = [
{ id: "columns-2", titleKey: "splitScreen.presets.columns2", panes: 2 },
{ id: "rows-2", titleKey: "splitScreen.presets.rows2", panes: 2 },
{ id: "columns-3", titleKey: "splitScreen.presets.columns3", panes: 3 },
{ id: "main-left-3", titleKey: "splitScreen.presets.mainLeft3", panes: 3 },
{
id: "main-bottom-3",
titleKey: "splitScreen.presets.mainBottom3",
panes: 3,
},
{ id: "grid-4", titleKey: "splitScreen.presets.grid4", panes: 4 },
{ id: "grid-5", titleKey: "splitScreen.presets.grid5", panes: 5 },
{ id: "grid-6", titleKey: "splitScreen.presets.grid6", panes: 6 },
];
type Sizes = { outer?: number[]; inner?: number[][] };
/**
* Builds a preset's tree, filling panes in reading order from `tabIds`.
* `sizes` lets the legacy mapping keep the user's divider positions.
*/
export function buildPreset(
id: SplitPresetId,
tabIds: (string | null)[] = [],
sizes: Sizes = {},
): LayoutNode {
const p = (index: number) => createPane(tabIds[index] ?? null);
const inner = (index: number) => sizes.inner?.[index];
switch (id) {
case "columns-2":
return createSplitNode("row", [p(0), p(1)], inner(0));
case "rows-2":
return createSplitNode("column", [p(0), p(1)], sizes.outer);
case "columns-3":
return createSplitNode("row", [p(0), p(1), p(2)], inner(0));
case "main-left-3": {
const first = inner(0)?.[0];
return createSplitNode(
"row",
[p(0), createSplitNode("column", [p(1), p(2)], sizes.outer)],
first !== undefined ? [first, 100 - first] : undefined,
);
}
case "main-bottom-3":
return createSplitNode(
"column",
[createSplitNode("row", [p(0), p(1)], inner(0)), p(2)],
sizes.outer,
);
case "grid-4":
return createSplitNode(
"column",
[
createSplitNode("row", [p(0), p(1)], inner(0)),
createSplitNode("row", [p(2), p(3)], inner(1)),
],
sizes.outer,
);
case "grid-5":
return createSplitNode(
"column",
[
createSplitNode("row", [p(0), p(1), p(2)], inner(0)),
createSplitNode("row", [p(3), p(4)], inner(1)),
],
sizes.outer,
);
case "grid-6":
return createSplitNode(
"column",
[
createSplitNode("row", [p(0), p(1), p(2)], inner(0)),
createSplitNode("row", [p(3), p(4), p(5)], inner(1)),
],
sizes.outer,
);
}
}
/**
* Re-lays an existing split out as a preset, keeping its tabs in reading
* order. Tabs past the preset's pane count drop out of the split.
*/
export function applyPreset(state: SplitState, id: SplitPresetId): SplitState {
const tabIds = listPanes(state.root).flatMap((pane) =>
pane.tabId ? [pane.tabId] : [],
);
return createSplitState(buildPreset(id, tabIds));
}
/** Split modes from before the layout tree, still found in storage and old workspaces. */
export type LegacySplitMode =
| "2-way"
| "2-way-horizontal"
| "3-way"
| "3-way-horizontal"
| "4-way"
| "5-way"
| "6-way";
const LEGACY_PRESETS: Record<LegacySplitMode, SplitPresetId> = {
"2-way": "columns-2",
"2-way-horizontal": "rows-2",
"3-way": "main-left-3",
"3-way-horizontal": "main-bottom-3",
"4-way": "grid-4",
"5-way": "grid-5",
"6-way": "grid-6",
};
function validSizes(value: unknown): number[] | undefined {
return Array.isArray(value) &&
value.length > 0 &&
value.every((n) => typeof n === "number" && n > 0)
? value
: undefined;
}
/** Maps an old fixed-mode split onto the tree, keeping sizes where they fit. */
export function fromLegacyConfig(
mode: string,
paneTabIds: (string | null)[],
rowSizes?: unknown,
rowColSizes?: unknown,
): LayoutNode | null {
const presetId = LEGACY_PRESETS[mode as LegacySplitMode];
if (!presetId) return null;
const inner = Array.isArray(rowColSizes)
? rowColSizes.map((row) => validSizes(row) ?? [])
: undefined;
return buildPreset(presetId, paneTabIds, {
outer: validSizes(rowSizes),
inner: inner?.map((row) => (row.length > 0 ? row : undefined)) as
number[][] | undefined,
});
}
+347
View File
@@ -0,0 +1,347 @@
import type { LayoutNode, SplitState, Tab } from "@/types/ui-types";
import {
assignTab,
clearTab,
createSplitState,
findPaneByTab,
focusPane,
listPanes,
mapTabIds,
normalizeState,
tabIdsInSplit,
} from "./split-tree";
import { fromLegacyConfig, type SplitPresetId } from "./split-presets";
/**
* Split tabs as they live in the shell's tab list. A split tab owns its
* layout tree; every tab shown in one of its panes carries parentSplitTabId
* so the tab bar hides it. These keep the two in step.
*/
export const SPLIT_TAB_TYPE = "split-screen";
export type SplitTab = Tab & { split: SplitState };
export function isSplitTab(tab: Tab | undefined | null): tab is SplitTab {
return !!tab && tab.type === SPLIT_TAB_TYPE && !!tab.split;
}
/** Tabs a pane may hold: anything but the dashboard and other splits. */
export function canJoinSplit(tab: Tab | undefined | null): boolean {
return !!tab && tab.type !== "dashboard" && tab.type !== SPLIT_TAB_TYPE;
}
export function splitTabOf(tabs: Tab[], tabId: string): SplitTab | undefined {
const tab = tabs.find((t) => t.id === tabId);
const parentId = tab?.parentSplitTabId;
const parent = parentId ? tabs.find((t) => t.id === parentId) : undefined;
if (isSplitTab(parent) && findPaneByTab(parent.split, tabId)) return parent;
return tabs.find(
(t): t is SplitTab => isSplitTab(t) && !!findPaneByTab(t.split, tabId),
);
}
/**
* Makes parentSplitTabId match the trees. Pane tab ids that no longer exist
* are emptied, and a tab claimed by two splits stays with the first.
*/
export function syncSplitChildren(tabs: Tab[]): Tab[] {
const joinable = new Set(tabs.filter(canJoinSplit).map((tab) => tab.id));
const owner = new Map<string, string>();
let changed = false;
const withSplits = tabs.map((tab) => {
if (!isSplitTab(tab)) return tab;
const split = normalizeState(
tab.split,
(id) => joinable.has(id) && !owner.has(id),
);
for (const id of tabIdsInSplit(split)) owner.set(id, tab.id);
if (split === tab.split) return tab;
changed = true;
return { ...tab, split };
});
const next = withSplits.map((tab) => {
const parent = owner.get(tab.id);
if (parent) {
if (tab.parentSplitTabId === parent) return tab;
changed = true;
return { ...tab, parentSplitTabId: parent };
}
if (tab.parentSplitTabId === undefined) return tab;
changed = true;
const { parentSplitTabId: _released, ...released } = tab;
return released;
});
return changed ? next : tabs;
}
/** Empties the panes holding these tabs in every split but `exceptSplitId`. */
function releaseFromSplits(
tabs: Tab[],
tabIds: string[],
exceptSplitId?: string,
): Tab[] {
if (tabIds.length === 0) return tabs;
return tabs.map((tab) => {
if (!isSplitTab(tab) || tab.id === exceptSplitId) return tab;
let split = tab.split;
for (const id of tabIds) split = clearTab(split, id);
return split === tab.split ? tab : { ...tab, split };
});
}
/**
* Applies `fn` to one split's state. Returning null closes the split and
* sends its tabs back to the tab bar.
*/
export function updateSplit(
tabs: Tab[],
splitTabId: string,
fn: (state: SplitState) => SplitState | null,
): Tab[] {
const target = tabs.find((tab) => tab.id === splitTabId);
if (!isSplitTab(target)) return tabs;
const next = fn(target.split);
if (next === target.split) return tabs;
if (!next) return closeSplitTab(tabs, splitTabId);
const claimed = tabIdsInSplit(next);
const released = releaseFromSplits(tabs, claimed, splitTabId);
return syncSplitChildren(
released.map((tab) =>
tab.id === splitTabId ? { ...tab, split: next } : tab,
),
);
}
export function makeSplitTab(
instanceId: string,
label: string,
split: SplitState,
openedAt = Date.now(),
): SplitTab {
return {
id: `split-${instanceId}`,
instanceId,
type: SPLIT_TAB_TYPE,
label,
openedAt,
split,
};
}
/** Adds a split tab, taking its tabs out of any other split. */
export function addSplitTab(tabs: Tab[], splitTab: SplitTab): Tab[] {
const released = releaseFromSplits(tabs, tabIdsInSplit(splitTab.split));
return syncSplitChildren([...released, splitTab]);
}
/** Removes a split tab. Its tabs go back to the tab bar. */
export function closeSplitTab(tabs: Tab[], splitTabId: string): Tab[] {
return syncSplitChildren(tabs.filter((tab) => tab.id !== splitTabId));
}
/**
* Removes a closed tab. A pane that held it stays, empty and focused, so the
* next thing the user opens can go straight into it.
*/
export function removeTab(tabs: Tab[], tabId: string): Tab[] {
const without = tabs
.filter((tab) => tab.id !== tabId)
.map((tab) => {
if (!isSplitTab(tab)) return tab;
const pane = findPaneByTab(tab.split, tabId);
if (!pane) return tab;
return {
...tab,
split: focusPane(clearTab(tab.split, tabId), pane.id),
};
});
return syncSplitChildren(without);
}
/** Puts a tab in a pane of a split and focuses that pane. */
export function placeTabInPane(
tabs: Tab[],
splitTabId: string,
paneId: string,
tabId: string,
): Tab[] {
if (!canJoinSplit(tabs.find((tab) => tab.id === tabId))) return tabs;
return updateSplit(tabs, splitTabId, (state) =>
focusPane(assignTab(state, paneId, tabId), paneId),
);
}
/** What the tab bar asks the shell to do with splits. */
export type TabSplitAction =
| { kind: "split"; tabId: string; edge: "right" | "bottom" }
| { kind: "addToPane"; tabId: string; splitTabId: string; paneId: string }
| {
kind: "addPane";
tabId: string;
splitTabId: string;
edge: "right" | "bottom";
}
| { kind: "unsplit"; splitTabId: string }
| { kind: "splitActive"; edge: "right" | "bottom" }
| { kind: "preset"; presetId: SplitPresetId };
/** The lowest N not already used by a "Split N" style label. */
export function nextSplitNumber(
tabs: Tab[],
labelFor: (n: number) => string,
): number {
const used = new Set(
tabs.filter((tab) => tab.type === SPLIT_TAB_TYPE).map((tab) => tab.label),
);
let n = 1;
while (used.has(labelFor(n))) n += 1;
return n;
}
export interface SplitPaneSummary {
id: string;
/** 1-based, in reading order. */
index: number;
tabId: string | null;
/** The tab's label, or null for an empty pane. */
label: string | null;
}
export interface SplitSummary {
id: string;
label: string;
panes: SplitPaneSummary[];
full: boolean;
}
export function summarizeSplits(tabs: Tab[], maxPanes: number): SplitSummary[] {
const byId = new Map(tabs.map((tab) => [tab.id, tab]));
return tabs.filter(isSplitTab).map((tab) => {
const panes = listPanes(tab.split.root);
return {
id: tab.id,
label: tab.label,
panes: panes.map((pane, i) => {
const inPane = pane.tabId ? byId.get(pane.tabId) : undefined;
return {
id: pane.id,
index: i + 1,
tabId: pane.tabId,
label: inPane ? inPane.customLabel || inPane.label : null,
};
}),
full: panes.length >= maxPanes,
};
});
}
// ─── Persistence ──────────────────────────────────────────────────────────────
/** Saved in localStorage; pane tab ids are tab instanceIds, which survive a reload. */
export type PersistedSplitTab = {
version: 2;
instanceId: string;
label: string;
root: LayoutNode;
focusedPaneId: string;
};
/** The shape saved before the layout tree. */
type LegacyPersistedSplitTab = {
instanceId: string;
label: string;
mode: string;
paneInstanceIds: (string | null)[];
rowSizes?: number[];
rowColSizes?: number[][];
};
export function serializeSplitTabs(tabs: Tab[]): PersistedSplitTab[] {
const instanceIdById = new Map(tabs.map((tab) => [tab.id, tab.instanceId]));
return tabs.filter(isSplitTab).map((tab) => ({
version: 2,
instanceId: tab.instanceId,
label: tab.label,
root: mapTabIds(tab.split.root, (id) => instanceIdById.get(id) ?? null),
focusedPaneId: tab.split.focusedPaneId,
}));
}
function isLayoutNode(value: unknown): value is LayoutNode {
if (!value || typeof value !== "object") return false;
const node = value as Partial<LayoutNode>;
if (node.kind === "pane") return typeof node.id === "string";
if (node.kind === "split") {
return (
typeof node.id === "string" &&
(node.direction === "row" || node.direction === "column") &&
Array.isArray(node.children) &&
node.children.length > 0 &&
Array.isArray(node.sizes) &&
node.children.every(isLayoutNode)
);
}
return false;
}
/**
* Rebuilds a saved split's tree with live tab ids. `resolve` maps whatever
* the save used (instanceIds, workspace slotIds) to a live tab id. Null when
* the entry is unreadable or none of its tabs came back.
*/
export function restoreSplitState(
entry: unknown,
resolve: (savedId: string) => string | null,
): SplitState | null {
if (!entry || typeof entry !== "object") return null;
const saved = entry as Partial<PersistedSplitTab> &
Partial<LegacyPersistedSplitTab>;
let root: LayoutNode | null = null;
let focusedPaneId: string | undefined;
if (isLayoutNode(saved.root)) {
root = mapTabIds(saved.root, resolve);
focusedPaneId = saved.focusedPaneId;
} else if (
typeof saved.mode === "string" &&
Array.isArray(saved.paneInstanceIds)
) {
root = fromLegacyConfig(
saved.mode,
saved.paneInstanceIds.map((id) => (id ? resolve(id) : null)),
saved.rowSizes,
saved.rowColSizes,
);
}
if (!root) return null;
const state = normalizeState(createSplitState(root, focusedPaneId));
return tabIdsInSplit(state).length > 0 ? state : null;
}
export function restoreSplitTabs(
persisted: unknown[],
tabs: Tab[],
openedAt = Date.now(),
): Tab[] {
const tabIdByInstanceId = new Map(
tabs.map((tab) => [tab.instanceId, tab.id]),
);
let next = tabs;
for (const entry of persisted) {
const saved = entry as { instanceId?: unknown; label?: unknown };
if (typeof saved?.instanceId !== "string") continue;
const instanceId = saved.instanceId;
if (next.some((tab) => tab.instanceId === instanceId)) continue;
const split = restoreSplitState(
entry,
(id) => tabIdByInstanceId.get(id) ?? null,
);
if (!split) continue;
const label = typeof saved.label === "string" ? saved.label : "";
next = addSplitTab(next, makeSplitTab(instanceId, label, split, openedAt));
}
return next;
}
+65
View File
@@ -0,0 +1,65 @@
import { useSyncExternalStore } from "react";
import type { SplitSummary } from "./split-tabs";
/**
* Lets menus outside the shell (the host list) offer "Open in split" without
* threading split state through every sidebar component. The shell publishes
* its splits here and registers how to aim the next opened tab at a pane.
*/
export type SplitOpenTarget =
| { kind: "pane"; splitTabId: string; paneId: string }
| { kind: "newPane"; splitTabId: string }
/** A new split holding the active tab and the opened one. */
| { kind: "newSplit" };
export interface SplitTargetsSnapshot {
splits: SplitSummary[];
/** The active tab can start a new split. */
canStartSplit: boolean;
}
type Opener = (target: SplitOpenTarget, open: () => void) => void;
const EMPTY: SplitTargetsSnapshot = { splits: [], canStartSplit: false };
let snapshot: SplitTargetsSnapshot = EMPTY;
let snapshotKey = "";
let opener: Opener | null = null;
const listeners = new Set<() => void>();
export function publishSplitTargets(next: SplitTargetsSnapshot) {
const key = JSON.stringify(next);
if (key === snapshotKey) return;
snapshotKey = key;
snapshot = next;
for (const listener of listeners) listener();
}
export function setSplitOpener(next: Opener): () => void {
opener = next;
return () => {
if (opener === next) {
opener = null;
publishSplitTargets(EMPTY);
}
};
}
/** Runs `open` so whatever tab it opens lands in `target`. */
export function openInSplit(target: SplitOpenTarget, open: () => void) {
if (opener) opener(target, open);
else open();
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function useSplitTargets(): SplitTargetsSnapshot {
return useSyncExternalStore(
subscribe,
() => snapshot,
() => EMPTY,
);
}
+571
View File
@@ -0,0 +1,571 @@
import { createId } from "@/lib/create-id";
import type {
LayoutNode,
PaneNode,
SplitDirection,
SplitNode,
SplitState,
} from "@/types/ui-types";
/**
* The layout of one split tab: a tree where every leaf is a pane holding at
* most one tab, and every inner node lays its children out in a row (side by
* side) or a column (stacked). All functions here are pure and return a new
* state, so the shell can keep the whole thing on the split tab itself.
*/
export const MAX_PANES = 8;
/** Smallest share of its parent a pane or group can be dragged down to. */
export const MIN_PANE_SIZE = 10;
export type {
SplitDirection,
PaneNode,
SplitNode,
LayoutNode,
SplitState,
} from "@/types/ui-types";
export type PaneEdge = "left" | "right" | "top" | "bottom";
export type DropTarget = PaneEdge | "center";
export type NavDirection = "left" | "right" | "up" | "down";
export interface PaneRect {
left: number;
top: number;
right: number;
bottom: number;
}
export function createPane(tabId: string | null = null): PaneNode {
return { kind: "pane", id: createId(), tabId };
}
export function evenSizes(count: number): number[] {
return Array.from({ length: count }, () => 100 / count);
}
export function createSplitNode(
direction: SplitDirection,
children: LayoutNode[],
sizes?: number[],
): SplitNode {
return {
kind: "split",
id: createId(),
direction,
children,
sizes:
sizes && sizes.length === children.length
? scaleTo100(sizes)
: evenSizes(children.length),
};
}
export function createSplitState(
root: LayoutNode,
focusedPaneId?: string,
): SplitState {
const panes = listPanes(root);
const focused =
panes.find((pane) => pane.id === focusedPaneId) ??
panes.find((pane) => pane.tabId === null) ??
panes[0];
return { root, focusedPaneId: focused.id, zoomedPaneId: null };
}
export function listPanes(node: LayoutNode): PaneNode[] {
if (node.kind === "pane") return [node];
return node.children.flatMap(listPanes);
}
export function paneCount(state: SplitState): number {
return listPanes(state.root).length;
}
export function findPane(
state: SplitState,
paneId: string,
): PaneNode | undefined {
return listPanes(state.root).find((pane) => pane.id === paneId);
}
export function findPaneByTab(
state: SplitState,
tabId: string,
): PaneNode | undefined {
return listPanes(state.root).find((pane) => pane.tabId === tabId);
}
export function emptyPanes(state: SplitState): PaneNode[] {
return listPanes(state.root).filter((pane) => pane.tabId === null);
}
export function tabIdsInSplit(state: SplitState): string[] {
return listPanes(state.root).flatMap((pane) =>
pane.tabId ? [pane.tabId] : [],
);
}
/**
* The panes on screen: just the zoomed one, just the focused one when only
* one fits (mobile), else all of them.
*/
export function shownPanes(state: SplitState, onePaneOnly = false): PaneNode[] {
const panes = listPanes(state.root);
const single =
state.zoomedPaneId ?? (onePaneOnly ? state.focusedPaneId : null);
const pane = single ? panes.find((p) => p.id === single) : undefined;
return pane ? [pane] : panes;
}
export function canAddPane(state: SplitState): boolean {
return paneCount(state) < MAX_PANES;
}
function edgeDirection(edge: PaneEdge): SplitDirection {
return edge === "left" || edge === "right" ? "row" : "column";
}
function isLeadingEdge(edge: PaneEdge): boolean {
return edge === "left" || edge === "top";
}
function scaleTo100(sizes: number[]): number[] {
const total = sizes.reduce((sum, size) => sum + size, 0);
if (!(total > 0)) return evenSizes(sizes.length);
return sizes.map((size) => (size / total) * 100);
}
function mapPanes(
node: LayoutNode,
fn: (pane: PaneNode) => PaneNode,
): LayoutNode {
if (node.kind === "pane") return fn(node);
let changed = false;
const children = node.children.map((child) => {
const next = mapPanes(child, fn);
if (next !== child) changed = true;
return next;
});
return changed ? { ...node, children } : node;
}
function mapSplit(
node: LayoutNode,
splitId: string,
fn: (split: SplitNode) => SplitNode,
): LayoutNode {
if (node.kind === "pane") return node;
if (node.id === splitId) return fn(node);
let changed = false;
const children = node.children.map((child) => {
const next = mapSplit(child, splitId, fn);
if (next !== child) changed = true;
return next;
});
return changed ? { ...node, children } : node;
}
/**
* Collapses groups with one child, inlines a child group running the same
* way as its parent, and rescales sizes. Keeps the tree in the one shape the
* rest of the code expects after any edit.
*/
export function normalizeNode(node: LayoutNode): LayoutNode {
if (node.kind === "pane") return node;
const children: LayoutNode[] = [];
const sizes: number[] = [];
const baseSizes =
node.sizes.length === node.children.length
? node.sizes
: evenSizes(node.children.length);
let changed = baseSizes !== node.sizes;
node.children.forEach((raw, index) => {
const child = normalizeNode(raw);
if (child !== raw) changed = true;
const size = baseSizes[index] ?? 0;
if (child.kind === "split" && child.direction === node.direction) {
changed = true;
child.children.forEach((grandchild, i) => {
children.push(grandchild);
sizes.push((size * child.sizes[i]) / 100);
});
} else {
children.push(child);
sizes.push(size);
}
});
if (children.length === 1) return children[0];
const total = sizes.reduce((sum, size) => sum + size, 0);
if (!changed && Math.abs(total - 100) < 0.01) return node;
return { ...node, children, sizes: scaleTo100(sizes) };
}
function insertBeside(
node: LayoutNode,
paneId: string,
edge: PaneEdge,
newPane: PaneNode,
): LayoutNode {
const direction = edgeDirection(edge);
if (node.kind === "pane") {
if (node.id !== paneId) return node;
return createSplitNode(
direction,
isLeadingEdge(edge) ? [newPane, node] : [node, newPane],
);
}
const index = node.children.findIndex(
(child) => child.kind === "pane" && child.id === paneId,
);
if (index !== -1 && node.direction === direction) {
const children = [...node.children];
const sizes = [...node.sizes];
const half = sizes[index] / 2;
const insertAt = isLeadingEdge(edge) ? index : index + 1;
sizes[index] = half;
children.splice(insertAt, 0, newPane);
sizes.splice(insertAt, 0, half);
return { ...node, children, sizes };
}
let changed = false;
const children = node.children.map((child) => {
const next = insertBeside(child, paneId, edge, newPane);
if (next !== child) changed = true;
return next;
});
return changed ? { ...node, children } : node;
}
/** Removes `tabId` from every pane except `keepPaneId`: a tab lives in one pane. */
function releaseTabElsewhere(
node: LayoutNode,
tabId: string,
keepPaneId: string,
): LayoutNode {
return mapPanes(node, (pane) =>
pane.tabId === tabId && pane.id !== keepPaneId
? { ...pane, tabId: null }
: pane,
);
}
/**
* Adds a pane next to `paneId`, holding `tabId` or empty. Null when the pane
* does not exist or the split is full.
*/
export function splitPane(
state: SplitState,
paneId: string,
edge: PaneEdge,
tabId: string | null = null,
): { state: SplitState; paneId: string } | null {
if (!findPane(state, paneId) || !canAddPane(state)) return null;
const newPane = createPane(tabId);
let root = insertBeside(state.root, paneId, edge, newPane);
if (tabId) root = releaseTabElsewhere(root, tabId, newPane.id);
return {
state: {
...state,
root: normalizeNode(root),
focusedPaneId: newPane.id,
zoomedPaneId: null,
},
paneId: newPane.id,
};
}
/** Adds a pane along one outer edge of the whole split. */
export function addPaneAtEdge(
state: SplitState,
edge: PaneEdge,
tabId: string | null = null,
): { state: SplitState; paneId: string } | null {
if (!canAddPane(state)) return null;
const direction = edgeDirection(edge);
const newPane = createPane(tabId);
const leading = isLeadingEdge(edge);
let root: LayoutNode;
if (state.root.kind === "split" && state.root.direction === direction) {
const count = state.root.children.length;
const share = 100 / (count + 1);
const scaled = state.root.sizes.map((size) => (size * count) / (count + 1));
root = {
...state.root,
children: leading
? [newPane, ...state.root.children]
: [...state.root.children, newPane],
sizes: leading ? [share, ...scaled] : [...scaled, share],
};
} else {
root = createSplitNode(
direction,
leading ? [newPane, state.root] : [state.root, newPane],
);
}
if (tabId) root = releaseTabElsewhere(root, tabId, newPane.id);
return {
state: {
...state,
root: normalizeNode(root),
focusedPaneId: newPane.id,
zoomedPaneId: null,
},
paneId: newPane.id,
};
}
function withoutPane(node: LayoutNode, paneId: string): LayoutNode | null {
if (node.kind === "pane") return node.id === paneId ? null : node;
const children: LayoutNode[] = [];
const sizes: number[] = [];
let changed = false;
node.children.forEach((child, index) => {
const next = withoutPane(child, paneId);
if (next !== child) changed = true;
if (next) {
children.push(next);
sizes.push(node.sizes[index]);
}
});
if (!changed) return node;
if (children.length === 0) return null;
return { ...node, children, sizes };
}
/** Removes a pane. Null when it was the last one, so the split should close. */
export function removePane(
state: SplitState,
paneId: string,
): SplitState | null {
const before = listPanes(state.root);
const index = before.findIndex((pane) => pane.id === paneId);
if (index === -1) return state;
const raw = withoutPane(state.root, paneId);
if (!raw) return null;
const root = normalizeNode(raw);
const after = listPanes(root);
const focusedPaneId =
state.focusedPaneId !== paneId &&
after.some((pane) => pane.id === state.focusedPaneId)
? state.focusedPaneId
: after[Math.max(0, index - 1)].id;
return {
root,
focusedPaneId,
zoomedPaneId: state.zoomedPaneId === paneId ? null : state.zoomedPaneId,
};
}
/** Puts a tab in a pane (or empties it with null), moving it out of any other pane. */
export function assignTab(
state: SplitState,
paneId: string,
tabId: string | null,
): SplitState {
if (!findPane(state, paneId)) return state;
const root = mapPanes(state.root, (pane) => {
if (pane.id === paneId)
return pane.tabId === tabId ? pane : { ...pane, tabId };
if (tabId && pane.tabId === tabId) return { ...pane, tabId: null };
return pane;
});
return root === state.root ? state : { ...state, root };
}
/** Empties whichever pane holds the tab, leaving the pane in place. */
export function clearTab(state: SplitState, tabId: string): SplitState {
const root = mapPanes(state.root, (pane) =>
pane.tabId === tabId ? { ...pane, tabId: null } : pane,
);
return root === state.root ? state : { ...state, root };
}
export function swapPanes(
state: SplitState,
firstId: string,
secondId: string,
): SplitState {
const first = findPane(state, firstId);
const second = findPane(state, secondId);
if (!first || !second || firstId === secondId) return state;
const root = mapPanes(state.root, (pane) => {
if (pane.id === firstId) return { ...pane, tabId: second.tabId };
if (pane.id === secondId) return { ...pane, tabId: first.tabId };
return pane;
});
return { ...state, root };
}
/**
* Drops one pane onto another: the center swaps their contents, an edge
* moves the dragged pane to that side of the target.
*/
export function movePane(
state: SplitState,
fromId: string,
toId: string,
target: DropTarget,
): SplitState {
if (fromId === toId) return state;
const from = findPane(state, fromId);
if (!from || !findPane(state, toId)) return state;
if (target === "center") {
return { ...swapPanes(state, fromId, toId), focusedPaneId: toId };
}
const removed = removePane(state, fromId);
if (!removed) return state;
const moved = splitPane(removed, toId, target, from.tabId);
return moved ? moved.state : state;
}
export function focusPane(state: SplitState, paneId: string): SplitState {
if (state.focusedPaneId === paneId || !findPane(state, paneId)) return state;
return {
...state,
focusedPaneId: paneId,
// Moving focus out of a zoomed pane would leave the user looking at a
// pane they are not typing into.
zoomedPaneId: state.zoomedPaneId ? paneId : state.zoomedPaneId,
};
}
export function toggleZoom(state: SplitState, paneId: string): SplitState {
if (!findPane(state, paneId)) return state;
const zoomed = state.zoomedPaneId === paneId;
return {
...state,
focusedPaneId: paneId,
zoomedPaneId: zoomed ? null : paneId,
};
}
export function resizeSplit(
state: SplitState,
splitId: string,
sizes: number[],
): SplitState {
const root = mapSplit(state.root, splitId, (split) =>
sizes.length === split.children.length
? { ...split, sizes: scaleTo100(sizes) }
: split,
);
return root === state.root ? state : { ...state, root };
}
export function equalizeSplit(state: SplitState, splitId: string): SplitState {
const root = mapSplit(state.root, splitId, (split) => ({
...split,
sizes: evenSizes(split.children.length),
}));
return root === state.root ? state : { ...state, root };
}
/**
* Moves the divider between children `index` and `index + 1` by `delta`
* percent, keeping both above MIN_PANE_SIZE.
*/
export function moveDivider(
sizes: number[],
index: number,
delta: number,
): number[] {
const a = sizes[index];
const b = sizes[index + 1];
if (a === undefined || b === undefined) return sizes;
const nextA = Math.max(
MIN_PANE_SIZE,
Math.min(a + b - MIN_PANE_SIZE, a + delta),
);
const next = [...sizes];
next[index] = nextA;
next[index + 1] = a + b - nextA;
return next;
}
/**
* Repairs a state read from storage or left over after tabs closed: drops
* tab ids that no longer exist, keeps each tab in one pane, fixes focus.
*/
export function normalizeState(
state: SplitState,
isLiveTab: (tabId: string) => boolean = () => true,
): SplitState {
const seen = new Set<string>();
const root = normalizeNode(
mapPanes(state.root, (pane) => {
if (!pane.tabId) return pane;
if (!isLiveTab(pane.tabId) || seen.has(pane.tabId)) {
return { ...pane, tabId: null };
}
seen.add(pane.tabId);
return pane;
}),
);
const panes = listPanes(root);
const focusedPaneId = panes.some((pane) => pane.id === state.focusedPaneId)
? state.focusedPaneId
: panes[0].id;
const zoomedPaneId = panes.some((pane) => pane.id === state.zoomedPaneId)
? (state.zoomedPaneId ?? null)
: null;
if (
root === state.root &&
focusedPaneId === state.focusedPaneId &&
zoomedPaneId === (state.zoomedPaneId ?? null)
) {
return state;
}
return { root, focusedPaneId, zoomedPaneId };
}
/** Rewrites every pane's tab id, e.g. live ids to saved instance ids and back. */
export function mapTabIds(
node: LayoutNode,
fn: (tabId: string) => string | null,
): LayoutNode {
return mapPanes(node, (pane) =>
pane.tabId ? { ...pane, tabId: fn(pane.tabId) } : pane,
);
}
/**
* The pane next to `paneId` in a direction, by on-screen position. Picks the
* closest pane that overlaps along the other axis, then the one with the
* most overlap, so it works for any tree shape.
*/
export function neighborPane(
paneId: string,
direction: NavDirection,
rects: Record<string, PaneRect>,
): string | null {
const from = rects[paneId];
if (!from) return null;
let best: { id: string; distance: number; overlap: number } | null = null;
for (const [id, rect] of Object.entries(rects)) {
if (id === paneId) continue;
let distance: number;
let overlap: number;
if (direction === "left" || direction === "right") {
distance =
direction === "right" ? rect.left - from.right : from.left - rect.right;
overlap =
Math.min(rect.bottom, from.bottom) - Math.max(rect.top, from.top);
} else {
distance =
direction === "down" ? rect.top - from.bottom : from.top - rect.bottom;
overlap =
Math.min(rect.right, from.right) - Math.max(rect.left, from.left);
}
// A pixel of slack for the dividers and sub-pixel layout.
if (distance < -2 || overlap <= 0) continue;
if (
!best ||
distance < best.distance - 1 ||
(Math.abs(distance - best.distance) <= 1 && overlap > best.overlap)
) {
best = { id, distance, overlap };
}
}
return best?.id ?? null;
}