Files
apes-sidebar/tests/side-card-section-rows.spec.tsx
T
Menghuan1918 85c7d12785 chore(shell): 删除 titleBar 让位机制及全部相关配置(#430)
插件自 v0.19.0 起不再自绘顶部 chrome:`223b254` 把那三条读 strip 的规则
(`top: calc(var(--dsh-title-bar-strip, 40px) + 3px)` / 右面板
`padding-top: var(--dsh-title-bar-strip, 40px)` / 折叠态 `+14px`)连同自绘
chrome 一起删掉了。此后「位置兼容模式」四方案仍在写
`--dsh-title-bar-strip` + `body[data-dsh-title-bar-compat]`,但**没有任何
消费者**:`src/**/*.css` 零命中,宿主也不读这条契约(DSH 核心整树 grep
`windowControlsOverlay|dsh-desktop-titlebar-inset|titlebarInset|
title-bar-strip|title-bar-compat` 与 `desktopWindow` 全部零命中)。结果是
用户改设置只写变量、什么都不动,而设置项描述(「标题栏条带高度:侧边栏
按钮与内容下移的像素数」)与现实不符。整套删除,不留兼容层。

删除范围(先做了完整消费者普查,见新增的设计文档):
- 计算与写入:`src/client/titlebar-strip.ts`、`src/client/wco.ts`、
  `src/client/shell-presets.ts` 三个文件整体删除;`Sidebar.tsx` 里的 strip
  计算 + 写 `--dsh-title-bar-strip` / `body[data-dsh-title-bar-compat]` 的
  effect 与 `titleBarCompat` 局部量一并清理。
- 壳信号:`desktop-env.ts` 的 `parseDesktopEnv` / `DesktopEnv` /
  `probeDesktopWindow` 与 `context-types.ts` 的 `SidebarDesktopWindowService`
  (含 Insets / DragRegion)删除。#864 新增的 `desktopWindow` 优先读取随之
  消失。**`desktop-env.ts` 文件保留**:同文件的 `hostTransportBase()` 另有
  3 个消费者(`host-route-url.ts` / `TextEditor.tsx` / `changes/DiffPane.tsx`),
  是反向代理前缀与 `dsh-app://` 自定义 scheme 的解析基准,与本机制无关。
- 配置:`titleBarScheme` / `titleBarPresetId` / `titleBarCompat` /
  `titleBarStripPx` 及 `TITLE_BAR_STRIP_{MIN,MAX,DEFAULT}` / `TITLE_BAR_SCHEMES`
  / `TitleBarScheme` / `clampTitleBarStrip`(`prefs-shared.ts` 的字段与默认值、
  `config.ts` 的 schema 字段、`client/prefs.ts` 的读迁移逻辑)。
- 设置界面:常规行的方案下拉 + 「自定义方案」齿轮弹窗 + `titleBarSchemeValue`
  / `onSchemeSelect` / `detectedEnv` / `stripSettingsOpen` 全部删除;
  **自定义 CSS 逃生口保留**,搬到独立的「自定义 CSS」分组,并去掉 scheme
  门控(非空即生效)。`SideCardSection.module.css` 的死样式 `.rowGear` 同步删。
- 词典:21 份(`locales.ts` 的 zh + en 与 19 个 `locales-*.ts`)同步删除 12 个
  只服务这些设置的 key(`settingsTitleBar*` / `settingsScheme*` /
  `presetDshDesktopDesc`);`settingsCustomCssPlaceholder` 的示例改为
  `[data-dsh-bottom-panel]` + `--dsw-font-mono`,不再引用已删变量。
- 文档:指南 §12.1 重写(删四方案 / strip 取值链 / 壳信号 / 迁移,保留用户
  空间 CSS 与两条拖拽区退出)、§7 的 `toggles` 键清单、AGENTS §5 皮肤契约与
  「契约反向引用」;新增 `docs/plans/2026-10-05-remove-titlebar-compat-strip.md`
  记录普查结论与去留理由。`docs/plans/` 的历史文档未改。

迁移安全(旧偏好数据被安全忽略):四个已删键在 OPEN 的宿主 schema 里是未知键,
解析不报错、不写回(`plugin-shape.spec.ts`);客户端 `parsePrefs` 只按声明字段
构造结果,旧键不进入 UI(`prefs.spec.ts`);一次性 `settings.yaml` 回迁按
`Config.dict` 的声明字段过滤,已删键被丢弃而非转发(`smoke.spec.ts`)。
三条新断言都做过变异证伪:让 `parsePrefs` 透传原记录 / 让 schema 重新声明
`titleBarCompat` / 去掉回迁的声明字段过滤,对应用例分别红在
「不要带上已删键」「解析结果不得含该字段」「回迁不得保留该键」。

测试:删除 `tests/titlebar-strip.spec.ts` / `wco.spec.ts` /
`shell-presets.spec.ts` / `desktop-window-strip.spec.tsx` /
`desktop-env.spec.ts`(五个文件断言的行为已整体移除,不留断言已删行为的测试);
`prefs.spec.ts` / `plugin-shape.spec.ts` / `smoke.spec.ts` /
`side-card-section{,-rows}.spec.tsx` 的夹具与断言改写;`mount.e2e.ts` 删掉 WCO
与壳预设两个场景,URL 戳记场景保留挂载与拖拽区断言、只删 strip 断言,
自定义 CSS 场景改为只写 `customCss`。

门禁:`pnpm typecheck`(0 错误)/ `pnpm lint`(0 问题)/
`pnpm exec vitest run --maxWorkers=3` —— 179 文件 / 2075 passed + 13 skipped
(删除前基线 184 文件 / 2117 passed + 13 skipped;差额 = 5 个被删 spec 的
41 条 + `prefs.spec.ts` 净减 1 条)。词典 parity(`locales.spec.ts`)与皮肤
契约(`theme.spec.ts`)均绿。
2026-10-05 23:38:04 +08:00

265 lines
10 KiB
TypeScript

/**
* Interactive tests for the settings popup's text/number/select rows: the
* draft is local state committed on blur through the parent's onCommit; the
* parent's canonical return is adopted (clamped numbers, stored value for
* invalid input), and the row remounts when the committed pref value changes
* (a failed commit reverts prefs → the stored value reappears). Select rows
* commit the picked option's value (single) or the picked values in options
* order (multi) through onSelectValue.
*
* Rendered with createRoot + act() in jsdom (the SSR specs stay in
* side-card-section.spec.tsx; this file exercises the event paths).
*/
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { createElement } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot, setupReactAct } from './test-utils.ts'
// The act() environment flag (React 18.2 reads it before flushing effects).
setupReactAct()
import type { SidebarSettingToggle } from '../src/client/service.ts'
import { FeatureSettingsRows } from '../src/client/SideCardSection.tsx'
import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts'
/** Type into an input and commit it via blur (React 18: input event +
* focusout). The native setter bypasses React's value tracker so the
* change is actually seen. */
function typeAndBlur(input: HTMLInputElement, value: string): void {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
act(() => {
setter.call(input, value)
input.dispatchEvent(new Event('input', { bubbles: true }))
input.dispatchEvent(new FocusEvent('focusout', { bubbles: true }))
})
}
const prefs = { ...SIDEBAR_PREFS_DEFAULTS }
/** The row renderer reads `prefs[toggle.key]`, so a plugin-shaped fixture key
* needs a widened copy (a fresh literal with an undeclared key fails
* excess-property checking). */
const withPluginKey = (key: string, value: unknown): typeof prefs => ({ ...prefs, [key]: value })
describe('FeatureSettingsRows typed rows (interactive)', () => {
it('commits the raw text on blur and adopts the canonical return', () => {
const commits: Array<[string, string]> = []
const toggle: SidebarSettingToggle = {
key: 'myPluginFontFamily',
type: 'text',
title: () => 'Font family',
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
onToggle: () => {},
onCommit: (t, raw) => {
commits.push([t.key, raw])
return raw
},
}))
const input = container.querySelector('input')!
typeAndBlur(input, 'Monaco')
expect(commits).toEqual([['myPluginFontFamily', 'Monaco']])
// The canonical return is adopted into the draft.
expect(input.value).toBe('Monaco')
unmount()
})
it('clamps numbers into the declared bounds on commit', () => {
const commits: Array<[string, number]> = []
const toggle: SidebarSettingToggle = {
key: 'myPluginRowPx',
type: 'number',
title: () => 'Row height',
min: 0,
max: 120,
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: withPluginKey('myPluginRowPx', 40),
onToggle: () => {},
onCommit: (t, raw) => {
const parsed = Number(raw)
const clamped = Math.min(120, Math.max(0, Math.round(parsed)))
commits.push([t.key, clamped])
return String(clamped)
},
}))
const input = container.querySelector('input')!
// Above the declared max: the commit clamps to 120.
typeAndBlur(input, '130')
expect(commits).toEqual([['myPluginRowPx', 120]])
expect(input.value).toBe('120')
unmount()
})
it('clamps an emptied number input to the lower bound on commit (width-row precedent)', () => {
const commits: Array<[string, number]> = []
const toggle: SidebarSettingToggle = {
key: 'myPluginRowPx',
type: 'number',
title: () => 'Row height',
min: 0,
max: 120,
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: withPluginKey('myPluginRowPx', 40),
onToggle: () => {},
// The parent mirrors the real handler: an emptied number parses to 0
// and clamps into the bounds (a browser number input never holds a
// non-numeric string — the draft can only be empty or numeric).
onCommit: (t, raw) => {
const clamped = Math.min(120, Math.max(0, Math.round(Number(raw))))
commits.push([t.key, clamped])
return String(clamped)
},
}))
const input = container.querySelector('input')!
typeAndBlur(input, '')
expect(commits).toEqual([['myPluginRowPx', 0]])
expect(input.value).toBe('0')
unmount()
})
it('reverts the draft to the committed value after a failed commit reverts prefs', () => {
const toggle: SidebarSettingToggle = {
key: 'terminalFontFamily',
type: 'text',
title: () => 'Font family',
}
// The parent mirrors the real handler: the optimistic commit adopts the
// typed value, and a FAILED write reverts prefs to the stored one.
let prefsNow = { ...prefs, terminalFontFamily: 'Old' }
const { container, rerender, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: prefsNow,
onToggle: () => {},
onCommit: (_t, raw) => raw,
}))
const input = container.querySelector('input')!
typeAndBlur(input, 'New')
// Optimistic commit: the draft adopts the typed value.
expect(input.value).toBe('New')
// The optimistic pref lands (parent state): the key changes, the row
// remounts with the same value — no visible reset while editing.
prefsNow = { ...prefsNow, terminalFontFamily: 'New' }
rerender(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: prefsNow,
onToggle: () => {},
onCommit: (_t, raw) => raw,
}))
expect(container.querySelector('input')!.value).toBe('New')
// The write fails: prefs revert to the stored value and the row
// remounts with it (the stale draft is gone).
prefsNow = { ...prefsNow, terminalFontFamily: 'Old' }
rerender(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: prefsNow,
onToggle: () => {},
onCommit: (_t, raw) => raw,
}))
expect(container.querySelector('input')!.value).toBe('Old')
unmount()
})
})
/** Open one select row's dropdown: click the anchor, the Menu portals its
* list into document.body (role="menuitem" rows). */
function openSelect(container: HTMLDivElement): HTMLElement[] {
const anchor = container.querySelector<HTMLButtonElement>('button[aria-haspopup="listbox"]')!
act(() => { anchor.click() })
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
}
describe('FeatureSettingsRows select rows (interactive)', () => {
const options: NonNullable<SidebarSettingToggle['options']> = [
{ value: true, icon: (size: number) => createElement('i', { 'data-size': size }), title: () => 'Merged', desc: () => 'Docked tree' },
{ value: false, icon: (size: number) => createElement('i', { 'data-size': size }), title: () => 'Split', desc: () => 'Two tabs' },
]
it('commits the picked option value and closes (iconed single select)', () => {
const commits: Array<[string, unknown]> = []
const toggle: SidebarSettingToggle = {
key: 'editorExplorer',
type: 'select',
title: () => 'Editor explorer',
options,
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
// Merged is the selected option for this scenario (the default is now
// separate — the anchor must render whatever value the prefs carry).
prefs: { ...prefs, editorExplorer: true },
onToggle: () => {},
onSelectValue: (t, next) => { commits.push([t.key, next]) },
}))
// The closed anchor shows the selected option's title (icon variant).
expect(container.textContent).toContain('Merged')
const items = openSelect(container)
// Big-icon cards: title + desc per option.
expect(items.map(item => item.textContent)).toEqual(['MergedDocked tree', 'SplitTwo tabs'])
act(() => { items[1]!.click() })
expect(commits).toEqual([['editorExplorer', false]])
// Single-pick closes the dropdown.
expect(document.querySelectorAll('[role="menuitem"]')).toHaveLength(0)
unmount()
})
it('toggles membership and commits the picked values in options order (multi)', () => {
const commits: Array<[string, unknown]> = []
const plain: NonNullable<SidebarSettingToggle['options']> = [
{ value: 'a', title: () => 'Alpha' },
{ value: 'b', title: () => 'Beta' },
{ value: 'c', title: () => 'Gamma' },
]
const toggle: SidebarSettingToggle = {
key: 'pluginKey',
type: 'select',
multi: true,
title: () => 'Pick several',
options: plain,
}
const rows = (value: unknown) => createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
onToggle: () => {},
onSelectValue: (t, next) => { commits.push([t.key, next]) },
valueSource: () => value,
})
const { container, rerender, unmount } = renderRoot(rows(['c', 'a']))
// The anchor shows the picked titles; options follow the declared order.
const items = openSelect(container)
expect(items.map(item => item.textContent)).toEqual(['Alpha', 'Beta', 'Gamma'])
// Deselect 'a' → ['c'] is normalized to options order… (['c'] here).
act(() => { items[0]!.click() })
expect(commits).toEqual([['pluginKey', ['c']]])
// The menu stays open under multi; re-render with the committed value.
rerender(rows(['c']))
const again = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
expect(again).toHaveLength(3)
// Select 'b' → committed in OPTIONS order, not pick order.
act(() => { again[1]!.click() })
expect(commits[1]).toEqual(['pluginKey', ['b', 'c']])
unmount()
})
it('shows an em dash when nothing is selected', () => {
const toggle: SidebarSettingToggle = {
key: 'editorExplorer',
type: 'select',
title: () => 'Editor explorer',
options,
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
onToggle: () => {},
valueSource: () => undefined,
}))
expect(container.querySelector('button[aria-haspopup="listbox"]')!.textContent).toContain('—')
unmount()
})
})