mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
feat(app): quote selected timeline text into the composer
This commit is contained in:
parent
23937b284a
commit
b4fd01b10b
6 changed files with 764 additions and 0 deletions
|
|
@ -424,6 +424,14 @@
|
|||
--session-dropzone-card: var(--v2-background-bg-layer-01);
|
||||
}
|
||||
|
||||
[data-component="timeline-quote"] {
|
||||
background-color: var(--v2-background-bg-base);
|
||||
}
|
||||
|
||||
[data-color-scheme="dark"] [data-component="timeline-quote"] {
|
||||
background-color: var(--v2-background-bg-layer-01);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-component="session-dropzone"][data-visible="true"],
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-content"],
|
||||
|
|
|
|||
|
|
@ -596,6 +596,10 @@ export const dict = {
|
|||
|
||||
"session.search.placeholder": "Find...",
|
||||
"session.search.noResults": "No matches",
|
||||
"session.quote.actions": "Quote selection",
|
||||
"session.quote.add": "Quote",
|
||||
"session.quote.addWithComment": "Quote and comment",
|
||||
"session.quote.tooLong": "Selection too long",
|
||||
"session.header.open.finder": "Finder",
|
||||
"session.header.open.fileExplorer": "File Explorer",
|
||||
"session.header.open.fileManager": "File Manager",
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ import { useServerSDK } from "@/runtime/server/client"
|
|||
import { showToast } from "@/shell/notifications/toast"
|
||||
import { useLocal } from "@/providers/models/selection"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { uuid } from "@/runtime/persistence/uuid"
|
||||
import { contextItemKey } from "@/composer/schema"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { requireServerKey, sessionHref } from "@/shell/routes/session"
|
||||
import { useComposerCommands } from "@/composer/commands"
|
||||
|
|
@ -268,6 +270,17 @@ export function createActiveSessionRegion(input: {
|
|||
active: () => active()?.drop.active() ?? false,
|
||||
input: () => active()?.drop.input(),
|
||||
},
|
||||
quote: {
|
||||
// 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) => {
|
||||
const item = { type: "quote" as const, text, commentID: uuid() }
|
||||
prompt.context.add(item)
|
||||
|
||||
if (comment) return prompt.capture().quoteComment.set(contextItemKey(item))
|
||||
focus()
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
timeline: {
|
||||
get revert() {
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import { SideRegion } from "@/runtime/extension/side-region"
|
|||
import { createSessionTimelineInteraction } from "./timeline/interaction"
|
||||
import { createTimelineSearchController } from "./timeline/search-controller"
|
||||
import { TimelineSearchBar } from "./timeline/search-bar"
|
||||
import { createTimelineQuote, TimelineQuote } from "./timeline/quote"
|
||||
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
|
||||
import { SessionIdentityHeader } from "./session-identity-header"
|
||||
import { SessionReviewToggle } from "./header/session-header-actions"
|
||||
|
|
@ -227,6 +228,13 @@ function SessionScreenContent(props: {
|
|||
props.bindBackground(composer.requests.background.tasks)
|
||||
useUsageExceededDialogs()
|
||||
|
||||
const quote = createTimelineQuote({
|
||||
root: timeline.scroller,
|
||||
sessionKey: session.identity.sessionKey,
|
||||
enabled: () => conversationVisible() && composer.quote.available(),
|
||||
add: composer.quote.add,
|
||||
})
|
||||
|
||||
const sessionErrorFallback = (cause: unknown, reset: () => void) => {
|
||||
createEffect(on(session.identity.sessionKey, reset, { defer: true }))
|
||||
|
||||
|
|
@ -304,6 +312,7 @@ function SessionScreenContent(props: {
|
|||
input={composer.drop.input()}
|
||||
identity={session.layout.tabKey}
|
||||
/>
|
||||
<TimelineQuote controller={quote} />
|
||||
<Show when={!isDesktop() && !!session.identity.params.id && !bottomMobileTabs()}>{mobileTabs()}</Show>
|
||||
{/* Surface query errors without suspending session metadata while messages load. */}
|
||||
<Show when={timeline.resource.error}>
|
||||
|
|
|
|||
326
packages/app/src/session/timeline/quote-text.ts
Normal file
326
packages/app/src/session/timeline/quote-text.ts
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
/** About 5k tokens. */
|
||||
export const QUOTE_MAX_LENGTH = 20_000
|
||||
|
||||
// Diff viewers render their lines in a shadow root.
|
||||
const SHADOW_HOSTS = "diffs-container"
|
||||
|
||||
type Point = { node: Node; offset: number }
|
||||
|
||||
/** `range` is in the document; `start` and `end` may be inside a diff viewer's shadow root. */
|
||||
export type TimelineSelection = { range: Range; start: Point; end: Point; backward: boolean }
|
||||
|
||||
/** The part of the current selection inside the timeline, including diff viewers. */
|
||||
export function timelineSelection(selection: Selection, root: HTMLElement): TimelineSelection | undefined {
|
||||
if (selection.rangeCount === 0) return
|
||||
|
||||
// Safari before 17 has no composed ranges.
|
||||
const composed =
|
||||
"getComposedRanges" in Selection.prototype
|
||||
? selection.getComposedRanges({
|
||||
shadowRoots: [...root.querySelectorAll(SHADOW_HOSTS)].flatMap((host) =>
|
||||
host.shadowRoot ? [host.shadowRoot] : [],
|
||||
),
|
||||
})[0]
|
||||
: selection.getRangeAt(0)
|
||||
|
||||
if (!composed || composed.collapsed) return
|
||||
|
||||
const range = document.createRange()
|
||||
const start = documentPoint({ node: composed.startContainer, offset: composed.startOffset }, false)
|
||||
const end = documentPoint({ node: composed.endContainer, offset: composed.endOffset }, true)
|
||||
range.setStart(start.node, start.offset)
|
||||
range.setEnd(end.node, end.offset)
|
||||
|
||||
if (!range.intersectsNode(root)) return
|
||||
const content = document.createRange()
|
||||
content.selectNodeContents(root)
|
||||
const clampedStart = range.compareBoundaryPoints(Range.START_TO_START, content) < 0
|
||||
const clampedEnd = range.compareBoundaryPoints(Range.END_TO_END, content) > 0
|
||||
|
||||
if (clampedStart) range.setStart(content.startContainer, content.startOffset)
|
||||
|
||||
if (clampedEnd) range.setEnd(content.endContainer, content.endOffset)
|
||||
|
||||
if (range.collapsed) return
|
||||
|
||||
return {
|
||||
range,
|
||||
backward: backward(selection),
|
||||
start: clampedStart
|
||||
? { node: range.startContainer, offset: range.startOffset }
|
||||
: { node: composed.startContainer, offset: composed.startOffset },
|
||||
end: clampedEnd
|
||||
? { node: range.endContainer, offset: range.endOffset }
|
||||
: { node: composed.endContainer, offset: composed.endOffset },
|
||||
}
|
||||
}
|
||||
|
||||
export function selectionRects(selection: TimelineSelection) {
|
||||
const outer = document.createRange()
|
||||
const start = documentPoint(selection.start, true)
|
||||
const end = documentPoint(selection.end, false)
|
||||
outer.setStart(start.node, start.offset)
|
||||
|
||||
if (outer.comparePoint(end.node, end.offset) > 0) outer.setEnd(end.node, end.offset)
|
||||
|
||||
return [outer, ...shadowRanges(selection)]
|
||||
.flatMap((range) => [...range.getClientRects()])
|
||||
.filter((rect) => rect.width > 0 && rect.height > 0)
|
||||
}
|
||||
|
||||
/** The box of the character after a point, or before it with `before`. */
|
||||
export function characterRect(point: Point, before: boolean) {
|
||||
if (!(point.node instanceof Text) || point.node.data.length === 0) return
|
||||
const offset = Math.min(Math.max(before ? point.offset - 1 : point.offset, 0), point.node.data.length - 1)
|
||||
const range = document.createRange()
|
||||
range.setStart(point.node, offset)
|
||||
range.setEnd(point.node, offset + 1)
|
||||
const rect = range.getBoundingClientRect()
|
||||
|
||||
return rect.height > 0 ? rect : undefined
|
||||
}
|
||||
|
||||
export function narrowSelection(selection: TimelineSelection, start: Point, end: Point): TimelineSelection {
|
||||
const range = document.createRange()
|
||||
const outerStart = documentPoint(start, false)
|
||||
const outerEnd = documentPoint(end, true)
|
||||
range.setStart(outerStart.node, outerStart.offset)
|
||||
range.setEnd(outerEnd.node, outerEnd.offset)
|
||||
|
||||
return { range, start, end, backward: selection.backward }
|
||||
}
|
||||
|
||||
export function shadowRanges(selection: TimelineSelection) {
|
||||
const hosts = selection.range.commonAncestorContainer
|
||||
|
||||
const candidates =
|
||||
hosts instanceof Element || hosts instanceof DocumentFragment ? [...hosts.querySelectorAll(SHADOW_HOSTS)] : []
|
||||
|
||||
return candidates.flatMap((host) =>
|
||||
host.shadowRoot && selection.range.intersectsNode(host) ? [innerRange(host.shadowRoot, selection)] : [],
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The plain text of a selection in the timeline. The shell disables text selection and content opts back in, so only
|
||||
* selectable text is quoted; buttons, titles, and timestamps are left out.
|
||||
*/
|
||||
export function quoteText(selection: TimelineSelection) {
|
||||
const styles = new Map<Element, CSSStyleDeclaration>()
|
||||
|
||||
const style = (element: Element) => {
|
||||
const cached = styles.get(element)
|
||||
|
||||
if (cached) return cached
|
||||
|
||||
const value = getComputedStyle(element)
|
||||
styles.set(element, value)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const selectable = new Map<Element, boolean>()
|
||||
|
||||
// Not every browser resolves `user-select: auto` in computed style.
|
||||
const isSelectable = (element: Element): boolean => {
|
||||
const cached = selectable.get(element)
|
||||
|
||||
if (cached !== undefined) return cached
|
||||
|
||||
const value = style(element).userSelect || style(element).webkitUserSelect
|
||||
|
||||
const result =
|
||||
value === "auto" ? (element.parentElement ? isSelectable(element.parentElement) : true) : value !== "none"
|
||||
|
||||
selectable.set(element, result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
const blockOf = (element: Element): Element => {
|
||||
const display = style(element).display
|
||||
|
||||
if (!display.startsWith("inline") && display !== "contents") return element
|
||||
|
||||
return element.parentElement ? blockOf(element.parentElement) : element
|
||||
}
|
||||
|
||||
const inlineSeparator = (previous: Element, current: Element) => {
|
||||
const item = itemOf(current, previous)
|
||||
const row = item.parentElement
|
||||
|
||||
if (!row || item.contains(previous)) return
|
||||
|
||||
if (style(item).display === "table-cell") return "\t"
|
||||
|
||||
const display = style(row).display
|
||||
|
||||
if ((display === "flex" || display === "inline-flex") && style(row).flexDirection.startsWith("row")) return " "
|
||||
}
|
||||
|
||||
const output: string[] = []
|
||||
let length = 0
|
||||
let truncated = false
|
||||
let previous: { block: Element; part: Element | null } | undefined
|
||||
let first: Point | undefined
|
||||
let last: Point | undefined
|
||||
let left = Infinity
|
||||
let right = -Infinity
|
||||
|
||||
const append = (value: string) => {
|
||||
output.push(value)
|
||||
length += value.length
|
||||
|
||||
if (length > QUOTE_MAX_LENGTH) truncated = true
|
||||
}
|
||||
|
||||
const endsWithBreak = () => {
|
||||
const last = output.at(-1)
|
||||
|
||||
return last === undefined || last.endsWith("\n")
|
||||
}
|
||||
|
||||
const separate = (separator: string) => {
|
||||
if (separator === "\n\n") append(endsWithBreak() ? "\n" : "\n\n")
|
||||
else if (!endsWithBreak()) append(separator)
|
||||
}
|
||||
|
||||
const visit = (node: Text, range: Range) => {
|
||||
const parent = node.parentElement
|
||||
|
||||
if (!parent || !isSelectable(parent) || style(parent).visibility !== "visible") return
|
||||
const start = node === range.startContainer ? range.startOffset : 0
|
||||
const end = node === range.endContainer ? range.endOffset : (node.nodeValue?.length ?? 0)
|
||||
const raw = (node.nodeValue ?? "").slice(start, end)
|
||||
const pre = /^(pre|break-spaces)/.test(style(parent).whiteSpace)
|
||||
const text = pre ? raw : raw.replace(/\s+/g, " ")
|
||||
|
||||
if (!text) return
|
||||
const current = { block: blockOf(parent), part: partOf(parent) }
|
||||
|
||||
if (!pre && text === " ") {
|
||||
if (previous?.block === current.block && !endsWithBreak() && !output.at(-1)?.endsWith(" ")) append(" ")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const starts = previous?.block !== current.block
|
||||
|
||||
if (previous && current.part !== previous.part) separate("\n\n")
|
||||
else if (previous && starts) separate(inlineSeparator(previous.block, current.block) ?? "\n")
|
||||
previous = current
|
||||
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)
|
||||
|
||||
for (const rect of piece.getClientRects()) {
|
||||
if (rect.width === 0) continue
|
||||
left = Math.min(left, rect.left)
|
||||
right = Math.max(right, rect.right)
|
||||
}
|
||||
}
|
||||
|
||||
const walk = (range: Range) => {
|
||||
const root = range.commonAncestorContainer
|
||||
|
||||
if (root instanceof Text) return visit(root, range)
|
||||
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
|
||||
acceptNode(node) {
|
||||
if (!range.intersectsNode(node)) return NodeFilter.FILTER_REJECT
|
||||
|
||||
if (node instanceof Text) return NodeFilter.FILTER_ACCEPT
|
||||
|
||||
if (!(node instanceof Element)) return NodeFilter.FILTER_REJECT
|
||||
|
||||
if (node.tagName === "BUTTON" || node.getAttribute("aria-hidden") === "true" || style(node).display === "none")
|
||||
return NodeFilter.FILTER_REJECT
|
||||
|
||||
return node.tagName === "BR" || node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
|
||||
},
|
||||
})
|
||||
|
||||
while (!truncated && walker.nextNode()) {
|
||||
const node = walker.currentNode
|
||||
|
||||
if (node instanceof Text) visit(node, range)
|
||||
else if (node instanceof Element && node.shadowRoot) walk(innerRange(node.shadowRoot, selection))
|
||||
else if (previous) append("\n")
|
||||
}
|
||||
}
|
||||
|
||||
walk(selection.range)
|
||||
|
||||
return {
|
||||
text: output
|
||||
.join("")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.join("\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim(),
|
||||
truncated,
|
||||
first,
|
||||
last,
|
||||
horizontal: left < right ? { left, right } : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// `Selection.direction` reads "none" for mouse selections in Chromium.
|
||||
function backward(selection: Selection) {
|
||||
if (!selection.anchorNode || !selection.focusNode) return false
|
||||
const range = document.createRange()
|
||||
range.setStart(selection.anchorNode, selection.anchorOffset)
|
||||
|
||||
return range.comparePoint(selection.focusNode, selection.focusOffset) < 0
|
||||
}
|
||||
|
||||
function documentPoint(point: Point, end: boolean): Point {
|
||||
const root = point.node.getRootNode()
|
||||
|
||||
if (!(root instanceof ShadowRoot)) return point
|
||||
const parent = root.host.parentNode!
|
||||
|
||||
return documentPoint({ node: parent, offset: [...parent.childNodes].indexOf(root.host) + (end ? 1 : 0) }, end)
|
||||
}
|
||||
|
||||
function innerRange(root: ShadowRoot, selection: TimelineSelection) {
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(root)
|
||||
|
||||
if (root.contains(selection.start.node)) range.setStart(selection.start.node, selection.start.offset)
|
||||
|
||||
if (root.contains(selection.end.node)) range.setEnd(selection.end.node, selection.end.offset)
|
||||
|
||||
return range
|
||||
}
|
||||
|
||||
function partOf(element: Element): Element | null {
|
||||
const part = element.closest("[data-timeline-part-id], [data-index]")
|
||||
|
||||
if (part) return part
|
||||
const root = element.getRootNode()
|
||||
|
||||
return root instanceof ShadowRoot ? partOf(root.host) : null
|
||||
}
|
||||
|
||||
function itemOf(current: Element, previous: Element): Element {
|
||||
const parent = current.parentElement
|
||||
|
||||
if (!parent || parent.contains(previous)) return current
|
||||
|
||||
return itemOf(parent, previous)
|
||||
}
|
||||
|
||||
function marker(element: Element) {
|
||||
const type = element.closest("[data-line-type]")?.getAttribute("data-line-type")
|
||||
|
||||
if (type === "change-deletion") return "-"
|
||||
|
||||
if (type === "change-addition") return "+"
|
||||
|
||||
return ""
|
||||
}
|
||||
404
packages/app/src/session/timeline/quote.tsx
Normal file
404
packages/app/src/session/timeline/quote.tsx
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
import { createEffect, on, onCleanup, Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Portal } from "solid-js/web"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { createMediaQuery } from "@solid-primitives/media"
|
||||
import { createResizeObserver } from "@solid-primitives/resize-observer"
|
||||
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 {
|
||||
characterRect,
|
||||
narrowSelection,
|
||||
quoteText,
|
||||
selectionRects,
|
||||
timelineSelection,
|
||||
type TimelineSelection,
|
||||
} from "./quote-text"
|
||||
|
||||
const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
|
||||
|
||||
const SETTLE_MS = 150
|
||||
|
||||
const SHORT_LINES = 3
|
||||
|
||||
const GAP = 8
|
||||
|
||||
type Rect = { top: number; bottom: number; left: number; right: number }
|
||||
|
||||
type Extent = Rect & { short: boolean; backward: boolean }
|
||||
|
||||
/** Offers to quote text selected in the session timeline into the composer. */
|
||||
export function createTimelineQuote(input: {
|
||||
root: () => HTMLElement | undefined
|
||||
sessionKey: () => string
|
||||
enabled: () => boolean
|
||||
add: (text: string, comment: boolean) => void
|
||||
}) {
|
||||
const [state, setState] = createStore<{
|
||||
text: string | undefined
|
||||
truncated: boolean
|
||||
extent: Extent | undefined
|
||||
bounds: Rect | undefined
|
||||
}>({ text: undefined, truncated: false, extent: undefined, bounds: undefined })
|
||||
|
||||
let selected: TimelineSelection | undefined
|
||||
let horizontal: { left: number; right: number; origin: number } | undefined
|
||||
let element: HTMLElement | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let frame: number | undefined
|
||||
let pointer = false
|
||||
let reflow: number | undefined
|
||||
// The selection Escape dismissed, which stays dismissed until it changes or clears.
|
||||
let dismissed: Range | undefined
|
||||
|
||||
const close = () => {
|
||||
selected = undefined
|
||||
horizontal = undefined
|
||||
dismissed = undefined
|
||||
clearTimeout(timer)
|
||||
|
||||
if (reflow !== undefined) cancelAnimationFrame(reflow)
|
||||
reflow = undefined
|
||||
setState({ text: undefined, truncated: false, extent: undefined, bounds: undefined })
|
||||
}
|
||||
|
||||
const dismiss = () => {
|
||||
const focused = document.activeElement instanceof Node && !!element?.contains(document.activeElement)
|
||||
const selection = window.getSelection()
|
||||
close()
|
||||
dismissed = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined
|
||||
|
||||
if (focused) input.root()?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
const place = () => {
|
||||
const root = input.root()
|
||||
|
||||
if (!root || !selected) return
|
||||
const view = root.getBoundingClientRect()
|
||||
const sticky = root.querySelector("[data-session-title]")
|
||||
|
||||
const bounds = {
|
||||
top: view.top + (sticky instanceof HTMLElement ? sticky.offsetHeight : 0),
|
||||
bottom: view.bottom,
|
||||
left: view.left,
|
||||
right: view.right,
|
||||
}
|
||||
|
||||
// The virtualizer removed the selected rows.
|
||||
if (selected.range.collapsed) return close()
|
||||
|
||||
const rects = selectionRects(selected)
|
||||
const first = characterRect(selected.start, false)
|
||||
const last = characterRect(selected.end, true)
|
||||
const top = first?.top ?? Math.min(...rects.map((rect) => rect.top))
|
||||
const bottom = last?.bottom ?? Math.max(...rects.map((rect) => rect.bottom))
|
||||
|
||||
const visible = rects.filter(
|
||||
(rect) => rect.bottom > Math.max(bounds.top, top) && rect.top < Math.min(bounds.bottom, bottom),
|
||||
)
|
||||
|
||||
const line =
|
||||
first?.height ?? rects.map((rect) => rect.height).sort((a, b) => a - b)[Math.floor(rects.length / 2)] ?? 0
|
||||
|
||||
setState({
|
||||
bounds,
|
||||
extent: visible.length
|
||||
? {
|
||||
top,
|
||||
bottom,
|
||||
left: horizontal
|
||||
? horizontal.left + view.left - horizontal.origin
|
||||
: Math.min(...visible.map((rect) => rect.left)),
|
||||
right: horizontal
|
||||
? horizontal.right + view.left - horizontal.origin
|
||||
: Math.max(...visible.map((rect) => rect.right)),
|
||||
short: bottom - top < line * (SHORT_LINES + 0.5),
|
||||
backward: selected.backward,
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const read = () => {
|
||||
if (pointer) return
|
||||
const root = input.root()
|
||||
const selection = window.getSelection()
|
||||
|
||||
if (dismissed && selection?.rangeCount && sameRange(selection.getRangeAt(0), dismissed)) return
|
||||
dismissed = undefined
|
||||
const next = root && input.enabled() && selection ? timelineSelection(selection, root) : undefined
|
||||
const quote = next ? quoteText(next) : undefined
|
||||
|
||||
if (!root || !next || !quote?.text) return close()
|
||||
horizontal = quote.horizontal && { ...quote.horizontal, origin: root.getBoundingClientRect().left }
|
||||
// Selecting a whole paragraph ends the selection at the start of the next block.
|
||||
selected = quote.first
|
||||
? narrowSelection(next, quote.first, quote.truncated ? next.end : (quote.last ?? next.end))
|
||||
: next
|
||||
setState({ text: quote.text, truncated: quote.truncated })
|
||||
place()
|
||||
}
|
||||
|
||||
const schedule = () => {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(read, SETTLE_MS)
|
||||
}
|
||||
|
||||
const schedulePlace = () => {
|
||||
if (frame !== undefined || !selected) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
place()
|
||||
})
|
||||
}
|
||||
|
||||
const release = () => {
|
||||
if (!pointer) return
|
||||
pointer = false
|
||||
schedule()
|
||||
}
|
||||
|
||||
const inside = (target: EventTarget | null) => target instanceof Node && !!element?.contains(target)
|
||||
|
||||
// Select all from the keyboard or the app menu covers the whole window; in the timeline it selects the conversation.
|
||||
const containSelectAll = () => {
|
||||
const root = input.root()
|
||||
const selection = window.getSelection()
|
||||
const active = document.activeElement
|
||||
|
||||
if (pointer || !root || !input.enabled() || !selection || selection.rangeCount === 0) return
|
||||
|
||||
if (active !== document.body && !(active instanceof Node && root.contains(active) && !editable(active))) return
|
||||
const range = selection.getRangeAt(0)
|
||||
const content = document.createRange()
|
||||
content.selectNodeContents(root)
|
||||
|
||||
if (
|
||||
range.compareBoundaryPoints(Range.START_TO_START, content) < 0 &&
|
||||
range.compareBoundaryPoints(Range.END_TO_END, content) > 0
|
||||
)
|
||||
selection.selectAllChildren(root)
|
||||
}
|
||||
|
||||
makeEventListener(document, "selectionchange", () => {
|
||||
containSelectAll()
|
||||
|
||||
// Only a new selection waits to settle; a cleared one closes at once.
|
||||
if (window.getSelection()?.isCollapsed ?? true) return close()
|
||||
schedule()
|
||||
})
|
||||
makeEventListener(document, "pointerdown", (event) => {
|
||||
if (inside(event.target) || event.button !== 0) return
|
||||
pointer = true
|
||||
const selection = window.getSelection()
|
||||
const target = event.target instanceof Element ? event.target : undefined
|
||||
|
||||
if (state.text === undefined || event.shiftKey || !selection?.rangeCount || target?.closest(".scroll-view__thumb"))
|
||||
return
|
||||
const range = selection.getRangeAt(0).cloneRange()
|
||||
|
||||
// A press on the selection itself may start dragging it; the page clears it on release otherwise.
|
||||
if (
|
||||
[...range.getClientRects()].some(
|
||||
(rect) =>
|
||||
event.clientX >= rect.left &&
|
||||
event.clientX <= rect.right &&
|
||||
event.clientY >= rect.top &&
|
||||
event.clientY <= rect.bottom,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
// A press on content the shell makes unselectable leaves the selection as it was, so clear it once the press is
|
||||
// handled.
|
||||
setTimeout(() => {
|
||||
if (selection.rangeCount && sameRange(selection.getRangeAt(0), range)) selection.removeAllRanges()
|
||||
})
|
||||
})
|
||||
makeEventListener(document, "pointerup", release)
|
||||
makeEventListener(document, "pointercancel", release)
|
||||
makeEventListener(document, "contextmenu", release)
|
||||
makeEventListener(window, "blur", release)
|
||||
makeEventListener(document, "keydown", (event) => {
|
||||
if (event.defaultPrevented || event.isComposing) return
|
||||
const root = input.root()
|
||||
const active = document.activeElement
|
||||
|
||||
if (event.key === "Escape" && state.text !== undefined) return dismiss()
|
||||
const action = element?.querySelector<HTMLButtonElement>("button:not(:disabled)")
|
||||
|
||||
if (
|
||||
event.key === "Tab" &&
|
||||
!event.shiftKey &&
|
||||
!event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
action &&
|
||||
(active === root || active === document.body)
|
||||
) {
|
||||
event.preventDefault()
|
||||
action.focus()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// The shell disables selection, so the browser's select all finds nothing.
|
||||
if (
|
||||
root &&
|
||||
input.enabled() &&
|
||||
(event.metaKey || event.ctrlKey) &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey &&
|
||||
event.key.toLowerCase() === "a" &&
|
||||
active instanceof Node &&
|
||||
root.contains(active) &&
|
||||
!editable(active)
|
||||
) {
|
||||
event.preventDefault()
|
||||
window.getSelection()?.selectAllChildren(root)
|
||||
}
|
||||
})
|
||||
makeEventListener(document, "scroll", schedulePlace, { capture: true, passive: true })
|
||||
makeEventListener(window, "resize", schedulePlace)
|
||||
|
||||
// A resized timeline, such as when a side panel opens, reflows the selected text.
|
||||
createResizeObserver(input.root, () => {
|
||||
if (!selected || reflow !== undefined) return
|
||||
reflow = requestAnimationFrame(() => {
|
||||
reflow = undefined
|
||||
read()
|
||||
})
|
||||
})
|
||||
|
||||
createEffect(on(input.sessionKey, close, { defer: true }))
|
||||
createEffect(() => {
|
||||
if (!input.enabled()) close()
|
||||
})
|
||||
onCleanup(() => {
|
||||
clearTimeout(timer)
|
||||
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
|
||||
if (reflow !== undefined) cancelAnimationFrame(reflow)
|
||||
})
|
||||
|
||||
return {
|
||||
state,
|
||||
// With Alt held, the quote opens its comment editor in the composer.
|
||||
add: (comment: boolean) => {
|
||||
const text = state.text
|
||||
|
||||
if (!text || state.truncated) return
|
||||
window.getSelection()?.removeAllRanges()
|
||||
close()
|
||||
input.add(text, comment)
|
||||
},
|
||||
setElement: (value: HTMLElement | undefined) => {
|
||||
element = value
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type TimelineQuoteController = ReturnType<typeof createTimelineQuote>
|
||||
|
||||
export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
||||
const language = useLanguage()
|
||||
const quote = props.controller
|
||||
// Touch screens show their own menu over the selection.
|
||||
const docked = createMediaQuery("(hover: none)")
|
||||
const [size, setSize] = createStore({ width: 0, height: 0 })
|
||||
|
||||
const position = () => {
|
||||
const bounds = quote.state.bounds
|
||||
const extent = quote.state.extent
|
||||
|
||||
if (!bounds || !extent) return
|
||||
|
||||
const pinned = bounds.bottom - size.height - GAP
|
||||
|
||||
if (docked()) return { top: pinned, left: (bounds.left + bounds.right - size.width) / 2 }
|
||||
|
||||
const above = extent.top - size.height - GAP
|
||||
const below = extent.bottom + GAP
|
||||
const fitsAbove = above >= bounds.top + GAP && extent.top <= bounds.bottom
|
||||
const fitsBelow = below + size.height <= bounds.bottom - GAP && extent.bottom >= bounds.top
|
||||
|
||||
// Short selections get it above; taller ones at the end they were dragged towards.
|
||||
const sides =
|
||||
extent.short || extent.backward
|
||||
? [fitsAbove && above, fitsBelow && below]
|
||||
: [fitsBelow && below, fitsAbove && above]
|
||||
|
||||
const top = sides.find((side) => side !== false) ?? pinned
|
||||
const center = (extent.left + extent.right - size.width) / 2
|
||||
|
||||
return {
|
||||
top,
|
||||
left: Math.min(Math.max(center, bounds.left + GAP), bounds.right - size.width - GAP),
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Show when={quote.state.text !== undefined && position()}>
|
||||
{(place) => (
|
||||
<Portal>
|
||||
<div
|
||||
ref={(element) => {
|
||||
quote.setElement(element)
|
||||
createResizeObserver(element, () => setSize({ width: element.offsetWidth, height: element.offsetHeight }))
|
||||
onCleanup(() => quote.setElement(undefined))
|
||||
}}
|
||||
data-component="timeline-quote"
|
||||
data-prevent-autofocus
|
||||
role="toolbar"
|
||||
aria-label={language.t("session.quote.actions")}
|
||||
class="fixed z-50 flex items-center gap-0.5 rounded-[8px] p-0.5 shadow-[var(--v2-elevation-raised)]"
|
||||
style={{
|
||||
top: `${place().top}px`,
|
||||
left: `${place().left}px`,
|
||||
visibility: size.height === 0 ? "hidden" : undefined,
|
||||
}}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
>
|
||||
<Show when={quote.state.truncated}>
|
||||
<span class="px-2 text-[12px] leading-[var(--line-height-compact)] text-v2-text-text-muted [font-weight:440]">
|
||||
{language.t("session.quote.tooLong")}
|
||||
</span>
|
||||
</Show>
|
||||
<Tooltip
|
||||
value={
|
||||
<>
|
||||
{language.t("session.quote.addWithComment")}
|
||||
<Keybind keys={[IS_MAC ? "⌥" : language.t("common.key.alt")]} variant="neutral" />
|
||||
</>
|
||||
}
|
||||
placement="top"
|
||||
openDelay={1200}
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
icon="outline-quote"
|
||||
disabled={quote.state.truncated}
|
||||
onClick={(event: MouseEvent) => quote.add(event.altKey)}
|
||||
>
|
||||
{language.t("session.quote.add")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
function sameRange(a: Range, b: Range) {
|
||||
return a.compareBoundaryPoints(Range.START_TO_START, b) === 0 && a.compareBoundaryPoints(Range.END_TO_END, b) === 0
|
||||
}
|
||||
|
||||
function editable(node: Node) {
|
||||
return node instanceof HTMLElement && (/^(INPUT|TEXTAREA|SELECT)$/.test(node.tagName) || node.isContentEditable)
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue