Files
apes-sidebar/tests/native-guide.spec.tsx
T
Menghuan1918 daf0329666 refactor(ui): 外壳与残余件接入统一组件层(B4)
- Switch.tsx 删除,唯一消费者 native/guide-order.tsx 改用 ui 的 ToggleSwitch
  (native checkbox → button role="switch",受控写回契约不变:下一次值仍由 prop 推导)。
- tests/switch.spec.tsx 改名 tests/toggle-switch.spec.tsx,断言改 aria-checked;
  native-guide 两处开关查询同步改选择器。
- sidebar/dock-fallback.tsx 与 split-pane.tsx 判断不接入:前者只有定位/让位逻辑
  与 BottomDockToggle 包壳,后者是纯布局与 pointer 拖拽手柄,统一层没有语义对应件。
- 收敛文档补 B4 实施记录,并把映射表中这两行改为「判断不接入」及理由。
2026-11-25 01:05:35 +08:00

558 lines
23 KiB
TypeScript

// @vitest-environment jsdom
/**
* Start-page component and catalog: the chain component's cards, the More
* card, hidden entries, the terminal shell menu, and the registry catalog.
*/
import { beforeAll, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { renderToString } from 'react-dom/server'
import { act } from 'react-dom/test-utils'
import { GuideGrid, NativeGuide } from '../src/client/native/guide.tsx'
import { createNativeGuideCatalog, mergeGuideEntries } from '../src/client/native/guide-catalog.ts'
import { registerNativeSurface } from '../src/client/native/index.ts'
import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx'
import { createBetterSidebarService } from '../src/client/service.ts'
import { createSidebarStore } from '../src/client/state.ts'
import type { NativeGuideEntry } from '../src/client/native/guide-catalog.ts'
import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts'
import { renderRoot, setupReactAct } from './test-utils.ts'
/** The settings wire the start-page writes end up on (asserted below). */
const settingsUpdate = vi.fn<
(patch: Record<string, unknown>) => Promise<{ value: unknown; revision: number }>
>(async () => ({ value: {}, revision: 2 }))
// Partial mock: only the write this spec drives is stubbed, everything else
// keeps the real client.
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return {
...actual,
api: {
...actual.api,
settingsUpdate: (patch: Record<string, unknown>) => settingsUpdate(patch),
},
}
})
setupReactAct()
beforeAll(() => {
Object.defineProperty(navigator, 'language', { value: 'en-US', configurable: true })
})
/** One synthetic card. */
function entry(key: string, kind = key): NativeGuideEntry {
return {
key,
providerId: 'p',
entryId: key,
kind,
title: () => key.toUpperCase(),
description: () => key + ' description',
icon: ({ size }: { size?: number }) => createElement('svg', { 'data-icon': 'entry-' + key, width: size, height: size }),
}
}
/** The five cards most layout tests use. */
const entries = ['a', 'b', 'c', 'd', 'e'].map(key => entry(key))
/** Render one grid into HTML. */
function htmlOf(props: {
entries?: readonly NativeGuideEntry[]
prefs?: Partial<typeof SIDEBAR_PREFS_DEFAULTS>
width?: number
onOpen?: (entry: NativeGuideEntry, params?: Record<string, unknown>) => void
shellMenu?: { launchShells: (signal: AbortSignal) => Promise<{ shells: { name: string; path: string }[]; selectedShell?: string }>; selectShell: (path: string) => void }
}): string {
return renderToString(createElement(GuideGrid, {
entries: props.entries ?? entries,
prefs: { ...SIDEBAR_PREFS_DEFAULTS, ...props.prefs },
width: props.width ?? 600,
onOpen: props.onOpen ?? (() => {}),
...(props.shellMenu === undefined ? {} : { shellMenu: props.shellMenu }),
}))
}
describe('GuideGrid', () => {
it('draws two columns and one data entry per card, with the persistent More card', () => {
const html = htmlOf({})
expect(html).toContain('data-guide-columns="2"')
expect(html).toContain('data-guide-rows="6"')
for (const key of ['a', 'b', 'c', 'd', 'e']) {
expect(html, key).toContain('data-sidebar-right-guide-entry="' + key + '"')
}
// The More card is also the host-actions entry point, so it is always there.
expect(html).toContain('data-guide-more')
expect(html).toContain('a description')
})
it('switches to one column and turns the overflow into the More card', () => {
const wide = htmlOf({ prefs: { guideRows: 1 }, width: 600 })
expect(wide).toContain('data-guide-columns="2"')
expect(wide).toContain('data-guide-rows="1"')
expect(wide).toContain('data-sidebar-right-guide-entry="a"')
expect(wide).not.toContain('data-sidebar-right-guide-entry="b"')
expect(wide).toContain('data-guide-more="true"')
const narrow = htmlOf({ prefs: { guideRows: 1 }, width: 400 })
expect(narrow).toContain('data-guide-columns="1"')
expect(narrow).toContain('data-guide-rows="1"')
// At capacity one the More card is the only cell.
expect(narrow).not.toContain('data-sidebar-right-guide-entry="a"')
expect(narrow).toContain('data-guide-more="true"')
})
it('publishes the stored vertical alignment (center by default)', () => {
expect(htmlOf({})).toContain('data-guide-align="center"')
expect(htmlOf({ prefs: { guideAlign: 'top' } })).toContain('data-guide-align="top"')
})
it('omits hidden cards and keeps the explicit order', () => {
const html = htmlOf({
prefs: { guideOrder: ['c', 'a'], guideHidden: { a: true } },
width: 400,
})
expect(html).not.toContain('data-sidebar-right-guide-entry="a"')
expect(html.indexOf('data-sidebar-right-guide-entry="c"'))
.toBeLessThan(html.indexOf('data-sidebar-right-guide-entry="b"'))
})
it('opens a card through the supplied action and closes the guide tab', () => {
const onOpen = vi.fn()
const mounted = renderRoot(createElement(GuideGrid, {
entries,
prefs: { ...SIDEBAR_PREFS_DEFAULTS },
width: 600,
onOpen,
}))
const card = mounted.container.querySelector('[data-sidebar-right-guide-entry="a"] button')
expect(card).not.toBeNull()
act(() => { (card as HTMLButtonElement).click() })
expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ key: 'a' }))
mounted.unmount()
})
it('draws the More menu rows with an icon and a title', async () => {
const mounted = renderRoot(createElement(GuideGrid, {
entries,
prefs: { ...SIDEBAR_PREFS_DEFAULTS, guideRows: 1 },
width: 600,
onOpen: () => {},
}))
const trigger = mounted.container.querySelector('[data-guide-more]')
expect(trigger).not.toBeNull()
await act(async () => {
;(trigger as HTMLButtonElement).click()
await Promise.resolve()
})
const items = [...document.querySelectorAll('[role="menuitem"]')]
const overflow = items.find(node => node.textContent?.includes('B'))
expect(overflow).toBeDefined()
expect(overflow?.querySelector('svg[data-icon]')).not.toBeNull()
mounted.unmount()
})
it('offers the host browse/create plugin actions in the More menu', async () => {
const onBrowsePlugins = vi.fn()
const onCreatePlugin = vi.fn()
const onOpenSettings = vi.fn()
const mounted = renderRoot(createElement(GuideGrid, {
entries,
prefs: { ...SIDEBAR_PREFS_DEFAULTS },
width: 600,
onOpen: () => {},
onBrowsePlugins,
onCreatePlugin,
onOpenSettings,
}))
const trigger = mounted.container.querySelector('[data-guide-more]')
await act(async () => {
;(trigger as HTMLButtonElement).click()
await Promise.resolve()
})
const rows = [...document.querySelectorAll('[role="menuitem"]')]
const browse = rows.find(node => node.textContent?.includes('Browse more plugins'))
const create = rows.find(node => node.textContent?.includes('Create your plugin'))
expect(browse).toBeDefined()
expect(create).toBeDefined()
act(() => { (create as HTMLElement).click() })
expect(onCreatePlugin).toHaveBeenCalled()
// The menu closes after an action; reopen it for the second row.
await act(async () => {
;(trigger as HTMLButtonElement).click()
await Promise.resolve()
})
const browseAgain = [...document.querySelectorAll('[role="menuitem"]')]
.find(node => node.textContent?.includes('Browse more plugins'))
act(() => { (browseAgain as HTMLElement).click() })
expect(onBrowsePlugins).toHaveBeenCalled()
await act(async () => { (trigger as HTMLButtonElement).click(); await Promise.resolve() })
const settings = [...document.querySelectorAll('[role="menuitem"]')]
.find(node => node.textContent?.includes('Sidebar settings'))
expect(settings).toBeDefined()
act(() => { (settings as HTMLElement).click() })
expect(onOpenSettings).toHaveBeenCalledOnce()
mounted.unmount()
})
it('uses the feature switch (tabsEnabled) for a Better Sidebar row and can turn it back on', async () => {
const gitEntry: NativeGuideEntry = {
...entry('git'),
descriptorId: 'git',
title: () => 'Git',
}
const onToggleHidden = vi.fn()
const mounted = renderRoot(createElement(GuideGrid, {
entries: [gitEntry],
prefs: { ...SIDEBAR_PREFS_DEFAULTS, tabsEnabled: { git: false } },
width: 600,
onOpen: () => {},
onToggleHidden,
}))
await act(async () => {
;(mounted.container.querySelector('[data-guide-more]') as HTMLButtonElement).click()
await Promise.resolve()
})
const reorder = [...document.querySelectorAll('[role="menuitem"]')]
.find(node => node.textContent?.includes('Reorder'))
await act(async () => {
;(reorder as HTMLElement).click()
await Promise.resolve()
})
const toggle = document.querySelector('[role="switch"][aria-label="Enable: Git"]') as HTMLElement
expect(toggle).not.toBeNull()
expect(toggle.getAttribute('aria-checked')).toBe('false')
act(() => { toggle.click() })
expect(onToggleHidden).toHaveBeenCalledWith(expect.objectContaining({ key: 'git' }), false)
mounted.unmount()
})
it('also exposes the shared row-count control inside the reorder dialog', async () => {
const mounted = renderRoot(createElement(GuideGrid, {
entries,
prefs: { ...SIDEBAR_PREFS_DEFAULTS, guideRows: 1 },
width: 600,
onOpen: () => {},
}))
const trigger = mounted.container.querySelector('[data-guide-more]')
await act(async () => {
;(trigger as HTMLButtonElement).click()
await Promise.resolve()
})
const reorder = [...document.querySelectorAll('[role="menuitem"]')]
.find(node => node.textContent?.includes('Reorder'))
expect(reorder).toBeDefined()
await act(async () => {
;(reorder as HTMLElement).click()
await Promise.resolve()
})
const input = document.querySelector('input[aria-label="Maximum rows"]')
expect(input).not.toBeNull()
expect((input as HTMLInputElement).value).toBe('1')
mounted.unmount()
})
it('draws the terminal shell trigger only when the host offers both shell faces', () => {
const terminal = entry('terminal')
const without = htmlOf({ entries: [terminal] })
expect(without).not.toContain('data-guide-shell-menu')
const shells = {
launchShells: async () => ({ shells: [{ name: 'zsh', path: '/bin/zsh' }], selectedShell: '/bin/zsh' }),
selectShell: () => {},
}
const withMenu = htmlOf({ entries: [terminal], shellMenu: shells })
expect(withMenu).toContain('data-guide-shell-menu')
})
it('lists host shells and opens the chosen shell', async () => {
const terminal = entry('terminal')
const selectShell = vi.fn()
const launchShells = vi.fn(async () => ({
shells: [{ name: 'zsh', path: '/bin/zsh' }, { name: 'bash', path: '/bin/bash' }],
selectedShell: '/bin/zsh',
}))
const onOpen = vi.fn()
const mounted = renderRoot(createElement(GuideGrid, {
entries: [terminal],
prefs: { ...SIDEBAR_PREFS_DEFAULTS },
width: 600,
onOpen,
shellMenu: { launchShells, selectShell },
}))
const trigger = mounted.container.querySelector('[data-sidebar-right-guide-entry="terminal"] button[aria-haspopup="menu"]')
expect(trigger).not.toBeNull()
await act(async () => {
;(trigger as HTMLButtonElement).click()
await Promise.resolve()
})
expect(launchShells).toHaveBeenCalled()
const bash = [...document.querySelectorAll('[role="menuitem"]')].find(node => node.textContent?.includes('bash'))
expect(bash).toBeDefined()
act(() => { (bash as HTMLElement).click() })
expect(selectShell).toHaveBeenCalledWith('/bin/bash')
expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ kind: 'terminal' }), { shellPath: '/bin/bash' })
mounted.unmount()
})
})
describe('NativeGuide', () => {
it('renders from a real store and catalog without losing their method receivers', () => {
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
const catalog = { getSnapshot: () => entries, subscribe: () => () => {} }
const openTab = vi.fn()
const close = vi.fn()
const mounted = renderRoot(createElement(NativeGuide, {
catalog,
store,
service,
useTabInfo: () => ({ tab: { actions: { openTab, close } } }),
}))
const card = mounted.container.querySelector('[data-sidebar-right-guide-entry="a"] button')
expect(card).not.toBeNull()
act(() => { (card as HTMLButtonElement).click() })
expect(openTab).toHaveBeenCalledWith('a', { replaceTab: true })
expect(close).toHaveBeenCalled()
mounted.unmount()
})
it('re-showing a hidden card sends the explicit false on the wire (#1212)', async () => {
settingsUpdate.mockClear()
// The host resolves the merged document: the touched key is now false.
settingsUpdate.mockResolvedValue({ value: { guideHidden: { a: false } }, revision: 2 })
const store = createSidebarStore()
store.setSession('s1')
store.setPrefs({ ...store.getPrefs(), guideHidden: { a: true } })
const service = createBetterSidebarService(store)
// One stable snapshot: useSyncExternalStore loops on a fresh array.
const catalogEntries = [entry('a')]
const catalog = { getSnapshot: () => catalogEntries, subscribe: () => () => {} }
const mounted = renderRoot(createElement(NativeGuide, { catalog, store, service }))
await act(async () => {
;(mounted.container.querySelector('[data-guide-more]') as HTMLButtonElement).click()
await Promise.resolve()
})
const reorder = [...document.querySelectorAll('[role="menuitem"]')]
.find(node => node.textContent?.includes('Reorder'))
expect(reorder).toBeDefined()
await act(async () => {
;(reorder as HTMLElement).click()
await Promise.resolve()
})
const toggle = document.querySelector('[role="switch"][aria-label="Show on the start page: A"]') as HTMLElement
expect(toggle).not.toBeNull()
expect(toggle.getAttribute('aria-checked')).toBe('false')
await act(async () => {
toggle.click()
// The host deep-merges nested plain objects, so a patch with the key
// absent would leave the stored true in place: the wire must carry false.
await vi.waitFor(() => {
expect(settingsUpdate).toHaveBeenCalledWith({ guideHidden: { a: false } })
})
// Every reader asks `guideHidden[key] === true`, so a stored false
// already reads as shown; no map normalization is needed.
await vi.waitFor(() => {
expect(store.getPrefs().guideHidden.a).not.toBe(true)
})
})
mounted.unmount()
})
})
describe('registerNativeSurface start-page takeover', () => {
it('registers one chain guide and releases it with the seat', () => {
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
service.registerTab({ id: 'git', title: 'Changes', component: () => null })
const records = createNativeTabRecords()
const catalog = { getSnapshot: () => [], subscribe: () => () => {} }
const slotRegistrations: Array<{ name: string; options: Record<string, unknown> }> = []
const released: string[] = []
const registry = {
register: (definition: { id: string; kind: string }) => () => { released.push(definition.id) },
}
const ctx = {
inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => {
const cleanup = callback({ get: () => registry })
return { dispose: () => { if (typeof cleanup === 'function') cleanup() } }
},
get: () => undefined,
slots: {
inject: (_key: string, callback: () => () => void) => callback(),
register: (options: Record<string, unknown>) => {
slotRegistrations.push({ name: String(options.name), options })
return () => { released.push('slot:' + String(options.name)) }
},
},
}
const dispose = registerNativeSurface({
ctx: ctx as never,
store,
service,
records,
guideCatalog: catalog,
})
const guide = slotRegistrations.filter(item => item.name === 'sidebar.right.tab.guide')
expect(guide).toHaveLength(1)
const select = guide[0]?.options.select as (() => unknown) | undefined
expect(select?.()).toEqual({})
const inject = guide[0]?.options.inject as ((sessionId: string) => Record<string, unknown>) | undefined
const face = inject?.('s1')
expect(face?.catalog).toBe(catalog)
expect(face?.store).toBe(store)
expect(face?.shellMenu).toBeUndefined()
// The preference disarms the takeover and restores it without touching the
// tab types.
store.setPrefs({ ...store.getPrefs(), guideTakeover: false })
expect(released).toContain('slot:sidebar.right.tab.guide')
expect(slotRegistrations.filter(item => item.name === 'sidebar.right.tab.guide')).toHaveLength(1)
store.setPrefs({ ...store.getPrefs(), guideTakeover: true })
expect(slotRegistrations.filter(item => item.name === 'sidebar.right.tab.guide')).toHaveLength(2)
dispose()
expect(released).toContain('slot:sidebar.right.tab.guide')
})
})
describe('host services for the start page', () => {
it('calls webTerminals, pluginNavigation and uiWorkspace with their receivers', async () => {
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
const records = createNativeTabRecords()
const catalog = { getSnapshot: () => [], subscribe: () => () => {} }
const shellCalls: Array<{ sessionId: string; signal: AbortSignal }> = []
const terminals = {
remote: { shells: [{ name: 'zsh', path: '/bin/zsh' }] },
selected: undefined as string | undefined,
view: () => { throw new Error('unused') },
close: () => {},
recover: async () => [],
launchShells(sessionId: string, signal: AbortSignal) {
shellCalls.push({ sessionId, signal })
return Promise.resolve({ shells: this.remote.shells as Array<{ name: string; path: string }> })
},
selectShell(path: string) {
this.selected = path
},
}
const navigation = { opened: false, openList() { this.opened = true } }
const workspace = {
started: undefined as { sessionId: string | undefined; options: Record<string, unknown> } | undefined,
startSession(sessionId: string | undefined, options: Record<string, unknown>) {
this.started = { sessionId, options }
},
}
const slotRegistrations: Array<{ name: string; options: Record<string, unknown> }> = []
const registry = { register: () => () => {} }
const ctx = {
inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => {
const cleanup = callback({ get: () => registry })
return { dispose: () => { if (typeof cleanup === 'function') cleanup() } }
},
get: (name: string) => {
if (name === 'webTerminals') return terminals
if (name === 'pluginNavigation') return navigation
if (name === 'uiWorkspace') return workspace
return undefined
},
slots: {
inject: (_key: string, callback: () => () => void) => callback(),
register: (options: Record<string, unknown>) => {
slotRegistrations.push({ name: String(options.name), options })
return () => {}
},
},
}
const dispose = registerNativeSurface({ ctx: ctx as never, store, service, records, guideCatalog: catalog })
const guide = slotRegistrations.find(item => item.name === 'sidebar.right.tab.guide')
const face = (guide?.options.inject as ((sessionId: string) => Record<string, unknown>) | undefined)?.('s1')
const browse = face?.onBrowsePlugins as (() => void) | undefined
const create = face?.onCreatePlugin as (() => void) | undefined
const shellMenu = face?.shellMenu as { launchShells: (signal: AbortSignal) => Promise<unknown>; selectShell: (path: string) => void } | undefined
browse?.()
expect(navigation.opened).toBe(true)
create?.()
expect(workspace.started?.sessionId).toBeUndefined()
expect(workspace.started?.options.agentPreset).toBe('cordis')
expect(workspace.started?.options.whenDraftExists).toBe('append')
expect(typeof workspace.started?.options.prompt).toBe('string')
const signal = new AbortController().signal
await shellMenu?.launchShells(signal)
expect(shellCalls).toEqual([{ sessionId: 's1', signal }])
shellMenu?.selectShell('/bin/zsh')
expect(terminals.selected).toBe('/bin/zsh')
dispose()
})
})
describe('mergeGuideEntries', () => {
it('adds a synthetic row for a descriptor whose native type is disabled', () => {
const merged = mergeGuideEntries([entry('host')], [
{ id: 'git', title: 'Changes', component: () => null, order: 30 },
], { git: false })
const git = merged.find(item => item.descriptorId === 'git')
expect(git?.key).toBe('dsh-better-sidebar:git::git')
expect(git?.kind).toBe('git')
expect(git?.title()).toBe('Changes')
})
})
describe('createNativeGuideCatalog', () => {
it('maps guide cards to stable keys and the owning descriptor', () => {
const registry = {
guide: () => [
{ id: 'files', kind: 'files', providerId: 'dsh-better-sidebar:files', title: () => 'Files' },
{ id: 'git', kind: 'git', providerId: 'dsh-better-sidebar:git', title: () => 'Git', description: () => 'Changes' },
{ id: 'new', kind: 'terminal', providerId: 'dsh-client-ui-sidebar-terminal', title: () => 'Terminal' },
],
subscribe: () => () => {},
}
const ctx = {
inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => {
const cleanup = callback({ get: () => registry })
return { dispose: () => { if (typeof cleanup === 'function') cleanup() } }
},
}
const created = createNativeGuideCatalog(ctx as never)
const snapshot = created.catalog.getSnapshot()
expect(snapshot.map(item => item.key)).toEqual([
'dsh-better-sidebar:files::files',
'dsh-better-sidebar:git::git',
'dsh-client-ui-sidebar-terminal::new',
])
expect(snapshot[0]?.descriptorId).toBe('editor')
expect(snapshot[1]?.descriptorId).toBe('git')
expect(snapshot[2]?.descriptorId).toBeUndefined()
expect(snapshot[1]?.description?.()).toBe('Changes')
created.dispose()
})
it('notifies subscribers when the registry changes', () => {
let cards: Array<{ id: string; kind: string; providerId: string; title: () => string }> = []
const listeners = new Set<() => void>()
const registry = {
guide: () => cards,
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
}
const ctx = {
inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => {
const cleanup = callback({ get: () => registry })
return { dispose: () => { if (typeof cleanup === 'function') cleanup() } }
},
}
const created = createNativeGuideCatalog(ctx as never)
const listener = vi.fn()
created.catalog.subscribe(listener)
cards = [{ id: 'x', kind: 'x', providerId: 'p', title: () => 'X' }]
for (const notify of listeners) notify()
expect(listener).toHaveBeenCalled()
expect(created.catalog.getSnapshot()).toHaveLength(1)
created.dispose()
})
})