dsh-brain/src-client/panel/register.ts

85 lines
3.1 KiB
TypeScript

// Adapted from dsh-mnemon native-sidebar.tsx (MIT), see vendor/dsh-mnemon/LICENSE.
// Registers the Brain panel on the two native shell seats:
// sidebar.panellist -> the left-rail row (glyph only)
// main -> the centre panel mounted while selected
// Both are lazy seats: when the shell does not provide them the inject callback
// simply never runs and the settings card fallback stays in place.
import * as React from 'react'
import { BrainIcon } from './brain-icon'
import { BrainPanel } from './BrainPanel'
export const PANEL_ID = 'dsh-brain'
export const PANEL_ORDER = 30
interface LayoutPanelInfo {
getSnapshot(): { activePanelId: string | null }
subscribe(listener: () => void): () => void
}
export interface BrainPanelSeatFace {
panelId: string
ctx: any
usePanelInfo?: <T>(selector: (info: { activePanelId: string | null }) => T) => T
}
function makeUsePanelInfo(ctx: any, panelId: string): (<T>(selector: (info: { activePanelId: string | null }) => T) => T) {
return function usePanelInfo<T>(selector: (info: { activePanelId: string | null }) => T): T {
const panelInfo = ctx?.layout?.panelInfo as LayoutPanelInfo | undefined
const read = (): T => selector(panelInfo === undefined ? { activePanelId: panelId } : panelInfo.getSnapshot())
const [value, setValue] = React.useState<T>(read)
React.useEffect(() => {
if (panelInfo === undefined) return
const update = (): void => setValue(read())
update()
return panelInfo.subscribe(update)
}, [panelInfo, panelId])
return value
}
}
export function registerBrainPanel(ctx: any): () => void {
let stopNative: (() => void) | undefined
let disposed = false
try {
stopNative = ctx.slots.inject('main', () =>
ctx.slots.inject('sidebar.panellist', () => {
const usePanelInfo = makeUsePanelInfo(ctx, PANEL_ID)
const panel = (props: any) => React.createElement(BrainPanel, { ...props, ctx, panelId: PANEL_ID, usePanelInfo })
const icon = (props: any) => React.createElement(BrainIcon, { size: props?.size ?? 18 })
const stopMain = ctx.slots.register({ name: 'main', key: PANEL_ID, inject: () => ({ panelId: PANEL_ID }) }, panel as never)
let stopIcon: (() => void) | undefined
try {
stopIcon = ctx.slots.register({
name: 'sidebar.panellist',
id: PANEL_ID,
order: PANEL_ORDER,
label: () => 'Brain',
locale: 'dsh-brain',
}, icon as never)
} catch (failure) {
stopMain?.()
throw failure
}
return () => {
stopIcon?.()
stopMain?.()
}
}),
)
} catch (failure) {
if (typeof console !== 'undefined') {
console.info('[dsh-brain] sidebar panel seats unavailable; the settings card fallback stays active: ' + (failure instanceof Error ? failure.message : String(failure)))
}
}
return () => {
if (disposed) return
disposed = true
try {
stopNative?.()
} catch {
/* a seat disposer must never break plugin teardown */
}
stopNative = undefined
}
}