mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 13:05:14 +03:00
feat(app): highlight quote source while writing its first comment (#59286)
Co-authored-by: Kit Langton <kit.langton@gmail.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
51e4de1da6
commit
4a85158e27
@@ -2095,6 +2095,256 @@ test("quotes plain timeline text into the composer, with or without a comment",
|
||||
await expect(chips).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("highlights a quote's source only while its first comment is written", async ({ page }) => {
|
||||
let reject = true
|
||||
await setupTimeline(page, {
|
||||
messages: [
|
||||
userMessage(),
|
||||
assistantMessage([
|
||||
textPart("prt_highlight_first", "The same **quoted** **words**."),
|
||||
textPart("prt_highlight_second", "The same **quoted** **words**."),
|
||||
]),
|
||||
],
|
||||
onPrompt: () => {
|
||||
if (reject) throw new Error("Quote send failed")
|
||||
},
|
||||
})
|
||||
const firstID = renderedPartID("prt_highlight_first")
|
||||
const secondID = renderedPartID("prt_highlight_second")
|
||||
const first = page.locator(`[data-timeline-part-id="${firstID}"] [data-slot="text-part-body"]`)
|
||||
const second = page.locator(`[data-timeline-part-id="${secondID}"] [data-slot="text-part-body"]`)
|
||||
await expect(second).toHaveText("The same quoted words.")
|
||||
|
||||
const highlights = () =>
|
||||
page.evaluate(() =>
|
||||
["timeline-quote-source"].map((name) =>
|
||||
[...(CSS.highlights.get(name) ?? [])].map((range) => ({
|
||||
part: range.startContainer.parentElement
|
||||
?.closest("[data-timeline-part-id]")
|
||||
?.getAttribute("data-timeline-part-id"),
|
||||
text: range.toString(),
|
||||
})),
|
||||
),
|
||||
)
|
||||
|
||||
const selectionCollapsed = () => page.evaluate(() => window.getSelection()?.isCollapsed ?? true)
|
||||
|
||||
const select = (target: Locator) =>
|
||||
target.evaluate((element) => {
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(element)
|
||||
window.getSelection()?.removeAllRanges()
|
||||
window.getSelection()?.addRange(range)
|
||||
})
|
||||
|
||||
const toolbar = page.getByRole("toolbar", { name: "Quote selection" })
|
||||
const chips = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]')
|
||||
const editor = page.locator('[data-component="composer-editor"]')
|
||||
const comment = page.locator('[data-component="composer-quote-comment"] textarea')
|
||||
const firstRange = { part: firstID, text: "The same quoted words." }
|
||||
const scroll = page.locator('[data-slot="session-timeline-scroll"] > [data-scrollable]')
|
||||
|
||||
await scroll.focus()
|
||||
await select(first)
|
||||
await toolbar.getByRole("button", { name: "Quote", exact: true }).click({ modifiers: ["Alt"] })
|
||||
await expect(comment).toBeFocused()
|
||||
await comment.fill("Keep this passage visible while I write.")
|
||||
await expect.poll(highlights).toEqual([[firstRange]])
|
||||
|
||||
for (const palette of [
|
||||
{ colorScheme: "dark" as const, background: "color(srgb 0.635294 0.737255 1 / 0.25)" },
|
||||
{ colorScheme: "light" as const, background: "color(srgb 0.133333 0.219608 0.560784 / 0.1)" },
|
||||
]) {
|
||||
await page.emulateMedia({ colorScheme: palette.colorScheme })
|
||||
await expect
|
||||
.poll(() =>
|
||||
first.evaluate((element) =>
|
||||
[
|
||||
"::selection",
|
||||
"::highlight(timeline-quote-source)",
|
||||
].map((pseudo) => {
|
||||
const style = getComputedStyle(element, pseudo)
|
||||
|
||||
return {
|
||||
background: style.backgroundColor,
|
||||
preservesText: style.color === getComputedStyle(element).color,
|
||||
}
|
||||
}),
|
||||
),
|
||||
)
|
||||
.toEqual([
|
||||
{ background: palette.background, preservesText: true },
|
||||
{ background: palette.background, preservesText: true },
|
||||
])
|
||||
}
|
||||
|
||||
await comment.press("Enter")
|
||||
await expect(comment).toHaveCount(0)
|
||||
await expect.poll(highlights).toEqual([[]])
|
||||
|
||||
await select(second)
|
||||
await toolbar.getByRole("button", { name: "Quote", exact: true }).click()
|
||||
await expect(chips).toHaveCount(2)
|
||||
await expect(editor).toBeFocused()
|
||||
await expect.poll(selectionCollapsed).toBe(true)
|
||||
await expect.poll(highlights).toEqual([[]])
|
||||
|
||||
const before = await scroll.evaluate((element) => element.scrollTop)
|
||||
await chips.nth(0).hover()
|
||||
await expect(editor).toBeFocused()
|
||||
expect(await scroll.evaluate((element) => element.scrollTop)).toBe(before)
|
||||
await expect.poll(highlights).toEqual([[]])
|
||||
|
||||
// Editing an existing quote's comment shows no source highlight.
|
||||
await chips.nth(0).click()
|
||||
await expect(comment).toBeFocused()
|
||||
await expect(comment).toHaveValue("Keep this passage visible while I write.")
|
||||
await expect.poll(highlights).toEqual([[]])
|
||||
await comment.press("Escape")
|
||||
await expect(comment).toHaveCount(0)
|
||||
|
||||
await page
|
||||
.locator('[data-component="composer-attachments"]')
|
||||
.getByRole("button", { name: "Remove attachment" })
|
||||
.nth(0)
|
||||
.click()
|
||||
await expect(chips).toHaveCount(1)
|
||||
|
||||
const rejected = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" && response.url().includes("/prompt") && response.status() === 500,
|
||||
)
|
||||
|
||||
await editor.press("Enter")
|
||||
await rejected
|
||||
await expect(chips).toHaveCount(1)
|
||||
await expect(editor).toBeFocused()
|
||||
reject = false
|
||||
await editor.press("Enter")
|
||||
await expect(chips).toHaveCount(0)
|
||||
await expect.poll(highlights).toEqual([[]])
|
||||
await expect(page.locator('[data-component="timeline-quote-background"]')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("keeps the native selection height after quoting wrapped and formatted text", async ({ page }) => {
|
||||
await setupTimeline(page, {
|
||||
messages: [
|
||||
userMessage(),
|
||||
assistantMessage([
|
||||
textPart(
|
||||
"prt_quote_height",
|
||||
"A selected passage with **bold text** and `inline code` that continues onto another line. ".repeat(4),
|
||||
),
|
||||
]),
|
||||
],
|
||||
})
|
||||
|
||||
const source = page.locator(
|
||||
`[data-timeline-part-id="${renderedPartID("prt_quote_height")}"] [data-slot="text-part-body"]`,
|
||||
)
|
||||
|
||||
await expect(source).toContainText("A selected passage with bold text and inline code")
|
||||
await source.evaluate((element) => {
|
||||
const paragraph = element.querySelector("p")!
|
||||
const range = document.createRange()
|
||||
range.setStart(paragraph.firstChild!, 2)
|
||||
range.setEnd(paragraph, paragraph.childNodes.length - 2)
|
||||
window.getSelection()?.removeAllRanges()
|
||||
window.getSelection()?.addRange(range)
|
||||
})
|
||||
await page
|
||||
.getByRole("toolbar", { name: "Quote selection" })
|
||||
.getByRole("button", { name: "Quote", exact: true })
|
||||
.click({ modifiers: ["Alt"] })
|
||||
await expect(page.locator('[data-component="composer-quote-comment"] textarea')).toBeFocused()
|
||||
|
||||
await page.setViewportSize({ width: 700, height: 900 })
|
||||
const height = await source.locator("p").evaluate((element) => parseFloat(getComputedStyle(element).lineHeight))
|
||||
await expect
|
||||
.poll(() =>
|
||||
source.locator('[data-component="timeline-quote-background"] > span').evaluateAll(
|
||||
(lines, height) =>
|
||||
lines.length > 0 && lines.every((line) => Math.abs(line.getBoundingClientRect().height - height) < 0.1),
|
||||
height,
|
||||
),
|
||||
)
|
||||
.toBe(true)
|
||||
})
|
||||
|
||||
test("reveals a pending quote's source and restores its retained draft after its row remounts", async ({ page }) => {
|
||||
await setupTimeline(page, {
|
||||
seedHistory: true,
|
||||
messages: [
|
||||
userMessage(),
|
||||
assistantMessage([textPart("prt_quote_remount", "Keep this exact source highlighted.")]),
|
||||
userMessage([userText("Continue with the next step.")], { id: "msg_quote_following_user" }),
|
||||
assistantMessage([textPart("prt_quote_following_answer", "The next step is ready.")], {
|
||||
id: "msg_quote_following_answer",
|
||||
parentID: "msg_quote_following_user",
|
||||
}),
|
||||
],
|
||||
})
|
||||
const partID = renderedPartID("prt_quote_remount")
|
||||
const source = page.locator(`[data-timeline-part-id="${partID}"] [data-slot="text-part-body"]`)
|
||||
await expect(source).toHaveText("Keep this exact source highlighted.")
|
||||
await source.evaluate((element) => {
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(element)
|
||||
window.getSelection()?.removeAllRanges()
|
||||
window.getSelection()?.addRange(range)
|
||||
})
|
||||
await page
|
||||
.getByRole("toolbar", { name: "Quote selection" })
|
||||
.getByRole("button", { name: "Quote", exact: true })
|
||||
.click({ modifiers: ["Alt"] })
|
||||
const chip = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]')
|
||||
const comment = page.locator('[data-component="composer-quote-comment"] textarea')
|
||||
await expect(comment).toBeFocused()
|
||||
await expect(chip).toContainText("Keep this exact source highlighted.")
|
||||
|
||||
const highlighted = () =>
|
||||
page.evaluate(() =>
|
||||
[...(CSS.highlights.get("timeline-quote-source") ?? [])].flatMap((range) =>
|
||||
range.startContainer.isConnected ? [range.toString()] : [],
|
||||
),
|
||||
)
|
||||
|
||||
await expect.poll(highlighted).toEqual(["Keep this exact source highlighted."])
|
||||
|
||||
const scroll = page.locator('[data-slot="session-timeline-scroll"] > [data-scrollable]')
|
||||
await scroll.hover({ position: { x: 20, y: 100 } })
|
||||
await page.mouse.wheel(0, -10000)
|
||||
await expect(source).toHaveCount(0)
|
||||
const top = await scroll.evaluate((element) => element.scrollTop)
|
||||
await chip.hover()
|
||||
expect(await scroll.evaluate((element) => element.scrollTop)).toBe(top)
|
||||
|
||||
// Clicking the pending card closes its open comment, and reveals the source before it does.
|
||||
await chip.click()
|
||||
await expect(comment).toHaveCount(0)
|
||||
await expect(source).toBeInViewport()
|
||||
await expect.poll(highlighted).toEqual([])
|
||||
|
||||
// An existing quote's card edits its comment without moving the timeline to its source.
|
||||
await scroll.hover({ position: { x: 20, y: 100 } })
|
||||
await page.mouse.wheel(0, -10000)
|
||||
await expect(source).toHaveCount(0)
|
||||
await chip.click()
|
||||
await expect(comment).toBeFocused()
|
||||
await expect(source).toHaveCount(0)
|
||||
await expect.poll(highlighted).toEqual([])
|
||||
await comment.press("Escape")
|
||||
|
||||
const href = new URL(page.url()).pathname
|
||||
await page.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await expect(chip).toHaveCount(0)
|
||||
await expect.poll(highlighted).toEqual([])
|
||||
await page.locator(`[data-titlebar-tab-link][href="${href}"]`).click()
|
||||
await expect(chip).toContainText("Keep this exact source highlighted.")
|
||||
await expect.poll(highlighted).toEqual([])
|
||||
await expect(comment).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("quotes table rows and diff lines selected across a diff viewer", async ({ page }) => {
|
||||
const prompts: string[] = []
|
||||
await setupTimeline(page, {
|
||||
@@ -2137,6 +2387,9 @@ test("quotes table rows and diff lines selected across a diff viewer", async ({
|
||||
const removed = page.locator('[data-line-type="change-deletion"][data-line]')
|
||||
const added = page.locator('[data-line-type="change-addition"][data-line]')
|
||||
await expect(added).toHaveText("export const value = 'after'")
|
||||
await expect
|
||||
.poll(() => added.evaluate((element) => getComputedStyle(element, "::selection").backgroundColor))
|
||||
.toBe("color(srgb 0.133333 0.219608 0.560784 / 0.1)")
|
||||
|
||||
const drag = async (from: Locator, to: Locator) => {
|
||||
const start = await from.boundingBox()
|
||||
@@ -2152,10 +2405,27 @@ test("quotes table rows and diff lines selected across a diff viewer", async ({
|
||||
const toolbar = page.getByRole("toolbar", { name: "Quote selection" })
|
||||
const chips = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]')
|
||||
|
||||
// A drag from the table into the diff viewer quotes both, table cells by tabs and diff lines with their markers.
|
||||
await drag(page.locator("th").getByText("File", { exact: true }), added)
|
||||
await toolbar.getByRole("button", { name: "Quote", exact: true }).click()
|
||||
// Headers are unselectable chrome; body cells quote with tabs, followed by the diff lines and their markers.
|
||||
await drag(page.locator("td").getByText("a.ts", { exact: true }), added)
|
||||
await toolbar.getByRole("button", { name: "Quote", exact: true }).click({ modifiers: ["Alt"] })
|
||||
await expect(chips).toHaveCount(1)
|
||||
await expect(page.locator('[data-component="composer-quote-comment"] textarea')).toBeFocused()
|
||||
|
||||
const diffHighlights = (name: string) =>
|
||||
page.evaluate(
|
||||
(name) =>
|
||||
[...(CSS.highlights.get(name) ?? [])].flatMap((range) =>
|
||||
range.startContainer.getRootNode() instanceof ShadowRoot ? [range.toString()] : [],
|
||||
),
|
||||
name,
|
||||
)
|
||||
|
||||
await expect
|
||||
.poll(() => diffHighlights("timeline-quote-source"))
|
||||
.toEqual(["export const value = 'before'", "export const value = 'after'"])
|
||||
// Only the first comment keeps the source highlighted; saving it clears the highlight.
|
||||
await page.locator('[data-component="composer-quote-comment"] textarea').press("Enter")
|
||||
await expect.poll(() => diffHighlights("timeline-quote-source")).toEqual([])
|
||||
|
||||
// The quote stops where a selection inside the diff viewer ends.
|
||||
await drag(page.locator("td").getByText("a.ts", { exact: true }), removed)
|
||||
@@ -2168,7 +2438,6 @@ test("quotes table rows and diff lines selected across a diff viewer", async ({
|
||||
.toEqual([
|
||||
[
|
||||
"The user quoted the following from earlier in the conversation:",
|
||||
"> File\tChange",
|
||||
"> a.ts\trename",
|
||||
"> ",
|
||||
"> -export const value = 'before'",
|
||||
|
||||
@@ -273,6 +273,7 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
onFileRemove={(file) => props.controller.removeContext(file.key)}
|
||||
editingQuote={props.controller.editingQuote()}
|
||||
onEditQuote={props.controller.editQuote}
|
||||
quoteSource={props.controller.quoteSource}
|
||||
onQuoteComment={(quote, comment) => props.controller.commentQuote(quote.key, comment)}
|
||||
searchPaths={props.controller.searchPaths}
|
||||
/>
|
||||
@@ -689,6 +690,7 @@ function ComposerAttachments(props: {
|
||||
onFileRemove?: (file: Extract<ComposerComment, { type: "file" }>) => void
|
||||
editingQuote?: string
|
||||
onEditQuote?: (key?: string) => void
|
||||
quoteSource?: ComposerEditorModel["quoteSource"]
|
||||
onQuoteComment?: (quote: Extract<ComposerComment, { type: "quote" }>, comment: string) => void
|
||||
searchPaths?: (query: string) => Promise<string[]>
|
||||
}) {
|
||||
@@ -747,11 +749,11 @@ function ComposerAttachments(props: {
|
||||
title={quoteTitle(comment)}
|
||||
tooltip={quoteHint(comment)}
|
||||
active={commentActive(comment)}
|
||||
onClick={() =>
|
||||
comment.type === "quote"
|
||||
? props.onEditQuote?.(props.editingQuote === comment.key ? undefined : comment.key)
|
||||
: props.onCommentClick?.(comment)
|
||||
}
|
||||
onClick={() => {
|
||||
if (comment.type !== "quote") return props.onCommentClick?.(comment)
|
||||
props.quoteSource?.reveal(comment.key)
|
||||
props.onEditQuote?.(props.editingQuote === comment.key ? undefined : comment.key)
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
<button
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { clonePrompt, isAttachment, promptLength } from "../prompt-parts"
|
||||
import type { ComposerQueue } from "../adapter"
|
||||
import { isCommentItem } from "../state"
|
||||
import type { createComposerQuoteSource } from "../quote-source"
|
||||
|
||||
export type ComposerSelectControl = {
|
||||
options: Accessor<ComposerOption[]>
|
||||
@@ -79,6 +80,7 @@ export function createComposerEditor(input: {
|
||||
onContextRemove?: (item: ComposerComment) => void
|
||||
onQuoteComment?: (item: Extract<ComposerComment, { type: "quote" }>, comment: string) => void
|
||||
quoteComment?: { key: Accessor<string | undefined>; set: (key?: string) => void }
|
||||
quoteSource?: Pick<ReturnType<typeof createComposerQuoteSource>, "reveal">
|
||||
onEditor?: (element: HTMLElement) => void
|
||||
onSuggestionSelect?: (item: ComposerSuggestion) => (() => void) | void
|
||||
view: ComposerEditorView
|
||||
@@ -588,6 +590,7 @@ export function createComposerEditor(input: {
|
||||
input.openContext?.(id)
|
||||
},
|
||||
editingQuote: () => quoteComment.key(),
|
||||
quoteSource: input.quoteSource,
|
||||
editQuote: (key?: string) => quoteComment.set(key),
|
||||
commentQuote(id: string, comment: string) {
|
||||
const item = draft.state.context.items.find((entry) => entry.key === id)
|
||||
|
||||
@@ -4,6 +4,7 @@ import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { createResizeObserver } from "@solid-primitives/resize-observer"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { LineCommentEditor } from "@opencode/ui/line-comment"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
|
||||
const GAP = 8
|
||||
|
||||
@@ -18,6 +19,8 @@ export function QuoteCommentEditor(props: {
|
||||
onSubmit: (comment: string) => void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const language = useLanguage()
|
||||
|
||||
const [state, setState] = createStore({
|
||||
draft: props.comment,
|
||||
rect: bounds(props.anchor),
|
||||
@@ -70,6 +73,7 @@ export function QuoteCommentEditor(props: {
|
||||
onInput={(value) => setState("draft", value)}
|
||||
onCancel={props.onClose}
|
||||
onSubmit={props.onSubmit}
|
||||
placeholder={language.t("session.quote.commentPlaceholder")}
|
||||
allowEmpty
|
||||
mention={{ items: props.mention }}
|
||||
selection={
|
||||
|
||||
@@ -62,6 +62,13 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
const platform = usePlatform()
|
||||
const serverSDK = useServerSDK()
|
||||
const prompt = adapter.state
|
||||
// Editor actions write the captured store directly, rather than going through the context methods.
|
||||
createEffect(
|
||||
on(
|
||||
() => prompt.context.items(),
|
||||
(items) => prompt.quoteSource.retain(items.map((item) => item.key)),
|
||||
),
|
||||
)
|
||||
let editor: HTMLDivElement | undefined
|
||||
// A path attachment's image is read through the server, which can see both local and uploaded paths.
|
||||
const pathImages = new Map<string, Promise<string | undefined>>()
|
||||
@@ -416,6 +423,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
})),
|
||||
onQuoteComment: (item, comment) => prompt.context.updateComment(item.commentID, { comment }),
|
||||
quoteComment: prompt.quoteComment,
|
||||
quoteSource: prompt.quoteSource,
|
||||
onContextRemove(item) {
|
||||
if (item.type === "file" && item.commentID) comments.remove(item.path, item.commentID)
|
||||
},
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createStore } from "solid-js/store"
|
||||
|
||||
/** Client-only source coordinates; never included in persisted drafts or requests. */
|
||||
export type QuoteSource = {
|
||||
partID: string
|
||||
revealID: string
|
||||
body?: string
|
||||
shadow?: { host: number; line: string }
|
||||
start: number
|
||||
end: number
|
||||
text: string
|
||||
}[]
|
||||
|
||||
export function createComposerQuoteSource() {
|
||||
const [state, setState] = createStore<{
|
||||
sources: Record<string, QuoteSource | undefined>
|
||||
/** The quote being commented for the first time, the only one whose source stays highlighted. */
|
||||
pending?: string
|
||||
reveal?: { key: string; sequence: number }
|
||||
}>({ sources: {} })
|
||||
|
||||
return {
|
||||
state,
|
||||
add: (key: string, source: QuoteSource) => setState("sources", key, source),
|
||||
pend: (key: string) => setState("pending", key),
|
||||
settle: () => setState("pending", undefined),
|
||||
retain: (keys: string[]) => {
|
||||
Object.keys(state.sources).forEach((key) => {
|
||||
if (!keys.includes(key)) setState("sources", key, undefined)
|
||||
})
|
||||
|
||||
if (state.pending && !keys.includes(state.pending)) setState("pending", undefined)
|
||||
},
|
||||
reveal: (key: string) => {
|
||||
if (state.pending === key) setState("reveal", { key, sequence: (state.reveal?.sequence ?? 0) + 1 })
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import { ServerScope } from "@/runtime/server/scope"
|
||||
import type { Platform } from "@/runtime/platform/platform"
|
||||
import { clonePrompt } from "./prompt-parts"
|
||||
import { createComposerQuoteSource } from "./quote-source"
|
||||
import {
|
||||
ComposerStore,
|
||||
DEFAULT_PROMPT,
|
||||
@@ -116,6 +117,7 @@ export interface ComposerStateValue {
|
||||
readonly key: Accessor<string | undefined>
|
||||
readonly set: (key?: string) => void
|
||||
}
|
||||
readonly quoteSource: ReturnType<typeof createComposerQuoteSource>
|
||||
readonly set: (prompt: Prompt, cursorPosition?: number) => void
|
||||
readonly reset: () => void
|
||||
readonly capture: () => ComposerStateValue
|
||||
@@ -128,6 +130,9 @@ function createComposerStateValue(
|
||||
const actions = createComposerActions(setStore)
|
||||
// The quote whose comment editor is open, by key; a request made before the composer shows waits for it.
|
||||
const [quoteComment, setQuoteComment] = createSignal<string>()
|
||||
const quoteSource = createComposerQuoteSource()
|
||||
|
||||
const retainQuoteSources = () => quoteSource.retain(store.context.items.map((item) => item.key))
|
||||
|
||||
const clearRetry = () => {
|
||||
if (untrack(() => store.retry) !== undefined) setStore("retry", undefined)
|
||||
@@ -166,11 +171,13 @@ function createComposerStateValue(
|
||||
},
|
||||
remove(key: string) {
|
||||
setStore("context", "items", (items) => items.filter((x) => x.key !== key))
|
||||
retainQuoteSources()
|
||||
clearRetry()
|
||||
},
|
||||
/** Removes the file comment, note, or quote with this commentID. */
|
||||
removeComment(commentID: string) {
|
||||
setStore("context", "items", (items) => items.filter((item) => item.commentID !== commentID))
|
||||
retainQuoteSources()
|
||||
clearRetry()
|
||||
},
|
||||
/** Edits the file comment, note, or quote with this commentID; only file comments carry a preview. */
|
||||
@@ -199,6 +206,7 @@ function createComposerStateValue(
|
||||
key,
|
||||
})),
|
||||
)
|
||||
retainQuoteSources()
|
||||
clearRetry()
|
||||
},
|
||||
replaceComments(items: ContextItem[]) {
|
||||
@@ -206,10 +214,19 @@ function createComposerStateValue(
|
||||
...current.filter((item) => !isCommentItem(item)),
|
||||
...items.map((item) => ({ ...item, key: contextItemKey(item) })),
|
||||
])
|
||||
retainQuoteSources()
|
||||
clearRetry()
|
||||
},
|
||||
},
|
||||
quoteComment: { key: quoteComment, set: (key?: string) => setQuoteComment(key) },
|
||||
quoteComment: {
|
||||
key: quoteComment,
|
||||
set: (key?: string) => {
|
||||
setQuoteComment(key)
|
||||
|
||||
if (key !== quoteSource.state.pending) quoteSource.settle()
|
||||
},
|
||||
},
|
||||
quoteSource,
|
||||
set: (prompt: Prompt, cursorPosition?: number) => actions.set(prompt, cursorPosition),
|
||||
reset: () => actions.reset(),
|
||||
capture: () => value,
|
||||
|
||||
@@ -9,6 +9,13 @@ export function createComposerSubmission(input: {
|
||||
context: (ContextItem & { key: string })[]
|
||||
}) {
|
||||
const initial = input.target
|
||||
|
||||
const sources = input.context.flatMap((item) => {
|
||||
const source = initial.quoteSource.state.sources[item.key]
|
||||
|
||||
return source ? [{ key: item.key, source }] : []
|
||||
})
|
||||
|
||||
let target = input.target
|
||||
let cleared: Prompt | undefined
|
||||
let following: Prompt | undefined
|
||||
@@ -17,6 +24,7 @@ export function createComposerSubmission(input: {
|
||||
return {
|
||||
prompt: input.prompt,
|
||||
context: input.context,
|
||||
sources,
|
||||
target: () => target,
|
||||
clear() {
|
||||
if (initial !== target) {
|
||||
@@ -32,6 +40,7 @@ export function createComposerSubmission(input: {
|
||||
},
|
||||
retarget(next: ComposerStateTarget, options?: { preserveDraft?: boolean }) {
|
||||
input.context.forEach((item) => next.context.add(item))
|
||||
sources.forEach((item) => next.quoteSource.add(item.key, item.source))
|
||||
target = next
|
||||
preserveDraft = options?.preserveDraft ?? false
|
||||
},
|
||||
|
||||
@@ -452,6 +452,7 @@ function restoreSubmission(
|
||||
}
|
||||
}),
|
||||
)
|
||||
submission.sources.forEach((item) => restored.target.quoteSource.add(item.key, item.source))
|
||||
restored.context.forEach((item) => {
|
||||
if (item.type === "file" && !item.comment?.trim())
|
||||
restored.target.context.add({
|
||||
|
||||
@@ -231,7 +231,7 @@ function NewSessionTips(props: { selection: ComposerModel["model"]["selection"];
|
||||
<Tooltip
|
||||
class="hover-reveal absolute left-full top-0 flex h-6 w-7 items-center justify-end delay-0 duration-0 group-hover/new-session-tip:delay-[250ms] group-hover/new-session-tip:duration-150 group-hover/new-session-tip:opacity-100 focus-within:delay-0 focus-within:duration-0 focus-within:opacity-100"
|
||||
placement="top"
|
||||
openDelay={1000}
|
||||
openDelay={800}
|
||||
value={language.t("common.dismiss")}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -660,6 +660,7 @@ export const dict = {
|
||||
"session.quote.actions": "Quote selection",
|
||||
"session.quote.add": "Quote",
|
||||
"session.quote.addWithComment": "Quote and comment",
|
||||
"session.quote.commentPlaceholder": "Add a comment about this quote",
|
||||
"session.quote.tooLong": "Selection too long",
|
||||
"session.header.open.finder": "Finder",
|
||||
"session.header.open.fileExplorer": "File Explorer",
|
||||
|
||||
@@ -21,6 +21,7 @@ import { useLocal } from "@/providers/models/selection"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { uuid } from "@/runtime/persistence/uuid"
|
||||
import { contextItemKey } from "@/composer/schema"
|
||||
import type { QuoteSource } from "@/composer/quote-source"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { requireServerKey, sessionHref } from "@/shell/routes/session"
|
||||
import { useComposerCommands } from "@/composer/commands"
|
||||
@@ -333,13 +334,21 @@ export function createActiveSessionRegion(input: {
|
||||
input: () => active()?.drop.input(),
|
||||
},
|
||||
quote: {
|
||||
source: () => prompt.capture().quoteSource,
|
||||
// A child session has no composer to quote into, and a shell command takes no quotes.
|
||||
available: () => !input.session.data.isChild() && prompt.capture().mode.current() !== "shell",
|
||||
add: (text: string, comment: boolean) => {
|
||||
add: (text: string, comment: boolean, source: QuoteSource) => {
|
||||
const item = { type: "quote" as const, text, commentID: uuid() }
|
||||
prompt.context.add(item)
|
||||
|
||||
if (comment) return prompt.capture().quoteComment.set(contextItemKey(item))
|
||||
if (source.length) prompt.capture().quoteSource.add(contextItemKey(item), source)
|
||||
|
||||
if (comment) {
|
||||
prompt.capture().quoteSource.pend(contextItemKey(item))
|
||||
|
||||
return prompt.capture().quoteComment.set(contextItemKey(item))
|
||||
}
|
||||
|
||||
focusPrompt()
|
||||
},
|
||||
focus: focusPrompt,
|
||||
|
||||
@@ -40,6 +40,7 @@ import { createSessionTimelineInteraction } from "./timeline/interaction"
|
||||
import { createTimelineSearchController } from "./timeline/search-controller"
|
||||
import { TimelineSearchBar } from "./timeline/search-bar"
|
||||
import { createTimelineQuote, TimelineQuote } from "./timeline/quote"
|
||||
import { createTimelineQuoteHighlight } from "./timeline/quote-highlight"
|
||||
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
|
||||
import { SessionIdentityHeader, SessionLocation } from "./session-identity-header"
|
||||
import { SessionHeaderDrag, windowDragEnabled } from "./header/drag-area"
|
||||
@@ -248,6 +249,17 @@ function SessionScreenContent(props: {
|
||||
add: composer.quote.add,
|
||||
})
|
||||
|
||||
createTimelineQuoteHighlight({
|
||||
root: timeline.scroller,
|
||||
visible: timeline.visible,
|
||||
source: composer.quote.source,
|
||||
enabled: () => conversationVisible() && composer.quote.available(),
|
||||
reveal: (id, partID) => {
|
||||
if (!timeline.actions.revealPart(partID)) timeline.actions.revealMessage(id, partID)
|
||||
},
|
||||
unpin: timeline.view.unpin,
|
||||
})
|
||||
|
||||
const sessionErrorFallback = (cause: unknown, reset: () => void) => {
|
||||
createEffect(on(session.identity.sessionKey, reset, { defer: true }))
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
type Rect = { left: number; top: number; right: number; bottom: number }
|
||||
|
||||
/** Native selection fills line boxes; custom highlights only fill the smaller font boxes. */
|
||||
export function createQuoteBackground() {
|
||||
const hosts = new Map<HTMLElement, { layer: HTMLSpanElement; relative: boolean }>()
|
||||
|
||||
const remove = (parent: HTMLElement) => {
|
||||
const host = hosts.get(parent)
|
||||
|
||||
if (!host) return
|
||||
host.layer.remove()
|
||||
parent.classList.remove("timeline-quote-highlight-host")
|
||||
|
||||
if (host.relative) parent.classList.remove("timeline-quote-highlight-relative")
|
||||
hosts.delete(parent)
|
||||
}
|
||||
|
||||
return {
|
||||
update(ranges: Range[]) {
|
||||
const styles = new Map<Element, CSSStyleDeclaration>()
|
||||
const boxes = new Map<Element, DOMRect>()
|
||||
const lines = new Map<HTMLElement, Rect[]>()
|
||||
|
||||
const style = (element: Element) => {
|
||||
const value = styles.get(element) ?? getComputedStyle(element)
|
||||
styles.set(element, value)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
ranges.forEach((range) => {
|
||||
const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT)
|
||||
|
||||
const visit = (node: Node) => {
|
||||
const parent = node.parentElement
|
||||
|
||||
if (!(parent instanceof HTMLElement) || !range.intersectsNode(node)) return
|
||||
const piece = document.createRange()
|
||||
piece.setStart(node, node === range.startContainer ? range.startOffset : 0)
|
||||
piece.setEnd(node, node === range.endContainer ? range.endOffset : node.textContent!.length)
|
||||
const block = lineBlock(parent, style)
|
||||
const height = parseFloat(style(block).lineHeight)
|
||||
const box = boxes.get(block) ?? block.getBoundingClientRect()
|
||||
boxes.set(block, box)
|
||||
const top = box.top + parseFloat(style(block).borderTopWidth) + parseFloat(style(block).paddingTop)
|
||||
|
||||
const rects = [...piece.getClientRects()].flatMap((rect) => {
|
||||
if (!rect.width || !rect.height) return []
|
||||
|
||||
const y =
|
||||
Number.isFinite(height) && height >= rect.height
|
||||
? top + Math.floor((rect.top + rect.height / 2 - top) / height) * height
|
||||
: rect.top
|
||||
|
||||
return [{ left: rect.left, right: rect.right, top: y, bottom: y + Math.max(height || 0, rect.height) }]
|
||||
})
|
||||
|
||||
if (!rects.length) return
|
||||
const current = lines.get(parent) ?? []
|
||||
current.push(...rects)
|
||||
lines.set(parent, current)
|
||||
}
|
||||
|
||||
if (range.commonAncestorContainer instanceof Text) return visit(range.commonAncestorContainer)
|
||||
|
||||
while (walker.nextNode()) visit(walker.currentNode)
|
||||
})
|
||||
|
||||
hosts.forEach((_host, parent) => {
|
||||
if (!lines.has(parent)) remove(parent)
|
||||
})
|
||||
lines.forEach((_rects, parent) => {
|
||||
const existing = hosts.get(parent)
|
||||
|
||||
// A renderer can replace a retained element's textContent, removing its background child.
|
||||
if (existing) {
|
||||
if (existing.layer.parentElement !== parent) parent.append(existing.layer)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const layer = document.createElement("span")
|
||||
layer.dataset.component = "timeline-quote-background"
|
||||
layer.setAttribute("aria-hidden", "true")
|
||||
const relative = style(parent).position === "static"
|
||||
parent.classList.add("timeline-quote-highlight-host")
|
||||
|
||||
if (relative) parent.classList.add("timeline-quote-highlight-relative")
|
||||
parent.append(layer)
|
||||
hosts.set(parent, { layer, relative })
|
||||
})
|
||||
|
||||
// Inline containing blocks can start at their first fragment, not their bounding box's left edge.
|
||||
const origins = new Map([...hosts].map(([parent, host]) => [parent, host.layer.getBoundingClientRect()]))
|
||||
lines.forEach((rects, parent) => {
|
||||
const host = hosts.get(parent)!
|
||||
const origin = origins.get(parent)!
|
||||
|
||||
const merged = rects
|
||||
.sort((a, b) => a.top - b.top || a.left - b.left)
|
||||
.reduce<Rect[]>((result, rect) => {
|
||||
const previous = result.at(-1)
|
||||
|
||||
if (
|
||||
previous &&
|
||||
Math.abs(previous.top - rect.top) < 0.5 &&
|
||||
Math.abs(previous.bottom - rect.bottom) < 0.5 &&
|
||||
rect.left <= previous.right + 0.5
|
||||
) {
|
||||
previous.right = Math.max(previous.right, rect.right)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
result.push({ ...rect })
|
||||
|
||||
return result
|
||||
}, [])
|
||||
|
||||
host.layer.replaceChildren(
|
||||
...merged.map((rect) => {
|
||||
const element = document.createElement("span")
|
||||
element.style.left = `${rect.left - origin.left}px`
|
||||
element.style.top = `${rect.top - origin.top}px`
|
||||
element.style.width = `${rect.right - rect.left}px`
|
||||
element.style.height = `${rect.bottom - rect.top}px`
|
||||
|
||||
return element
|
||||
}),
|
||||
)
|
||||
})
|
||||
},
|
||||
clear: () => hosts.forEach((_host, parent) => remove(parent)),
|
||||
}
|
||||
}
|
||||
|
||||
function lineBlock(element: HTMLElement, style: (element: Element) => CSSStyleDeclaration): HTMLElement {
|
||||
if (!/^(inline|contents)$/.test(style(element).display) || !element.parentElement) return element
|
||||
|
||||
return lineBlock(element.parentElement, style)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import { createEffect, on, onCleanup } from "solid-js"
|
||||
import type { QuoteSource, createComposerQuoteSource } from "@/composer/quote-source"
|
||||
import { createQuoteBackground } from "./quote-background"
|
||||
|
||||
const BASE = "timeline-quote-source"
|
||||
|
||||
/** Capture exact offsets in stable parts, rather than finding the first occurrence of the quoted text. */
|
||||
export function captureQuoteSource(ranges: Range[]): QuoteSource {
|
||||
const indexes = new Map<Element, Map<Text, number>>()
|
||||
|
||||
return ranges.reduce<QuoteSource>((sources, range) => {
|
||||
const node = range.startContainer
|
||||
const root = node.getRootNode()
|
||||
const parent = node.parentElement
|
||||
const part = (root instanceof ShadowRoot ? root.host : parent)?.closest("[data-timeline-part-id]")
|
||||
const partID = part?.getAttribute("data-timeline-part-id")
|
||||
const revealID = part?.closest("[data-message-id]")?.getAttribute("data-message-id")
|
||||
|
||||
if (!part || !partID || !revealID || !parent || !(node instanceof Text)) return sources
|
||||
const body = parent.closest('[data-slot="text-part-body"], [data-slot="user-message-text"]')
|
||||
const line = root instanceof ShadowRoot ? parent.closest("[data-line][data-line-type]") : undefined
|
||||
const container = root instanceof ShadowRoot ? line : (body ?? part)
|
||||
|
||||
if (!container) return sources
|
||||
const index = indexes.get(container) ?? new Map(textNodes(container).map((item) => [item.node, item.start]))
|
||||
indexes.set(container, index)
|
||||
const offset = index.get(node)
|
||||
|
||||
if (offset === undefined) return sources
|
||||
|
||||
const source = {
|
||||
partID,
|
||||
revealID,
|
||||
body: body ? `[data-slot="${body.getAttribute("data-slot")}"]` : undefined,
|
||||
shadow:
|
||||
root instanceof ShadowRoot && line
|
||||
? {
|
||||
host: [...part.querySelectorAll("diffs-container")].indexOf(root.host),
|
||||
line: `[data-line="${CSS.escape(line.getAttribute("data-line")!)}"][data-line-type="${CSS.escape(line.getAttribute("data-line-type")!)}"]`,
|
||||
}
|
||||
: undefined,
|
||||
start: offset + range.startOffset,
|
||||
end: offset + range.endOffset,
|
||||
text: range.toString(),
|
||||
}
|
||||
|
||||
const previous = sources.at(-1)
|
||||
|
||||
// Token spans and inline formatting are contiguous text within the same source container.
|
||||
if (
|
||||
previous &&
|
||||
previous.partID === source.partID &&
|
||||
previous.body === source.body &&
|
||||
previous.shadow?.host === source.shadow?.host &&
|
||||
previous.shadow?.line === source.shadow?.line &&
|
||||
previous.end === source.start
|
||||
) {
|
||||
previous.end = source.end
|
||||
previous.text += source.text
|
||||
|
||||
return sources
|
||||
}
|
||||
|
||||
sources.push(source)
|
||||
|
||||
return sources
|
||||
}, [])
|
||||
}
|
||||
|
||||
export function createTimelineQuoteHighlight(input: {
|
||||
root: () => HTMLElement | undefined
|
||||
visible: () => HTMLElement | undefined
|
||||
source: () => ReturnType<typeof createComposerQuoteSource>
|
||||
enabled: () => boolean
|
||||
reveal: (id: string, partID: string) => void
|
||||
unpin: () => void
|
||||
}) {
|
||||
let pending: { key: string; source: ReturnType<typeof createComposerQuoteSource> } | undefined
|
||||
|
||||
const reveal = () => {
|
||||
const root = input.root()
|
||||
const source = input.source()
|
||||
const first = pending && pending.source === source && source.state.sources[pending.key]?.[0]
|
||||
|
||||
if (!first || !root || !input.enabled()) return
|
||||
const range = resolveQuoteRange(root, first, new Map())
|
||||
const rect = range && [...range.getClientRects()].find((rect) => rect.width > 0 && rect.height > 0)
|
||||
|
||||
if (!rect) return
|
||||
pending = undefined
|
||||
const viewport = input.visible()?.getBoundingClientRect() ?? root.getBoundingClientRect()
|
||||
const sticky = root.querySelector<HTMLElement>("[data-session-title]")
|
||||
const top = viewport.top + (sticky?.offsetHeight ?? 0)
|
||||
|
||||
if (rect.top >= top && rect.bottom <= viewport.bottom) return
|
||||
input.unpin()
|
||||
root.scrollBy({ top: rect.top - top - (viewport.bottom - top) / 2, behavior: "instant" })
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
const root = input.root()
|
||||
const source = input.source()
|
||||
const pieces = source.state.pending ? source.state.sources[source.state.pending] : undefined
|
||||
|
||||
if (!root || !input.enabled() || !pieces?.length || typeof Highlight === "undefined" || !CSS.highlights) return
|
||||
const base = new Highlight()
|
||||
base.priority = -2
|
||||
CSS.highlights.set(BASE, base)
|
||||
let frame: number | undefined
|
||||
const background = createQuoteBackground()
|
||||
const observed = new Set<Element>()
|
||||
|
||||
const schedule = () => {
|
||||
if (frame !== undefined) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
apply()
|
||||
})
|
||||
}
|
||||
|
||||
const apply = () => {
|
||||
base.clear()
|
||||
observer.disconnect()
|
||||
const shadows = new Set<ShadowRoot>()
|
||||
const containers = new Map<Element, ReturnType<typeof textNodes>>()
|
||||
const ranges: Range[] = []
|
||||
|
||||
pieces.forEach((piece) => {
|
||||
const range = resolveQuoteRange(root, piece, containers, (shadow) => {
|
||||
if (shadows.has(shadow)) return
|
||||
shadows.add(shadow)
|
||||
})
|
||||
|
||||
if (!range) return
|
||||
base.add(range)
|
||||
ranges.push(range)
|
||||
})
|
||||
background.update(ranges)
|
||||
reveal()
|
||||
observer.observe(root, { childList: true, subtree: true, characterData: true })
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "class", "dir"] })
|
||||
shadows.forEach((shadow) => observer.observe(shadow, { childList: true, subtree: true, characterData: true }))
|
||||
const targets = new Set<Element>([root, ...containers.keys()])
|
||||
observed.forEach((element) => {
|
||||
if (targets.has(element)) return
|
||||
resize.unobserve(element)
|
||||
observed.delete(element)
|
||||
})
|
||||
targets.forEach((element) => {
|
||||
if (observed.has(element)) return
|
||||
observed.add(element)
|
||||
resize.observe(element)
|
||||
})
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(schedule)
|
||||
const resize = new ResizeObserver(schedule)
|
||||
document.fonts.addEventListener("loadingdone", schedule)
|
||||
|
||||
apply()
|
||||
onCleanup(() => {
|
||||
observer.disconnect()
|
||||
resize.disconnect()
|
||||
document.fonts.removeEventListener("loadingdone", schedule)
|
||||
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
background.clear()
|
||||
CSS.highlights.delete(BASE)
|
||||
})
|
||||
})
|
||||
|
||||
createEffect(
|
||||
on(
|
||||
() => [input.source(), input.source().state.reveal?.sequence] as const,
|
||||
([current], previous) => {
|
||||
const source = input.source()
|
||||
const key = source.state.reveal?.key
|
||||
const first = key && source.state.sources[key]?.[0]
|
||||
const root = input.root()
|
||||
|
||||
pending = undefined
|
||||
|
||||
if (current !== previous?.[0] || !first || !root || !input.enabled()) return
|
||||
pending = { key, source }
|
||||
reveal()
|
||||
|
||||
if (!pending) return
|
||||
input.unpin()
|
||||
input.reveal(first.revealID, first.partID)
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function resolveQuoteRange(
|
||||
root: HTMLElement,
|
||||
piece: QuoteSource[number],
|
||||
containers: Map<Element, ReturnType<typeof textNodes>>,
|
||||
observe?: (shadow: ShadowRoot) => void,
|
||||
) {
|
||||
const part = root.querySelector(`[data-timeline-part-id="${CSS.escape(piece.partID)}"]`)
|
||||
const shadow = piece.shadow && part?.querySelectorAll("diffs-container")[piece.shadow.host]?.shadowRoot
|
||||
|
||||
if (shadow) observe?.(shadow)
|
||||
|
||||
const container = piece.shadow
|
||||
? shadow?.querySelector(piece.shadow.line)
|
||||
: piece.body
|
||||
? part?.querySelector(piece.body)
|
||||
: part
|
||||
|
||||
if (!container) return
|
||||
const nodes = containers.get(container) ?? textNodes(container)
|
||||
containers.set(container, nodes)
|
||||
const start = nodes.find((item) => item.start <= piece.start && item.end > piece.start)
|
||||
const end = nodes.find((item) => item.start < piece.end && item.end >= piece.end)
|
||||
|
||||
if (!start || !end) return
|
||||
const range = document.createRange()
|
||||
range.setStart(start.node, piece.start - start.start)
|
||||
range.setEnd(end.node, piece.end - end.start)
|
||||
|
||||
// A changed tool result or rerender must never highlight unrelated text at the old offset.
|
||||
return range.toString() === piece.text ? range : undefined
|
||||
}
|
||||
|
||||
function textNodes(root: Element) {
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
|
||||
const nodes: { node: Text; start: number; end: number }[] = []
|
||||
let offset = 0
|
||||
|
||||
while (walker.nextNode()) {
|
||||
// SAFETY: SHOW_TEXT restricts this walker to Text nodes.
|
||||
const node = walker.currentNode as Text
|
||||
nodes.push({ node, start: offset, end: offset + node.length })
|
||||
offset += node.length
|
||||
}
|
||||
|
||||
return nodes
|
||||
}
|
||||
@@ -159,6 +159,7 @@ export function quoteText(selection: TimelineSelection) {
|
||||
}
|
||||
|
||||
const output: string[] = []
|
||||
const ranges: Range[] = []
|
||||
let length = 0
|
||||
let truncated = false
|
||||
let previous: { block: Element; part: Element | null } | undefined
|
||||
@@ -197,9 +198,15 @@ export function quoteText(selection: TimelineSelection) {
|
||||
|
||||
if (!text) return
|
||||
const current = { block: blockOf(parent), part: partOf(parent) }
|
||||
const piece = document.createRange()
|
||||
piece.setStart(node, start)
|
||||
piece.setEnd(node, end)
|
||||
|
||||
if (!pre && text === " ") {
|
||||
if (previous?.block === current.block && !endsWithBreak() && !output.at(-1)?.endsWith(" ")) append(" ")
|
||||
if (previous?.block === current.block && !endsWithBreak() && !output.at(-1)?.endsWith(" ")) {
|
||||
append(" ")
|
||||
ranges.push(piece)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -212,9 +219,7 @@ export function quoteText(selection: TimelineSelection) {
|
||||
append((starts ? marker(parent) : "") + (!pre && endsWithBreak() ? text.trimStart() : text))
|
||||
first ??= { node, offset: start + raw.search(/\S|$/) }
|
||||
last = { node, offset: start + raw.trimEnd().length }
|
||||
const piece = document.createRange()
|
||||
piece.setStart(node, start)
|
||||
piece.setEnd(node, end)
|
||||
ranges.push(piece)
|
||||
|
||||
for (const rect of piece.getClientRects()) {
|
||||
if (rect.width === 0) continue
|
||||
@@ -263,6 +268,7 @@ export function quoteText(selection: TimelineSelection) {
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim(),
|
||||
truncated,
|
||||
ranges,
|
||||
first,
|
||||
last,
|
||||
horizontal: left < right ? { left, right } : undefined,
|
||||
|
||||
@@ -8,6 +8,8 @@ import { Button } from "@opencode/ui/button"
|
||||
import { Keybind } from "@opencode/ui/keybind"
|
||||
import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { QuoteSource } from "@/composer/quote-source"
|
||||
import { captureQuoteSource } from "./quote-highlight"
|
||||
import {
|
||||
characterRect,
|
||||
narrowSelection,
|
||||
@@ -34,7 +36,7 @@ export function createTimelineQuote(input: {
|
||||
root: () => HTMLElement | undefined
|
||||
sessionKey: () => string
|
||||
enabled: () => boolean
|
||||
add: (text: string, comment: boolean) => void
|
||||
add: (text: string, comment: boolean, source: QuoteSource) => void
|
||||
}) {
|
||||
const [state, setState] = createStore<{
|
||||
text: string | undefined
|
||||
@@ -292,9 +294,10 @@ export function createTimelineQuote(input: {
|
||||
const text = state.text
|
||||
|
||||
if (!text || state.truncated) return
|
||||
const source = selected ? captureQuoteSource(quoteText(selected).ranges) : []
|
||||
window.getSelection()?.removeAllRanges()
|
||||
close()
|
||||
input.add(text, comment)
|
||||
input.add(text, comment, source)
|
||||
},
|
||||
setElement: (value: HTMLElement | undefined) => {
|
||||
element = value
|
||||
@@ -376,7 +379,7 @@ export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
||||
</>
|
||||
}
|
||||
placement="top"
|
||||
openDelay={1200}
|
||||
openDelay={800}
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
|
||||
@@ -40,6 +40,32 @@ describe("prompt submission state", () => {
|
||||
expect(session.context.items()[0]).toMatchObject({ type: "file", path: "src/index.ts" })
|
||||
})
|
||||
|
||||
test("captures quote sources before submission clears the draft and carries them to the promoted session", () => {
|
||||
const draft = createMemoryComposerState()
|
||||
const session = createMemoryComposerState()
|
||||
draft.context.add({ type: "quote", commentID: "quote-source", text: "quoted passage" })
|
||||
const key = draft.context.items()[0]!.key
|
||||
const source = [{ partID: "part-source", revealID: "message-source", start: 4, end: 18, text: "quoted passage" }]
|
||||
draft.quoteSource.add(key, source)
|
||||
|
||||
const submission = createComposerSubmission({
|
||||
target: draft,
|
||||
prompt: draft.current(),
|
||||
context: draft.context.items(),
|
||||
})
|
||||
|
||||
submission.retarget(session)
|
||||
expect(session.quoteSource.state.sources[key]).toEqual(source)
|
||||
|
||||
// Optimistic cleanup must release the draft's source without losing the failed request's recovery snapshot.
|
||||
session.context.replaceComments([])
|
||||
expect(session.quoteSource.state.sources[key]).toBeUndefined()
|
||||
expect(submission.sources).toEqual([{ key, source }])
|
||||
expect(submission.restore()?.context).toEqual([
|
||||
{ key, type: "quote", commentID: "quote-source", text: "quoted passage" },
|
||||
])
|
||||
})
|
||||
|
||||
test("clears the original first-submit prompt after retargeting", () => {
|
||||
const workspace = createMemoryComposerState()
|
||||
const session = createMemoryComposerState()
|
||||
|
||||
@@ -202,7 +202,7 @@ export function TerminalQuote(props: { term: Term; container: HTMLElement; targe
|
||||
</>
|
||||
}
|
||||
placement="top"
|
||||
openDelay={1200}
|
||||
openDelay={800}
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
:root,
|
||||
:host {
|
||||
--timeline-quote-background: light-dark(
|
||||
rgb(from var(--v2-blue-1100) r g b / 0.1),
|
||||
rgb(from var(--v2-blue-400) r g b / 0.25)
|
||||
);
|
||||
}
|
||||
|
||||
[data-slot="session-timeline-scroll"] ::selection,
|
||||
:host ::selection,
|
||||
::highlight(timeline-quote-source) {
|
||||
background-color: var(--timeline-quote-background);
|
||||
color: currentColor;
|
||||
}
|
||||
|
||||
.timeline-quote-highlight-host {
|
||||
isolation: isolate;
|
||||
|
||||
&::highlight(timeline-quote-source) {
|
||||
background-color: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-quote-highlight-relative {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
[data-component="timeline-quote-background"] {
|
||||
position: absolute;
|
||||
/* These offsets share the physical coordinate system of DOMRects, including in RTL. */
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
|
||||
> span {
|
||||
position: absolute;
|
||||
background-color: var(--timeline-quote-background);
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,13 @@
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
[data-slot="tool-error-card-content"] :where(*)::selection {
|
||||
[data-slot="tool-error-card-content"] {
|
||||
--timeline-quote-background: var(--v2-state-bg-danger);
|
||||
}
|
||||
|
||||
[data-slot="tool-error-card-content"] :where(*)::selection,
|
||||
[data-slot="tool-error-card-content"] :where(*)::highlight(timeline-quote-source),
|
||||
[data-slot="tool-error-card-content"] :where(*)::highlight(timeline-quote-source-active) {
|
||||
background: var(--v2-state-bg-danger);
|
||||
color: var(--v2-text-text-base);
|
||||
}
|
||||
|
||||
@@ -21,8 +21,15 @@ export function AttachmentCard(props: {
|
||||
data-clickable={props.clickable ? "true" : undefined}
|
||||
data-wide={props.wide ? "true" : undefined}
|
||||
data-surface={props.surface}
|
||||
role={props.clickable ? "button" : undefined}
|
||||
tabIndex={props.clickable ? 0 : undefined}
|
||||
title={props.hover}
|
||||
onClick={() => props.onClick?.()}
|
||||
onKeyDown={(event) => {
|
||||
if (!props.clickable || (event.key !== "Enter" && event.key !== " ")) return
|
||||
event.preventDefault()
|
||||
props.onClick?.()
|
||||
}}
|
||||
>
|
||||
<span ref={(element) => props.titleRef?.(element)} data-slot="attachment-card-title">
|
||||
{props.title}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { OpenCodeTheme } from "@opencode/ui/context/highlight-theme"
|
||||
import { ComponentProps } from "solid-js"
|
||||
import { lineCommentStyles } from "../components/line-comment-styles"
|
||||
import quoteHighlightStyles from "../components/quote-highlight.css?inline"
|
||||
|
||||
// Pierre resolves themes on the main thread and hands them to its workers, so register before any viewer renders.
|
||||
registerCustomTheme(OpenCodeTheme.name, () => Promise.resolve(OpenCodeTheme), "zed")
|
||||
@@ -68,12 +69,11 @@ const unsafeCSS = `
|
||||
/* Use explicit alpha instead of color-mix(..., transparent) to avoid Safari's non-premultiplied interpolation bugs. */
|
||||
--diffs-bg-selection: var(--diffs-bg-selection-override, rgb(from var(--diffs-selection-base) r g b / 0.2));
|
||||
--diffs-bg-selection-number: var(--diffs-bg-selection-number-override, var(--diffs-bg-selection));
|
||||
--diffs-bg-selection-text: rgb(from var(--diffs-selection-base) r g b / 0.2);
|
||||
}
|
||||
|
||||
[data-diff] ::selection,
|
||||
[data-file] ::selection {
|
||||
background-color: var(--diffs-bg-selection-text);
|
||||
background-color: var(--timeline-quote-background);
|
||||
}
|
||||
|
||||
[data-indicators='bars'] [data-column-number][data-line-type='change-addition']::before,
|
||||
@@ -141,6 +141,13 @@ const unsafeCSS = `
|
||||
background-color: rgb(from var(--surface-warning-base) r g b / 0.35);
|
||||
}
|
||||
|
||||
[data-diff] ::highlight(timeline-quote-source),
|
||||
[data-file] ::highlight(timeline-quote-source),
|
||||
[data-diff] ::highlight(timeline-quote-source-active),
|
||||
[data-file] ::highlight(timeline-quote-source-active) {
|
||||
background-color: var(--timeline-quote-background);
|
||||
}
|
||||
|
||||
::highlight(opencode-find-current) {
|
||||
background-color: rgb(from var(--surface-warning-strong) r g b / 0.55);
|
||||
}
|
||||
@@ -263,6 +270,7 @@ const unsafeCSS = `
|
||||
}
|
||||
|
||||
${lineCommentStyles}
|
||||
${quoteHighlightStyles}
|
||||
|
||||
`
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
@import "../components/message-part.css" layer(components);
|
||||
@import "../components/message-nav.css" layer(components);
|
||||
@import "../components/question-prompt.css" layer(components);
|
||||
@import "../components/quote-highlight.css" layer(components);
|
||||
@import "../components/session-review.css" layer(components);
|
||||
@import "../components/session-compaction.css" layer(components);
|
||||
@import "../components/session-turn.css" layer(components);
|
||||
|
||||
Reference in New Issue
Block a user