Files
apes-sidebar/tests/editor-refresh.spec.tsx
T
Menghuan1918 5ee81fb073 feat(clues): collect resources from files, Feishu and GitHub, adapted to DSH 0.2.2-rc.2
This lands the clue collection line on top of origin/dev (v0.32.1, DSH
0.2.2-rc.2). The 14 commits that carried it are squashed into this one
because every one of them overlapped upstream's own changes (version,
19 dictionaries, CHANGELOG), and each intermediate commit would have
failed to compile against rc.2's menu API. The pre-integration head is
kept at backup/clues-uiux-refresh-pre-rebase.

What the feature is:
- a Clues tab that reads local files, Feishu tasks/docs and GitHub
  issues/pulls through one source registry, with a scope row, shared
  search, filters, paging and stable [[dsh-clue:...]] references;
- one window host for detail, pack management, source configuration,
  new pack and sharing (preview and edit are separate paths: a read is
  never saved over);
- .cluepack export/import with per-row resolvability previews;
- a source runtime that owns dependency installs and connection
  authorization (gh, lark-cli device code) and only probes on an
  explicit read;
- the public betterSidebarClues service and the windows capability
  (features gains clues / windowHost).

Merged with upstream rather than over it:
- the settings section keeps upstream's start-page takeover group and
  this branch's clue sources group; navigation is now six groups;
- the dictionaries keep both sides' new keys (1211 each, verified equal
  across all 19), the external-plugin guide and CHANGELOG keep both
  histories, and service features list both capability sets.

Adapted to 0.2.2-rc.2:
- menu call sites use anchorPoint instead of getAnchorRect;
- the shared SelectMenu mounts the host menu only while open, because
  rc.2's Menu reads the DOM during render and broke server-rendered
  settings surfaces;
- the submenu flip workaround stays deleted (the host positions
  submenus now), pinned by an updated layout-css assertion.

Version 0.33.0 (three synced spots) with a new 未发布 / Unreleased
changelog section; package.json regains the ./clues export, lib/clues.js
and the uqr dependency that upstream never had.

Gates: typecheck, lint, 5410 unit tests, build, check:consumer-types and
the full mount lane (35 passed) against dsh 0.2.2-rc.2 in Chromium.
2026-11-24 16:43:26 +08:00

245 lines
9.8 KiB
TypeScript

/**
* EditorHost refresh behaviors (issue #167): the manual refresh button
* re-runs the load (A), returning from edit to preview reloads unless the
* draft is dirty or the save failed (B), and a preview-mode save reloads on
* the 'saved' edge (C). A mock viewer reports a hoisted toolbar so the host
* chrome renders exactly like the real text editor.
*/
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement, useEffect, useState } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot, setupReactAct } from './test-utils.ts'
import type { Context } from '../src/context-types.ts'
import { EditorHost } from '../src/client/EditorHost.tsx'
import { createBetterSidebarService, type FileViewerProps } from '../src/client/service.ts'
import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/state.ts'
// The act() environment flag (React 18.2 reads it before flushing effects).
setupReactAct()
const fsRead = vi.fn()
vi.mock('../src/client/api.ts', () => {
class SidebarApiError extends Error {
readonly code: string
constructor(code: string, message: string) { super(message); this.name = 'SidebarApiError'; this.code = code }
}
return {
api: { fsRead: (...args: unknown[]) => fsRead(...args) },
mediaUrl: () => '',
SidebarApiError,
}
})
/** One fsRead call counter reset per test. */
function reads(): number {
return fsRead.mock.calls.length
}
interface MockViewerProps {
initialMode?: 'preview' | 'edit'
dirty?: boolean
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onToolbarState?: (state: any) => void
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onToolbarControls?: (controls: any) => void
}
/** A viewer that hoists a real toolbar (mode toggle + save state). */
function MockTextViewer({ initialMode = 'preview', dirty = false, onToolbarState, onToolbarControls }: MockViewerProps) {
const [mode, setMode] = useState(initialMode)
const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved' | 'failed'>('idle')
useEffect(() => {
onToolbarState?.({ modes: true, mode, dirty, editable: true, saveState })
}, [mode, saveState, dirty, onToolbarState])
useEffect(() => {
onToolbarControls?.({
setMode,
// A synchronous save (saving then saved in one batch) drives the edge.
save: () => { setSaveState('saving'); setSaveState('saved') },
})
return () => { onToolbarControls?.(null) }
}, [onToolbarControls])
return createElement('div', null, `mock-${mode}`)
}
function setup(initialMode: 'preview' | 'edit' = 'preview', dirty = false): {
ctx: Context
fileTab: () => SidebarTab
} {
const store = createSidebarStore()
const service = createBetterSidebarService(store)
service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null })
service.registerFileViewer({
id: 'mock-text',
exts: ['ts'],
priority: 0,
fetchStrategy: 'fsRead',
component: (props: FileViewerProps) => createElement(MockTextViewer, {
initialMode,
dirty,
onToolbarState: props.onToolbarState,
onToolbarControls: props.onToolbarControls,
}),
})
store.setSession('editor-home-session')
const sessionsSnapshot = { byId: { 'editor-home-session': { cwd: '/tmp' } }, current: 'editor-home-session' }
const ctx = {
betterSidebar: service,
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
get: (name: string) => name === 'betterSidebar' ? service : undefined,
} as unknown as Context
ctx.betterSidebar.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' })
const fileTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
.find(tab => tab.path === '/tmp/a.ts')!
return { ctx, fileTab }
}
function mount(ctx: Context, tab: () => SidebarTab): { container: HTMLDivElement; unmount: () => void } {
return renderRoot(createElement(EditorHost, {
ctx, store: ctx.betterSidebar as never, scope: { sessionId: 'editor-home-session' },
tab: tab(), expanded: [], revealed: [], onToggleDir: () => {}, onReferenceFile: () => {},
}))
}
/** The header's refresh button (locale-dependent aria-label), or null. */
function refreshButton(container: HTMLDivElement): HTMLButtonElement | null {
return container.querySelector('button[aria-label="Refresh"], button[aria-label="刷新"]')
}
function click(button: HTMLButtonElement): void {
act(() => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
}
beforeEach(() => {
fsRead.mockReset()
fsRead.mockResolvedValue({ kind: 'text', content: 'hello', size: 5 })
})
describe('EditorHost refresh (issue #167)', () => {
it('A: the refresh button renders for a toolbar-reporting viewer and re-runs the load', async () => {
const { ctx, fileTab } = setup()
const { container, unmount } = mount(ctx, fileTab)
try {
// The initial load ran once; settle the async fsRead.
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(1)
const refresh = refreshButton(container)
expect(refresh).not.toBeNull()
click(refresh!)
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(2)
} finally {
unmount()
}
})
it('B: returning from edit to preview reloads (fresh content shows after save)', async () => {
const { ctx, fileTab } = setup('edit')
const { container, unmount } = mount(ctx, fileTab)
try {
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(1)
const preview = Array.from(container.querySelectorAll('button'))
.find(button => button.textContent === 'Preview')!
click(preview)
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(2)
} finally {
unmount()
}
})
it('B: keyboard selection keeps focus on preview across its asynchronous reload', async () => {
const { ctx, fileTab } = setup('preview')
const { container, unmount } = mount(ctx, fileTab)
try {
await act(async () => { await Promise.resolve() })
const [preview, edit] = [...container.querySelectorAll<HTMLButtonElement>('[role="tab"]')]
preview!.focus()
act(() => { preview!.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true })) })
expect(edit!.getAttribute('aria-selected')).toBe('true')
expect(document.activeElement).toBe(edit)
let release: (value: { kind: string; content: string; size: number }) => void = () => {}
fsRead.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
act(() => { edit!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Home', bubbles: true })) })
expect(reads()).toBe(2)
expect(container.querySelector('[role="tab"][aria-selected="true"]')).toBe(preview)
expect(document.activeElement).toBe(preview)
await act(async () => { release({ kind: 'text', content: 'fresh', size: 5 }); await Promise.resolve() })
const selected = container.querySelector<HTMLButtonElement>('[role="tab"][aria-selected="true"]')
expect(selected?.textContent).toBe('Preview')
expect(document.activeElement).toBe(selected)
} finally {
unmount()
}
})
it('clears the retained toolbar when the reload fails', async () => {
const { ctx, fileTab } = setup()
const { container, unmount } = mount(ctx, fileTab)
try {
await act(async () => { await Promise.resolve() })
fsRead.mockRejectedValueOnce(new Error('read failed'))
click(refreshButton(container)!)
await act(async () => { await Promise.resolve() })
expect(container.querySelector('[role="tablist"]')).toBeNull()
expect(container.querySelector('button[aria-label="Save"]')).toBeNull()
expect(container.querySelector('[role="alert"]')?.textContent).toContain('read failed')
} finally {
unmount()
}
})
it('clears the retained toolbar when the same file selects another viewer', async () => {
const { ctx, fileTab } = setup()
const { container, unmount } = mount(ctx, fileTab)
try {
await act(async () => { await Promise.resolve() })
ctx.betterSidebar.registerFileViewer({
id: 'plain', exts: ['ts'], priority: 100, fetchStrategy: 'none',
component: () => createElement('div', null, 'plain viewer'),
})
click(refreshButton(container)!)
await act(async () => { await Promise.resolve() })
expect(container.textContent).toContain('plain viewer')
expect(container.querySelector('[role="tablist"]')).toBeNull()
expect(container.querySelector('button[aria-label="Save"]')).toBeNull()
} finally {
unmount()
}
})
it('B: a dirty draft suppresses the edit→preview reload (the draft would be dropped)', async () => {
const { ctx, fileTab } = setup('edit', true)
const { container, unmount } = mount(ctx, fileTab)
try {
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(1)
const preview = Array.from(container.querySelectorAll('button'))
.find(button => button.textContent === 'Preview')!
click(preview)
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(1)
} finally {
unmount()
}
})
it('C: a preview-mode save reloads on the saved edge', async () => {
const { ctx, fileTab } = setup('preview')
const { container, unmount } = mount(ctx, fileTab)
try {
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(1)
const save = container.querySelector('button[aria-label="Save"]') as HTMLButtonElement
click(save)
await act(async () => { await Promise.resolve() })
expect(reads()).toBe(2)
} finally {
unmount()
}
})
})