// src/layout/hooks/usePanelActiveLeaf.ts import { useState, useEffect } from 'react' import type { WorkspaceLeaf, PanelSide } from '../../plugin/workspace' import type { App } from '../../plugin/app' /** * React hook that subscribes to the App's per-panel active leaf events. * * Returns the current active leaf for the given panel side, re-rendering * when workspace.setActivePanelLeaf() fires 'panel-leaf-change' on app.reamsEvents. * * The Workspace is the single source of truth — this hook only reads. */ export function usePanelActiveLeaf( app: App, side: PanelSide, ): WorkspaceLeaf | null { const workspace = app.workspace const [activeLeaf, setActiveLeaf] = useState( () => side === 'left' ? workspace.activeLeftLeaf : workspace.activeRightLeaf ) useEffect(() => { // Sync on mount in case state changed between initial render and effect const current = side === 'left' ? workspace.activeLeftLeaf : workspace.activeRightLeaf setActiveLeaf(current) const ref = app.reamsEvents.on('panel-leaf-change', (eventSide, leaf) => { if (eventSide === side) { setActiveLeaf(leaf) } }) return () => { app.reamsEvents.offref(ref) } }, [app, workspace, side]) return activeLeaf }