merge fix/settings-nav-icon-slot: 设置导航图标改走宿主插槽,消除双图标

This commit is contained in:
Menghuan1918 committed 2026-11-05 00:55:21 +08:00
commit 11e6c8e63a
8 files changed
+85 -263

No files matched your search

+5
View File
@@ -2,6 +2,11 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### 未发布
- 🎯 **设置页「侧边卡片」的导航图标不再叠成两个**:插件此前按"宿主设置导航还没有图标通道"的老假设,用 CSS 把兜底齿轮藏起来、再画自己的图标;宿主早已提供按 section id 寻址的 `settings.section.icon` 插槽,而且图标的 DOM 外面多了一层 span,老选择器失效后兜底 SVG 露了出来,与插件图标并排显示。现在改为**走宿主插槽**提供图标,删掉标记 + CSS 遮罩那一套(顺带去掉了一个监听整个 document 的 MutationObserver)。
- 🧪 测试:`tests/settings-nav-icon.spec.tsx` 钉住图标按宿主给的 `size` 缩放、只用 `currentColor`;真实宿主上用无头浏览器确认导航行只剩一个 `svg`、无残留标记。
### v0.30.0
- 🧭 **适配 DSH 0.2.2-rc.1(本版 peer 下限抬到 `^0.2.2-rc.1`)**:宿主把模型选择从可安装的 `ModelSelectionRef` 换成 agent 自有的 `AgentModel`——`agent.model.select()` 同时落盘并作用于下一步,侧边对话的线程模型选择随之改写(不再自己 install 一份 ref);`dsh-tools` 移除了 PTC(`tool/ptc-dispatch*`)的事件**类型声明**(运行期仍记录),宿主图标由内联 `<path>` 改为 sprite `<use href="#dsw-icon-…">`。**支持线随之移动**:0.x 的 caret 不跨 minor,因此 DSH 0.2.1 线(`0.2.1-rc.1 ~ rc.5`,即当前的宿主 npm `latest`)请继续固定插件 **v0.28.2**(`v0.29.0` 从未发布到 npm),0.2.2-rc.1+ 请用 **v0.30.0**。
+5
View File
@@ -4,6 +4,11 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### Unreleased
- 🎯 **The "Side card" settings row no longer shows two icons**: the plugin still assumed the settings navigation had no icon channel, so it hid the fallback gear with CSS and painted its own glyph. The shell has long since exposed a `settings.section.icon` slot addressed by section id, and it now wraps the nav icon in a span — the stale `> svg:first-child` rule stopped hiding the fallback, so both glyphs rendered side by side. The row now contributes its icon **through the slot**, and the marker + CSS-mask apparatus is gone (along with a document-wide MutationObserver).
- 🧪 `tests/settings-nav-icon.spec.tsx` pins the glyph to the slot-provided `size` and `currentColor`; a headless pass against a real host confirms one `svg` in the row and no leftover marker.
### v0.30.0
- 🧭 **Adapted to DSH 0.2.2-rc.1 (peer floors move to `^0.2.2-rc.1`)**: the host replaced the installable `ModelSelectionRef` with an agent-owned `AgentModel` — `agent.model.select()` records the choice durably and applies it to the next step, so the side-chat thread model selection rides the agent's own handle instead of an installed ref. `dsh-tools` dropped the PTC (`tool/ptc-dispatch*`) event **type declarations** (the runtime still records them), and host icons switched from inline `<path>` to sprite `<use href="#dsw-icon-…">`. **The support line moves with it**: a 0.x caret never spans a minor, so DSH 0.2.1 hosts (`0.2.1-rc.1 ~ rc.5`, today's npm `latest`) keep pinning plugin **v0.28.2** (`v0.29.0` was never published), while 0.2.2-rc.1+ takes **v0.30.0**.
+13
View File
@@ -26,6 +26,19 @@ export const IconTerminalOutline16 = ({ size = 16, className }: IconProps) => (
</svg>
)
/**
* Settings-navigation glyph for the "Side card" section. The shell asks for a
* square edge and tints the SVG with `currentColor`, so this stays a plain
* two-tone outline mark: the side panel plus the two rails it docks against.
*/
export const IconSideCardNav = ({ size = 16, className }: IconProps) => (
<svg width={size} height={size} className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 7v10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
<path d="M6 5v14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
<rect x="10" y="3" width="12" height="18" rx="2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)
/** Diff glyph in the app's outline style: a file frame with a plus and a minus row. */
export const IconDiffOutline16 = ({ size = 16, className }: IconProps) => (
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+15 -10
View File
@@ -26,7 +26,8 @@ import { createNativeSurface } from './native/surface.ts'
import { isTargetAvailable, openInterceptedLink, registerLinkInterception, shouldTakeOverLink } from './link-intercept.ts'
import { registerImeGuard } from './ime-guard.ts'
import { registerQuoteSource } from './selection-quote.ts'
import { registerSettingsNavIcon } from './settings-nav-icon.ts'
import { IconSideCardNav } from './icons.tsx'
import type { SettingsSectionIconOwnerProps } from '@deepseek-ai/dsh-client-ui-settings/client'
import { loadBootDecision } from './prefs.ts'
import { SideCardSection } from './SideCardSection.tsx'
import { api } from './api.ts'
@@ -462,15 +463,19 @@ export function apply(ctx: Context): void {
'dsh-better-sidebar: IME composition guard',
)
// DSH 0.1.x does not yet carry an icon through the settings.section
// registration contract: its shell renders a generic gear for every
// external section. Mark only this plugin's localized nav row so
// layout.css can paint the requested Side card SVG; the disposer clears
// the marker for HMR / plugin disable.
ctx.effect(
() => registerSettingsNavIcon(() => t('settingsNav')),
'dsh-better-sidebar: settings navigation icon',
)
// The settings nav icon, contributed through the shell's own slot. The
// contract addresses an icon by the section id (an unmatched id never
// renders) and says the shell keeps its default glyph when none is
// registered — so filling the slot REPLACES the fallback. The old
// marker-and-CSS-mask replacement is gone with it: under the current shell
// the nav icon is wrapped in a span, the stale `> svg:first-child` rule
// stopped hiding the fallback and the row painted two glyphs.
ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
name: 'settings.section.icon',
id: 'better-sidebar',
order: 100,
label: () => t('settingsNav'),
}, ({ size }: SettingsSectionIconOwnerProps) => createElement(IconSideCardNav, { size })))
// The "Side card" settings section: appears in the DSH Settings shell
// once the shell's declaration is on the ledger (slots.inject waits for
-19
View File
@@ -55,25 +55,6 @@ body[data-dsh-sidebar-dragging] #root [data-dsh-center-col] {
transition: none;
}
/* DSH 0.1.x gives external settings sections a generic gear and exposes no
icon field in the settings.section contract. settings-nav-icon.ts marks
only this plugin's localized row; render the requested Lucide
gallery-horizontal-end SVG as a currentColor mask so it follows the native
nav hover/active colors without changing the shell's 16px icon rhythm. */
[data-dsh-better-sidebar-settings-nav] > svg:first-child {
display: none;
}
[data-dsh-better-sidebar-settings-nav]::before {
content: '';
flex: none;
width: 16px;
height: 16px;
background: currentColor;
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2 7v10'/%3E%3Cpath d='M6 5v14'/%3E%3Crect width='12' height='18' x='10' y='3' rx='2'/%3E%3C/svg%3E") center / contain no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2 7v10'/%3E%3Cpath d='M6 5v14'/%3E%3Crect width='12' height='18' x='10' y='3' rx='2'/%3E%3C/svg%3E") center / contain no-repeat;
}
@media (prefers-reduced-motion: reduce) {
#root [data-dsh-center-col] {
transition: none;
-68
View File
@@ -1,68 +0,0 @@
/**
* Mark this plugin's row in the DSH settings navigation so its bundled CSS
* can replace the shell's fallback gear with the Side card glyph.
*
* DSH 0.1.x projects only `id`, `order`, and `label` from a
* `settings.section` registration, then chooses icons inside the settings
* shell from a closed list of built-in ids. Until that public contract grows
* an icon field, the plugin identifies only its own localized row after the
* dialog mounts. The marker owns no shell structure and is removed on fiber
* disposal, so the adaptation remains HMR-safe.
*
* Mutation bursts are coalesced into one sync per animation frame: the
* observer watches the whole body, so chat streaming would otherwise run the
* document-wide row query at microtask cadence.
*/
export const SETTINGS_NAV_MARKER = 'data-dsh-better-sidebar-settings-nav'
/**
* Keep the marker on the settings-nav button whose visible text is this
* plugin's current localized section label.
* @param label - locale-aware label resolver used by the section registration.
* @returns disposer that disconnects observation and removes owned markers.
*/
export function registerSettingsNavIcon(label: () => string): () => void {
let disposed = false
let frame: number | null = null
const sync = (): void => {
if (disposed) return
const currentLabel = label().trim()
const buttons = document.querySelectorAll<HTMLButtonElement>('[role="dialog"] nav button')
for (const button of buttons) {
const matches = currentLabel.length > 0 && button.textContent?.trim() === currentLabel
if (matches) button.setAttribute(SETTINGS_NAV_MARKER, '')
else button.removeAttribute(SETTINGS_NAV_MARKER)
}
}
/** One sync per frame at most: the first mutation of a burst schedules it. */
const schedule = (): void => {
if (disposed || frame !== null) return
frame = requestAnimationFrame(() => {
frame = null
sync()
})
}
sync()
// No `characterData`: the marker is a function of the mounted buttons and
// their text, and every dialog mount/unmount or row insert/remove already
// changes childList. Watching character data made this observer fire for
// every streamed token in the main conversation — a document-wide
// `querySelectorAll('[role="dialog"] nav button')` per token burst.
const observer = new MutationObserver(schedule)
observer.observe(document.body, { childList: true, subtree: true })
return () => {
disposed = true
observer.disconnect()
if (frame !== null) {
cancelAnimationFrame(frame)
frame = null
}
document.querySelectorAll(`[${SETTINGS_NAV_MARKER}]`)
.forEach(element => { element.removeAttribute(SETTINGS_NAV_MARKER) })
}
}
-166
View File
@@ -1,166 +0,0 @@
// @vitest-environment jsdom
/**
* Settings-navigation icon marker tests (including delayed dialog mount).
*
* v0.25 的稳态开销治理:观察者改 rAF 合帧 + 去掉 `characterData`。三条契约:
* 1. 标记仍然落在本地化标签匹配的那一行上(挂载/改标签的既有用例);
* 2. 同一帧里的一串 DOM 文本 mutation 只做**一次**全文档行查询;
* 3. 纯文本节点内容变化(对话流式输出就是它)不再触发任何查询。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { registerSettingsNavIcon, SETTINGS_NAV_MARKER } from '../src/client/settings-nav-icon.ts'
/** 被观察者查询的行选择器(统计它,而不是 disposer 的标记清理查询)。 */
const NAV_SELECTOR = '[role="dialog"] nav button'
/** 确定性 rAF:只有在 flushFrame() 里才推进一帧。 */
let frames: Map<number, FrameRequestCallback>
let nextFrameId: number
function flushFrame(): void {
const callbacks = [...frames.values()]
frames.clear()
for (const callback of callbacks) callback(0)
}
function navButton(label: string): HTMLButtonElement {
const button = document.createElement('button')
button.innerHTML = `<svg data-fallback="gear"></svg><span>${label}</span>`
return button
}
function dialogWith(...buttons: HTMLButtonElement[]): HTMLElement {
const dialog = document.createElement('div')
dialog.setAttribute('role', 'dialog')
const nav = document.createElement('nav')
nav.append(...buttons)
dialog.append(nav)
return dialog
}
async function mutationTick(): Promise<void> {
await new Promise<void>(resolve => { setTimeout(resolve, 0) })
}
/** 一次 mutation 走到「观察者回调(微任务)→ 合帧后的一次 sync」。 */
async function settleMarker(): Promise<void> {
await mutationTick()
flushFrame()
}
/** 观察者查询行的次数(标记清理的查询不算)。 */
function navQueries(spy: { mock: { calls: unknown[][] } }): number {
return spy.mock.calls.filter(call => call[0] === NAV_SELECTOR).length
}
beforeEach(() => {
frames = new Map()
nextFrameId = 1
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
frames.set(nextFrameId, callback)
return nextFrameId++
})
vi.stubGlobal('cancelAnimationFrame', (id: number) => {
frames.delete(id)
})
})
afterEach(() => {
document.body.innerHTML = ''
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
describe('registerSettingsNavIcon', () => {
it('marks only the matching settings row and preserves the shell icon DOM', () => {
const general = navButton('General')
const sideCard = navButton('Side card')
document.body.append(dialogWith(general, sideCard))
const dispose = registerSettingsNavIcon(() => 'Side card')
expect(general.hasAttribute(SETTINGS_NAV_MARKER)).toBe(false)
expect(sideCard.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true)
expect(sideCard.querySelector('[data-fallback="gear"]')).not.toBeNull()
dispose()
expect(sideCard.hasAttribute(SETTINGS_NAV_MARKER)).toBe(false)
})
it('marks a dialog mounted later and follows a localized label change', async () => {
let label = 'Side card'
const dispose = registerSettingsNavIcon(() => label)
const english = navButton('Side card')
const chinese = navButton('侧边卡片')
const dialog = dialogWith(english, chinese)
document.body.append(dialog)
await settleMarker()
expect(english.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true)
expect(chinese.hasAttribute(SETTINGS_NAV_MARKER)).toBe(false)
label = '侧边卡片'
chinese.querySelector('span')!.textContent = '侧边卡片 '
await settleMarker()
expect(english.hasAttribute(SETTINGS_NAV_MARKER)).toBe(false)
expect(chinese.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true)
dispose()
})
it('coalesces a burst of mutations into one sync per frame', async () => {
const dispose = registerSettingsNavIcon(() => 'Side card')
const button = navButton('Side card')
document.body.append(dialogWith(button))
// 对话正文的形态:转写每来一个 token 就往正文容器里插一个文本节点,而设置行本身
// 一动不动。观察者盯的是整个 body,所以这些 mutation 都会打到它身上。
const stream = document.createElement('div')
document.body.append(stream)
await settleMarker()
const query = vi.spyOn(document, 'querySelectorAll')
for (let index = 0; index < 6; index++) {
stream.append(document.createTextNode(`token ${index}`))
// 每个 token 一个宏任务(流式输出的节拍):观察者是同步回调时,每次都会跑一次
// 全文档行查询。
await mutationTick()
}
expect(navQueries(query), '还没到帧,一次都不该查').toBe(0)
flushFrame()
expect(navQueries(query), '同一帧内的一串 mutation 只查一次').toBe(1)
// 合帧不改变结果:帧末那次 sync 仍把标记留在唯一匹配的行上。
expect(button.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true)
dispose()
})
it('ignores characterData-only mutations (streamed conversation tokens)', async () => {
const dispose = registerSettingsNavIcon(() => 'Side card')
const button = navButton('Side card')
document.body.append(dialogWith(button))
// 对话正文那样的一串文本节点:先排掉挂载那一次观察者回调。
const streamed = document.createTextNode('streaming 0')
document.body.append(streamed)
await settleMarker()
const query = vi.spyOn(document, 'querySelectorAll')
for (let index = 1; index <= 5; index++) {
streamed.data = `streaming ${index}`
await mutationTick()
}
flushFrame()
expect(navQueries(query), 'characterData 已被移出观察面').toBe(0)
expect(button.hasAttribute(SETTINGS_NAV_MARKER), '标记不受正文影响').toBe(true)
dispose()
})
it('cancels a pending frame when disposed', async () => {
const dispose = registerSettingsNavIcon(() => 'Side card')
document.body.append(dialogWith(navButton('Side card')))
// 观察到 mutation,但帧还没到就 dispose:回调必须被取消,不能再查一次。
await mutationTick()
const query = vi.spyOn(document, 'querySelectorAll')
dispose()
expect(frames.size, '待处理的那一帧被取消').toBe(0)
flushFrame()
expect(navQueries(query)).toBe(0)
})
})
+47
View File
@@ -0,0 +1,47 @@
/**
* The settings-nav glyph the plugin contributes through
* `settings.section.icon`.
*
* The shell owns the nav button and label and asks the registrant for a square
* glyph: it passes the requested edge as `size` and tints the SVG with
* `currentColor`, so the component must scale with that prop and must not carry
* its own color. This replaced a marker + CSS-mask hack that assumed the
* fallback gear was a direct `svg` child of the button; once the shell wrapped
* it in a span the stale rule stopped hiding it and the row painted two glyphs.
*/
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { createElement } from 'react'
import { renderRoot } from './test-utils.ts'
import { IconSideCardNav } from '../src/client/icons.tsx'
describe('settings navigation icon', () => {
it.each([16, 24])('honours the requested square edge (%i px)', (size) => {
const { container, unmount } = renderRoot(createElement(IconSideCardNav, { size }))
try {
const svg = container.querySelector('svg')
expect(svg).not.toBeNull()
expect(svg!.getAttribute('width')).toBe(String(size))
expect(svg!.getAttribute('height')).toBe(String(size))
expect(svg!.getAttribute('viewBox')).toBe('0 0 24 24')
} finally {
unmount()
}
})
it('paints with currentColor only (the shell owns the tint)', () => {
const { container, unmount } = renderRoot(createElement(IconSideCardNav, { size: 16 }))
try {
const svg = container.querySelector('svg')!
expect(svg.getAttribute('fill')).toBe('none')
for (const element of svg.querySelectorAll('path, rect, circle, line, polygon')) {
const stroke = element.getAttribute('stroke')
if (stroke !== null) expect(stroke).toBe('currentColor')
expect(element.getAttribute('fill')).toBeNull()
expect(element.getAttribute('style')).toBeNull()
}
} finally {
unmount()
}
})
})