Files
apes-sidebar/tests/editor-find.spec.tsx
T
suiyideali e2f53df484 feat(editor): 编辑器内查找——接入 @codemirror/search(Cmd/Ctrl+F)
- src/client/TextEditor.tsx: 共享扩展表新增 search({top:true}) + keymap.of(searchKeymap)
  (Mod-f 打开、面板固定编辑器顶部、Mod-g / Shift-Mod-g 下一个 / 上一个、Mod-Alt-g
  跳转到行、Escape 关闭)。搜索扩展与代码 / markdown 两个 viewer、只读「预览」与
  编辑模式共用同一份扩展表,不存在仅可编辑的分支;search 注册在编辑器自有 keymap
  之前,Escape 优先关面板(面板未开时 closeSearchPanel 返回 false,仍回落到
  simplifySelection),保存键 Mod-s 位置与优先级不变。
- src/client/cm-search.ts(新增): 面板 chrome 走 --dsw-* 令牌(CodeMirror 自带
  面板按 &light 上灰白配色,深色皮肤下会浮出一个白框);phrases facet 放进
  Compartment,语言切换就地 reconfigure(文档 / 撤销历史 / keymap / 滚动不动)。
- i18n: 新增 15 个 search* key——zh/en 在 locales.ts,其余 19 份词典全量补译
  (tests/locales.spec.ts 的 key-set 相等断言);locales.ts 新增 localeSignature(),
  TextEditor 同时订阅 DSH locale 与 better-locale override(tab-cell memo 不比较
  override,只靠父组件重渲染会漏掉 ja 切换)。
- README / README_EN: 快捷键表各加一行「文件内查找 / Find in file」。
- tests/editor-find.spec.tsx(新增): 扩展含 search keymap、Mod-f 开顶部面板、
  Escape 关闭、语言热切换后重开面板文案跟随、Mod-s 保存键仍生效。
- tests/e2e/mount.e2e.ts: 打开 seed 文件后补 Ctrl/Cmd+F → .cm-search 面板可见、
  Escape 关闭的真机断言(真实 Chromium + 懒加载 client-editor.js chunk)。

背景:package.json 里 @codemirror/search 一直是死依赖(src 零 import),编辑器
没有任何查找面板——Cmd+F 不被 CodeMirror 接管,长文件里浏览器原生查找只能命中
已渲染的行。本次只接入文件内查找,终端搜索(@xterm/addon-search)另开 PR。
2026-09-15 10:42:46 +08:00

152 lines
5.9 KiB
TypeScript

/**
* Find-in-file spec (Cmd/Ctrl+F): the editor wires CodeMirror's search
* extension into EVERY TextEditor view — the extension list is shared by the
* code and markdown viewers, so "preview" (read-mostly) and "edit" mode both
* get the panel, and the read-only markdown preview cannot be the only mode
* without it. Covers the three promises of the feature:
*
* - the extensions carry the upstream search extension + keymap (Mod-f
* open, Mod-g / Shift-Mod-g next/previous, Escape close),
* - Mod-f really opens the TOP-pinned panel in a mounted editor, and Escape
* closes it (the editor keymap's own Escape binding — `simplifySelection`
* — must not shadow it),
* - the panel copy follows the plugin dictionary: it opens in the active
* language and re-resolves after a locale switch (the phrases facet is
* baked into the EditorState, so this proves the compartment
* reconfigure), while the editor's own Mod-s save binding still fires.
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { act } from 'react-dom/test-utils'
import { EditorState } from '@codemirror/state'
import { keymap } from '@codemirror/view'
import './browser-globals.ts'
import { renderRoot, setupReactAct } from './test-utils.ts'
import { TextEditor } from '../src/client/TextEditor.tsx'
import { cmSearchExtensions } from '../src/client/cm-search.ts'
import { createSidebarStore } from '../src/client/state.ts'
import { attachLocale } from '../src/client/locales.ts'
import { api } from '../src/client/api.ts'
import type { FileViewerProps } from '../src/client/service.ts'
setupReactAct()
/** Minimal structural fake of the DSH LocaleService face (live-switchable). */
class FakeLocale {
active = 'zh'
private readonly listeners = new Set<() => void>()
getSnapshot(): { active: string } {
return { active: this.active }
}
subscribe(listener: () => void): () => void {
this.listeners.add(listener)
return () => { this.listeners.delete(listener) }
}
/** Switch the active locale and notify subscribers (the DSH live switch). */
switchTo(id: string): void {
this.active = id
for (const listener of this.listeners) listener()
}
}
let locale: FakeLocale
beforeEach(() => {
locale = new FakeLocale()
attachLocale(locale)
})
afterEach(() => {
attachLocale(undefined)
vi.restoreAllMocks()
document.body.innerHTML = ''
})
/** Mount the real editor for a plain-text file (the code viewer). */
function mountEditor(): { container: HTMLDivElement; unmount: () => void } {
const props: FileViewerProps = {
ctx: { locale, get: () => undefined } as unknown as FileViewerProps['ctx'],
store: createSidebarStore(),
scope: { sessionId: 's1', cwd: '/p' },
path: '/p/hello.txt',
title: 'hello.txt',
viewerId: 'code',
content: 'alpha\nbeta\nalpha\n',
}
return renderRoot(createElement(TextEditor, props))
}
/** Dispatch one keydown on `target` (jsdom is non-mac, so Mod = Ctrl). */
function press(target: Element, key: string, init: KeyboardEventInit = {}): void {
act(() => {
target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...init }))
})
}
/** The editor's content DOM (CodeMirror's keydown listener target). */
function contentOf(container: HTMLElement): Element {
const content = container.querySelector('.cm-content')
if (content === null) throw new Error('the mounted editor has no .cm-content')
return content
}
/** The open search panel's search field (null while the panel is closed). */
function searchField(container: HTMLElement): HTMLInputElement | null {
return container.querySelector<HTMLInputElement>('.cm-search input[name=search]')
}
describe('editor find-in-file (Cmd/Ctrl+F)', () => {
it('carries the search extension and the upstream search keymap', () => {
const state = EditorState.create({ doc: 'alpha', extensions: cmSearchExtensions() })
const keys = state.facet(keymap).flatMap(bindings => bindings.map(binding => binding.key))
// Open, next/previous, go-to-line, close — the upstream searchKeymap.
expect(keys).toContain('Mod-f')
expect(keys).toContain('Mod-g')
expect(keys).toContain('Mod-Alt-g')
expect(keys).toContain('Escape')
})
it('opens the top-pinned panel on Mod-f and closes it with Escape', () => {
const { container, unmount } = mountEditor()
expect(searchField(container), 'no panel before the shortcut').toBeNull()
press(contentOf(container), 'f', { ctrlKey: true })
const panel = container.querySelector('.cm-panels.cm-panels-top .cm-search')
expect(panel, 'Mod-f must open the search panel pinned to the editor top').not.toBeNull()
// The panel copy comes from the plugin dictionary (zh is the active one).
expect(searchField(container)?.placeholder).toBe('查找')
press(searchField(container)!, 'Escape')
expect(searchField(container), 'Escape must close the panel').toBeNull()
unmount()
})
it('keeps the editor\'s own Mod-s save binding working', () => {
const write = vi.spyOn(api, 'fsWrite').mockResolvedValue({ ok: true })
const { container, unmount } = mountEditor()
press(contentOf(container), 's', { ctrlKey: true })
expect(write, 'the editor keymap still owns Mod-s').toHaveBeenCalledTimes(1)
unmount()
})
it('re-resolves the panel copy after a live locale switch', () => {
const { container, unmount } = mountEditor()
press(contentOf(container), 'f', { ctrlKey: true })
expect(searchField(container)?.placeholder).toBe('查找')
press(searchField(container)!, 'Escape')
// The phrases facet is part of the EditorState: without the compartment
// reconfigure the reopened panel would still show the old language.
act(() => { locale.switchTo('en') })
press(contentOf(container), 'f', { ctrlKey: true })
expect(searchField(container)?.placeholder).toBe('Find')
unmount()
})
})