Merge pull request #8858 from deepseek-harness/perf/conversation-width-axis-restyle

perf(ui-conversation): stop restyling the transcript on every resize frame
This commit is contained in:
imccyu authored and GitHub committed 2026-11-20 12:21:34 +08:00
commit 40c607086c
39 files changed
+907 -209

No files matched your search

@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-11-20-rightbar-drag-restyle-budget.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md
/agent-note-right-sidebar-drag-restyle-budget:
en: a467dea2219bda57
zh: 7bcd04d8a6dd8481
/agent-note-right-sidebar-drag-restyle-budget/problem:
en: 693e8d1e4423b78f
zh: c63608002d762c12
/agent-note-right-sidebar-drag-restyle-budget/decision:
en: 83d40f59669f4d33
zh: 1e8de8d1b7e62861
/agent-note-right-sidebar-drag-restyle-budget/calibration:
en: dc1b35868c5ea353
zh: 546aca16b16ca98b
/agent-note-right-sidebar-drag-restyle-budget/alternatives-considered:
en: 721cbfb3276fcb5b
zh: 9557ee132f77f5a6
/agent-note-right-sidebar-drag-restyle-budget/consequences:
en: 8efe7bc510ccabc8
zh: 7c3bca6253797e40
@@ -0,0 +1,41 @@
# Agent Note: Right Sidebar drag restyle budget
Status: implemented
English | [中文](2026-11-20-rightbar-drag-restyle-budget.zh.md)
## Problem
Dragging the right Sidebar beside a long transcript stalled for hundreds of milliseconds per frame. The Conversation body published measured widths as unregistered, inherited custom properties on an ancestor of the whole transcript, so every frame restyled every transcript element, even when the resolved content width did not change; later resize observers that read geometry forced that work synchronously. Existing browser benchmarks open, page, and stream a long Session, but none resizes it, so the regression had no gate.
## Decision
The [right Sidebar drag benchmark](../../../../benchmarks/rightbar-drag-browser/README.md) joins the serial browser inventory. It loads a 120-turn synthetic Session completely, opens the right Sidebar, and drags its handle 40 trusted 8px mouse steps outward and back in a 1680×1000 viewport, in two fresh scaffold worlds and browsers. At that width the transcript column stays below the 680px content-width floor, and each drag asserts it, so the drag changes the column but not the resolved content width.
The restyle ratio is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count. The 1680px case budgets the upper median per direction at 1. A second case keeps the rendered column at 720px and crosses the hidden Session panel's reserve-room threshold. It budgets each direction at 0.10: a single transcript-wide recalculation matters even if it happens on only one of the 40 steps. Neither count scales with CPU speed, and no wall-clock endpoint is budgeted or passed to the scaling report.
## Calibration
Local Linux x64 Chromium samples, 40-step drags:
| Workload | Widen | Narrow |
|---|---:|---:|
| 200 turns, before the width axis change | 1,479,947 / 28,895 = 51.2 | 1,909,568 / 28,895 = 66.1 |
| 200 turns, after | 2,622 / 28,895 = 0.09 | 3,368 / 28,895 = 0.12 |
| 120 turns, after (both samples) | 2,622 / 18,383 = 0.14 | 3,368 / 18,383 = 0.18 |
The restyled count after the change is identical across samples and history lengths, so the ratio leaves more than five times headroom at 120 turns, while the pre-change behavior exceeds the budget fifty-fold. The case's first test replays these recorded values as its negative control.
In the 120-turn Chromium trace, 40 `Layout` events per direction ran inside script before the geometry-read fix and none afterwards. A second budget allows 20 script-nested layouts per drag: it rejects repeated synchronous layout without requiring every callback to be layout-free or penalizing normal reflow after script returns.
At 2560px with 120 turns and a 720px rendered column, the required benchmark traces the full drag against built Web artifacts, including the press and release. Before the fix, widening restyled 18,239 / 18,428 = 0.98974, failing the 0.10 budget. A diagnostic trace attributed 14,911 restyled elements to a single reserve-room flip. After the fix, widening restyled 380 / 18,428 = 0.02062 and narrowing restyled 379 / 18,428 = 0.02057. The Sidebar moved 80px each way, the column stayed at 720px, and the probe switched in both directions. The budget allows 1,842 restyles: nearly five times either passing count, but less than 40 updates of 82 elements even without the single large recalculation.
## Alternatives considered
- Budget frame gaps or style milliseconds. Rejected for the gate: they need browser-runner calibration that does not exist yet, and they also include the transcript reflow at each new column width, which a resize legitimately pays. They remain diagnostics.
- Add the drag to the manual `apps/web` performance lane. Rejected: that lane runs only on request, and this regression must fail CI.
- Budget a viewport where the content width changes during the drag. Rejected: inherited width changes legitimately restyle descendants, so the count would measure the content width's consumers rather than the regression.
## Consequences
A regression that again publishes per-frame inputs to the transcript fails CI within one benchmark run, with no timing calibration. The case does not cap total layout or paint cost, nor does it cover window resizing, the Conversation's own width handles, or a docked Session panel, whose end reserve can change the content inset during a drag. Chromium's element counting may change across browser versions; an upgrade that moves the counts re-records the calibration values above and in the negative control.
@@ -0,0 +1,41 @@
# Agent Note:右侧栏拖动样式重算预算
Status: implemented
[English](2026-11-20-rightbar-drag-restyle-budget.md) | 中文
## 问题
在长会话旁拖动右侧栏时,每帧会卡住数百毫秒。Conversation 主体把测得的宽度作为未注册、可继承的自定义属性写在整段记录的祖先元素上,因此即使解析后的正文宽度不变,每一帧也要重算整段记录所有元素的样式;随后读取几何值的 ResizeObserver 又迫使这些工作同步完成。现有浏览器基准覆盖打开、分页和流式输出长会话,但没有一个调整它的宽度,所以这一回归没有门禁。
## 决定
[右侧栏拖动基准](../../../../benchmarks/rightbar-drag-browser/README.zh.md)加入串行浏览器清单。它完整加载一个 120 轮合成会话,打开右侧栏,在 1680×1000 视口中把拖拽条向外拖 40 个 8px 的真实鼠标步再拖回,在两个全新的脚手架环境和浏览器中各做一次。该宽度下正文列始终窄于 680px 的正文宽度下限,每次拖动都会断言这一点,因此拖动改变的是列宽,而不是解析后的正文宽度。
样式重算比值是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` 追踪事件报告的元素数之和,除以页面元素数。1680px 用例按方向取上中位数,最多为 1。另一个用例让实际渲染的正文列保持 720px,同时跨越隐藏会话面板的空间预留阈值。其每个方向的比值不得超过 0.10:在 40 步中,即使只有一步重算整段记录的样式,也不能忽略。两种计数都不随 CPU 速度缩放;没有为墙钟终点设置预算,也不将其传给缩放报告。
## 校准
本地 Linux x64 Chromium 样本,每次拖动 40 步:
| 负载 | 加宽 | 缩窄 |
|---|---:|---:|
| 200 轮,宽度轴改动前 | 1,479,947 / 28,895 = 51.2 | 1,909,568 / 28,895 = 66.1 |
| 200 轮,改动后 | 2,622 / 28,895 = 0.09 | 3,368 / 28,895 = 0.12 |
| 120 轮,改动后(两个样本相同) | 2,622 / 18,383 = 0.14 | 3,368 / 18,383 = 0.18 |
改动后重算的元素数在各样本和不同历史长度下完全相同,因此 120 轮时比值留有五倍以上余量,而改动前的行为超出预算五十倍。用例的第一个测试回放这些记录值作为负对照。
在 120 轮负载的 Chromium 追踪中,几何读取修复前每个方向都有 40 次 `Layout` 发生在脚本执行期间,修复后均为 0 次。第二项预算允许每次拖动最多 20 次脚本内布局:它能拦住反复触发同步布局的回归,而不要求每个回调都没有布局,也不惩罚脚本返回后的正常重排。
在 2560px 视口中完整加载 120 轮、正文实际列宽固定为 720px 时,必需基准使用构建后的 Web 产物,追踪包含按下和松开鼠标的整个拖动过程。修复前,加宽方向的重算比值为 18,239 / 18,428 = 0.98974,超过 0.10 的预算。诊断追踪显示,仅一次预留状态翻转就重算了 14,911 个元素。修复后,加宽方向为 380 / 18,428 = 0.02062,缩窄方向为 379 / 18,428 = 0.02057。两个方向的侧栏都移动了 80px,正文列保持 720px,探针均发生翻转。预算允许重算 1,842 个元素,接近两个实测值的五倍;即使没有那次大幅重算,每步重算 82 个元素、连续 40 步也会超限。
## 备选方案
- 为帧间隔或样式毫秒数设预算。门禁不采用:它们需要尚不存在的浏览器 runner 校准,而且还包含按每个新列宽重排正文的成本,这是缩放本应付出的。它们保留为诊断输出。
- 把拖动加入 `apps/web` 的手动性能通道。不采用:该通道只按需运行,而这一回归必须让 CI 失败。
- 选一个拖动中正文宽度会变化的视口设预算。不采用:继承的宽度变化本来就会重算后代样式,计数测到的会是正文宽度的使用者,而不是这一回归。
## 影响
再次把逐帧变化的输入传给整段记录的回归会在一次基准运行内让 CI 失败,不需要任何计时校准。本用例不为布局或绘制的总成本设限,也不覆盖窗口缩放、Conversation 自身的宽度拖拽条,也不测量停靠的 Session 面板,因为它的末端预留可能在拖动中改变正文内边距。Chromium 的元素计数方式可能随浏览器版本变化;改变计数的升级需要重新记录上面的校准值和负对照中的值。
+3 -3
View File
@@ -216,13 +216,13 @@ async function awaitTableLayout(target: Page): Promise<void> {
const element = document.querySelector('[data-sidebar-collapsed][data-rightbar-collapsed]')
if (element === null) return false
const tracks = getComputedStyle(element).gridTemplateColumns.split(' ').map(Number.parseFloat)
const root = element.querySelector<HTMLElement>('div[data-phase]')
const body = element.querySelector<HTMLElement>('div[data-phase] [data-conversation-content]')
// Desktop retains the rail; the mobile drawer leaves the whole width to the transcript.
return tracks[0] === (element.hasAttribute('data-sidebar-drawer') ? 0 : 56) && tracks.at(-1) === 0
&& element.getAnimations().every(animation =>
animation.playState === 'finished' || animation.playState === 'idle')
&& root !== null
&& root.style.getPropertyValue('--dsh-conversation-column-width') === `${String(root.offsetWidth)}px`
&& body !== null
&& body.style.getPropertyValue('--dsh-conversation-column-width') === `${String(body.offsetWidth)}px`
}, undefined, { timeout: 10_000 })
}
+7 -2
View File
@@ -474,7 +474,10 @@ describe('web e2e: shipped right Sidebar', () => {
}
await expect.poll(async () => await tabTitles(column)).toEqual(['Start'])
await expectTitleAlignment(column.locator('[data-dockkit-tab-title]'))
const guideTitle = column.locator('[data-dockkit-tab-title]')
await expectTitleAlignment(guideTitle)
// Even this short, unclosable title has the ordinary edge mask, not the close-button mask.
expect(await guideTitle.evaluate(el => getComputedStyle(el).maskImage)).toContain('16px')
await expect.poll(async () => await column.locator('[data-sidebar-right-guide-entry]').count()).toBe(2)
expect(await column.locator('[data-sidebar-right-guide-entry="browser"]').count()).toBe(0)
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
@@ -484,7 +487,9 @@ describe('web e2e: shipped right Sidebar', () => {
const addTab = column.locator('[data-dockkit-add-tab]')
const filesTab = column.locator('[data-dockkit-tab]').filter({ hasText: 'Files' })
await expect.poll(async () => await tabTitles(column)).toEqual(['Files'])
await expectTitleAlignment(filesTab.locator('[data-dockkit-tab-title]'))
const filesTitle = filesTab.locator('[data-dockkit-tab-title]')
await expectTitleAlignment(filesTitle)
expect(await filesTitle.evaluate(el => getComputedStyle(el).maskImage)).toContain('14px')
await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' })
expect(await filesTab.locator('[data-dockkit-tab-close]').count()).toBe(1)
await expect.poll(async () => await addTab.count()).toBe(1)
@@ -0,0 +1,13 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write benchmarks/rightbar-drag-browser/README.md
/right-sidebar-drag-browser-benchmark:
en: 0ec06c11a4e9680c
zh: 2aa104d63575bfcf
/right-sidebar-drag-browser-benchmark/run:
en: 0dce8b92617ea78b
zh: 22ce9ccc29acda36
/right-sidebar-drag-browser-benchmark/measurements:
en: ece05c9d313f7906
zh: 0c54ddf5bb75b162
@@ -0,0 +1,23 @@
# Right Sidebar drag browser benchmark
English | [中文](README.zh.md)
The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) drags the right Sidebar's resize handle beside a synthetic 120-turn Session whose older pages are all loaded, and counts restyled elements and layouts during the drag. The shipped Web scaffold owns the isolated home, persistence, and loopback listener; Chromium loads the built Web artifacts.
## Run
`pnpm run test:bench` builds libraries, workers, and Web artifacts before running the serial benchmark inventory. With artifacts already built, select this directory through `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/rightbar-drag-browser`. A shell that exports `NODE_USE_ENV_PROXY` unsets it first, as the [test proxy setup](../../scripts/test-proxy-environment.ts) requires.
## Measurements
Each Chromium trace spans one trusted drag through two animation frames after release. The benchmark uses two fresh browser processes and scaffold worlds, with the Session panel hidden.
- **Changing column:** Each sample widens the right Sidebar by 40 steps of 8px and drags it back in a 1680×1000 viewport. The rendered transcript column must narrow as the Sidebar widens and widen on return; both endpoints must be below the 680px content-width floor.
- **Fixed column:** The first sample also opens the same 120 turns in a separate page with fresh storage, a 2560×1000 viewport and a saved 720px content width. After the opening slide settles, the visible Sidebar must reach each of 40 steps of 2px, from 1152px to 1232px and back. Every delivered transcript column width must be 720px. The Session panel's reserve-room value at its dock probe must switch from 1px to 0px and back.
- **Restyles:** Sum the elements reported by each style recalculation and divide by the page's element count. For the changing column, the upper median per direction must not exceed 1 (one page's worth). For the fixed column, each direction must not exceed 0.10.
- **Layouts:** Each changing-column drag must produce at least one `Layout` event. `layoutCount` includes them all; `scriptNestedLayoutCount` counts each layout fully enclosed by a script event on the same process and thread, including animation frame callbacks. This subset must not exceed 20 per drag (half the mouse steps). Nesting is a proxy for synchronous layout, not evidence that every nested layout is unnecessary; browser reflow outside script does not consume the budget.
Frame gaps and style and layout durations are diagnostics only. Neither budget scales with CPU speed.
The fixture contains mixed-language prose, lists, 12 code fences, 8 tables, reasoning, and 24 tool results. No model, tool, external network, recorded Session, or private Harness home supplies its content. The [decision record](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md) owns the workload choice, calibration, alternatives, and exclusions.
@@ -0,0 +1,23 @@
# 右侧栏拖动浏览器基准
[English](README.md) | 中文
[rightbar-drag.bench.ts](rightbar-drag.bench.ts) 中的必需 Chromium 用例在一个已加载全部更早分页的 120 轮合成会话旁拖动右侧栏的宽度拖拽条,并统计拖动期间重算样式的元素数和布局次数。随产品发布的 Web 测试脚手架提供隔离的 home、持久化和回环监听;Chromium 加载已构建的 Web 产物。
## 运行
`pnpm run test:bench` 先构建库、worker 和 Web 产物,再运行串行基准清单。产物已构建时,可通过 `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/rightbar-drag-browser` 只运行本目录。导出了 `NODE_USE_ENV_PROXY` 的 shell 需要先取消它,这是[测试代理设置](../../scripts/test-proxy-environment.ts)的要求。
## 测量
每次 Chromium 追踪覆盖一次真实鼠标拖动,直到松开后的两个动画帧。基准使用两个全新的浏览器进程和脚手架环境,均隐藏会话面板。
- **列宽变化:** 每个样本都在 1680×1000 视口中把右侧栏加宽 40 步(每步 8px),再拖回。实际渲染的正文列必须随侧栏加宽而变窄、随侧栏缩窄而变宽;起止列宽都必须低于 680px 的正文宽度下限。
- **列宽固定:** 第一个样本还在单独页面中打开相同的 120 轮记录;该页面使用独立存储,视口为 2560×1000,预存的正文宽度为 720px。侧栏展开动画结束后,从 1152px 到 1232px 再拖回,每个方向 40 步,每步 2px,可见侧栏必须逐步到达目标宽度。每次观察到的正文列宽都必须是 720px。会话面板的停靠探针上,标记预留空间是否足够的值必须从 1px 变为 0px,再变回 1px。
- **样式重算:** 各次样式重算报告的元素数之和除以页面元素数。列宽变化时,每个方向的上中位数不得超过 1(即一整个页面的元素数)。列宽固定时,每个方向的比值不得超过 0.10。
- **布局:** 列宽变化时,每次拖动必须产生至少一个 `Layout` 事件。`layoutCount` 统计所有布局;`scriptNestedLayoutCount` 只统计起止时间均落在同一进程、同一线程的脚本事件内的布局,每次布局只计一次,动画帧回调也算脚本事件。每次拖动此项不得超过 20(鼠标步数的一半)。嵌套关系是判断同步布局的间接指标,并不说明每次嵌套布局都多余;脚本以外的浏览器重排不占用该预算。
帧间隔、样式重算耗时和布局耗时仅作诊断。两项预算都不随 CPU 速度缩放。
夹具包含中英混排的正文、列表、12 个代码块、8 个表格、推理内容和 24 个工具结果。内容不来自任何模型、工具、外部网络、录制会话或私有 Harness home。[决策记录](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md)负责说明负载选择、校准、备选方案和排除项。
@@ -0,0 +1,290 @@
/** Required browser budgets for restyles and script-nested layout while dragging the right Sidebar beside a long history. */
import { chromium, type Browser, type Page } from 'playwright'
import { expect, it } from 'vitest'
import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from '../../apps/web/tests/scaffold.ts'
import { newEnglishPage } from '../../apps/web/tests/support.ts'
import { HISTORY_TURNS, SESSION_ID, syntheticHistory } from './synthetic-history.ts'
const SAMPLES = 2
/** Below the content width's 680px floor at this width, so the drag changes the column but not the resolved content width. */
const VIEWPORT = { width: 1680, height: 1000 }
const CONTENT_WIDTH_FLOOR_PX = 680
const FIXED_VIEWPORT = { width: 2560, height: 1000 }
const FIXED_COLUMN_PX = 720
const FIXED_PANEL_START_PX = 1152
const FIXED_STEP_PX = 2
const FIXED_RESTYLE_BUDGET = 0.1
const STEPS = 40
const STEP_PX = 8
const STEP_GAP_MS = 8
const TAIL = '[data-chat-flow-key*="turn-tail"]'
/**
* Elements restyled over one whole drag, as a multiple of the page's elements. A drag that restyles the
* transcript on every frame reaches about one multiple per frame; one that restyles only what the resize
* changes stays far below a single multiple.
*/
const RESTYLE_BUDGET = 1
/** The regression put one layout inside script per step; occasional script-nested layouts need not be waste. */
const SCRIPT_NESTED_LAYOUT_BUDGET = STEPS / 2
const SCRIPT_EVENTS = new Set(['FunctionCall', 'EventDispatch', 'FireAnimationFrame', 'TimerFire', 'RunMicrotasks', 'v8.callFunction'])
interface TraceEvent {
name: string
ph: string
pid: number
tid: number
ts: number
dur?: number
args?: { elementCount?: number }
}
interface TraceSummary {
styledElements: number
styleMs: number
layoutMs: number
layoutCount: number
scriptNestedLayoutCount: number
}
interface DragSample extends TraceSummary {
restyleRatio: number
frameP95Ms: number
columnWidthBefore: number
columnWidth: number
}
function expectRestylesWithinBudget(ratio: number, budget = RESTYLE_BUDGET): void {
expect(ratio).toBeLessThanOrEqual(budget)
}
function median(values: number[]): number {
return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]!
}
/** Style recalculation and layout totals from a Chromium timeline trace. */
function summarizeTrace(buffer: Buffer): TraceSummary {
const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[]
const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(event => event.ph === 'X')
const styles = events.filter(event => event.name === 'UpdateLayoutTree')
const layouts = events.filter(event => event.name === 'Layout')
const scripts = events.filter(event => SCRIPT_EVENTS.has(event.name))
expect(scripts.length, 'drag trace must contain script events').toBeGreaterThan(0)
const end = (event: TraceEvent): number => event.ts + (event.dur ?? 0)
const ms = (list: TraceEvent[]): number => list.reduce((total, event) => total + (event.dur ?? 0), 0) / 1000
return {
styledElements: styles.reduce((total, event) => total + (event.args?.elementCount ?? 0), 0),
styleMs: ms(styles),
layoutMs: ms(layouts),
layoutCount: layouts.length,
scriptNestedLayoutCount: layouts.filter(layout => scripts.some(script =>
script.pid === layout.pid && script.tid === layout.tid && script.ts <= layout.ts && end(layout) <= end(script),
)).length,
}
}
async function loadAll(page: Page): Promise<number> {
let count = await page.locator(TAIL).count()
while (count < HISTORY_TURNS) {
await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
await page.waitForFunction(
({ selector, previous }) => document.querySelectorAll(selector).length > previous,
{ selector: TAIL, previous: count },
)
count = await page.locator(TAIL).count()
}
return count
}
async function openLoadedSidebar(page: Page, url: string): Promise<number> {
page.setDefaultTimeout(60_000)
await page.goto(url, { waitUntil: 'load' })
await page.getByRole('treeitem').first().click()
await page.getByRole('treeitem').nth(1).click()
await page.locator(TAIL).last().waitFor()
expect(await loadAll(page)).toBe(HISTORY_TURNS)
await page.getByRole('button', { name: 'Open right sidebar' }).first().click()
await page.locator('[data-side="rightbar"]').waitFor()
// The Sidebar opens with a track transition; the drag starts from its settled width.
await page.waitForFunction(() => document.querySelector('[data-rightbar-collapsed], [data-animating]') === null)
return page.evaluate(() => document.querySelectorAll('*').length)
}
/** Frame timestamps the page collects during one drag. */
type FrameProbe = Window & { benchmarkFrames?: { frames: number[]; running: boolean } }
type FixedWidthProbe = typeof window & { benchmarkWidths: { column: Set<number>; panel: number } }
async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: number, fixedPanelStart?: number): Promise<DragSample> {
const box = await page.locator('[data-side="rightbar"]').boundingBox()
if (box === null) throw new Error('right Sidebar resize handle missing')
const x = box.x + box.width / 2
const y = box.y + box.height / 2
const readColumnWidth = (): Promise<number> => page.locator('[data-chat-flow]').first().evaluate(element => element.getBoundingClientRect().width)
const columnWidthBefore = await readColumnWidth()
await page.evaluate(() => {
const probe = { frames: [] as number[], running: true }
;(window as FrameProbe).benchmarkFrames = probe
const tick = (time: number): void => {
if (!probe.running) return
probe.frames.push(time)
requestAnimationFrame(tick)
}
requestAnimationFrame(tick)
})
await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] })
await page.mouse.move(x, y)
await page.mouse.down()
for (let step = 1; step <= STEPS; step++) {
const delta = direction * step * (fixedPanelStart === undefined ? STEP_PX : FIXED_STEP_PX)
await page.mouse.move(x - delta, y)
if (fixedPanelStart === undefined) await page.waitForTimeout(STEP_GAP_MS)
else {
// Observe the actual panel before sending the next move; a freeze or coalesced drag must not reduce the work count.
await page.waitForFunction(width => (window as FixedWidthProbe).benchmarkWidths.panel === width, fixedPanelStart + delta)
}
}
await page.mouse.up()
// Two animation frames let the release reach style and layout before the trace closes.
await page.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))))
const trace = summarizeTrace(await browser.stopTracing())
const frames = await page.evaluate(() => {
const probe = (window as FrameProbe).benchmarkFrames!
probe.running = false
return probe.frames
})
const gaps = frames.slice(1).map((time, index) => time - frames[index]!).sort((a, b) => a - b)
return {
...trace,
restyleRatio: trace.styledElements / elements,
frameP95Ms: gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * 0.95))] ?? 0,
columnWidthBefore,
columnWidth: await readColumnWidth(),
}
}
async function measureFixedColumn(browser: Browser, url: string): Promise<void> {
const page = await newEnglishPage(browser, FIXED_VIEWPORT.height)
try {
const consoleWatch = watchConsole(page)
await page.setViewportSize(FIXED_VIEWPORT)
await page.addInitScript(width => { localStorage.setItem('dsh.conversation.contentWidth', String(width)) }, FIXED_COLUMN_PX)
const elements = await openLoadedSidebar(page, url)
const panelSelector = '[data-sidebar-right-panel="push"][data-sidebar-right-open]'
const panel = page.locator(panelSelector)
// The sliding dock items animate inside the panel, independently of its grid track.
await panel.evaluate(async node => {
await Promise.all(node.getAnimations({ subtree: true }).filter(animation => animation instanceof CSSTransition && animation.transitionProperty === 'transform').map(animation => animation.finished))
})
await page.evaluate(selector => {
const panel = document.querySelector(selector)!
const column = document.querySelector('[data-chat-flow]')!
const widths = { column: new Set<number>(), panel: 0 }
;(window as FixedWidthProbe).benchmarkWidths = widths
// Use delivered border boxes rather than forcing layout from a per-frame geometry read.
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
const width = entry.borderBoxSize[0]!.inlineSize
if (entry.target === panel) widths.panel = width
else widths.column.add(width)
}
})
observer.observe(panel, { box: 'border-box' })
observer.observe(column, { box: 'border-box' })
}, panelSelector)
await page.waitForFunction(() => (window as FixedWidthProbe).benchmarkWidths.column.size > 0)
const reserveRoom = (): Promise<string> => page.locator('[data-session-panel-probe]').first().evaluate(node =>
getComputedStyle(node).getPropertyValue('--dsh-session-panel-reserve-room').trim())
let panelStart = FIXED_PANEL_START_PX
for (const direction of [1, -1] as const) {
expect(await page.evaluate(() => (window as FixedWidthProbe).benchmarkWidths.panel)).toBe(panelStart)
const reserveBefore = await reserveRoom()
const result = await drag(browser, page, direction, elements, panelStart)
const reserveAfter = await reserveRoom()
const geometry = await page.evaluate(() => {
const { panel, column } = (window as FixedWidthProbe).benchmarkWidths
return { panelWidth: panel, columnWidths: [...column] }
})
console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/fixed-column', direction, elements, budget: FIXED_RESTYLE_BUDGET, panelStart, ...geometry, reserveBefore, reserveAfter, ...result }))
panelStart += direction * STEPS * FIXED_STEP_PX
expect(geometry.panelWidth).toBe(panelStart)
expect(geometry.columnWidths).toEqual([FIXED_COLUMN_PX])
expect([result.columnWidthBefore, result.columnWidth]).toEqual([FIXED_COLUMN_PX, FIXED_COLUMN_PX])
expect([reserveBefore, reserveAfter]).toEqual(direction === 1 ? ['1px', '0px'] : ['0px', '1px'])
expect(result.styledElements).toBeGreaterThan(0)
expectRestylesWithinBudget(result.restyleRatio, FIXED_RESTYLE_BUDGET)
}
expect(consoleWatch.pageErrors).toEqual([])
} finally {
await page.close()
}
}
it('accepts recorded restyle ratios and rejects a drag that restyles the transcript every frame', () => {
// 200-turn local samples: 1,479,947 and 1,909,568 elements restyled beside 28,895 before the width axis
// kept resize inputs on the Conversation body; 2,622 and 3,368 after.
for (const restyled of [1_479_947, 1_909_568]) expect(() => expectRestylesWithinBudget(restyled / 28_895)).toThrow()
for (const restyled of [2_622, 3_368]) expectRestylesWithinBudget(restyled / 28_895)
expectRestylesWithinBudget(RESTYLE_BUDGET)
expect(() => expectRestylesWithinBudget(RESTYLE_BUDGET + 0.01)).toThrow()
})
it('rejects the fixed-column drag that restyled the transcript when reserve room flipped', () => {
const elements = 18_428
expect(() => expectRestylesWithinBudget(18_239 / elements, FIXED_RESTYLE_BUDGET)).toThrow()
for (const restyled of [380, 379]) expectRestylesWithinBudget(restyled / elements, FIXED_RESTYLE_BUDGET)
})
it('counts each layout enclosed by script on the same thread once, including frame callbacks', () => {
const event = (name: string, ts: number, dur: number, pid = 1, tid = 1): TraceEvent => ({ name, ph: 'X', ts, dur, pid, tid })
const events = [
event('FireAnimationFrame', 10, 10), event('FunctionCall', 11, 5),
event('Layout', 10, 10), event('Layout', 12, 1),
event('Layout', 19, 2), event('Layout', 12, 1, 2, 1), event('Layout', 12, 1, 1, 2),
event('PrePaint', 30, 5), event('Layout', 31, 1),
]
expect(summarizeTrace(Buffer.from(JSON.stringify(events)))).toMatchObject({ layoutCount: 6, scriptNestedLayoutCount: 2 })
})
it(`bounds restyles and script-nested layouts while the right Sidebar is dragged beside ${String(HISTORY_TURNS)} turns`, async () => {
if (webSnapshotMode() !== 'replay') throw new Error('browser benchmarks require keyless replay mode')
const samples: Record<'widen' | 'narrow', DragSample[]> = { widen: [], narrow: [] }
for (let sample = 0; sample < SAMPLES; sample++) {
const failures: unknown[] = []
// The scaffold owns a private home, persistence root, and loopback listener for this sample.
const scaffold = await launchWebScaffold()
try {
await seedSession(scaffold, syntheticHistory(), SESSION_ID)
const browser = await chromium.launch({ headless: true })
try {
if (sample === 0) await measureFixedColumn(browser, scaffold.authenticatedUrl)
const page = await newEnglishPage(browser, VIEWPORT.height)
await page.setViewportSize(VIEWPORT)
const consoleWatch = watchConsole(page)
const elements = await openLoadedSidebar(page, scaffold.authenticatedUrl)
for (const [direction, key] of [[1, 'widen'], [-1, 'narrow']] as const) {
const result = await drag(browser, page, direction, elements)
console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/sample', sample, direction: key, elements, ...result }))
// The transcript column moves opposite the Sidebar width while the resolved content width stays at its floor.
expect(Math.max(result.columnWidthBefore, result.columnWidth)).toBeLessThan(CONTENT_WIDTH_FLOOR_PX)
if (key === 'widen') expect(result.columnWidth).toBeLessThan(result.columnWidthBefore)
else expect(result.columnWidth).toBeGreaterThan(result.columnWidthBefore)
expect(result.layoutCount).toBeGreaterThan(0)
expect(result.scriptNestedLayoutCount).toBeLessThanOrEqual(SCRIPT_NESTED_LAYOUT_BUDGET)
samples[key].push(result)
}
expect(consoleWatch.pageErrors).toEqual([])
} catch (error) { failures.push(error) } finally {
await browser.close().catch((error: unknown) => failures.push(error))
}
} catch (error) { failures.push(error) } finally {
await scaffold.close().catch((error: unknown) => failures.push(error))
}
if (failures.length > 0) throw new AggregateError(failures, 'browser benchmark failed')
}
const aggregate = {
widen: median(samples.widen.map(sample => sample.restyleRatio)),
narrow: median(samples.narrow.map(sample => sample.restyleRatio)),
}
console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/median', turns: HISTORY_TURNS, steps: STEPS, budget: RESTYLE_BUDGET, aggregate, samples }))
expectRestylesWithinBudget(aggregate.widen)
expectRestylesWithinBudget(aggregate.narrow)
})
@@ -0,0 +1,67 @@
/** Synthetic current-generation history whose rows wrap, for measuring transcript restyles during a resize. */
import { brandString } from '@deepseek-ai/dsh-brand'
import { createAssistantMessage, createSystemMessage, createToolResultMessage, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm'
import { Session, type SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-session-title'
/** Closed turns in the workload; every one is loaded before the drag. */
export const HISTORY_TURNS = 120
/** Identity private to each isolated scaffold. */
export const SESSION_ID = 'benchmark-rightbar-drag'
const TITLE = 'SYNTHETIC_RIGHTBAR_DRAG'
function prose(turn: number): string {
const paragraph = `Turn ${String(turn)} synthetic analysis: the renderer measures every row, wraps mixed text 混合中文段落用于换行测量, and keeps \`inline code\` beside **bold** words. `
const parts = [paragraph.repeat(6), paragraph.repeat(4)]
parts.push(Array.from({ length: 6 }, (_, i) => `- item ${String(i)}: ${paragraph.slice(0, 120)}`).join('\n'))
if (turn % 10 === 0) {
parts.push('```ts\n' + Array.from({ length: 40 }, (_, i) => `const value${String(i)} = compute(${String(i)}, "${'x'.repeat(30)}")`).join('\n') + '\n```')
}
if (turn % 15 === 0) {
parts.push('| a | b | c |\n|---|---|---|\n' + Array.from({ length: 8 }, (_, i) => `| ${String(i)} | ${paragraph.slice(0, 60)} | ${String(i * 3)} |`).join('\n'))
}
return parts.join('\n\n')
}
/**
* Create prose, lists, code, tables, reasoning, and tool output without reading user data.
* @returns Current Session JSONL accepted by the shared Web seeder.
*/
export function syntheticHistory(): string {
const session = Session.create(brandString<SessionId>(SESSION_ID))
for (let turn = 1; turn <= HISTORY_TURNS; turn++) {
session.append('turn/start', { turn })
session.append('step/start', { turn, step: 1 })
if (turn === 1) session.append('system/message', { turn, step: 1, message: createSystemMessage('') }, { surfaceOp: 'append' })
const user = session.append('user/message', createUserMessage({
content: [{ type: 'text', text: `Question ${String(turn)}: ` + '请检查宽度变化时的排版。 '.repeat(12) }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
if (turn === 1) session.append('session/title', { title: TITLE, messageSeqs: [user.seq], source: { kind: 'fallback' } })
const tool = turn % 5 === 0
const callId = brandString<ToolCallId>(`synthetic-call-${String(turn)}`)
const args = '{"path":"src/a.ts"}'
session.append('assistant/message', {
turn, step: 1, stream: [],
message: createAssistantMessage({
source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
content: [
{ type: 'reasoning', text: 'Compare the synthetic module and test. '.repeat(20) },
{ type: 'text', text: prose(turn) },
...tool ? [{ type: 'tool-call' as const, id: callId, name: 'synthetic_tool', arguments: args }] : [],
],
}),
usage: { inputTokens: 4000, outputTokens: 800 },
}, { surfaceOp: 'append' })
if (tool) {
const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_tool', arguments: args })
session.append('tool/result', { turn, step: 1, message: createToolResultMessage({
callId, isError: false, content: [{ type: 'text', text: 'Synthetic tool output line.\n'.repeat(40) }],
}) }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] })
}
session.append('step/end', { turn, step: 1 })
session.append('turn/end', { turn, reason: { kind: 'completed' } })
}
const header = { type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 1700000000000, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 }
return [JSON.stringify(header), ...session.snapshotEvents().map(event => JSON.stringify(event)), ''].join('\n')
}
@@ -21,8 +21,8 @@
en: 4a094cd97426ad18
zh: 5faadddb7e2b0a43
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props:
en: fe90de63be885e2d
zh: 8ab904422097357f
en: a26620af27311633
zh: 875ec18d3396feee
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry:
en: 876be274c65b56d9
zh: c3adbf5a16e0e38e
+2 -2
View File
@@ -94,7 +94,7 @@ The context-occupancy button shows a ring and percentage below the input card, a
With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility.
While the root-scoped `conversation.session.header.views.actions` list has registrations, a **More conversation views** button with a tooltip follows the View tabs in the tab row. It opens a menu whose rows are that list's registrations. Each receives `entries` (Views outside the header in registration order with `id`, `label`, `pinned`, and `active`; Chat is never listed), `onOpen(id)`, which selects the View in this Session, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The header keeps an in-memory list of unpinned View ids shared by every Session; the tab bar omits unpinned Views and places registered Chat first so it always remains outside More. Plugin reload resets pin choices, and legacy localStorage values are ignored. The tab bar's visibility counts available Views, not pinned ones, so the bar and More stay while every other View is unpinned. Unpinning the active View hides its tab immediately without changing the selected content. More lists only Views outside the header and identifies the current View through `active`. The header reads its available row width, reserves 48px for More and padding, and estimates 120px per tab. Remaining Views keep registration order in More. A single ResizeObserver watches the tab row so window resizing and sidebar expansion update the split; active selection does not change the order. The observer disconnects when the row is removed. If ResizeObserver is unavailable, the initial width calculation still applies without subsequent observation. The More button highlights when the active View is folded. Each tab label estimates its text width from the glyphs; its full-name tooltip appears only when that estimate exceeds the 88px cell. At least one preferred tab remains outside. Unregistered View ids remain in the in-memory pin list until plugin reload.
While the root-scoped `conversation.session.header.views.actions` list has registrations, a **More conversation views** button with a tooltip follows the View tabs in the tab row. It opens a menu whose rows are that list's registrations. Each receives `entries` (Views outside the header in registration order with `id`, `label`, `pinned`, and `active`; Chat is never listed), `onOpen(id)`, which selects the View in this Session, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The header keeps an in-memory list of unpinned View ids shared by every Session; the tab bar omits unpinned Views and places registered Chat first so it always remains outside More. Plugin reload resets pin choices, and legacy localStorage values are ignored. The tab bar's visibility counts available Views, not pinned ones, so the bar and More stay while every other View is unpinned. Unpinning the active View hides its tab immediately without changing the selected content. More lists only Views outside the header and identifies the current View through `active`. The header reads its available row width, reserves 48px for More and padding, and estimates 120px per tab. Remaining Views keep registration order in More. After the initial measurement, the header uses the tab row width delivered by ResizeObserver when the window or sidebar resizes; active selection does not change the order. The observer disconnects when the row is removed. If ResizeObserver is unavailable, the initial width calculation still applies without subsequent observation. The More button highlights when the active View is folded. Each tab label estimates its text width from the glyphs; its full-name tooltip appears only when that estimate exceeds the 88px cell. At least one preferred tab remains outside. Unregistered View ids remain in the in-memory pin list until plugin reload.
The composer registers the File command action and owns its label, availability, and native file-dialog callback. Menu availability and invocation both consult the mounted composer's current attachment-intake policy. Unmounting or locking the composer disables that action; disposing the plugin removes its registration. The callback binding stays inside the input module.
@@ -126,7 +126,7 @@ The width-handle indicator follows the pointer only during a captured drag; ordi
<a id="end-reserve"></a>
The main Conversation body can keep room free at its inline end for something that stays beside the transcript, such as the docked [Session panel](../ui-session-panel/README.md#docking). A stylesheet asks for it by setting the `--dsh-chat-end-reserve` length on the `[data-conversation-content]` element. The scrollport then pads its end by `--dsh-chat-end-inset`, twice the missing gutter, which moves the centered transcript column and the composer toward the start edge at their own widths until the space after the column equals the reserve. `--dsh-chat-end-reserve-max` is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger request gets no inset, so whatever asks for room reads the maximum before it relies on that room. The body derives these lengths from the scrollport's width, which it publishes as `--dsh-conversation-viewport-width`, so they have the same values in the scrollport, the width handles, and the Chat aside layer. The width handles move with the column. While the inset is above zero the reserve holds the column's end edge, so a drag on either handle moves only the start edge and changes the width by the pointer's travel instead of twice it; a column dragged wider than the start gutter can give gets no inset and centers again. The inset applies at once. A stylesheet that wants a change of it animated also sets `--dsh-chat-end-reserve-transition`, a duration and an easing, on the same element for as long as that change lasts; the scrollport's padding and the Chat aside layer's margin then follow it together. An embedded occurrence makes no room: its maximum and its inset are 0.
The main Conversation body can keep room free at its inline end for something that stays beside the transcript, such as the docked [Session panel](../ui-session-panel/README.md#docking). A stylesheet asks for it by setting the `--dsh-chat-end-reserve` length on the `[data-conversation-content]` element. The scrollport then pads its end by `--dsh-chat-end-inset`, twice the missing gutter, which moves the centered transcript column and the composer toward the start edge at their own widths until the space after the column equals the reserve. `--dsh-chat-end-reserve-max` is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger request gets no inset, so whatever asks for room reads the maximum before it relies on that room. The maximum changes on every resize and is not inherited: a stylesheet reads it on the `[data-conversation-content]` element itself and derives what its descendants need there as a registered length, which changes only when the derived value does. The body keeps its other varying inputs uninherited as well and gives descendants `--dsh-chat-content-width` and `--dsh-chat-end-inset` as computed lengths, so resizing restyles the transcript only when one of those changes. The body derives these lengths from the scrollport's width, which it publishes as `--dsh-conversation-viewport-width`, so they have the same values in the scrollport, the width handles, and the Chat aside layer. The width handles move with the column. While the inset is above zero the reserve holds the column's end edge, so a drag on either handle moves only the start edge and changes the width by the pointer's travel instead of twice it; a column dragged wider than the start gutter can give gets no inset and centers again. The inset applies at once. A stylesheet that wants a change of it animated also sets `--dsh-chat-end-reserve-transition`, a duration and an easing, on the same element for as long as that change lasts; the scrollport's padding and the Chat aside layer's margin then follow it together. An embedded occurrence makes no room: its maximum and its inset are 0.
The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), the claimed slash command is an atomic leading chip that carries its claim, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews use the [UserText Factory](#sent-user-text) (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. On Apple platforms, Home and End move the caret to the start or end of the current visual line instead of scrolling the conversation, and Shift extends the selection; End immediately before a quote takes the same path as Cmd+Right to the end of that line. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start.
+2 -2
View File
@@ -94,7 +94,7 @@ composer 在挂载、切换 Session 和解除锁定时使用共享的[文字输
关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。
root 作用域的 `conversation.session.header.views.actions` list 有注册项时,标签行中的 View 标签之后显示带提示框的**更多会话视图**按钮。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的头部之外的 View,含 `id`、`label`、`pinned` 与 `active`;不含 Chat)、在本 Session 选择 View 的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。头部在内存中保存所有 Session 共用的已收起 View id 列表;标签栏不显示已收起的 View,并将已注册的 Chat 放在首位,确保它始终留在更多菜单外。插件重新加载时 Pin 选择重置,不读取旧 localStorage 值。标签栏是否显示按可用 View 计算,不按已固定的 View 计算,因此其他 View 全部收起时,标签栏和“更多”仍然显示。收起当前激活的 View 会立即隐藏其标签,但不会切走其内容。更多菜单仅包含头部之外的 View,通过 `active` 标识当前 View。头部读取当前行可用宽度,为更多按钮与内边距预留 48px,每个标签估算 120px,其余 View 按注册顺序进入更多。单个 ResizeObserver 观察标签行,使窗口缩放和侧栏展开能够更新分组;当前选中项变化不改变顺序。标签行移除时断开观察。如果环境没有 ResizeObserver,仍按初始宽度计算,但不继续观察。当前 View 收起时,更多按钮高亮。每个标签按字符宽度估算文本宽度;只有估算结果超过 88px 单元格时,才通过提示框提供全名。至少保留一个优先展示的外部标签。未注册 View 的 id 保留在内存 Pin 列表中,直到插件重新加载。
root 作用域的 `conversation.session.header.views.actions` list 有注册项时,标签行中的 View 标签之后显示带提示框的**更多会话视图**按钮。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的头部之外的 View,含 `id`、`label`、`pinned` 与 `active`;不含 Chat)、在本 Session 选择 View 的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。头部在内存中保存所有 Session 共用的已收起 View id 列表;标签栏不显示已收起的 View,并将已注册的 Chat 放在首位,确保它始终留在更多菜单外。插件重新加载时 Pin 选择重置,不读取旧 localStorage 值。标签栏是否显示按可用 View 计算,不按已固定的 View 计算,因此其他 View 全部收起时,标签栏和“更多”仍然显示。收起当前激活的 View 会立即隐藏其标签,但不会切走其内容。更多菜单仅包含头部之外的 View,通过 `active` 标识当前 View。头部读取当前行可用宽度,为更多按钮与内边距预留 48px,每个标签估算 120px,其余 View 按注册顺序进入更多。初次测量后,窗口或侧栏缩放时,头部使用 ResizeObserver 送达的标签行宽度更新分组;当前选中项变化不改变顺序。标签行移除时断开观察。如果环境没有 ResizeObserver,仍按初始宽度计算,但不继续观察。当前 View 收起时,更多按钮高亮。每个标签按字符宽度估算文本宽度;只有估算结果超过 88px 单元格时,才通过提示框提供全名。至少保留一个优先展示的外部标签。未注册 View 的 id 保留在内存 Pin 列表中,直到插件重新加载。
输入框注册「文件」命令动作,负责其标题、可用性和原生文件选择器回调。菜单可用性与实际调用都读取已挂载输入框当前的附件接收策略。输入框卸载或锁定后该动作不可用,插件 dispose(资源释放)时移除注册。回调绑定留在输入模块内部。
@@ -126,7 +126,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染
<a id="end-reserve"></a>
主 Conversation body 可以在行向末端空出一段位置,留给停在 transcript 旁边的内容,例如停靠的[会话面板](../ui-session-panel/README.zh.md#docking)。样式表在 `[data-conversation-content]` 元素上设置长度 `--dsh-chat-end-reserve` 来提出申请。滚动容器随即给末端加上 `--dsh-chat-end-inset` 的内边距,大小是所缺留白的两倍,居中的 transcript 列和输入框保持各自宽度向起始边缘移动,直到列后的空间等于预留值。`--dsh-chat-end-reserve-max` 是在列保持宽度和两侧内边距的前提下,起始留白能让出的最大预留;超出它的申请得不到任何内边距,因此申请方要先读取这个最大值,再依赖这段位置。主体从滚动容器的宽度推出这些长度,并把该宽度发布为 `--dsh-conversation-viewport-width`,因此它们在滚动容器、宽度拖拽条和 Chat 侧边层中的值相同。宽度拖拽条随列移动。内边距大于零时,预留固定了列的末端边缘,因此拖动任一拖拽条都只移动起始边缘,宽度的变化等于指针移动的距离而不是它的两倍;列被拖到超过起始留白能让出的宽度时不再有内边距,重新居中。内边距立即生效。样式表如果希望某次变化带动画,就在这次变化期间在同一个元素上再设置 `--dsh-chat-end-reserve-transition`(一个时长和一条缓动曲线),滚动容器的内边距和 Chat 侧边层的外边距随之一起过渡。嵌入式 occurrence 不让位:它的最大预留和内边距都是 0。
主 Conversation body 可以在行向末端空出一段位置,留给停在 transcript 旁边的内容,例如停靠的[会话面板](../ui-session-panel/README.zh.md#docking)。样式表在 `[data-conversation-content]` 元素上设置长度 `--dsh-chat-end-reserve` 来提出申请。滚动容器随即给末端加上 `--dsh-chat-end-inset` 的内边距,大小是所缺留白的两倍,居中的 transcript 列和输入框保持各自宽度向起始边缘移动,直到列后的空间等于预留值。`--dsh-chat-end-reserve-max` 是在列保持宽度和两侧内边距的前提下,起始留白能让出的最大预留;超出它的申请得不到任何内边距,因此申请方要先读取这个最大值,再依赖这段位置。这个最大值随每次缩放变化且不继承:样式表在 `[data-conversation-content]` 元素本身上读取它,并在那里把后代需要的值推导为已注册的长度,只有推导结果变化时该长度才变化。主体的其他变化输入同样不继承,传给后代的 `--dsh-chat-content-width` 与 `--dsh-chat-end-inset` 是计算后的长度,因此缩放只有在它们变化时才重新计算正文样式。主体从滚动容器的宽度推出这些长度,并把该宽度发布为 `--dsh-conversation-viewport-width`,因此它们在滚动容器、宽度拖拽条和 Chat 侧边层中的值相同。宽度拖拽条随列移动。内边距大于零时,预留固定了列的末端边缘,因此拖动任一拖拽条都只移动起始边缘,宽度的变化等于指针移动的距离而不是它的两倍;列被拖到超过起始留白能让出的宽度时不再有内边距,重新居中。内边距立即生效。样式表如果希望某次变化带动画,就在这次变化期间在同一个元素上再设置 `--dsh-chat-end-reserve-transition`(一个时长和一条缓动曲线),滚动容器的内边距和 Chat 侧边层的外边距随之一起过渡。嵌入式 occurrence 不让位:它的最大预留和内边距都是 0。
常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 是携带认领的行首原子 chip,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览使用 [UserText Factory](#sent-user-text)(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 在 Apple 平台上,Home 与 End 把光标移到当前视觉行的行首或行末,而不是滚动对话,按住 Shift 时扩展选区;光标紧贴在 quote 左侧时,End 与 Cmd+Right 走同一路径移到该行末尾。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。
@@ -454,6 +454,49 @@
flex: none;
}
/* The width axis's inputs and its continuously varying derived lengths are
registered without inheritance, so they exist only on the body: a resize
that changes them every frame does not restyle the transcript below it.
The resolved lengths compute to absolute values here, and the public
aliases the body declares from them inherit text that changes only when a
resolved width changes. */
@property --dsh-conversation-column-width {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
@property --dsh-conversation-viewport-width {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
/* Without an initial value an unset preference stays invalid, so the body
falls back to the adaptive width. */
@property --dsh-chat-user-width {
syntax: '*';
inherits: false;
}
@property --dsh-chat-content-width-resolved {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
@property --dsh-chat-end-reserve-max {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
@property --dsh-chat-end-inset-resolved {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
/* Band below the header: the scrollport plus the width handles. Anchoring the
handles here keeps their full-height strips and glow under the header's
bottom edge at every header height. */
@@ -467,10 +510,11 @@
/* Shared width axis for the transcript, dock cards, composer, and takeover
cards. Main width controls publish the live body width and optional user
preference; embedded occurrences override this adaptive axis below. */
--dsh-chat-content-width: var(
--dsh-chat-content-width-resolved: var(
--dsh-chat-user-width,
clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 880px)
clamp(680px, calc(var(--dsh-conversation-column-width) * 0.64), 880px)
);
--dsh-chat-content-width: var(--dsh-chat-content-width-resolved);
--dsh-composer-card-max-width: calc(var(--dsh-chat-content-width) + 32px);
--dsh-composer-side-clearance: 16px;
--dsh-composer-dock-inset: 8px;
@@ -484,23 +528,26 @@
--dsh-chat-end-reserve-max is the largest reserve the start gutter can
give while the column keeps its width and its side inset; a larger one
gets no inset at all, so the surface reads the maximum before it relies
on the room. Every length derives from the scrollport's measured width,
on the room. The maximum varies with every resize and is not inherited:
a stylesheet derives what it needs on this element, as a registered
length that changes only when its own value does. Every length derives from the scrollport's measured width,
so the same values hold where a percentage would resolve against
another box. The inset applies at once unless the stylesheet also sets
--dsh-chat-end-reserve-transition, a duration and an easing, for as long
as it wants a change of the inset animated. */
--dsh-chat-end-reserve-max: calc(
var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width) - var(--dsh-composer-side-clearance) - 16px
var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved) - var(--dsh-composer-side-clearance) - 16px
);
/* The first term is 0 for a reserve above the maximum and at least 1000px, above any inset, otherwise: a
step at the maximum, within a ten-thousandth of a pixel. */
--dsh-chat-end-inset: min(
--dsh-chat-end-inset-resolved: min(
max(0px, calc((var(--dsh-chat-end-reserve-max) - var(--dsh-chat-end-reserve, 0px)) * 10000000 + 1000px)),
calc(2 * max(
0px,
var(--dsh-chat-end-reserve, 0px) - (var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width)) / 2
var(--dsh-chat-end-reserve, 0px) - (var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved)) / 2
))
);
--dsh-chat-end-inset: var(--dsh-chat-end-inset-resolved);
}
/* An embedded occurrence makes no room: its column already follows its frame's width. */
@@ -123,13 +123,19 @@ export function ConversationSessionHeader({
useLayoutEffect(() => {
const row = tabRow.current
if (row === null || !hasEntryActions) return
const updateLimit = (): void => {
setVisibleViewLimit(Math.max(1, Math.floor((row.clientWidth - 48) / 120)))
const updateLimit = (width: number): void => {
setVisibleViewLimit(Math.max(1, Math.floor((width - 48) / 120)))
}
updateLimit()
updateLimit(row.clientWidth)
if (typeof ResizeObserver === 'undefined') return
const observer = new ResizeObserver(updateLimit)
observer.observe(row)
// The row has padding but no border or scrollbar. Its delivered border-box width,
// rounded like clientWidth, preserves the tab thresholds without forcing layout again.
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
for (const size of entry.borderBoxSize) updateLimit(Math.round(size.inlineSize))
}
})
observer.observe(row, { box: 'border-box' })
return () => { observer.disconnect() }
}, [showTabs, hasEntryActions])
const { visibleTabs, moreTabs } = useMemo(() => {
@@ -158,20 +158,23 @@ function WidthHandle(props: {
* @returns two active-phase width handles, or no controls outside the active phase.
*/
export function ConversationWidthControls({ container, phase }: ConversationWidthControlsProps) {
const publishWidths = useCallback((container: HTMLDivElement): void => {
const target = container.parentElement ?? container
const column = container.offsetWidth
target.style.setProperty('--dsh-conversation-column-width', `${column}px`)
const publishWidths = useCallback((container: HTMLDivElement, column: number): void => {
// The axis registers these inputs without inheritance, so they belong on the body that derives from them.
container.style.setProperty('--dsh-conversation-column-width', `${column}px`)
const preference = readWidthPreference()
if (preference === null) target.style.removeProperty('--dsh-chat-user-width')
else target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`)
if (preference === null) container.style.removeProperty('--dsh-chat-user-width')
else container.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`)
}, [])
useLayoutEffect(() => {
if (container === null) return
const observer = new ResizeObserver(() => { publishWidths(container) })
observer.observe(container)
publishWidths(container)
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
for (const size of entry.borderBoxSize) publishWidths(container, Math.round(size.inlineSize))
}
})
observer.observe(container, { box: 'border-box' })
publishWidths(container, container.offsetWidth)
return () => { observer.disconnect() }
}, [container, publishWidths])
@@ -181,15 +184,14 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt
}, [container])
const onDrag = useCallback((width: number): void => {
if (container === null) return
const target = container.parentElement ?? container
target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`)
container.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`)
}, [container])
const onCommit = useCallback((width: number): void => {
if (container === null) return
localStorage.setItem(WIDTH_PREF_KEY, `${resolveContentWidth(container.offsetWidth, width)}`)
}, [container])
const onEnd = useCallback((): void => {
if (container !== null) publishWidths(container)
if (container !== null) publishWidths(container, container.offsetWidth)
}, [container, publishWidths])
if (container === null || phase !== 'active') return null
@@ -27,13 +27,33 @@ describe('Conversation body end reserve', () => {
it('derives the largest reserve and the inset from the scrollport width, the content width, and the side inset', () => {
expect(body['--dsh-composer-side-clearance']).toBe('16px')
expect(body['--dsh-chat-end-reserve-max']).toBe(
'calc(var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width) - var(--dsh-composer-side-clearance) - 16px)',
'calc(var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved) - var(--dsh-composer-side-clearance) - 16px)',
)
expect(body['--dsh-chat-end-inset']).toBe(
expect(body['--dsh-chat-end-inset-resolved']).toBe(
'min(max(0px, calc((var(--dsh-chat-end-reserve-max) - var(--dsh-chat-end-reserve, 0px)) * 10000000 + 1000px)),'
+ ' calc(2 * max(0px, var(--dsh-chat-end-reserve, 0px)'
+ ' - (var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width)) / 2)))',
+ ' - (var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved)) / 2)))',
)
expect(body['--dsh-chat-end-inset']).toBe('var(--dsh-chat-end-inset-resolved)')
})
it('keeps the continuously varying lengths on the body and publishes resolved lengths to its descendants', () => {
// Registered without inheritance: a resize that changes them every frame does not restyle the transcript.
const registered = Object.fromEntries([...css.matchAll(/@property\s+(--[\w-]+)\s*\{([^{}]*)\}/g)]
.map((match): [string, string] => [match[1] ?? '', (match[2] ?? '').replace(/\s+/g, ' ').trim()]))
expect(registered).toEqual({
'--dsh-conversation-column-width': "syntax: '<length>'; inherits: false; initial-value: 0px;",
'--dsh-conversation-viewport-width': "syntax: '<length>'; inherits: false; initial-value: 0px;",
'--dsh-chat-user-width': "syntax: '*'; inherits: false;",
'--dsh-chat-content-width-resolved': "syntax: '<length>'; inherits: false; initial-value: 0px;",
'--dsh-chat-end-reserve-max': "syntax: '<length>'; inherits: false; initial-value: 0px;",
'--dsh-chat-end-inset-resolved': "syntax: '<length>'; inherits: false; initial-value: 0px;",
})
// The inherited public names repeat a computed length, whose text changes only with the resolved width.
expect(body['--dsh-chat-content-width-resolved']).toBe(
'var(--dsh-chat-user-width, clamp(680px, calc(var(--dsh-conversation-column-width) * 0.64), 880px))',
)
expect(body['--dsh-chat-content-width']).toBe('var(--dsh-chat-content-width-resolved)')
})
it('moves the column aside by twice the missing gutter at its own width, and makes no room once the start gutter is at the side inset', () => {
@@ -79,9 +79,14 @@ class ResizeObserverStub {
}
/** Fires every recorded observer whose target list includes the element. */
function fireResize(el: Element): void {
function fireResize(el: Element, inlineSize = 0): void {
const size = [{ inlineSize, blockSize: 0 }]
const change: ResizeObserverEntry = {
target: el, contentRect: new DOMRectReadOnly(0, 0, inlineSize, 0),
borderBoxSize: size, contentBoxSize: size, devicePixelContentBoxSize: size,
}
for (const entry of resizeObservers) {
if (entry.targets.includes(el)) entry.callback([], undefined as never)
if (entry.targets.includes(el)) entry.callback([change], undefined as never)
}
}
@@ -836,22 +841,22 @@ describe('ConversationRoot resident composer', () => {
})
it('folds and restores Views on container resize without changing selection, and disconnects on unmount', () => {
let width = 1000
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width)
const liveWidth = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(1000)
const viewTabs = ['chat', 'trajectory', 'timeline', 'inspector', 'notes'].map(id => ({ id, label: id }))
const b = mount(sessionSnapshotOf(), undefined, undefined, { viewTabs, entryActions: true })
const row = b.view.getByRole('tablist').parentElement!
const external = () => within(b.view.getByRole('tablist')).getAllByRole('tab').map(tab => tab.textContent)
expect(external()).toEqual(viewTabs.map(tab => tab.label))
act(() => { b.store.actions.setView('notes') })
width = 300
act(() => { fireResize(row) })
liveWidth.mockClear()
// 287.6px rounds to 288px (two Views); do not re-read a changed DOM during delivery.
act(() => { fireResize(row, 287.6) })
expect(external()).toEqual(['chat', 'trajectory'])
fireEvent.click(b.view.getByRole('button', { name: zh['session.moreViews'] }))
expect(b.actionsOwner().entries.map(entry => entry.id)).toEqual(['timeline', 'inspector', 'notes'])
expect(b.actionsOwner().entries.find(entry => entry.id === 'notes')?.active).toBe(true)
width = 1000
act(() => { fireResize(row) })
act(() => { fireResize(row, 1000) })
expect(liveWidth.mock.contexts).not.toContain(row)
expect(external()).toEqual(viewTabs.map(tab => tab.label))
expect(b.view.getByRole('tab', { name: 'notes' }).getAttribute('aria-selected')).toBe('true')
expect(b.actionsOwner().entries).toEqual([])
@@ -950,26 +955,23 @@ describe('ConversationRoot resident composer', () => {
expect(b.view.queryByRole('button', { name: 'Retry' })).toBeNull()
})
it('publishes the column width as a px variable for the shared width axis', () => {
it('publishes the column width as a px variable on the body for the shared width axis', () => {
const b = mount(sessionSnapshotOf())
const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement
const root = content.parentElement as HTMLElement
// jsdom offsetWidth is 0 until faked: the observer publishes whatever the
// layout reports, and the CSS clamp() floors the axis at 680px either way.
Object.defineProperty(content, 'offsetWidth', { value: 1200, configurable: true })
act(() => { fireResize(content) })
expect(root.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px')
const readWidth = vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
act(() => { fireResize(content, 1199.75) })
expect(content.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px')
expect(readWidth.mock.contexts).not.toContain(content)
// No dragged preference: the user-width override stays absent so the
// adaptive clamp term applies.
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('')
expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('')
})
it('drag → persist → window clamp round-trip on a width handle', () => {
const b = mount(sessionSnapshotOf())
const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement
const root = content.parentElement as HTMLElement
Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true })
act(() => { fireResize(content) })
act(() => { fireResize(content, 1600) })
const handle = b.view.container.querySelector('[data-width-handle="right"]') as HTMLElement
expect(handle).not.toBeNull()
// jsdom lacks pointer capture: emulate per-element so hasPointerCapture
@@ -991,13 +993,13 @@ describe('ConversationRoot resident composer', () => {
expect(handle.style.getPropertyValue('--dsh-width-handle-pointer-y')).toBe('300px')
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 825, clientY: 300 })
expect(handle.hasAttribute('data-dragging')).toBe(false)
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px')
expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
// Window shrinks: the displayed width re-clamps (900 − 176 = 724) but the
// preference stays.
Object.defineProperty(content, 'offsetWidth', { value: 900, configurable: true })
act(() => { fireResize(content) })
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px')
act(() => { fireResize(content, 900) })
expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
// A press without travel (a real double-click delivers two such
// press/release rounds) must not commit the clamped display value over
@@ -1005,7 +1007,7 @@ describe('ConversationRoot resident composer', () => {
fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 })
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 800, clientY: 300 })
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px')
expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px')
// No reset affordance on the handle: double-click leaves the preference alone.
fireEvent.doubleClick(handle)
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
@@ -1020,10 +1022,9 @@ describe('ConversationRoot resident composer', () => {
it('changes the width by the pointer travel, not twice it, while the scrollport pads its end for a reserve', () => {
const b = mount(sessionSnapshotOf())
const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement
const root = content.parentElement as HTMLElement
const scrollport = content.querySelector('[data-conversation-scroll]') as HTMLElement
Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true })
act(() => { fireResize(content) })
act(() => { fireResize(content, 1600) })
const handle = b.view.container.querySelector('[data-width-handle="left"]') as HTMLElement
const names = ['setPointerCapture', 'releasePointerCapture', 'hasPointerCapture'] as const
const originals = names.map(name =>
@@ -1042,12 +1043,12 @@ describe('ConversationRoot resident composer', () => {
// The reserve holds the column's end edge: 25px outward on the start handle moves the start edge 25px → 880 + 25.
fireEvent.pointerDown(handle, { pointerId: 1, clientX: 400, clientY: 300 })
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 375, clientY: 300 })
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('905px')
expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('905px')
// Without the inset the column is centered and both edges move: 905 + 2 × 10.
inset = '0px'
fireEvent.pointerDown(handle, { pointerId: 1, clientX: 400, clientY: 300 })
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 390, clientY: 300 })
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('925px')
expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('925px')
} finally {
for (const [name, descriptor] of originals) {
if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name)
+2 -2
View File
@@ -21,8 +21,8 @@
en: 5e025290e8881fa8
zh: 2bc9c3ff83914241
/deepseek-ai-dsh-client-ui-dockkit/interaction-rules-worth-keeping:
en: cf2d00ce2b7d5719
zh: 5510420f8872e23a
en: a34ab619b8c1d740
zh: b645bb7600e640db
/deepseek-ai-dsh-client-ui-dockkit/build-shape:
en: 69f87827f149270f
zh: 65e41db2b2400cd5
+2 -2
View File
@@ -80,9 +80,9 @@ The split control accepts localized tooltip text, separate effective keys throug
These are not stylistic; each one fixes a defect found in a real browser.
- **Capture the pointer** when a gesture starts. Without it any scroll container the pointer crosses can claim the gesture, which the browser reports as a cancelled pointer and an abandoned drag. Capture is hardening — the window listeners carry the gesture either way, so an environment without the API still works.
- **The chips give way; the strip's end controls never do.** The chip box is the strip's one shrinking part (`flex: 0 1 auto; min-width: 0; overflow-x: auto`): chips shrink down to an 80px floor and then scroll on the wheel with no scrollbar drawn, and the box fades its chips out over 24px at each side that hides some (`data-dockkit-strip-scroll`, written from the box's scroll reading after each commit, scroll, and resize). Whenever the active tab or the row of chips changes, the box scrolls so the active chip stands clear of the fade band; a chip already in view moves nothing. Where `DockLayout` draws a new strip for each newly selected tab, that strip first jumps to the offset the pane's previous strip recorded, so only the remaining distance animates; a strip with no recorded offset jumps straight to the active chip instead of scrolling from the row's start. A chip's title is never ellipsized: `TabTitle` reads its text against its box and sets `data-dockkit-tab-clipped` while the text is wider, which fades the text out over its last 16px. A chip's close control shows while the chip is active, hovered, or holds focus, over the title's last 14px, which fade under it, so the chip is the same width either way. The two slots beside the active chip draw no hairline, so the filled capsule stands between bare chips. The add, split, and chrome controls are `flex: none`, so they keep their width and place in any pane at least as wide as they are (about 130px with the chrome, 72px without). The surface's `min-width: 0` and the pane's `overflow: hidden` stop a body's longest unwrapped line from widening the pane past its box, which is what carried the controls and the body's scrollbar off-screen.
- **The chips give way; the strip's end controls never do.** The chip box is the strip's one shrinking part (`flex: 0 1 auto; min-width: 0; overflow-x: auto`): chips shrink down to an 80px floor and then scroll on the wheel with no scrollbar drawn, and the box fades its chips out over 24px at each side that hides some (`data-dockkit-strip-scroll`, written from the box's scroll reading after each commit, scroll, and resize). Whenever the active tab or the row of chips changes, the box scrolls so the active chip stands clear of the fade band; a chip already in view moves nothing. Where `DockLayout` draws a new strip for each newly selected tab, that strip first jumps to the offset the pane's previous strip recorded, so only the remaining distance animates; a strip with no recorded offset jumps straight to the active chip instead of scrolling from the row's start. A chip's title is never ellipsized: the last 16px of the title box always fade, including when a title just fits. The fade needs no width measurement. A chip's close control shows while the chip is active, hovered, or holds focus, over the title's last 14px, which fade under it, so the chip is the same width either way. The two slots beside the active chip draw no hairline, so the filled capsule stands between bare chips. The add, split, and chrome controls are `flex: none`, so they keep their width and place in any pane at least as wide as they are (about 130px with the chrome, 72px without). The surface's `min-width: 0` and the pane's `overflow: hidden` stop a body's longest unwrapped line from widening the pane past its box, which is what carried the controls and the body's scrollbar off-screen.
- **The chip box scrolls, but never claims a gesture.** A horizontal scroller would take press-and-move for itself and cancel the pointer; the box, the chips, and the strip set `touch-action: none` and the gesture captures the pointer, so a press-and-move on a chip is a drag and only the wheel scrolls the box.
- **A split needs room for two working halves.** A pane splits into equal halves, so each half must hold what cannot shrink: the strip's fixed part — measured as the strip's width minus the chip box and the fill, which is the padding, the gaps, and every control that pane draws (its own chrome included, so the top-right pane asks more) — plus one chip at its minimum — `.tab` declares `min-width: 80px` on a content-box, so its footprint is 80px plus 10px + 10px of padding, 100px, read from a rendered chip's computed style (the stylesheet figure when none can be read); the divider between the halves takes its rendered thickness (0 — its hairline paints over the seam without taking layout room, so a body's own rules run unbroken past it). A column split, which only an edge drop makes, needs each half to hold the strip (34px) plus a 48px body: one 13px secondary line at 1.6 line-height inside 12px of the body's own insets — the pane body itself is unpadded, so a tab's body reaches the strip's bottom edge and the pane's edges and draws its own. `halvesFit` in `geometry.ts` is the arithmetic; `measure.ts` reads the rectangles after every commit and whenever the surface resizes, because the layout state carries fractions, never pixels, and the engine's planners stay that way. A pane without room keeps its split control, disabled with `splitPaneNarrow` (hidden instead under `hideSplitWhenBlocked`), and offers no edge drop zone for that axis (the release is then not a move). Under `hideSplitWhenBlocked` the split control's own footprint — its box plus the strip's gap — is left out of the fixed part: hiding the control sheds exactly that footprint from the strip, so a reading that counted it would flip with the control's visibility and re-render forever; leaving it out is also what the half being asked about would carry, since a half too narrow to split hides its own control. A pane the user narrows afterwards — a divider or the embedder's column dragged — keeps its size: the rule only decides its next split.
- **A split needs room for two working halves.** A pane splits into equal halves, so each half must hold what cannot shrink: the strip's fixed part — measured as the strip's width minus the chip box and the fill, which is the padding, the gaps, and every control that pane draws (its own chrome included, so the top-right pane asks more) — plus one chip at its minimum — `.tab` declares `min-width: 80px` on a content-box, so its footprint is 80px plus 10px + 10px of padding, 100px, read from a rendered chip's computed style (the stylesheet figure when none can be read); the divider between the halves takes its rendered thickness (0 — its hairline paints over the seam without taking layout room, so a body's own rules run unbroken past it). A column split, which only an edge drop makes, needs each half to hold the strip (34px) plus a 48px body: one 13px secondary line at 1.6 line-height inside 12px of the body's own insets — the pane body itself is unpadded, so a tab's body reaches the strip's bottom edge and the pane's edges and draws its own. `halvesFit` in `geometry.ts` is the arithmetic; `measure.ts` reads the rectangles when the dock layout or split policy changes, and on size notifications for the surface, panes, and strip boxes. An embedder resizing its column does not require a separate measurement during its render commit. A pane without room keeps its split control, disabled with `splitPaneNarrow` (hidden instead under `hideSplitWhenBlocked`), and offers no edge drop zone for that axis (the release is then not a move). Under `hideSplitWhenBlocked` the split control's own footprint — its box plus the strip's gap — is left out of the fixed part: hiding the control sheds exactly that footprint from the strip, so a reading that counted it would flip with the control's visibility and re-render forever; leaving it out is also what the half being asked about would carry, since a half too narrow to split hides its own control. A pane the user narrows afterwards — a divider or the embedder's column dragged — keeps its size: the rule only decides its next split.
- **Focus lands on click, not on press.** A state change between `pointerdown` and the first `pointermove` rebuilds the pressed subtree, and a replaced element cancels the pointer. It also keeps a drag from recording a redundant focus operation first. Clicks on the chips, the strip's controls, and the embedder's chrome stop at the strip: the intent each reports already decides the active pane, or is the embedder's own, so the pane's click-to-focus records nothing extra. A floating panel's grip and corner report through their gesture the same way — a press released in place is a click that raises the panel, and a drag records only the move or resize, whose operation raises it — while a press on the panel's body raises it directly. A click on the pane that is active already, a click or key on that pane's selected chip, or a press on the panel that is active and on top already, changes nothing and records nothing.
- **A control nested inside a draggable chip stops its own press.** Otherwise the press starts a drag, captures the pointer, and the nested control's click never lands.
- **Emphasis takes the platform's accent, never `--dsw-alias-brand-primary`.** This platform binds `brand-primary` to its near-black (light) or near-white (dark) foreground, so the drop caret and the drop-zone hint use `--dsw-alias-brand-primary-new-colorprimary-new-color`, as the trajectory views do; a hovered divider takes the caption label ink instead, reading as a handle rather than a highlight. A floating panel draws no border — the menu's shadow (`--dsw-elevation-prominent`) outlines it — and the active panel gets no heavier frame: it is already on top and casts the same shadow; a darker frame around it read as a defect.
+2 -2
View File
@@ -80,9 +80,9 @@ Sidebar 使用的 `DockLayout` 在选中项变化、跨格移动与浮动期间
这些不是风格偏好;每一条都修复了在真实浏览器里发现的缺陷。
- **手势开始时捕获指针。** 不捕获的话,指针经过的任何滚动容器都可能接管手势,浏览器会将其报告为指针取消和拖动中止。捕获是加固——无论如何都由 window 监听器承载手势,所以没有该 API 的环境照样可用。
- **chip 让位;tab 条末端的控件永不让位。** chip 盒是 tab 条里唯一会收缩的部分(`flex: 0 1 auto; min-width: 0; overflow-x: auto`):chip 先缩到 80px 下限,再在盒内随滚轮横向滚动、不画滚动条,且盒在每个藏有 chip 的一侧把 chip 在 24px 内渐隐(`data-dockkit-strip-scroll`,在每次提交、滚动与尺寸变化后由盒的滚动读数写入)。每当活动 tab 或 chip 的排列变化,盒会滚动到让活动 chip 避开渐隐带;已在视野内的 chip 不动。`DockLayout` 为每个新选中的 tab 画出新 tab 条时,新 tab 条先跳到该格上一条 tab 条记录的偏移,只让剩余距离带动画;没有记录偏移的 tab 条直接跳到活动 chip,而不是从排列起点滚动过去。chip 的标题从不加省略号:`TabTitle` 拿文字宽度对照它的盒子,文字更宽时置 `data-dockkit-tab-clipped`,让文字在末端 16px 内渐隐。chip 的关闭控件在 chip 活动、悬停或持有焦点时显示,压在标题末端 14px 之上、标题在其下渐隐,因此 chip 宽度两种情况下都一样。活动 chip 两侧的槽不画细线,让填色胶囊立在裸 chip 之间。添加、分栏与 chrome 控件都是 `flex: none`,因此在任何不窄于它们自身的格里(带 chrome 约 130px,不带约 72px)都保持宽度与位置。停靠面的 `min-width: 0` 与格的 `overflow: hidden` 阻止正文里最长的不换行行把格撑出自己的盒子——正是那种情况把控件和正文滚动条推到了屏幕外。
- **chip 让位;tab 条末端的控件永不让位。** chip 盒是 tab 条里唯一会收缩的部分(`flex: 0 1 auto; min-width: 0; overflow-x: auto`):chip 先缩到 80px 下限,再在盒内随滚轮横向滚动、不画滚动条,且盒在每个藏有 chip 的一侧把 chip 在 24px 内渐隐(`data-dockkit-strip-scroll`,在每次提交、滚动与尺寸变化后由盒的滚动读数写入)。每当活动 tab 或 chip 的排列变化,盒会滚动到让活动 chip 避开渐隐带;已在视野内的 chip 不动。`DockLayout` 为每个新选中的 tab 画出新 tab 条时,新 tab 条先跳到该格上一条 tab 条记录的偏移,只让剩余距离带动画;没有记录偏移的 tab 条直接跳到活动 chip,而不是从排列起点滚动过去。chip 的标题从不加省略号:标题盒的末端 16px 始终渐隐,文字刚好放得下时也一样,无需测量宽度。chip 的关闭控件在 chip 活动、悬停或持有焦点时显示,压在标题末端 14px 之上、标题在其下渐隐,因此 chip 宽度两种情况下都一样。活动 chip 两侧的槽不画细线,让填色胶囊立在裸 chip 之间。添加、分栏与 chrome 控件都是 `flex: none`,因此在任何不窄于它们自身的格里(带 chrome 约 130px,不带约 72px)都保持宽度与位置。停靠面的 `min-width: 0` 与格的 `overflow: hidden` 阻止正文里最长的不换行行把格撑出自己的盒子——正是那种情况把控件和正文滚动条推到了屏幕外。
- **chip 盒会滚动,但绝不认领手势。** 横向滚动容器会把按下并移动的手势据为己有并取消指针;盒、chip 与 tab 条都设 `touch-action: none`,手势又捕获了指针,所以在 chip 上按下并移动是拖动,只有滚轮滚动盒子。
- **分栏需要给两个可用的半格留出空间。** 格被等分成两半,因此每一半都必须容得下不可收缩的部分:tab 条的固定部分——按 tab 条宽减去 chip 盒与填充条测得,即内边距、间隙以及该格绘制的每个控件(含它自己的 chrome,所以右上格要求更多)——加上一枚最小尺寸的 chip——`.tab` 在 content-box 上声明 `min-width: 80px`,所以它的足印是 80px 加 10px + 10px 内边距,即 100px,从已渲染 chip 的计算样式读取(读不到时用样式表数值);两半之间的分隔条取其渲染厚度(0——它的细线画在接缝上、不占布局空间,因此正文自己画的分隔线能不断线地穿过接缝)。纵向分栏只由边缘落下产生,它要求每一半容得下 tab 条(34px)加 48px 正文:正文自留的 12px 内边距内一行 13px、行高 1.6 的次级文字——格的正文容器本身没有内边距,tab 的正文直接贴到 tab 条底边和格的边缘,由自己留白。`geometry.ts` 里的 `halvesFit` 是算术;`measure.ts` 在每次提交后与停靠面尺寸变化时读取矩形,因为布局状态只携带比例、从不携带像素,引擎的 planner 也保持如此。没有空间的格保留分栏控件,以 `splitPaneNarrow` 禁用(开启 `hideSplitWhenBlocked` 时改为隐藏),并且在该轴上不提供边缘落区(松手就不是移动)。开启 `hideSplitWhenBlocked` 时,分栏控件自己的占位——它的盒子加 tab 条的间隙——不计入固定部分:隐藏控件让 tab 条卸下的恰是这份占位,把它算进去的读数会随控件的可见性来回翻转、无限重渲染;不计入也正是被询问的那一半会承载的量,因为窄到无法分栏的一半会隐藏自己的控件。用户随后拖窄的格——通过拖动分隔条或嵌入方的列——会保持原尺寸:规则只决定它的下一次分栏。
- **分栏需要给两个可用的半格留出空间。** 格被等分成两半,因此每一半都必须容得下不可收缩的部分:tab 条的固定部分——按 tab 条宽减去 chip 盒与填充条测得,即内边距、间隙以及该格绘制的每个控件(含它自己的 chrome,所以右上格要求更多)——加上一枚最小尺寸的 chip——`.tab` 在 content-box 上声明 `min-width: 80px`,所以它的足印是 80px 加 10px + 10px 内边距,即 100px,从已渲染 chip 的计算样式读取(读不到时用样式表数值);两半之间的分隔条取其渲染厚度(0——它的细线画在接缝上、不占布局空间,因此正文自己画的分隔线能不断线地穿过接缝)。纵向分栏只由边缘落下产生,它要求每一半容得下 tab 条(34px)加 48px 正文:正文自留的 12px 内边距内一行 13px、行高 1.6 的次级文字——格的正文容器本身没有内边距,tab 的正文直接贴到 tab 条底边和格的边缘,由自己留白。`geometry.ts` 里的 `halvesFit` 是算术;`measure.ts` 在停靠布局或分栏策略变化时读取矩形,也会响应停靠面、格和 tab 条各盒子的尺寸通知。嵌入方调整列宽时,不必在它的渲染提交中另测一次。没有空间的格保留分栏控件,以 `splitPaneNarrow` 禁用(开启 `hideSplitWhenBlocked` 时改为隐藏),并且在该轴上不提供边缘落区(松手就不是移动)。开启 `hideSplitWhenBlocked` 时,分栏控件自己的占位——它的盒子加 tab 条的间隙——不计入固定部分:隐藏控件让 tab 条卸下的恰是这份占位,把它算进去的读数会随控件的可见性来回翻转、无限重渲染;不计入也正是被询问的那一半会承载的量,因为窄到无法分栏的一半会隐藏自己的控件。用户随后拖窄的格——通过拖动分隔条或嵌入方的列——会保持原尺寸:规则只决定它的下一次分栏。
- **焦点落在 click 而不是按下。** 在 `pointerdown` 与第一次 `pointermove` 之间的状态变化会重建被按下的子树,而被替换的元素会取消指针。这也避免拖动先记录一条多余的焦点操作。chip、标签条各控件以及嵌入方 chrome 上的 click 都止于标签条:它们各自上报的意图已决定了活动格,或本就是嵌入方自己的事,所以格自身的点击聚焦不再多记一条。浮动面板的抓手与角柄同样通过手势上报——原地松开的按下是一次 click,抬起面板;真正的拖动只记录移动或缩放,由该操作自己抬起面板——而按在面板主体上则直接抬起它。点击本已活动的格、点击或按键选中该格本已选中的 chip,或按下本已活动且在最上层的面板,什么都不改变,也什么都不记录。
- **嵌套在可拖动 chip 里的控件要拦住自己的按下。** 否则按下会开始拖动、捕获指针,嵌套控件的 click 就永远落不下。
- **强调色用平台的强调 token,绝不用 `--dsw-alias-brand-primary`。** 本平台把 `brand-primary` 绑定到近黑(浅色)或近白(深色)的前景色,因此落点光标与落区提示都用 `--dsw-alias-brand-primary-new-colorprimary-new-color`,与轨迹视图一致;悬停的分隔条改用 caption 文字色,读起来是把手而不是高亮。浮窗不画边框——菜单同款阴影(`--dsw-elevation-prominent`)已勾出它的轮廓——活动浮窗也不加重边框:它本就在最上层、投同样的阴影;围它一圈更深的边框读起来像缺陷。
@@ -191,25 +191,31 @@ function Surface({
use(root)
}, [])
// The room rule reads pixels, which the layout state does not carry: measure
// after every commit (a split, a divider drag, a closed tab all move panes)
// and whenever the surface itself is resized (the embedder's column dragged
// wider or narrower). A reading that changed nothing renders nothing.
const remeasure = useCallback((): void => {
withSurface((root) => {
const next = measurePaneFits(root, hideSplitWhenBlocked)
setFits(current => sameFits(current, next) ? current : next)
})
}, [withSurface, hideSplitWhenBlocked])
useLayoutEffect(() => { remeasure() })
useEffect(() => { onRoom?.(fits) }, [fits, onRoom])
useEffect(() => {
useLayoutEffect(() => {
if (typeof ResizeObserver === 'undefined') remeasure()
})
useLayoutEffect(() => {
const root = surface.current
if (root === null || typeof ResizeObserver === 'undefined') return undefined
const observer = new ResizeObserver(() => { remeasure() })
// A layout change can replace a selected tab's pane and strip. Measure its
// initial fit before paint; parent width changes need only the resize delivery.
remeasure()
const observer = new ResizeObserver(remeasure)
observer.observe(root)
// A divider can resize a pane without resizing the surface. At fixed pane
// width, changing the strip controls takes space from its chips or its fill.
for (const box of root.querySelectorAll('[data-dockkit-pane], [data-dockkit-strip], [data-dockkit-strip-tabs], [data-dockkit-strip-fill]')) {
observer.observe(box, { box: 'border-box' })
}
return () => { observer.disconnect() }
}, [remeasure])
}, [remeasure, state, canSplit])
useEffect(() => { onRoom?.(fits) }, [fits, onRoom])
/** Why a pane cannot split right now: the budget first, then its own width. */
const splitBlock = (paneId: PaneId): SplitBlock | undefined => {
@@ -1,37 +1,8 @@
/**
* A chip's title: one line, clipped at the chip's inset, never ellipsized.
* While the text is wider than its box the span carries
* `data-dockkit-tab-clipped`, and the stylesheet fades the text out at the
* clipped edge in place of an ellipsis. Written to the DOM directly rather
* than through state: a reading changes nothing that renders, only how the
* stylesheet paints it. Re-read after every commit (the text may have
* changed) and whenever the span's box resizes (the chip shrank or grew).
*/
import { useLayoutEffect, useRef } from 'react'
/** Title content shared by strip chips and floating-panel headers. */
import type { ReactNode } from 'react'
import css from './dockkit.module.css'
/** Set or clear the span's `data-dockkit-tab-clipped` from its current geometry. */
function markClipped(element: HTMLElement): void {
// Sub-pixel widths: the text counts as clipped past one whole pixel.
if (element.scrollWidth > element.clientWidth + 1) element.dataset.dockkitTabClipped = ''
else delete element.dataset.dockkitTabClipped
}
/** The title span of a strip chip or a floating panel's header chip. */
/** The chip stylesheet fades the trailing edge without measuring the title. */
export function TabTitle({ children }: { readonly children: ReactNode }): ReactNode {
const span = useRef<HTMLSpanElement | null>(null)
useLayoutEffect(() => {
/* v8 ignore next -- the span is rendered unconditionally. */
if (span.current !== null) markClipped(span.current)
})
useLayoutEffect(() => {
const element = span.current
/* v8 ignore next -- the span is rendered unconditionally. */
if (element === null || typeof ResizeObserver === 'undefined') return undefined
const observer = new ResizeObserver(() => { markClipped(element) })
observer.observe(element)
return () => { observer.disconnect() }
}, [])
return <span ref={span} className={css.tabTitle} data-dockkit-tab-title>{children}</span>
return <span className={css.tabTitle} data-dockkit-tab-title>{children}</span>
}
@@ -377,11 +377,8 @@
centres on the text's line rather than sitting on its baseline and keeps
one distance from it. The clip is horizontal in intent; the line box must
hold the descenders it would otherwise cut, hence a line-height above the
chip's own 1. No ellipsis: a title wider than its box (`TabTitle` sets
`data-dockkit-tab-clipped`) fades out over its last 16px instead. A mask on
the title rather than a painted gradient: the chip's fill is bare,
translucent hover, or the active tag colour, and a mask matches every one
without naming it. */
chip's own 1. Only the last 16px of the title box fade, whether or not
the text overflows. A mask keeps the chip's fill visible underneath. */
.tabTitle {
display: flex;
flex: 1 1 auto;
@@ -390,25 +387,20 @@
min-width: 0;
overflow: hidden;
line-height: 1.4;
}
.tabTitle[data-dockkit-tab-clipped] {
mask-image: linear-gradient(to right, black calc(100% - 16px), transparent);
}
/* While the close shows, the title is gone under the close's circle and fades
out over the 16px before it: the circle spans the chip's last 24px and the
title ends 10px inside the chip, so the title's last 14px are under it.
Later than the clipped mask, so a clipped chip showing its close fades
under the close. A floating panel's header chip has no close, so it keeps
the clipped mask alone. */
.tab:not(.floatTitle):focus-within .tabTitle,
.tabActive .tabTitle {
Quiet and floating titles have no overlaid close. */
.tab:not(.floatTitle, .tabQuiet):focus-within .tabTitle,
.tabActive:not(.tabQuiet) .tabTitle {
mask-image: linear-gradient(to right, black calc(100% - 30px), transparent calc(100% - 14px));
}
@media (hover: hover) {
.tab:not(.floatTitle):hover .tabTitle {
.tab:not(.floatTitle, .tabQuiet):hover .tabTitle {
mask-image: linear-gradient(to right, black calc(100% - 30px), transparent calc(100% - 14px));
}
}
@@ -493,7 +485,7 @@
/* A pane's lone unclosable chip is a label, not a choice: no tab, no
hover fill — the primary ink on the pane's own ground. Its title never
yields to a close control, so it keeps the clipped fade alone. */
yields to a close control, so it keeps the ordinary title fade. */
.tab.tabQuiet {
color: var(--dsw-alias-label-primary);
background: transparent;
@@ -508,21 +500,6 @@
}
}
.tab.tabQuiet .tabTitle,
.tab.tabQuiet:focus-within .tabTitle {
mask-image: none;
}
@media (hover: hover) {
.tab.tabQuiet:hover .tabTitle {
mask-image: none;
}
}
.tab.tabQuiet .tabTitle[data-dockkit-tab-clipped] {
mask-image: linear-gradient(to right, black calc(100% - 16px), transparent);
}
.tabDragging {
opacity: 0.5;
}
@@ -19,6 +19,7 @@ import { applyOp } from '../src/engine/operations.ts'
import { FLOAT_DEFAULT_SIZE, FLOAT_MIN_SIZE } from '../src/engine/constraints.ts'
import { floatRectAt } from '../src/engine/geometry.ts'
import { DockSurface, type DockSurfaceProps } from '../src/components/DockSurface.tsx'
import { TabTitle } from '../src/components/TabTitle.tsx'
import type { TabMenuExtras } from '../src/contract/adapter.ts'
import { FloatLayer, type FloatLayerProps } from '../src/components/FloatLayer.tsx'
import { dockPaneIds, getPane } from '../src/engine/tree.ts'
@@ -574,51 +575,14 @@ describe('DockSurface', () => {
}
})
it('marks a chip title clipped while its text is wider than its box, re-reading on resize', () => {
class FakeResizeObserver implements ResizeObserver {
static readonly all: FakeResizeObserver[] = []
readonly observe = vi.fn()
readonly unobserve = vi.fn()
readonly disconnect = vi.fn()
constructor(private readonly callback: ResizeObserverCallback) {
FakeResizeObserver.all.push(this)
}
fire(): void {
this.callback([], this)
}
}
vi.stubGlobal('ResizeObserver', FakeResizeObserver)
let clientWidth = 200
const descriptors = ['scrollWidth', 'clientWidth'].map(name =>
[name, Object.getOwnPropertyDescriptor(Element.prototype, name)] as const)
const title = (element: Element): boolean => element.hasAttribute('data-dockkit-tab-title')
Object.defineProperty(Element.prototype, 'scrollWidth', { configurable: true, get(this: Element) { return title(this) ? 120 : 0 } })
Object.defineProperty(Element.prototype, 'clientWidth', { configurable: true, get(this: Element) { return title(this) ? clientWidth : 0 } })
try {
const controller = seededController()
const { unmount } = renderSurface(controller, spyIntents())
const span = document.querySelector<HTMLElement>('[data-dockkit-tab-title]')
if (span === null) throw new Error('expected a chip title')
const observer = FakeResizeObserver.all.find(candidate => candidate.observe.mock.calls.some(([target]) => target === span))
if (observer === undefined) throw new Error('expected the title to observe its own size')
expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(false)
// The chip narrowed under the text.
clientWidth = 80
act(() => { observer.fire() })
expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(true)
clientWidth = 200
act(() => { observer.fire() })
expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(false)
unmount()
expect(observer.disconnect).toHaveBeenCalledTimes(1)
} finally {
for (const [name, descriptor] of descriptors) {
if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name)
else Object.defineProperty(Element.prototype, name, descriptor)
}
vi.unstubAllGlobals()
}
it('renders and renames a chip title without querying its width', () => {
const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get')
const clientWidth = vi.spyOn(Element.prototype, 'clientWidth', 'get')
const view = render(<TabTitle>Files</TabTitle>)
view.rerender(<TabTitle>A long renamed file.ts</TabTitle>)
expect(view.getByText('A long renamed file.ts').hasAttribute('data-dockkit-tab-title')).toBe(true)
expect(scrollWidth).not.toHaveBeenCalled()
expect(clientWidth).not.toHaveBeenCalled()
})
it('asks for the seeded tab from the strip\'s add control, naming the pane and nothing else', () => {
@@ -0,0 +1,93 @@
// @vitest-environment jsdom
/** Split availability in the horizontal layout used by the right sidebar. */
import { act, cleanup, render } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { DockLayout } from '../src/components/DockSurface.tsx'
import { seededController, TEST_LABELS } from './fixtures.client.ts'
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() })
/** Deliver only size notifications for the given box, as opposed to a window resize. */
function observeSizes() {
const observers = new Set<Observer>()
class Observer {
readonly boxes = new Set<Element>()
constructor(readonly notify: () => void) { observers.add(this) }
observe(box: Element): void { this.boxes.add(box) }
disconnect(): void { observers.delete(this) }
}
vi.stubGlobal('ResizeObserver', Observer)
return (box: Element) => {
act(() => {
for (const observer of observers) if (observer.boxes.has(box)) observer.notify()
})
}
}
function panel() {
const controller = seededController()
controller.setExpanded(true)
const onRoom = vi.fn()
const paneReads = vi.fn()
let width = 300
let fixed = 80
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
if (this.hasAttribute('data-dockkit-pane')) { paneReads(); return new DOMRect(0, 0, width, 600) }
if (this.hasAttribute('data-dockkit-strip')) return new DOMRect(0, 0, width, 38)
if (this.hasAttribute('data-dockkit-strip-tabs')) return new DOMRect(0, 0, 100, 28)
if (this.hasAttribute('data-dockkit-strip-fill')) return new DOMRect(0, 0, width - fixed - 100, 0)
return new DOMRect()
})
const tree = () => <div style={{ width }}>
<DockLayout state={controller.getSnapshot().state} intents={controller} labels={TEST_LABELS} canSplit
renderTab={tab => <div>{tab.title}</div>} renderTabTitle={tab => <span>{tab.title}</span>}
chrome={<span style={{ width: fixed }} />} onRoom={onRoom} />
</div>
const view = render(tree())
return {
controller, paneReads, onRoom,
box: (selector: string) => view.container.querySelector(selector)!,
blocked: () => view.getByRole('button', { name: TEST_LABELS.splitPane }).hasAttribute('disabled'),
redraw: (size: number, controls = fixed) => { width = size; fixed = controls; view.rerender(tree()) },
}
}
it('measures the mounted pane immediately but not on width-only React commits', () => {
const resized = observeSizes()
const h = panel()
expect(h.blocked()).toBe(true)
h.paneReads.mockClear()
h.redraw(450)
h.redraw(500)
expect(h.paneReads).not.toHaveBeenCalled()
resized(h.box('[data-dockkit-surface]'))
expect(h.blocked()).toBe(false)
expect(h.onRoom).toHaveBeenLastCalledWith(new Map([[h.controller.getSnapshot().state.rootId, { row: true, column: true }]]))
})
it('tracks changing strip controls at fixed pane width, including after the selected tab replaces its strip', () => {
const resized = observeSizes()
const h = panel()
h.redraw(500)
resized(h.box('[data-dockkit-surface]'))
expect(h.blocked()).toBe(false)
const oldFill = h.box('[data-dockkit-strip-fill]')
h.controller.openContent({ kind: 'file', contentId: 'file:a', title: 'A' })
h.redraw(500, 180)
expect(h.blocked()).toBe(true)
const fill = h.box('[data-dockkit-strip-fill]')
expect(fill).not.toBe(oldFill)
h.redraw(500, 80)
resized(fill)
expect(h.blocked()).toBe(false)
})
it('keeps commit-time measurements when size observation is unavailable', () => {
vi.stubGlobal('ResizeObserver', undefined)
const h = panel()
expect(h.blocked()).toBe(true)
h.redraw(500)
expect(h.blocked()).toBe(false)
h.redraw(500, 180)
expect(h.blocked()).toBe(true)
})
@@ -27,8 +27,8 @@
en: 27fdd4ec3c830299
zh: 0e70ac367e4176f8
/deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation:
en: 78a25420651971d2
zh: 8bd34e5624f08208
en: a772926387782a82
zh: 909966795290c52e
/deepseek-ai-dsh-client-ui-session-panel/further-exploration:
en: decfa1b92e25ec6c
zh: 255c7862690a2f23
+1 -1
View File
@@ -83,7 +83,7 @@ A row whose single line clips its name or leaves out its owner, state, or measur
<details>
<summary>Implementation internals — click to expand</summary>
The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights.
The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`, which is readable only on the body, so the panel's stylesheet turns it there into a registered 0px or 1px step, `--dsh-session-panel-reserve-room`, that changes only when the reserve starts or stops covering the gutter; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The message flow does not inherit that step; crossing the docking threshold does not restyle its rows. The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights.
While the docking preference is on, the probe carries `data-session-panel-reserve`, and a `:has()` rule in the panel's stylesheet sets `--dsh-chat-end-reserve` to 348px on the Conversation body, which then pads its scrollport's end by the missing gutter ([end reserve](../ui-conversation/README.md#end-reserve)). The probe's second term reads the largest reserve, not the padding, so its answer is the same before and after the transcript moves: the room the transcript makes never changes the decision that asked for it.
@@ -83,7 +83,7 @@ kind: "package-reference"
<details>
<summary>实现内幕——点击展开</summary>
面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。
面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`,它只能在主体上读取,因此面板样式表在主体上把它转换为已注册的 0px 或 1px 阶跃值 `--dsh-session-panel-reserve-room`,只有预留开始或不再覆盖这段留白时才变化;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。消息流不继承这个阶跃值,因此跨过停靠阈值不会让消息行重算样式。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。
停靠偏好开启时,探针带有 `data-session-panel-reserve`,面板样式表中的一条 `:has()` 规则据此在 Conversation 主体上把 `--dsh-chat-end-reserve` 设为 348px,主体随即按所缺的留白给滚动容器的末端加上内边距([末端预留](../ui-conversation/README.zh.md#end-reserve))。探针的第二项读取的是最大预留而不是内边距,因此正文移动前后它的结果相同:正文让出的位置不会反过来改变提出让位的那项判断。
@@ -6,8 +6,10 @@
/* The docked panel's inline metrics: 40px clear of the transcript column,
past its width handle, 8px from the end edge, and at least 300px wide. The
panel's width and the dock probe both derive from them, so the gutter that
docks the panel is exactly the one that holds its minimum width. */
panel's width, the dock probe, and the reserve it asks the Conversation
body for all derive from them, so the gutter that docks the panel is
exactly the one that holds its minimum width. */
:global([data-conversation-content]),
.panel,
.dockProbe {
--panel-clear: 40px;
@@ -15,6 +17,31 @@
--panel-min-width: 300px;
}
/* Whether the Conversation body's largest end reserve covers the docked
panel's gutter: 1px when it does, otherwise 0. The body's maximum is not
inherited and changes on every resize, so this step derives on the body
itself, and as a registered length it reaches the dock probe only when the
decision flips. */
@property --dsh-session-panel-reserve-room {
syntax: '<length>';
inherits: true;
initial-value: 0px;
}
:global([data-conversation-content]) {
--dsh-session-panel-reserve-room: clamp(
0px,
calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px),
1px
);
}
/* The dock probe lives in the aside, not the message flow. Crossing its
threshold must not change the inherited style of every message. */
:global([data-slot='conversation.chat.flow']) {
--dsh-session-panel-reserve-room: initial;
}
/* While the docking preference is on, the dock probe carries a mark, and
the panel asks the Conversation body to keep the gutter that docks it:
the three metrics above, 348px. Where the gutter is narrower, the body
@@ -22,7 +49,7 @@
(ui-conversation's end reserve) and makes no room when the start gutter
cannot give it. */
:global([data-conversation-content]):has(.dockProbe[data-session-panel-reserve]) {
--dsh-chat-end-reserve: calc(40px + 8px + 300px);
--dsh-chat-end-reserve: calc(var(--panel-clear) + var(--panel-edge) + var(--panel-min-width));
}
.panel {
@@ -104,7 +131,7 @@
right: 0;
width: max(
calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px),
calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px)
var(--dsh-session-panel-reserve-room)
);
max-width: 1px;
height: 0;
@@ -31,10 +31,12 @@ const px = (value: string | undefined): number => {
}
describe('SessionPanel.module.css docking geometry', () => {
const metrics = declarationsOf('.panel, .dockProbe')
const metrics = declarationsOf(':global([data-conversation-content]), .panel, .dockProbe')
const clear = px(metrics['--panel-clear'])
const edge = px(metrics['--panel-edge'])
const minWidth = px(metrics['--panel-min-width'])
/** The body's reserve step, evaluated: clamped to 0..1px. */
const reserveRoom = (reserveMax: number): number => Math.min(1, Math.max(0, (reserveMax - clear - edge - minWidth) * 10000000 + 1))
it('derives the docked width and the dock probe from one set of metrics', () => {
expect([clear, edge, minWidth]).toEqual([40, 8, 300])
@@ -46,15 +48,28 @@ describe('SessionPanel.module.css docking geometry', () => {
const probe = declarationsOf('.dockProbe')
expect(probe['width']).toBe(
'max(calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px),'
+ ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px))',
+ ' var(--dsh-session-panel-reserve-room))',
)
expect(probe['max-width']).toBe('1px')
})
it('derives the reserve step on the Conversation body, where the non-inherited maximum is readable', () => {
expect(declarationsOf(':global([data-conversation-content])')).toEqual({
'--dsh-session-panel-reserve-room': 'clamp(0px,'
+ ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px),'
+ ' 1px)',
})
expect(declarationsOf(":global([data-slot='conversation.chat.flow'])")['--dsh-session-panel-reserve-room']).toBe('initial')
// The aside inherits the computed step when it flips; the message rows keep the initial value.
expect(css.replace(/\s+/g, ' ')).toContain(
"@property --dsh-session-panel-reserve-room { syntax: '<length>'; inherits: true; initial-value: 0px; }",
)
})
it('makes the probe 1px wide exactly from the gutter that holds the panel at its minimum width', () => {
// The declarations above, evaluated: a width below 0 is used as 0, and max-width caps the probe at 1px.
const probeWidth = (gutter: number, reserveMax = 0): number =>
Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, (reserveMax - clear - edge - minWidth) * 10000000 + 1))
Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, reserveRoom(reserveMax)))
const dockedWidth = (gutter: number): number => Math.min(360, Math.max(minWidth, gutter - clear - edge))
expect([probeWidth(0), probeWidth(347), probeWidth(347.5), probeWidth(348), probeWidth(900)]).toEqual([0, 0, 0.5, 1, 1])
// At the first gutter that docks, the panel is at its minimum width and keeps both clearances.
@@ -65,7 +80,7 @@ describe('SessionPanel.module.css docking geometry', () => {
it('gives the probe room as well from the largest end reserve that covers the gutter, whatever the gutter is', () => {
const probeWidth = (gutter: number, reserveMax: number): number =>
Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, (reserveMax - clear - edge - minWidth) * 10000000 + 1))
Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, reserveRoom(reserveMax)))
// A 260px gutter holds no panel, and the transcript can leave 348px: room. This term is a step at 348px, as the
// body's end inset is, so the probe has room exactly where the body makes it.
expect([probeWidth(260, 347), probeWidth(260, 347.96), probeWidth(260, 348), probeWidth(260, 900)]).toEqual([0, 0, 1, 1])
@@ -77,8 +92,7 @@ describe('SessionPanel.module.css docking geometry', () => {
it('asks the Conversation body for exactly the gutter that docks the panel while the probe carries the mark', () => {
const request = declarationsOf(':global([data-conversation-content]):has(.dockProbe[data-session-panel-reserve])')
expect(request).toEqual({ '--dsh-chat-end-reserve': 'calc(40px + 8px + 300px)' })
expect(40 + 8 + 300).toBe(clear + edge + minWidth)
expect(request).toEqual({ '--dsh-chat-end-reserve': 'calc(var(--panel-clear) + var(--panel-edge) + var(--panel-min-width))' })
})
it('keeps the probe out of sight, out of the layout flow, and away from the pointer', () => {
@@ -18,8 +18,8 @@
en: 3b007cc4d2d89c60
zh: 74d9795c6392ad74
/deepseek-ai-dsh-client-ui-sidebar-right/presentations:
en: 5024c4e5fe5dfd2e
zh: 535a7f585e1bcd97
en: aa03c00f30ef88f7
zh: b9b2cbe86775a864
/deepseek-ai-dsh-client-ui-sidebar-right/the-expand-button:
en: ca7a1966ad9cef31
zh: b9a7a967a14f067e
+1 -1
View File
@@ -47,7 +47,7 @@ With a coarse pointer, a disabled split button is hidden, whether blocked by ins
In Windows Electron, `html[data-windows-titlebar]` keeps fullscreen panels below the caption and to the right of the expanded sidebar. The frame's `--dsh-windows-sidebar-width` supplies that inset and maximum width; `--dsh-windows-content-radius` supplies the top-left radius. Only fullscreen panels clip overflow for that corner.
The seat reports presentation through `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()`; the frame does not inject this package. Switching fullscreen on a wide viewport leaves the center width unchanged, and the width handle appears only in expanded normal mode. Independent floating panels and `float`/`dock` operations remain available.
The seat reports presentation through `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()`; the frame does not inject this package. Switching fullscreen on a wide viewport leaves the center width unchanged, and the width handle appears only in expanded normal mode. After the panel opens, dragging changes its width without sending an inherited slide distance to tab contents. Closing moves each docked item by the full panel width, even in a split layout. Independent floating panels and `float`/`dock` operations remain available.
The panel has no header row. Its two controls — the presentation switch and the collapse button — ride the kit's chrome seat at the far end of the top-right pane's tab strip, so the strip is the panel's whole top edge. Each strip reads, left to right: the tab capsules with close controls where allowed, the add control (drawn only while that pane holds no guide tab; it opens the guide there through `ctx.sidebarRight.openTab`), the pane's split control, and in the top-right pane the two panel controls. Only the chips give way in a narrow pane; the controls after them never shrink or clip.
@@ -47,7 +47,7 @@ kind: "package-reference"
在 Windows Electron 中,`html[data-windows-titlebar]` 让全屏面板保持在顶栏下方及展开侧栏的右侧。框架的 `--dsh-windows-sidebar-width` 提供该缩进及最大宽度;`--dsh-windows-content-radius` 提供左上圆角。仅全屏面板为该圆角裁剪溢出内容。
席位通过 `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()` 报告呈现,框架不注入本包。宽屏切换全屏不改变中栏宽度;宽度拖拽区只在普通展开态显示。独立浮窗及 `float`/`dock` 操作保持可用。
席位通过 `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()` 报告呈现,框架不注入本包。宽屏切换全屏不改变中栏宽度;宽度拖拽区只在普通展开态显示。面板展开后,拖动只更新面板宽度,不向标签页内容传递滑动距离。即使分栏,收起时每个停靠项也按整个面板的宽度滑动。独立浮窗及 `float`/`dock` 操作保持可用。
面板没有标题行。它的两个控件——形态切换与折叠按钮——搭在套件 chrome 席位上,位于右上格 tab 条的最末端,因此 tab 条就是面板的整条上边。每条 tab 条从左到右读作:在允许时带关闭按钮的 tab 胶囊,添加控件(只在该格没有引导 tab 时绘制;它通过 `ctx.sidebarRight.openTab` 在该格打开引导页),该格的分栏控件,以及右上格里的两个面板控件。窄格里只有 chip 让位;其后的控件从不收缩或被裁切。
@@ -28,7 +28,14 @@
display: none;
}
@property --dsh-sidebar-right-panel-width {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
.panel {
width: var(--dsh-sidebar-right-panel-width);
--dsh-dockkit-dock-layer: 10;
--dsh-dockkit-float-layer: 60;
position: absolute;
@@ -47,6 +54,18 @@
pointer-events: none;
}
/* A split pane slides the full panel width, not its own width. An open panel
needs this inherited distance only for items mounting during an animated opening. */
.panel:not([data-sidebar-right-open]) {
--dsh-sidebar-width: var(--dsh-sidebar-right-panel-width);
}
@media (prefers-reduced-motion: no-preference) {
.panel[data-sidebar-right-opening] {
--dsh-sidebar-width: var(--dsh-sidebar-right-panel-width);
}
}
/* Only docked Grid items slide. Their common ancestor remains untransformed
and without a stacking context, so fixed floating children escape. */
.panel :global([data-dockkit-host='dock']),
@@ -346,8 +346,7 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject<H
// Fullscreen is 1px wider than the viewport: the first column's divider,
// which separates the panel from the conversation, sits past the window's
// left edge where the frame clips it, and slides into view with the panel.
style={{ width: fullscreen ? 'calc(100vw + 1px)' : width,
'--dsh-sidebar-width': fullscreen ? 'calc(100vw + 1px)' : `${width}px` } as CSSProperties}
style={{ '--dsh-sidebar-right-panel-width': fullscreen ? 'calc(100vw + 1px)' : `${width}px` } as CSSProperties}
data-sidebar-right-session={sessionId}
data-sidebar-right-panel={fullscreen ? 'fullscreen' : 'push'}
data-sidebar-right-open={expanded || undefined}
@@ -672,22 +672,37 @@ describe('RightbarSeat presentation', () => {
expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false)
})
it('resizes the split panel without writing an inherited slide distance', async () => {
const h = await mountSeat()
h.open()
const panel = element(h.view.container, '[data-sidebar-right-panel]')
fireEvent.transitionEnd(element(panel, "[data-dockkit-host='dock']"))
act(() => { h.actions.splitPane(SESSION) })
expect(h.view.container.querySelectorAll('[data-dockkit-pane]')).toHaveLength(2)
for (const width of [518, 620]) {
h.view.update({ width, viewportWidth: 1440, canShow: true })
expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe(`${width}px`)
expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('')
}
act(() => { h.actions.setExpanded(SESSION, false) })
expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('620px')
})
it('fills the viewport without replacing the content tree or releasing the wide track', async () => {
const h = await mountSeat()
const tab = h.open()
const panel = element(h.view.container, '[data-sidebar-right-panel]')
const body = element(h.view.container, '[data-tab-body]')
expect(panel.style.width).toBe('420px')
expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('420px')
fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]'))
expect(h.layout().mode).toBe('fullscreen')
expect(panel.style.width).toBe('calc(1px + 100vw)')
expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('calc(100vw + 1px)')
expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('calc(100vw + 1px)')
expect(panel.dataset['sidebarRightPanel']).toBe('fullscreen')
expect(element(h.view.container, '[data-tab-body]')).toBe(body)
expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, true)
expect(h.bodies.get(tab.id)?.sidebar).toEqual({ expanded: true, fullscreen: true })
fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]'))
expect(panel.style.width).toBe('420px')
expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('420px')
expect(element(h.view.container, '[data-tab-body]')).toBe(body)
expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, false)
fireEvent.click(element(h.view.container, '[data-sidebar-right-toggle]'))
@@ -8,6 +8,17 @@ const css = readFileSync(fileURLToPath(new URL('../src/client/shell/SidebarRight
const host = String.raw`:global\(\[data-dockkit-host='dock'\]\)`
describe('SidebarRight.module.css', () => {
it('keeps panel width local except for closed docks and items joining an animated opening', () => {
const distance = String.raw`--dsh-sidebar-width:\s*var\(--dsh-sidebar-right-panel-width\);`
expect(css).toMatch(/@property --dsh-sidebar-right-panel-width\s*\{\s*syntax: '<length>';\s*inherits: false;\s*initial-value: 0px;/)
expect(css).toMatch(/\.panel\s*\{[^{}]*\bwidth: var\(--dsh-sidebar-right-panel-width\);/)
expect(css).toMatch(new RegExp(String.raw`\.panel:not\(\[data-sidebar-right-open\]\)\s*\{\s*${distance}\s*}`))
// Reduced motion need not produce a transitionend to clear the opening marker.
expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: no-preference\)\s*\{\s*`
+ String.raw`\.panel\[data-sidebar-right-opening\]\s*\{\s*${distance}\s*}\s*}`))
expect(css.match(/--dsh-sidebar-width:/g)).toHaveLength(2)
})
it('starts docked items mounted by an opening at the closed position', () => {
expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*\.panel\[data-sidebar-right-opening\] ${host},[^{}]*\{`
+ String.raw`\s*transform: translateX\(var\(--dsh-sidebar-width\)\);\s*}\s*}`))
+1
View File
@@ -9,6 +9,7 @@ import { runPnpmCommand } from './compile-referenced-projects.ts'
*/
export const SERIAL_BENCH_FILES = [
'benchmarks/long-session-browser/long-session.bench.ts',
'benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts',
'benchmarks/user-text/user-text.bench.client.ts',
'benchmarks/conversation-fold/conversation-fold.bench.client.ts',
'benchmarks/active-stream-reconnect/reconnect.bench.client.ts',