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

79 lines
2.5 KiB
TypeScript

// Adapted from dsh-mnemon better-sidebar.tsx (MIT), see vendor/dsh-mnemon/LICENSE.
// Registers the "项目记忆" tab into the optional better-sidebar service.
// The service is probed at runtime; when it is absent the tab simply does not
// appear and the total Brain panel remains the full-featured surface.
import * as React from 'react'
import { BrainIcon } from '../panel/brain-icon'
import { ProjectMemoryView } from './ProjectMemoryView'
export const BETTER_SIDEBAR_TAB_ID = 'dsh-brain:memory'
interface BetterSidebarTabProps {
scope?: { cwd?: string; sessionId?: string }
visible?: boolean
}
interface BetterSidebarTabDescriptor {
id: string
title: string | (() => string)
description?: string
icon?: any
order?: number
single?: boolean
component: (props: BetterSidebarTabProps) => any
}
interface BetterSidebarService {
registerTab(descriptor: BetterSidebarTabDescriptor): () => void
}
export function mountBrainSidebarTab(ctx: any): () => void {
let current: { service: BetterSidebarService; dispose: () => void } | undefined
let disposed = false
const reconcile = (): void => {
if (disposed) return
const service = (typeof ctx?.get === 'function' ? ctx.get('betterSidebar') : ctx?.betterSidebar) as BetterSidebarService | undefined
if (current?.service === service) return
current?.dispose()
current = undefined
if (service === undefined || service === null || typeof service.registerTab !== 'function') return
const dispose = service.registerTab({
id: BETTER_SIDEBAR_TAB_ID,
title: () => '项目记忆',
description: '当前会话项目的本地记忆:空间/条目/搜索/部门召回',
icon: (size: number) => React.createElement(BrainIcon, { size }),
order: 60,
single: true,
component: ({ scope, visible }: BetterSidebarTabProps) => React.createElement(ProjectMemoryView, { key: scope?.cwd ?? '', ctx, scope, visible }),
})
current = { service, dispose }
}
reconcile()
let unsubscribe: (() => void) | undefined
if (typeof ctx?.on === 'function') {
try {
unsubscribe = ctx.on('internal/service', (name: string) => {
if (name === 'betterSidebar') reconcile()
})
} catch {
unsubscribe = undefined
}
}
return () => {
disposed = true
try {
unsubscribe?.()
} catch {
/* ignore teardown errors */
}
try {
current?.dispose()
} catch {
/* ignore teardown errors */
}
current = undefined
}
}