dsh-better-chat/src/client/chat-view-seat.ts

163 lines
5.9 KiB
TypeScript

/**
* Chat-view tab ownership for the reader-in-chat layout.
*
* The reader used to live in its own "阅读" View tab. It now occupies the
* built-in "对话" View id instead, so the transcript area draws the reader
* while the composer, header, approvals, and scroll port stay official.
*
* `conversation.view` is a list Slot: a registration with the same `id` at a
* lower priority wins the cell for rendering. The tab row, however, is derived
* from the raw entry ledger (`slots.entries`), and normally skips entries whose
* `id` is undefined. Shadowing alone would therefore show two "对话" tabs.
*
* The preferred way to hide the official row is to clear only its View `id`:
* the row, its children, store, and disposer stay entirely official, so the
* official disposer still releases `conversation.chat.flow` and the Chat store
* if ui-chat tears down while we shadow it. Removing the row would leak those
* and make the next ui-chat registration throw "slot is already declared".
*
* If the host still paints both tabs, the header fallback hides the extra
* button without editing the registration ledger.
*
* A subscription re-hides a ChatView row that ui-chat re-registers while the
* plugin stays mounted. Every visibility change bumps the ledger version with
* a throwaway probe registration (never selected) so View subscribers such as
* the header recompute their tab list.
*/
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
export const CHAT_VIEW_ID = 'chat';
/** Lower than the official ChatView registration (priority 0) so it shadows. */
export const CHAT_VIEW_PRIORITY = -10;
const PROBE_ID = 'dsh-better-chat:chat-view-ledger-probe';
const CHAT_TAB_LIST = '[data-conversation-tabs][role="tablist"]';
const DUPLICATE_TAB = 'data-better-chat-duplicate-tab';
/** Keep the outer header usable if the host still paints both chat registrations. */
export function hideDuplicateChatTabs(doc: Document): () => void {
const sync = () => {
for (const list of doc.querySelectorAll(CHAT_TAB_LIST)) {
let seenChat = false;
for (const tab of list.querySelectorAll<HTMLButtonElement>(':scope > button[role="tab"]')) {
const label = tab.textContent?.trim() ?? '';
const isChat = label === '对话' || label === '對話' || label === 'Chat';
tab.toggleAttribute(DUPLICATE_TAB, isChat && seenChat);
if (isChat) seenChat = true;
}
}
};
const observer = new MutationObserver(records => {
if (records.some(record => {
const target = record.target instanceof Element ? record.target : record.target.parentElement;
return target?.closest(CHAT_TAB_LIST) || Array.from(record.addedNodes).some(node =>
node instanceof Element && (node.matches(CHAT_TAB_LIST) || node.querySelector(CHAT_TAB_LIST)));
})) sync();
});
observer.observe(doc.documentElement, { childList: true, characterData: true, subtree: true });
sync();
return () => {
observer.disconnect();
for (const tab of doc.querySelectorAll(`[${DUPLICATE_TAB}]`)) tab.removeAttribute(DUPLICATE_TAB);
};
}
/** The registry operations this seat needs; documented public surface. */
export interface ViewLedger {
entries(name: string): readonly StoredEntry[];
register(options: {
name: string;
id: string;
priority?: number;
order?: number;
label?: () => string;
}, component: unknown): () => void;
subscribe(name: string, listener: () => void): () => void;
}
/** One active retirement per View ledger (`ctx.slots` is a single shared object). */
const ACTIVE = new WeakMap<ViewLedger, () => void>();
/**
* Hide the official ChatView row from the View tab projection by clearing its
* View `id`; the row itself stays live and keeps its official disposer.
* @param ledger - Slot registry surfaced through `ctx.slots`.
* @returns idempotent restore for plugin teardown.
*/
export function retireHostedChatView(ledger: ViewLedger): () => void {
if (ACTIVE.has(ledger)) return () => {};
const hidden = new Set<StoredEntry>();
let live = true;
let notifying = false;
// Splicing ids does not bump the slot version, so View subscribers would
// keep a stale tab list. A throwaway registration both notifies and is gone
// before paint: its id is never the selected View.
const notify = (): void => {
if (notifying) return;
notifying = true;
try {
const dispose = ledger.register({
name: 'conversation.view',
id: PROBE_ID,
priority: CHAT_VIEW_PRIORITY,
order: 0,
label: () => '',
}, () => null);
dispose();
} finally {
notifying = false;
}
};
const hide = (): void => {
let changed = false;
for (const entry of ledger.entries('conversation.view')) {
if (entry.options.id !== CHAT_VIEW_ID) continue;
if ((entry.options.priority ?? 0) === CHAT_VIEW_PRIORITY) continue;
if (hidden.has(entry)) continue;
try {
entry.options.id = undefined;
} catch {
// The header fallback handles immutable entry options.
}
if (entry.options.id === undefined) {
hidden.add(entry);
changed = true;
}
}
if (changed) notify();
};
// Registration-time callback; a later ui-chat registration also lands here.
const unsubscribe = ledger.subscribe('conversation.view', () => {
if (live) hide();
});
hide();
const restore = (): void => {
if (!live) return;
live = false;
unsubscribe();
ACTIVE.delete(ledger);
let changed = false;
const present = new Set(ledger.entries('conversation.view'));
for (const entry of hidden) {
if (!present.has(entry)) continue;
try {
entry.options.id = CHAT_VIEW_ID;
changed = true;
} catch {
// Frozen options are already the host's own limitation.
}
}
hidden.clear();
if (changed) notify();
};
ACTIVE.set(ledger, restore);
return restore;
}