/** * Client half of dsh-better-sidebar: resolves the user's "Side card" * preferences through the plugin's own fenced settings route, mounts the * right sidebar portal (inside an error boundary so a rendering failure * shows an error strip instead of a blank panel), registers the turn-tail * interception, and contributes the Side card settings section to the DSH * Settings shell. Requires the runtime's slots and sessions services; the * bundle itself is a module-table consumer only (react + ui-primitives + * xterm, all provided or inlined). */ import { createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import type { Context } from '../context-types.ts' import { allLeaves, createSidebarStore, isAgentTabId } from './state.ts' import { createBetterSidebarService, matchUrlTarget } from './service.ts' import { revalidateChunksOnReactivate, setChunkModuleSystem } from './chunk-loader.ts' import { registerBuiltins } from './builtins/index.ts' import { Sidebar } from './Sidebar.tsx' import { RenderBoundary } from './RenderBoundary.tsx' import { registerOpenPathInterception, registerTurnTailInterception } from './intercept.tsx' import { registerLinkInterception } from './link-intercept.ts' import { registerImeGuard } from './ime-guard.ts' import { registerSettingsNavIcon } from './settings-nav-icon.ts' import { loadExternalDisable, loadPrefs } from './prefs.ts' import { SideCardSection } from './SideCardSection.tsx' import { api } from './api.ts' import { LOCALE_NS, attachLocale, t, zh, en } from './locales.ts' import css from './sidebar.module.css' import './layout.css' /** Services required before mounting (provided by the client runtime; the * locale service backs the sidebar's copy — see locales.ts). `modules` * (rc.8+) is the client module system the chunk loader resolves its * externals through — Cordis guards service access without inject. */ export const inject = ['slots', 'sessions', 'connection', 'workspaces', 'locale', 'modules'] /** * Error boundary over the sidebar tree (root scope): a render error in the * sidebar SHELL itself must never blank the page silently — the shared * RenderBoundary shows a dismissible error strip and logs the stack. The * per-tab scope (Sidebar.tsx) catches viewer/editor crashes first; this root * boundary stays as the last resort for Workbench/shell errors. */ /** * Client plugin body. * @param ctx - the client cordis context (slots, sessions). */ export function apply(ctx: Context): void { // The sidebar follows the DSH i18n system: attach the locale service so // the module-level t()/isZh() resolve the Host-backed language preference // (and switch live — the Sidebar root subscribes to it), and register the // plugin's dictionaries into the shared locale registry. The disposers // run on fiber disposal, so re-activation (HMR) re-registers cleanly. attachLocale(ctx.locale) ctx.effect(() => { const offZh = ctx.locale.register(LOCALE_NS, 'zh', zh) const offEn = ctx.locale.register(LOCALE_NS, 'en', en) return () => { offZh(); offEn() } }, 'dsh-better-sidebar: dictionaries') // One store instance per activation: production code creates it only here, // then hands it to the mounted panel and closes over it in the slot // registrations (the official createXXXStore() factory rule — no // module-level singleton). const sidebarStore = createSidebarStore() // The sidebar registry service: external plugins register tab types and // file previewers through `ctx.betterSidebar.registerTab/registerFileViewer`. // Published before the panel mounts so consumers injecting 'betterSidebar' // are ready by the time the sidebar renders. const service = createBetterSidebarService(sidebarStore) ctx.provide('betterSidebar', service) // Terminal tab titles use the host's effective shell name (e.g. bash/zsh) // instead of "Terminal 1". Start with a safe fallback and replace it as // soon as the host shell info resolves. Tabs created before the response // arrives keep the fallback title, so also retitle any already-open UI // terminal tabs that still carry it. const fallbackTitle = t('terminal') let terminalTitle = fallbackTitle void api.shellGet().then(({ name }) => { terminalTitle = name const snapshot = service.getSnapshot() if (snapshot.state === undefined) return const tabs = allLeaves(snapshot.state.splits) .concat(allLeaves(snapshot.state.bottomSplits)) .flatMap(leaf => leaf.tabs) for (const tab of tabs) { if (tab.type === 'terminal' && !isAgentTabId(tab.id) && tab.title === fallbackTitle) { service.updateTab(tab.id, { title: name }) } } }).catch(() => { /* keep fallback */ }) // Register the plugin's own built-in tabs and viewers through the same // service (eating our own dogfood). The disposer unregisters them on // fiber disposal (HMR-safe). ctx.effect( () => registerBuiltins(ctx, service, { terminalTitle: () => terminalTitle }), 'dsh-better-sidebar: register built-in tabs and viewers', ) // A failure anywhere in the client lifecycle must never take the app down // silently: log with the plugin prefix and pin a visible diagnostic strip // to the page so a blank panel is never the only symptom. const fail = (phase: string, error: unknown): void => { console.error(`[dsh-better-sidebar] ${phase} error:`, error) try { const bar = document.createElement('div') bar.style.cssText = 'position:fixed;left:8px;bottom:8px;z-index:2147483000;max-width:70vw;padding:8px 12px;' + 'font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#f2a1a1;background:#1b1b22;' + 'border:1px solid #f2a1a1;border-radius:8px;white-space:pre-wrap' bar.textContent = `[dsh-better-sidebar] ${phase} error: ${error instanceof Error ? error.message : String(error)}` document.body.appendChild(bar) } catch { // Nothing left to report with. } } try { // rc.8+ exposes the client module system as the `ctx.modules` service // (no window.__DSH_MODULES__ page global anymore); the chunk loader needs // it to resolve its externals, so inject it before anything can load a // lazy chunk. The loader falls back to the rc.7 global when absent. setChunkModuleSystem(ctx.modules) // Fresh chunk state for this activation: drop per-test fixtures and // revalidate loaded chunk scripts against the bundle route's ETags — // unchanged chunks keep their resolved exports (no re-inject / // re-execute on HMR), changed ones are dropped for a clean re-fetch. void revalidateChunksOnReactivate() ctx.effect(() => { let disposed = false let root: Root | undefined let host: HTMLDivElement | undefined let mounted = false let bodyObserver: MutationObserver | undefined let hostCheckFrame: number | null = null const unmount = (): void => { if (!mounted) return mounted = false bodyObserver?.disconnect() bodyObserver = undefined if (hostCheckFrame !== null) { cancelAnimationFrame(hostCheckFrame) hostCheckFrame = null } root?.unmount() root = undefined host?.remove() host = undefined } /** Re-attach the host if the page (a desktop shell wrapper, SPA * navigation, …) ever removes it from
. Cheap: childList only, * no subtree, no attribute filtering. */ const guardAnchor = (): void => { if (bodyObserver !== undefined) return bodyObserver = new MutationObserver(() => { if (host !== undefined && !document.body.contains(host)) { document.body.appendChild(host) } }) bodyObserver.observe(document.body, { childList: true }) } /** One-shot geometry self-check: if the host page transforms * / itself (exotic shells), a fixed panel host would * track the transformed box instead of the viewport. Flip the * degraded mode and pin the host to the viewport every frame until * the ancestor transform is actually gone. The normal path (no * page-level transform) never runs the sync loop. */ const scheduleHostCheck = (): void => { hostCheckFrame ??= requestAnimationFrame(() => { hostCheckFrame = null const layer = host?.querySelector