From 330a13ba823368016e9d94eb342fbbd7724d2b2a Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:57:32 +0800 Subject: [PATCH] perf(ui-conversation): stop restyling the transcript on every resize frame Register the Conversation width axis inputs and its continuously varying derived lengths without inheritance, publish the content width and end inset to descendants as computed lengths, and derive the Session panel's docking step on the body as a registered 0px/1px length. A right Sidebar drag no longer restyles the whole transcript when the resolved width is unchanged. Refs #8856 --- apps/web/tests/markdown-wide-table.e2e.ts | 6 +- apps/web/tests/rightbar-drag.perf.ts | 245 ++++++++++++++++++ apps/web/tsconfig.json | 1 + .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../skeleton/ConversationRoot.module.css | 59 ++++- .../skeleton/ConversationWidthControls.tsx | 11 +- .../tests/end-reserve-styles.client.spec.ts | 26 +- .../tests/skeleton.client.spec.tsx | 19 +- .../client/ui-session-panel/README.i18n.yaml | 4 +- packages/client/ui-session-panel/README.md | 2 +- packages/client/ui-session-panel/README.zh.md | 2 +- .../src/client/SessionPanel.module.css | 29 ++- .../tests/session-panel-styles.client.spec.ts | 25 +- tsconfig.host.json | 1 + 16 files changed, 391 insertions(+), 47 deletions(-) create mode 100644 apps/web/tests/rightbar-drag.perf.ts diff --git a/apps/web/tests/markdown-wide-table.e2e.ts b/apps/web/tests/markdown-wide-table.e2e.ts index 16e45fd37a..f77ce2b3a9 100644 --- a/apps/web/tests/markdown-wide-table.e2e.ts +++ b/apps/web/tests/markdown-wide-table.e2e.ts @@ -216,13 +216,13 @@ async function awaitTableLayout(target: Page): Promise { 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('div[data-phase]') + const body = element.querySelector('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 }) } diff --git a/apps/web/tests/rightbar-drag.perf.ts b/apps/web/tests/rightbar-drag.perf.ts new file mode 100644 index 0000000000..015640f852 --- /dev/null +++ b/apps/web/tests/rightbar-drag.perf.ts @@ -0,0 +1,245 @@ +// Manual diagnostic: main-thread cost of dragging the right Sidebar's resize +// handle beside a long, fully loaded synthetic transcript. It reports frame +// gaps, style recalculation (with the element count it touched), layout, and +// the share of both forced synchronously from script, plus the final column +// and composer widths; host speed is not a correctness contract, so nothing is +// asserted beyond the loaded turn count. Run after `pnpm run build:artifacts`: +// RB_TURNS=200 RB_SAMPLES=3 RB_STEPS=40 DSH_SNAPSHOT=replay \ +// pnpm exec vitest run --config vitest.web.perf.config.ts apps/web/tests/rightbar-drag.perf.ts +import { performance } from 'node:perf_hooks' +import { chromium, type Browser, type Page } from 'playwright' +import { expect, it } from 'vitest' +import { brandString } from '@deepseek-ai/dsh-brand' +import { + type ToolCallId, + createAssistantMessage, + createSystemMessage, + createToolResultMessage, + createUserMessage, +} from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, type SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import { launchWebScaffold, seedSession, webSnapshotMode } from './scaffold.ts' +import { newEnglishPage } from './support.ts' + +const TURNS = Number(process.env.RB_TURNS ?? 200) +const SAMPLES = Number(process.env.RB_SAMPLES ?? 3) +const STEPS = Number(process.env.RB_STEPS ?? 40) +const STEP_PX = 8 +const STEP_GAP_MS = 8 +const SESSION_ID = 'perf-rightbar-drag' +const TAIL = '[data-chat-flow-key*="turn-tail"]' +/** A narrow window where the column falls below the content width, a wide one, and a wide one with a dragged preference. */ +const SCENARIOS = [ + { viewport: 1680, preference: null }, + { viewport: 2560, preference: null }, + { viewport: 2560, preference: 720 }, +] as const + +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') +} + +function historyFixture(): string { + const session = Session.create(brandString(SESSION_ID)) + for (let turn = 1; turn <= 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: 'RIGHTBAR_DRAG_PERF', messageSeqs: [user.seq], source: { kind: 'fallback' } }) + const tool = turn % 5 === 0 + const callId = brandString(`rb-call-${String(turn)}`) + 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: '{"path":"src/a.ts"}' }] : [], + ], + }), + usage: { inputTokens: 4000, outputTokens: 800 }, + }, { surfaceOp: 'append' }) + if (tool) { + const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_tool', arguments: '{"path":"src/a.ts"}' }) + 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' } }) + } + return [JSON.stringify({ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 1700000000000, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 }), + ...session.snapshotEvents().map(event => JSON.stringify(event)), ''].join('\n') +} + +interface TraceEvent { + name: string + ph: string + dur?: number + ts: number + tid: number + pid: number + args?: { elementCount?: number } +} + +const SCRIPT_EVENTS = new Set(['FunctionCall', 'EventDispatch', 'FireAnimationFrame', 'TimerFire', 'RunMicrotasks', 'v8.callFunction']) + +/** Frame timestamps the page collects during one drag. */ +type FrameProbe = Window & { rightbarFrames?: { frames: number[]; running: boolean } } + +/** Sum style recalculation, layout, and the share of each forced synchronously from script. */ +function summarizeTrace(buffer: Buffer): Record { + const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[] + const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(e => e.ph === 'X') + const scripts = events.filter(e => SCRIPT_EVENTS.has(e.name)) + // Style or layout run inside a script task is forced (synchronous) by a geometry read or style query. + const nested = (e: TraceEvent) => scripts.some(s => + s.tid === e.tid && s.pid === e.pid && s.ts <= e.ts && e.ts + (e.dur ?? 0) <= s.ts + (s.dur ?? 0)) + const ms = (list: TraceEvent[]) => list.reduce((t, e) => t + (e.dur ?? 0), 0) / 1000 + const layouts = events.filter(e => e.name === 'Layout') + const styles = events.filter(e => e.name === 'UpdateLayoutTree') + const forcedLayouts = layouts.filter(nested) + const forcedStyles = styles.filter(nested) + return { + layoutMs: ms(layouts), layouts: layouts.length, + forcedLayouts: forcedLayouts.length, forcedLayoutMs: ms(forcedLayouts), + styleMs: ms(styles), styles: styles.length, + forcedStyles: forcedStyles.length, forcedStyleMs: ms(forcedStyles), + styledElements: styles.reduce((t, e) => t + (e.args?.elementCount ?? 0), 0), + maxStyleMs: Math.max(0, ...styles.map(e => (e.dur ?? 0) / 1000)), + maxLayoutMs: Math.max(0, ...layouts.map(e => (e.dur ?? 0) / 1000)), + scriptMs: ms(events.filter(e => e.name === 'FunctionCall' || e.name === 'EventDispatch' || e.name === 'FireAnimationFrame')), + paintMs: ms(events.filter(e => e.name === 'Paint')), + } +} + +async function loadAll(page: Page): Promise { + let count = await page.locator(TAIL).count() + while (count < TURNS) { + const more = page.getByRole('button', { name: 'Load earlier', exact: true }) + await more.click({ timeout: 60_000 }) + await page.waitForFunction( + ({ selector, previous }) => document.querySelectorAll(selector).length > previous, + { selector: TAIL, previous: count }, + { timeout: 60_000 }, + ) + count = await page.locator(TAIL).count() + } + return count +} + +async function dragOnce(browser: Browser, page: Page, direction: 1 | -1): Promise> { + const handle = page.locator('[data-side="rightbar"]') + const box = await handle.boundingBox() + if (box === null) throw new Error('rightbar handle missing') + const x0 = box.x + box.width / 2 + const y = box.y + box.height / 2 + await page.evaluate(() => { + const probe = { frames: [] as number[], running: true } + ;(window as FrameProbe).rightbarFrames = probe + const tick = (t: number) => { if (!probe.running) return; probe.frames.push(t); requestAnimationFrame(tick) } + requestAnimationFrame(tick) + }) + await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) + await page.mouse.move(x0, y) + await page.mouse.down() + const start = performance.now() + for (let i = 1; i <= STEPS; i++) { + await page.mouse.move(x0 - direction * i * STEP_PX, y) + await page.waitForTimeout(STEP_GAP_MS) + } + const moved = performance.now() + await page.mouse.up() + // Settled: the last frame within a 600 ms window whose transcript column or composer width differs from its predecessor. + const settle = await page.evaluate(() => new Promise<{ settleMs: number; columnWidth: number; composerWidth: number }>((resolve) => { + const start = window.performance.now() + const read = () => [ + document.querySelector('[data-chat-flow]')?.getBoundingClientRect().width ?? 0, + document.querySelector('[data-composer-input]')?.getBoundingClientRect().width ?? 0, + ] + let last = read() + let changedAt = 0 + const tick = (t: number) => { + const next = read() + if (next[0] !== last[0] || next[1] !== last[1]) changedAt = t - start + last = next + if (t - start < 600) requestAnimationFrame(tick) + else resolve({ settleMs: changedAt, columnWidth: next[0]!, composerWidth: next[1]! }) + } + requestAnimationFrame(tick) + })) + const settled = moved + settle.settleMs + const trace = summarizeTrace(await browser.stopTracing()) + const frames = await page.evaluate(() => { + const probe = (window as FrameProbe).rightbarFrames! + probe.running = false + return probe.frames + }) + const gaps = frames.slice(1).map((t, i) => t - frames[i]!).sort((a, b) => a - b) + const pick = (q: number) => gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * q))] ?? 0 + return { + dragMs: moved - start, settleMs: settle.settleMs, totalMs: settled - start, + columnWidth: settle.columnWidth, composerWidth: settle.composerWidth, + frames: frames.length, frameP50: pick(0.5), frameP95: pick(0.95), frameMax: gaps.at(-1) ?? 0, + ...trace, + } +} + +function median(values: number[]): number { + return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]! +} + +it(`drags the right Sidebar beside ${String(TURNS)} loaded turns`, async () => { + if (webSnapshotMode() !== 'replay') throw new Error('requires DSH_SNAPSHOT=replay') + const scaffold = await launchWebScaffold() + const results: Record[]> = {} + try { + await seedSession(scaffold, historyFixture(), SESSION_ID) + const browser = await chromium.launch({ headless: true }) + try { + for (const { viewport, preference } of SCENARIOS) { + for (let sample = 0; sample < SAMPLES; sample++) { + const page = await newEnglishPage(browser) + await page.setViewportSize({ width: viewport, height: 1000 }) + page.setDefaultTimeout(60_000) + if (preference !== null) await page.addInitScript((value) => { localStorage.setItem('dsh.conversation.contentWidth', value) }, String(preference)) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator(TAIL).last().waitFor() + const loaded = await loadAll(page) + expect(loaded).toBe(TURNS) + await page.getByRole('button', { name: 'Open right sidebar' }).first().click() + await page.locator('[data-side="rightbar"]').waitFor() + await page.waitForTimeout(800) + const nodes = await page.evaluate(() => document.querySelectorAll('*').length) + for (const direction of [1, -1] as const) { + const key = `${String(viewport)}/${preference === null ? 'auto' : 'pref' + String(preference)}/${direction === 1 ? 'widen' : 'narrow'}` + const result = { ...await dragOnce(browser, page, direction), nodes } + ;(results[key] ??= []).push(result) + console.log(JSON.stringify({ rb: 'sample', key, sample, ...result })) + } + await page.close() + } + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } + const summary = Object.fromEntries(Object.entries(results).map(([key, samples]) => [key, + Object.fromEntries(Object.keys(samples[0]!).map(metric => [metric, Math.round(median(samples.map(s => s[metric]!)) * 10) / 10]))])) + console.log(JSON.stringify({ rb: 'median', turns: TURNS, steps: STEPS, summary }, null, 1)) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index cd716a0177..43561279e8 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -276,6 +276,7 @@ "tests/window-drag-inheritance.e2e.ts", "tests/complex-history.perf.ts", "tests/dingtalk-connection.e2e.ts", + "tests/rightbar-drag.perf.ts", "tests/pwsh-terminal.e2e.ts", "tests/wecom-connection.e2e.ts", "tests/tencent-meeting-connection.e2e.ts", diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 6f5dab646a..b98644469b 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: fe90de63be885e2d - zh: 8ab904422097357f + en: 756022173490c1ca + zh: 2d4d493cbb535f42 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 946c5b45bb..81102ed21b 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -126,7 +126,7 @@ The width-handle indicator follows the pointer only during a captured drag; ordi -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. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 6fa3fd2049..12bc1b8efa 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -126,7 +126,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 -主 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,因此光标回到草稿原来的位置而不是开头。 diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css index 3848b08ee1..6fba9152d4 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css @@ -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: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-conversation-viewport-width { + syntax: ''; + 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: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-chat-end-reserve-max { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-chat-end-inset-resolved { + syntax: ''; + 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. */ diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index 824fac86ad..de9fe79a24 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -159,12 +159,12 @@ function WidthHandle(props: { */ export function ConversationWidthControls({ container, phase }: ConversationWidthControlsProps) { const publishWidths = useCallback((container: HTMLDivElement): void => { - const target = container.parentElement ?? container + // The axis registers these inputs without inheritance, so they belong on the body that derives from them. const column = container.offsetWidth - target.style.setProperty('--dsh-conversation-column-width', `${column}px`) + 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(() => { @@ -181,8 +181,7 @@ 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 diff --git a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts index b662a89141..bf67551d06 100644 --- a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts +++ b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts @@ -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(([, name, block]) => [name, (block ?? '').replace(/\s+/g, ' ').trim()])) + expect(registered).toEqual({ + '--dsh-conversation-column-width': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-conversation-viewport-width': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-user-width': "syntax: '*'; inherits: false;", + '--dsh-chat-content-width-resolved': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-end-reserve-max': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-end-inset-resolved': "syntax: ''; 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', () => { diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index acb3f5dc6e..15c9a9aea0 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -950,24 +950,22 @@ 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') + expect(content.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px') // 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) }) const handle = b.view.container.querySelector('[data-width-handle="right"]') as HTMLElement @@ -991,13 +989,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') + 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 +1003,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,7 +1018,6 @@ 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) }) @@ -1042,12 +1039,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) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index 9eebb14d6c..e14977457c 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -27,8 +27,8 @@ en: 27fdd4ec3c830299 zh: 0e70ac367e4176f8 /deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: - en: 78a25420651971d2 - zh: 8bd34e5624f08208 + en: fa42d7d9a77863fc + zh: ffd22e65cca99a3b /deepseek-ai-dsh-client-ui-session-panel/further-exploration: en: decfa1b92e25ec6c zh: 255c7862690a2f23 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index b9e600aedd..04b68ec568 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -83,7 +83,7 @@ A row whose single line clips its name or leaves out its owner, state, or measur
Implementation internals — click to expand -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 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. diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index 07c9732b39..c0b292a5d9 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference"
实现内幕——点击展开 -面板是 [`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))。探针的第二项读取的是最大预留而不是内边距,因此正文移动前后它的结果相同:正文让出的位置不会反过来改变提出让位的那项判断。 diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css index 9451d4b3c1..59309b9b9c 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -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,25 @@ --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: ''; + 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 + ); +} + /* 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 +43,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 +125,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; diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts index 0f494e5d1e..889998a773 100644 --- a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -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,27 @@ 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)', + }) + // Registered as a length, the step computes to 0px or 1px on the body, so descendants see a change only when it flips. + expect(css.replace(/\s+/g, ' ')).toContain( + "@property --dsh-session-panel-reserve-room { syntax: ''; 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 +79,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 +91,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', () => { diff --git a/tsconfig.host.json b/tsconfig.host.json index a80e298cba..74698483d1 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -264,6 +264,7 @@ "apps/web/tests/window-drag-inheritance.e2e.ts", "apps/web/tests/complex-history.perf.ts", "apps/web/tests/dingtalk-connection.e2e.ts", + "apps/web/tests/rightbar-drag.perf.ts", "apps/web/tests/pwsh-terminal.e2e.ts", "apps/web/tests/wecom-connection.e2e.ts", "apps/web/tests/tencent-meeting-connection.e2e.ts",