Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): drag-to-highlight in the share card

Gretna0317a2397011
diff --git a/src/web/src/components/community/message-share-dialog.tsx b/src/web/src/components/community/message-share-dialog.tsx
index 55928cdd4..27b801f04 100644
--- a/src/web/src/components/community/message-share-dialog.tsx
+++ b/src/web/src/components/community/message-share-dialog.tsx
@@ -1,15 +1,16 @@
"use client"
-import { useRef, useState } from "react"
+import { useCallback, useRef, useState } from "react"
import Image from "next/image"
import { toBlob } from "html-to-image"
import { toast } from "sonner"
-import { Check, Copy, Download, Loader2 } from "lucide-react"
+import { Check, Copy, Download, Highlighter, Loader2 } from "lucide-react"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Avatar } from "./avatar"
import { MessageBody } from "./message-body"
import { tid } from "@/lib/community/testids"
+import { applyHighlightToRange, clearHighlights, hasHighlights } from "@/lib/community/highlight-range"
import type { RenderMsg } from "./_types"
// Share a single message as an image. Renders a self-contained "share card"
@@ -24,8 +25,39 @@ export function MessageShareDialog({ m, open, onClose }: {
onClose: () => void
}) {
const cardRef = useRef<HTMLDivElement>(null)
+ // The message-body wrapper — highlight operations are scoped to it so a drag
+ // can never wrap the avatar/name/footer, only the message text.
+ const bodyRef = useRef<HTMLDivElement>(null)
const [busy, setBusy] = useState<"copy" | "download" | null>(null)
const [copied, setCopied] = useState(false)
+ // Drives the Reset button's presence. Gus (uiux #95): the button is HIDDEN
+ // (not disabled) when there's nothing to reset — "less is more". Mirrors the
+ // DOM (`mark[data-hl]` count) after each apply/reset.
+ const [highlighted, setHighlighted] = useState(false)
+
+ // On mouseup inside the body, wrap the current selection in a highlight.
+ // Text-node-level wrapping (see highlight-range.ts) — never surroundContents,
+ // so it survives spanning multiple markdown elements. Drags stack; the
+ // browser selection is collapsed afterward so it doesn't also land in the PNG.
+ const onBodyMouseUp = useCallback(() => {
+ const body = bodyRef.current
+ if (!body) return
+ const sel = window.getSelection?.()
+ if (!sel || sel.isCollapsed || sel.rangeCount === 0) return
+ const range = sel.getRangeAt(0)
+ // Ignore selections that stray outside the message body.
+ if (!body.contains(range.commonAncestorContainer)) return
+ const added = applyHighlightToRange(body, range)
+ sel.removeAllRanges()
+ if (added > 0) setHighlighted(hasHighlights(body))
+ }, [])
+
+ const resetHighlights = useCallback(() => {
+ const body = bodyRef.current
+ if (!body) return
+ clearHighlights(body)
+ setHighlighted(false)
+ }, [])
// Rasterise the card node to a PNG blob. pixelRatio 2 for a crisp image on
// retina / when pasted into other apps. `cacheBust` avoids stale cross-origin
@@ -142,7 +174,11 @@ export function MessageShareDialog({ m, open, onClose }: {
avatar/name/footer sit outside this box and stay complete.
max-h ≈ 24 lines at the body's 15px/leading-snug. */}
{m.content && (
- <div className="max-h-[31rem] overflow-hidden line-clamp-[24]">
+ <div
+ ref={bodyRef}
+ onMouseUp={onBodyMouseUp}
+ className="max-h-[31rem] overflow-hidden line-clamp-[24] [&_mark[data-hl]]:bg-[rgba(255,208,92,0.5)] [&_mark[data-hl]]:[border-radius:2px] [&_mark[data-hl]]:[padding:0_1px] [&_mark[data-hl]]:[box-decoration-break:clone] [&_mark[data-hl]]:[-webkit-box-decoration-break:clone] [&_mark[data-hl]]:text-inherit"
+ >
<MessageBody text={m.content} />
</div>
)}
@@ -163,7 +199,19 @@ export function MessageShareDialog({ m, open, onClose }: {
</div>
</div>
- <div className="flex justify-end gap-2 px-5 pt-3 pb-5">
+ <div className="flex items-center justify-between gap-2 px-5 pt-3 pb-5">
+ {/* Left slot: Reset highlight — MOUNTED only when a highlight exists
+ (Gus uiux #95: appears when useful, not a disabled ghost). Empty
+ slot otherwise keeps Download/Copy right-aligned. */}
+ <div>
+ {highlighted && (
+ <Button variant="ghost" size="sm" onClick={resetHighlights} disabled={busy !== null}>
+ <Highlighter />
+ Reset highlight
+ </Button>
+ )}
+ </div>
+ <div className="flex gap-2">
<Button variant="ghost" size="sm" onClick={download} disabled={busy !== null}>
{busy === "download" ? <Loader2 className="animate-spin" /> : <Download />}
Download
@@ -177,6 +225,7 @@ export function MessageShareDialog({ m, open, onClose }: {
{busy === "copy" ? <Loader2 className="animate-spin" /> : copied ? <Check /> : <Copy />}
{copied ? "Copied" : "Copy image"}
</Button>
+ </div>
</div>
</DialogContent>
</Dialog>
diff --git a/src/web/src/lib/community/highlight-range.test.ts b/src/web/src/lib/community/highlight-range.test.ts
new file mode 100644
index 000000000..45b760282
--- /dev/null
+++ b/src/web/src/lib/community/highlight-range.test.ts
@@ -0,0 +1,123 @@
+import { describe, it, expect } from "vitest"
+import { planHighlight, planFromCoverage, type PlanNode, type NodeCoverage } from "./highlight-range"
+
+// Pure decision layer for the share-card drag-highlight (no DOM — this repo is
+// deliberately node-only for tests, see channel-ref-extension.test.ts:51). The
+// error-prone logic (boundary clamp, whole-middle-node, overlap-skip) lives in
+// `planHighlight`; the DOM executor (`applyHighlightToRange`) is a thin,
+// mechanical layer verified by the PNG render, not unit-tested here.
+
+const n = (length: number, insideMark = false): PlanNode => ({ length, insideMark })
+
+describe("planHighlight", () => {
+ it("clamps boundary offsets on the first and last node (partial coverage)", () => {
+ // Three 10-char nodes; select from offset 4 of node0 to offset 6 of node2.
+ const nodes = [n(10), n(10), n(10)]
+ const ops = planHighlight(nodes, { startIdx: 0, startOffset: 4, endIdx: 2, endOffset: 6 })
+ expect(ops).toEqual([
+ { idx: 0, sliceStart: 4, sliceEnd: 10 }, // first node: from startOffset to end
+ { idx: 1, sliceStart: 0, sliceEnd: 10 }, // middle node: whole
+ { idx: 2, sliceStart: 0, sliceEnd: 6 }, // last node: start to endOffset
+ ])
+ })
+
+ it("wraps whole middle nodes entirely", () => {
+ const nodes = [n(5), n(8), n(5)]
+ const ops = planHighlight(nodes, { startIdx: 0, startOffset: 0, endIdx: 2, endOffset: 5 })
+ expect(ops[1]).toEqual({ idx: 1, sliceStart: 0, sliceEnd: 8 })
+ })
+
+ it("skips nodes already inside a highlight (no nesting on overlapping drags)", () => {
+ // node1 is already highlighted → it must be skipped, node0 + node2 wrapped.
+ const nodes = [n(6), n(6, true), n(6)]
+ const ops = planHighlight(nodes, { startIdx: 0, startOffset: 0, endIdx: 2, endOffset: 6 })
+ expect(ops.map((o) => o.idx)).toEqual([0, 2])
+ })
+
+ it("single-node selection wraps just the selected slice", () => {
+ const ops = planHighlight([n(20)], { startIdx: 0, startOffset: 5, endIdx: 0, endOffset: 12 })
+ expect(ops).toEqual([{ idx: 0, sliceStart: 5, sliceEnd: 12 }])
+ })
+
+ it("drops empty / zero-width slices (a boundary offset covering nothing)", () => {
+ // End at offset 0 of node1 = node1 contributes nothing; only node0 wraps.
+ const nodes = [n(10), n(10)]
+ const ops = planHighlight(nodes, { startIdx: 0, startOffset: 0, endIdx: 1, endOffset: 0 })
+ expect(ops).toEqual([{ idx: 0, sliceStart: 0, sliceEnd: 10 }])
+ })
+
+ it("clamps offsets that exceed node length (defensive)", () => {
+ const ops = planHighlight([n(5)], { startIdx: 0, startOffset: 0, endIdx: 0, endOffset: 99 })
+ expect(ops).toEqual([{ idx: 0, sliceStart: 0, sliceEnd: 5 }])
+ })
+
+ it("returns nothing for an inverted range", () => {
+ expect(planHighlight([n(5), n(5)], { startIdx: 1, startOffset: 0, endIdx: 0, endOffset: 5 })).toEqual([])
+ })
+
+ it("returns nothing when every covered node is already highlighted", () => {
+ const nodes = [n(5, true), n(5, true)]
+ expect(planHighlight(nodes, { startIdx: 0, startOffset: 0, endIdx: 1, endOffset: 5 })).toEqual([])
+ })
+})
+
+// Coverage → plan (the element-boundary decision, previously the broken
+// DOM-side `findIdx`). Shelly #334: triple-click a <p> / select-all land BOTH
+// range endpoints on elements → every covered text node between first and last
+// must be included, not just the first.
+const cov = (
+ length: number,
+ covered: boolean,
+ extra?: { insideMark?: boolean; startOffset?: number; endOffset?: number },
+): NodeCoverage => ({ length, covered, insideMark: extra?.insideMark ?? false, ...extra })
+
+describe("planFromCoverage", () => {
+ it("triple-click a <p>: all three covered text nodes wrap (regression for the boundary bug)", () => {
+ // "Hello " / "bold" / " world" — both endpoints on the <p> element, so no
+ // per-node startOffset/endOffset; all three are `covered`.
+ const nodes = [cov(6, true), cov(4, true), cov(6, true)]
+ const ops = planFromCoverage(nodes)
+ expect(ops).toEqual([
+ { idx: 0, sliceStart: 0, sliceEnd: 6 },
+ { idx: 1, sliceStart: 0, sliceEnd: 4 },
+ { idx: 2, sliceStart: 0, sliceEnd: 6 },
+ ])
+ })
+
+ it("select-all: every covered node across blocks wraps", () => {
+ const nodes = [cov(5, true), cov(5, true), cov(5, true), cov(5, true)]
+ expect(planFromCoverage(nodes).map((o) => o.idx)).toEqual([0, 1, 2, 3])
+ })
+
+ it("text-boundary drag: honors per-node start/end offsets, ignores uncovered tail", () => {
+ // Drag from offset 2 of node0 through node1 to offset 3 of node2; node3 not covered.
+ const nodes = [
+ cov(6, true, { startOffset: 2 }),
+ cov(4, true),
+ cov(6, true, { endOffset: 3 }),
+ cov(6, false),
+ ]
+ expect(planFromCoverage(nodes)).toEqual([
+ { idx: 0, sliceStart: 2, sliceEnd: 6 },
+ { idx: 1, sliceStart: 0, sliceEnd: 4 },
+ { idx: 2, sliceStart: 0, sliceEnd: 3 },
+ ])
+ })
+
+ it("skips an already-highlighted node in the middle of a select-all", () => {
+ const nodes = [cov(5, true), cov(5, true, { insideMark: true }), cov(5, true)]
+ expect(planFromCoverage(nodes).map((o) => o.idx)).toEqual([0, 2])
+ })
+
+ it("returns nothing when no node is covered", () => {
+ expect(planFromCoverage([cov(5, false), cov(5, false)])).toEqual([])
+ })
+
+ it("gap in coverage still spans first→last covered (contiguous range assumption)", () => {
+ // A real selection is contiguous; if the middle shows uncovered (shouldn't
+ // happen), first→last still defines the span and planHighlight wraps the
+ // covered ends. Guards the first/last scan logic.
+ const nodes = [cov(5, true), cov(5, false), cov(5, true)]
+ expect(planFromCoverage(nodes).map((o) => o.idx)).toEqual([0, 1, 2])
+ })
+})
diff --git a/src/web/src/lib/community/highlight-range.ts b/src/web/src/lib/community/highlight-range.ts
new file mode 100644
index 000000000..2ba387c49
--- /dev/null
+++ b/src/web/src/lib/community/highlight-range.ts
@@ -0,0 +1,213 @@
+// Drag-to-highlight for the share card (plans/share-card-drag-highlight.md).
+//
+// The card body is Streamdown-rendered rich markdown — a DOM tree of
+// <p>/<strong>/<em>/<a>/… A user's text selection can span multiple elements,
+// so we CANNOT `range.surroundContents()` (it throws on a range that partially
+// selects a non-Text node). Instead we wrap only the TEXT NODES the selection
+// covers (splitting the boundary nodes so only the selected slice is wrapped)
+// in a `<mark>`. The mark is a plain DOM element with a CSS background, so
+// html-to-image rasterises it into the exported PNG (WYSIWYG).
+//
+// Two layers (this repo is deliberately node-only for tests — no jsdom, see
+// channel-ref-extension.test.ts:51 — so all the ERROR-PRONE logic lives in a
+// pure, DOM-free decision layer that's unit-tested; the DOM layer is a thin,
+// mechanical executor verified by the PNG render):
+// 1. `planHighlight(nodes, range)` — PURE. Models the covered text nodes as
+// plain data, returns a wrap plan (which node, which slice). Boundary
+// offset clamping, whole-middle-node coverage, and overlap-skip (a node
+// already inside a highlight) are all decided here.
+// 2. `applyHighlightToRange` / `clearHighlights` — DOM. Read the live range
+// into the plan's data shape, execute the plan (splitText + wrap), and
+// unwrap+normalize on reset.
+
+// Class + marker attribute on every highlight wrapper we create. The dialog
+// styles the mark via the `[data-hl]` attribute selector; the class is a
+// human-readable hook (not required for styling), kept module-local so it
+// isn't an unused public export (knip gate).
+const HIGHLIGHT_CLASS = "share-hl"
+const HIGHLIGHT_ATTR = "data-hl"
+
+// ── Pure decision layer (DOM-free, unit-tested) ────────────────────────────
+
+/** A text node modeled as data: its text length + whether it already sits
+ * inside an existing highlight (those are skipped so drags don't nest marks). */
+export type PlanNode = { length: number; insideMark: boolean }
+
+/** The selection, expressed as indices into the `PlanNode[]` array + offsets
+ * within the boundary nodes (mirrors a DOM Range's start/end container+offset,
+ * but resolved to array indices). */
+export type PlanRange = {
+ startIdx: number
+ startOffset: number
+ endIdx: number
+ endOffset: number
+}
+
+/** One wrap instruction: wrap `[sliceStart, sliceEnd)` of node `idx`. A slice
+ * covering the whole node is `sliceStart === 0 && sliceEnd === length`. */
+export type WrapOp = { idx: number; sliceStart: number; sliceEnd: number }
+
+/** Per-text-node coverage, computed from the live Range by the DOM layer and
+ * fed to the pure resolver. `covered` = the range intersects this node.
+ * `startOffset`/`endOffset` are set only when the node is the range's boundary
+ * text node (start offset on the first boundary, end offset on the last);
+ * undefined means "boundary landed on an element, use the whole node". */
+export type NodeCoverage = {
+ length: number
+ insideMark: boolean
+ covered: boolean
+ startOffset?: number
+ endOffset?: number
+}
+
+/**
+ * PURE. Turn per-node coverage into a `PlanRange` (first→last covered node,
+ * with boundary offsets), then delegate to `planHighlight`. This is where the
+ * element-boundary decision lives — a triple-click / select-all lands both
+ * range endpoints on elements, so EVERY covered text node between the first
+ * and last must be included (the old DOM-side `findIdx` collapsed end→first
+ * covered node, dropping everything after the first). Returns [] if nothing is
+ * covered.
+ */
+export function planFromCoverage(nodes: NodeCoverage[]): WrapOp[] {
+ let startIdx = -1
+ let endIdx = -1
+ for (let i = 0; i < nodes.length; i++) {
+ if (nodes[i].covered) {
+ if (startIdx === -1) startIdx = i
+ endIdx = i
+ }
+ }
+ if (startIdx === -1) return []
+ const startOffset = nodes[startIdx].startOffset ?? 0
+ const endOffset = nodes[endIdx].endOffset ?? nodes[endIdx].length
+ return planHighlight(nodes, { startIdx, startOffset, endIdx, endOffset })
+}
+
+/**
+ * PURE. Decide which slices of which text nodes to wrap for a selection.
+ * - Clamps the boundary offsets to the covered range (start node from
+ * `startOffset`, end node up to `endOffset`; middle nodes fully).
+ * - Skips nodes already inside a highlight (`insideMark`) — no nesting.
+ * - Skips empty slices (e.g. a boundary offset that covers nothing).
+ * Returns wrap ops in document order (0 if the range covers nothing new).
+ */
+export function planHighlight(nodes: PlanNode[], range: PlanRange): WrapOp[] {
+ const { startIdx, startOffset, endIdx, endOffset } = range
+ if (startIdx > endIdx) return []
+ const ops: WrapOp[] = []
+ for (let idx = startIdx; idx <= endIdx; idx++) {
+ const node = nodes[idx]
+ if (!node || node.insideMark) continue
+ const sliceStart = idx === startIdx ? startOffset : 0
+ const sliceEnd = idx === endIdx ? endOffset : node.length
+ // Clamp defensively and drop empty/inverted slices.
+ const lo = Math.max(0, Math.min(sliceStart, node.length))
+ const hi = Math.max(0, Math.min(sliceEnd, node.length))
+ if (hi > lo) ops.push({ idx, sliceStart: lo, sliceEnd: hi })
+ }
+ return ops
+}
+
+// ── DOM application layer (thin, mechanical) ───────────────────────────────
+
+function isInsideHighlight(node: Node): boolean {
+ let el: Node | null = node.parentNode
+ const stop = node.ownerDocument?.body ?? null
+ while (el && el !== stop) {
+ if (el.nodeType === 1 && (el as Element).hasAttribute?.(HIGHLIGHT_ATTR)) return true
+ el = el.parentNode
+ }
+ return false
+}
+
+/** All Text nodes under `container`, in document order. */
+function textNodesUnder(container: Node): Text[] {
+ const doc = container.ownerDocument ?? document
+ const walker = doc.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
+ acceptNode: (n) => ((n as Text).data.length ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT),
+ })
+ const out: Text[] = []
+ let n = walker.nextNode()
+ while (n) {
+ out.push(n as Text)
+ n = walker.nextNode()
+ }
+ return out
+}
+
+function wrapSlice(text: Text, sliceStart: number, sliceEnd: number): void {
+ // Isolate the slice as its own text node: split off the tail first (so the
+ // head offset stays valid), then the head.
+ let node = text
+ if (sliceEnd < node.data.length) node.splitText(sliceEnd)
+ if (sliceStart > 0) node = node.splitText(sliceStart)
+ const mark = (node.ownerDocument ?? document).createElement("mark")
+ mark.setAttribute(HIGHLIGHT_ATTR, "")
+ mark.className = HIGHLIGHT_CLASS
+ node.parentNode?.replaceChild(mark, node)
+ mark.appendChild(node)
+}
+
+/**
+ * Highlight the portion of `container` covered by `range`. Resolves the live
+ * range to the pure layer's data shape, plans the wraps, then executes them
+ * (right-to-left so earlier splits don't invalidate later node references).
+ * Returns the number of `<mark>`s created.
+ */
+export function applyHighlightToRange(container: Node, range: Range): number {
+ if (range.collapsed) return 0
+ const nodes = textNodesUnder(container)
+ if (nodes.length === 0) return 0
+
+ // DOM layer's ONLY job: compute per-node coverage as plain data. Which nodes
+ // to wrap (and how the element-boundary endpoints resolve) is decided purely
+ // in `planFromCoverage` — so a triple-click / select-all (both endpoints on
+ // elements) is handled by tested logic, not this thin executor.
+ const coverage: NodeCoverage[] = nodes.map((t) => {
+ // A node is covered iff the range intersects it. `intersectsNode` exists in
+ // browsers; fall back to comparePoint if absent.
+ const covered =
+ typeof range.intersectsNode === "function"
+ ? range.intersectsNode(t)
+ : range.comparePoint(t, 0) === 0 || range.comparePoint(t, t.data.length) === 0
+ return {
+ length: t.data.length,
+ insideMark: isInsideHighlight(t),
+ covered,
+ // Boundary offsets only when THIS node is the range's start/end text
+ // node; an element-boundary endpoint leaves them undefined → whole node.
+ ...(t === range.startContainer ? { startOffset: range.startOffset } : {}),
+ ...(t === range.endContainer ? { endOffset: range.endOffset } : {}),
+ }
+ })
+
+ const ops = planFromCoverage(coverage)
+ // Execute right-to-left so an earlier op's splitText can't shift a later
+ // op's node reference (each op targets a distinct original node anyway).
+ for (let i = ops.length - 1; i >= 0; i--) {
+ const op = ops[i]
+ wrapSlice(nodes[op.idx], op.sliceStart, op.sliceEnd)
+ }
+ return ops.length
+}
+
+/**
+ * Remove every highlight wrapper inside `container`, restoring the original
+ * text, and merge adjacent text nodes so a subsequent highlight round is clean.
+ */
+export function clearHighlights(container: Element): void {
+ const marks = container.querySelectorAll(`mark[${HIGHLIGHT_ATTR}]`)
+ marks.forEach((mark) => {
+ const parent = mark.parentNode
+ if (!parent) return
+ while (mark.firstChild) parent.insertBefore(mark.firstChild, mark)
+ parent.removeChild(mark)
+ })
+ container.normalize()
+}
+
+/** Whether `container` currently holds any highlight. */
+export function hasHighlights(container: Element): boolean {
+ return container.querySelector(`mark[${HIGHLIGHT_ATTR}]`) !== null
+}