Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): add Cmd+F in-page find to issue detail (MUL-4126) (#4989)
Bohan Jiangbcad2edc9e7d
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.cssindex de5a470670..0c53175b43 100644--- a/packages/ui/styles/base.css+++ b/packages/ui/styles/base.css@@ -278,3 +278,17 @@}}}++/* In-page find (Cmd/Ctrl+F on the issue detail page). Matches are painted with+ * the CSS Custom Highlight API — ranges only, no DOM mutation — so the tint+ * layers cleanly over React-rendered markdown and the contenteditable+ * title/description editors. `multica-find-active` is registered with a higher+ * priority so the current match paints on top of the dimmer all-matches tint. */+::highlight(multica-find) {+ background-color: var(--find-match);+ color: var(--find-match-foreground);+}+::highlight(multica-find-active) {+ background-color: var(--find-match-active);+ color: var(--find-match-foreground);+}diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.cssindex a4a21e689e..ab16eff53d 100644--- a/packages/ui/styles/tokens.css+++ b/packages/ui/styles/tokens.css@@ -96,6 +96,12 @@--scrollbar-thumb: oklch(0 0 0 / 10%);--scrollbar-thumb-hover: oklch(0 0 0 / 18%);--scrollbar-track: transparent;+ /* In-page find (Cmd/Ctrl+F) match tints, painted via the CSS Custom+ Highlight API. Bright fill + dark text so matches stay legible in+ both themes; the active match steps to orange. */+ --find-match: oklch(0.92 0.15 100);+ --find-match-active: oklch(0.82 0.17 62);+ --find-match-foreground: oklch(0.22 0.03 92);}.dark {@@ -142,4 +148,7 @@--scrollbar-thumb: oklch(1 0 0 / 8%);--scrollbar-thumb-hover: oklch(1 0 0 / 18%);--scrollbar-track: transparent;+ --find-match: oklch(0.82 0.16 100);+ --find-match-active: oklch(0.76 0.18 60);+ --find-match-foreground: oklch(0.18 0.02 92);}diff --git a/packages/views/issues/components/find-bar.tsx b/packages/views/issues/components/find-bar.tsxnew file mode 100644index 0000000000..b6f6e48716--- /dev/null+++ b/packages/views/issues/components/find-bar.tsx@@ -0,0 +1,116 @@+"use client";++import type { KeyboardEvent } from "react";+import { ChevronDown, ChevronUp, Search, X } from "lucide-react";+import { Input } from "@multica/ui/components/ui/input";+import { Button } from "@multica/ui/components/ui/button";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";+import type { UseInPageFindResult } from "../hooks/use-in-page-find";++// Floating find-in-page bar for the issue detail page. Presentational — all+// search state, highlighting, and scrolling live in `useInPageFind`. Rendered+// only while `find.open`, so the input's autoFocus fires on every open.+//+// `data-find-ignore` keeps the bar's own text out of the match walk.+export function FindBar({+ find,+ className,+}: {+ find: UseInPageFindResult;+ className?: string;+}) {+ const { t } = useT("issues");+ const {+ query,+ matchCount,+ activeIndex,+ setQuery,+ closeFind,+ goNext,+ goPrev,+ inputRef,+ } = find;++ const hasQuery = query.trim().length > 0;+ const countLabel = !hasQuery+ ? ""+ : matchCount === 0+ ? t(($) => $.detail.find.no_matches)+ : t(($) => $.detail.find.count, {+ current: activeIndex + 1,+ total: matchCount,+ });+ const noMatches = matchCount === 0;++ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter") {+ e.preventDefault();+ if (e.shiftKey) goPrev();+ else goNext();+ } else if (e.key === "Escape") {+ e.preventDefault();+ closeFind();+ }+ };++ return (+ <div+ data-find-ignore+ role="search"+ className={cn(+ "flex items-center gap-1 rounded-lg border bg-popover/95 p-1 pl-2 shadow-md backdrop-blur supports-[backdrop-filter]:bg-popover/80",+ className,+ )}+ >+ <Search className="size-3.5 shrink-0 text-muted-foreground" />+ <Input+ ref={inputRef}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={handleKeyDown}+ autoFocus+ placeholder={t(($) => $.detail.find.placeholder)}+ aria-label={t(($) => $.detail.find.placeholder)}+ className="h-7 w-44 border-0 bg-transparent px-1 shadow-none focus-visible:ring-0"+ />+ <span className="min-w-[3.5rem] shrink-0 whitespace-nowrap text-right text-xs tabular-nums text-muted-foreground">+ {countLabel}+ </span>+ <div className="flex items-center">+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ disabled={noMatches}+ onClick={goPrev}+ aria-label={t(($) => $.detail.find.previous)}+ title={t(($) => $.detail.find.previous)}+ >+ <ChevronUp />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ disabled={noMatches}+ onClick={goNext}+ aria-label={t(($) => $.detail.find.next)}+ title={t(($) => $.detail.find.next)}+ >+ <ChevronDown />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ onClick={closeFind}+ aria-label={t(($) => $.detail.find.close)}+ title={t(($) => $.detail.find.close)}+ >+ <X />+ </Button>+ </div>+ </div>+ );+}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 880db5af32..aa8a853f01 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -90,6 +90,8 @@ import { ProgressRing } from "./progress-ring";import { matchesPinyin } from "../../editor/extensions/pinyin-match";import { useT } from "../../i18n";import { useIssueDetailScrollRestore } from "../hooks/use-issue-detail-scroll-restore";+import { useInPageFind } from "../hooks/use-in-page-find";+import { FindBar } from "./find-bar";import {AnimatedRightSidebar,getAnimatedRightSidebarInitialOpen,@@ -1027,6 +1029,22 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr[timelineView.groups, expandedResolved],);+ // In-page find (Cmd/Ctrl+F). `items.length` is the content signal that+ // triggers a match recompute when comments are added/removed; text edits+ // are caught by the hook's own MutationObserver. Opening find forces the+ // timeline to render flat below so every comment is in the DOM to match.+ const find = useInPageFind({+ container: scrollContainerEl,+ contentKey: items.length,+ enabled: !!issue,+ });+ // Close the bar (and drop highlights) when navigating to another issue —+ // the web route reuses this component instead of remounting.+ const closeFind = find.closeFind;+ useEffect(() => {+ closeFind();+ }, [id, closeFind]);+// ID of the trailing activity block — the only one expanded by default.const lastActivityGroupId = useMemo(() => {for (let i = timelineView.groups.length - 1; i >= 0; i--) {@@ -1217,27 +1235,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr};}, [highlightCommentId, items, targetIdx, scrollContainerEl, replyToRoot, expandedResolved, timelineView, toggleResolvedExpand]);- // Cmd-F / Ctrl-F on a virtualized timeline only searches what's mounted in- // the viewport — off-screen comments are invisible to browser find-in-page.- // Intercept once per (session, issue) when the list is long enough that the- // user might actually try; let the keystroke pass through on short lists.- // Real fix is in-app search (separate PR); this is the toast stopgap.- useEffect(() => {- if (items.length <= 30) return;- const flagKey = `multica_cmdF_warned:${id}`;- const handler = (e: KeyboardEvent) => {- if (e.key !== "f" || !(e.metaKey || e.ctrlKey)) return;- if (sessionStorage.getItem(flagKey)) return;- e.preventDefault();- sessionStorage.setItem(flagKey, "1");- toast.message(t(($) => $.detail.cmdf_toast_title), {- description: t(($) => $.detail.cmdf_toast_description),- });- };- document.addEventListener("keydown", handler);- return () => document.removeEventListener("keydown", handler);- }, [id, items.length, t]);-const descEditorRef = useRef<ContentEditorRef>(null);const { isDragOver: descDragOver, dropZoneProps: descDropZoneProps } = useFileDropZone({onDrop: (files) => files.forEach((f) => descEditorRef.current?.uploadFile(f)),@@ -1796,7 +1793,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr: [];const detailContent = (- <div className="flex h-full min-w-0 flex-1 flex-col">+ <div className="relative flex h-full min-w-0 flex-1 flex-col">+ {/* In-page find bar — floats over the top-right of the content column+ (below the breadcrumb header), outside the scroll container so it+ stays put while the timeline scrolls and its own text isn't walked. */}+ {find.open && (+ <FindBar find={find} className="absolute right-4 top-14 z-20" />+ )}<BreadcrumbHeadersegments={breadcrumbSegments}leaf={@@ -2173,6 +2176,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// proportional to items.length (markdown + lowlight per// comment), which is acceptable in the deep-link case —// the user has explicit intent to land on a specific item.+ // - `find.open` (in-page Cmd/Ctrl+F) → also render flat, so+ // every comment is in the DOM for the find walk to match+ // and highlight. Same explicit-intent cold-mount trade-off.// - otherwise → Virtuoso. Browsing mode, virtualization// wins on first-paint perf for long timelines.//@@ -2180,7 +2186,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// on a target" have fundamentally opposed contracts (estimated// heights vs real heights). Trying to satisfy both in one// path is what produced the bug history this PR closes.- !highlightCommentId ? (+ !highlightCommentId && !find.open ? (!scrollContainerEl ? (// Skeleton while the callback ref populates so the gap// between IssueDetail mount and Virtuoso mount doesn'tdiff --git a/packages/views/issues/hooks/index.ts b/packages/views/issues/hooks/index.tsindex c7703d271b..52a39c8ea1 100644--- a/packages/views/issues/hooks/index.ts+++ b/packages/views/issues/hooks/index.ts@@ -2,3 +2,4 @@ export { useIssueTimeline } from "./use-issue-timeline";export { useIssueReactions } from "./use-issue-reactions";export { useIssueSubscribers } from "./use-issue-subscribers";export { useIssueDetailScrollRestore } from "./use-issue-detail-scroll-restore";+export { useInPageFind } from "./use-in-page-find";diff --git a/packages/views/issues/hooks/use-in-page-find.test.ts b/packages/views/issues/hooks/use-in-page-find.test.tsnew file mode 100644index 0000000000..dd6052e587--- /dev/null+++ b/packages/views/issues/hooks/use-in-page-find.test.ts@@ -0,0 +1,131 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { collectTextMatches, useInPageFind } from "./use-in-page-find";++function makeRoot(html: string): HTMLElement {+ const root = document.createElement("div");+ root.innerHTML = html;+ return root;+}++describe("collectTextMatches", () => {+ it("returns nothing for an empty query", () => {+ expect(collectTextMatches(makeRoot("<p>hello</p>"), "")).toEqual([]);+ });++ it("returns nothing when the query is not present", () => {+ expect(collectTextMatches(makeRoot("<p>hello</p>"), "zzz")).toEqual([]);+ });++ it("finds a case-insensitive match with node offsets", () => {+ const matches = collectTextMatches(makeRoot("<p>Hello World</p>"), "world");+ expect(matches).toHaveLength(1);+ expect(matches[0]!.node.nodeValue).toBe("Hello World");+ expect(matches[0]!.start).toBe(6);+ expect(matches[0]!.end).toBe(11);+ });++ it("finds every non-overlapping occurrence in one node, in order", () => {+ const matches = collectTextMatches(makeRoot("<p>ababab</p>"), "ab");+ expect(matches.map((m) => m.start)).toEqual([0, 2, 4]);+ });++ it("does not overlap on repeated characters", () => {+ const matches = collectTextMatches(makeRoot("<p>aaaa</p>"), "aa");+ expect(matches.map((m) => m.start)).toEqual([0, 2]);+ });++ it("matches inside separate text nodes but never across an element boundary", () => {+ // Text nodes: "foo ", "bar", " foobar". "foo" hits the first and third,+ // and the "bar" split across <strong> is never joined into a match.+ const root = makeRoot("<p>foo <strong>bar</strong> foobar</p>");+ const matches = collectTextMatches(root, "foo");+ expect(matches).toHaveLength(2);+ expect(collectTextMatches(root, "foobar")).toHaveLength(1);+ });++ it("skips <script> and <style> text", () => {+ const root = makeRoot(+ "<style>needle{}</style><script>needle</script><p>needle</p>",+ );+ const matches = collectTextMatches(root, "needle");+ expect(matches).toHaveLength(1);+ expect(matches[0]!.node.parentElement?.tagName).toBe("P");+ });++ it("skips subtrees marked data-find-ignore (e.g. the find bar itself)", () => {+ const root = makeRoot(+ '<div data-find-ignore><span>needle</span></div><p>needle</p>',+ );+ const matches = collectTextMatches(root, "needle");+ expect(matches).toHaveLength(1);+ expect(matches[0]!.node.parentElement?.tagName).toBe("P");+ });+});++// jsdom implements neither `CSS.highlights` nor `Highlight`, so the hook runs+// here exactly as it would on a browser without the CSS Custom Highlight API.+// This is the regression from the review: counting and prev/next navigation+// must keep working even though nothing gets painted.+describe("useInPageFind without the CSS Custom Highlight API", () => {+ let container: HTMLElement;++ beforeEach(() => {+ // jsdom lays nothing out and doesn't implement Range.getClientRects, which+ // the scroll-to-match path now calls in every browser. Return a single+ // zero-size rect so scrollRangeIntoView no-ops instead of throwing.+ (Range.prototype as { getClientRects: () => DOMRectList }).getClientRects =+ () =>+ [+ { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 },+ ] as unknown as DOMRectList;+ container = document.createElement("div");+ container.innerHTML = "<h1>Find me</h1><p>find me twice: find</p>";+ document.body.appendChild(container);+ });++ afterEach(() => {+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;+ container.remove();+ });++ // Flush the rAF-deferred recompute(s) the open/content effects schedule.+ async function flushFrames(count = 3): Promise<void> {+ for (let i = 0; i < count; i++) {+ await act(+ () =>+ new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),+ );+ }+ }++ it("counts matches and steps through them when highlighting is unavailable", async () => {+ const { result } = renderHook(() =>+ useInPageFind({ container, contentKey: 0 }),+ );++ expect(result.current.supported).toBe(false);++ act(() => {+ result.current.openFind();+ result.current.setQuery("find");+ });+ await flushFrames();++ // "find" appears once in the heading and twice in the paragraph.+ expect(result.current.matchCount).toBe(3);+ expect(result.current.activeIndex).toBe(0);++ act(() => result.current.goNext());+ expect(result.current.activeIndex).toBe(1);++ act(() => result.current.goPrev());+ act(() => result.current.goPrev());+ expect(result.current.activeIndex).toBe(2); // wraps past the start++ act(() => result.current.setQuery("absent"));+ await flushFrames();+ expect(result.current.matchCount).toBe(0);+ expect(result.current.activeIndex).toBe(-1);+ });+});diff --git a/packages/views/issues/hooks/use-in-page-find.ts b/packages/views/issues/hooks/use-in-page-find.tsnew file mode 100644index 0000000000..7b5154a1db--- /dev/null+++ b/packages/views/issues/hooks/use-in-page-find.ts@@ -0,0 +1,327 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++// ---------------------------------------------------------------------------+// In-page find (Cmd/Ctrl+F) for the issue detail page.+//+// The comment timeline is virtualized, so native browser find only sees the+// handful of comments mounted in the viewport. This hook powers a real+// find-in-page bar: the host force-renders the timeline flat while find is+// open (so every comment is in the DOM), and matches are painted with the+// CSS Custom Highlight API — ranges only, never DOM mutation, so it works+// over React-rendered markdown AND the contenteditable title/description+// editors without fighting ProseMirror.+// ---------------------------------------------------------------------------++const HIGHLIGHT_NAME = "multica-find";+const ACTIVE_HIGHLIGHT_NAME = "multica-find-active";++// Feature detection, evaluated lazily per call site. On browsers without the+// CSS Custom Highlight API the bar still opens and navigates, it just paints+// no tint. Guard `CSS`/`Highlight` for SSR too (no `window`).+function highlightApiSupported(): boolean {+ return (+ typeof CSS !== "undefined" &&+ "highlights" in CSS &&+ typeof Highlight !== "undefined"+ );+}++// Element text we never search.+const SKIP_TAGS = new Set(["SCRIPT", "STYLE", "NOSCRIPT"]);++export interface TextMatch {+ node: Text;+ start: number;+ end: number;+}++// Walk every visible text node under `root` and return each case-insensitive+// occurrence of `query`, in document order. Matches are confined to a single+// text node — a query straddling an element boundary (e.g. across a bold run)+// is not found, which is the standard trade-off for lightweight find.+//+// Pure and DOM-only (no React / no CSS API) so it is unit-testable in jsdom.+export function collectTextMatches(root: HTMLElement, query: string): TextMatch[] {+ const matches: TextMatch[] = [];+ const needle = query.toLowerCase();+ if (!needle) return matches;++ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {+ acceptNode(node) {+ const parent = node.parentElement;+ if (!parent) return NodeFilter.FILTER_REJECT;+ if (SKIP_TAGS.has(parent.tagName)) return NodeFilter.FILTER_REJECT;+ if (parent.closest("[data-find-ignore]")) return NodeFilter.FILTER_REJECT;+ const value = node.nodeValue;+ if (!value || value.trim().length === 0) return NodeFilter.FILTER_REJECT;+ return NodeFilter.FILTER_ACCEPT;+ },+ });++ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const textNode = node as Text;+ const haystack = (textNode.nodeValue ?? "").toLowerCase();+ let index = haystack.indexOf(needle);+ while (index !== -1) {+ matches.push({ node: textNode, start: index, end: index + needle.length });+ index = haystack.indexOf(needle, index + needle.length);+ }+ }++ return matches;+}++function isElementVisible(el: HTMLElement | null): boolean {+ return !!el && el.getClientRects().length > 0;+}++// Bring `range` into view by driving the scroll container's scrollTop directly.+// Never native scrollIntoView: on this page it propagates to the desktop shell+// wrapper and shoves the whole view off-screen (#3929). Only scrolls when the+// match is actually outside the comfortable viewport band.+function scrollRangeIntoView(container: HTMLElement | null, range: Range): void {+ if (!container) return;+ const rects = range.getClientRects();+ const rect = rects.length > 0 ? rects[0]! : range.getBoundingClientRect();+ if (!rect || (rect.width === 0 && rect.height === 0)) return;++ const containerRect = container.getBoundingClientRect();+ const pad = 80;+ const above = rect.top < containerRect.top + pad;+ const below = rect.bottom > containerRect.bottom - pad;+ if (!above && !below) return;++ const offsetWithin = rect.top - containerRect.top + container.scrollTop;+ const target = offsetWithin - container.clientHeight / 2 + rect.height / 2;+ container.scrollTop = Math.max(0, target);+}++export interface UseInPageFindResult {+ open: boolean;+ query: string;+ /** Total number of matches for the current query. */+ matchCount: number;+ /** 0-based index of the active match, or -1 when there are none. */+ activeIndex: number;+ /** Whether the CSS Custom Highlight API is available in this browser. */+ supported: boolean;+ inputRef: React.RefObject<HTMLInputElement | null>;+ setQuery: (value: string) => void;+ openFind: () => void;+ closeFind: () => void;+ goNext: () => void;+ goPrev: () => void;+}++export function useInPageFind(options: {+ /** The scroll container whose text is searched. */+ container: HTMLElement | null;+ /**+ * A value that changes whenever searchable content changes (e.g. timeline+ * length). Triggers a match recompute after the DOM settles.+ */+ contentKey: unknown;+ /** When false, the Cmd/Ctrl+F shortcut is inert (e.g. issue still loading). */+ enabled?: boolean;+}): UseInPageFindResult {+ const { container, contentKey, enabled = true } = options;++ const [open, setOpen] = useState(false);+ const [query, setQueryState] = useState("");+ const [matchCount, setMatchCount] = useState(0);+ const [activeIndex, setActiveIndex] = useState(-1);++ const inputRef = useRef<HTMLInputElement | null>(null);+ const containerRef = useRef<HTMLElement | null>(container);+ containerRef.current = container;+ const rangesRef = useRef<Range[]>([]);+ const activeIndexRef = useRef(activeIndex);+ activeIndexRef.current = activeIndex;+ const supported = highlightApiSupported();++ const clearHighlights = useCallback(() => {+ if (!supported) return;+ CSS.highlights.delete(HIGHLIGHT_NAME);+ CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);+ }, [supported]);++ // Paint the active match on top of the all-matches tint (higher priority)+ // and, when asked, bring it into view. Called both when the user navigates+ // and after a recompute, so the active tint always tracks live ranges — a+ // range that went stale (async re-highlight replacing text nodes) is+ // replaced even when the total match count is unchanged.+ const applyActive = useCallback(+ (ranges: Range[], index: number, scroll: boolean) => {+ const range = index >= 0 ? ranges[index] : undefined;+ // Painting the active tint is the only highlight-API-only step. Active+ // tracking and scroll-to-match must keep working on browsers without the+ // CSS Custom Highlight API, otherwise prev/next would open the bar but+ // never move the view.+ if (supported) {+ if (range) {+ const active = new Highlight(range);+ active.priority = 1;+ CSS.highlights.set(ACTIVE_HIGHLIGHT_NAME, active);+ } else {+ CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);+ }+ }+ if (range && scroll) scrollRangeIntoView(containerRef.current, range);+ },+ [supported],+ );++ // Rebuild the match set from the live DOM. `resetActive` starts navigation+ // over at the first match (query changed); otherwise the active index is+ // preserved as content shifts underneath (streaming comment, re-highlight).+ const recompute = useCallback(+ (resetActive: boolean) => {+ const root = containerRef.current;+ if (!open || !root || query.trim().length === 0) {+ rangesRef.current = [];+ clearHighlights();+ setMatchCount(0);+ setActiveIndex(-1);+ return;+ }++ const matches = collectTextMatches(root, query);+ const ranges = matches.map((m) => {+ const range = new Range();+ range.setStart(m.node, m.start);+ range.setEnd(m.node, m.end);+ return range;+ });+ rangesRef.current = ranges;++ if (ranges.length === 0) {+ clearHighlights();+ setMatchCount(0);+ setActiveIndex(-1);+ return;+ }++ if (supported) {+ CSS.highlights.set(HIGHLIGHT_NAME, new Highlight(...ranges));+ }+ setMatchCount(ranges.length);+ const prev = activeIndexRef.current;+ const nextActive =+ resetActive || prev < 0 ? 0 : Math.min(prev, ranges.length - 1);+ setActiveIndex(nextActive);+ // Scroll only when the query changed (resetActive) — never yank the view+ // while content mutates underneath a fixed active match.+ applyActive(ranges, nextActive, resetActive);+ },+ [open, query, supported, clearHighlights, applyActive],+ );++ const recomputeRef = useRef(recompute);+ recomputeRef.current = recompute;++ // Recompute when the query changes or the bar opens/closes → restart at the+ // first match. Deferred a frame so the flat (non-virtualized) render the host+ // switches to on open has committed before we walk the DOM.+ useEffect(() => {+ const raf = requestAnimationFrame(() => recomputeRef.current(true));+ return () => cancelAnimationFrame(raf);+ }, [open, query, container]);++ // Recompute when searchable content changes, keeping the active match.+ useEffect(() => {+ if (!open) return;+ const raf = requestAnimationFrame(() => recomputeRef.current(false));+ return () => cancelAnimationFrame(raf);+ }, [contentKey, open]);++ // Async DOM churn (markdown/code highlight settling, streamed replies)+ // invalidates the ranges; re-derive them, coalescing bursts into one frame.+ // Runs regardless of highlight support so fallback counting/navigation stay+ // in sync with the live DOM.+ useEffect(() => {+ if (!open || !container) return;+ let raf = 0;+ const observer = new MutationObserver(() => {+ cancelAnimationFrame(raf);+ raf = requestAnimationFrame(() => recomputeRef.current(false));+ });+ observer.observe(container, {+ subtree: true,+ childList: true,+ characterData: true,+ });+ return () => {+ observer.disconnect();+ cancelAnimationFrame(raf);+ };+ }, [open, container]);++ // Move the active tint and scroll when the user steps between matches.+ // (Recompute handles the active tint for content-driven changes.)+ useEffect(() => {+ if (!open) return;+ applyActive(rangesRef.current, activeIndex, true);+ }, [activeIndex, open, applyActive]);++ // Global Cmd/Ctrl+F. The listener is scoped to the mounted issue detail; on+ // desktop, <Activity> cycles this effect with tab visibility, so only the+ // visible tab intercepts the key. The visibility guard is defensive.+ useEffect(() => {+ if (!enabled) return;+ const onKeyDown = (e: KeyboardEvent) => {+ if (!(e.metaKey || e.ctrlKey) || e.altKey) return;+ if (e.key !== "f" && e.key !== "F") return;+ if (!isElementVisible(containerRef.current)) return;+ e.preventDefault();+ setOpen(true);+ requestAnimationFrame(() => {+ const input = inputRef.current;+ if (input) {+ input.focus();+ input.select();+ }+ });+ };+ document.addEventListener("keydown", onKeyDown);+ return () => document.removeEventListener("keydown", onKeyDown);+ }, [enabled]);++ // Drop highlights on unmount so a stale tint can't linger after navigation.+ useEffect(() => clearHighlights, [clearHighlights]);++ const setQuery = useCallback((value: string) => setQueryState(value), []);+ const openFind = useCallback(() => setOpen(true), []);+ const closeFind = useCallback(() => setOpen(false), []);++ const goNext = useCallback(() => {+ setActiveIndex((prev) => {+ const n = rangesRef.current.length;+ if (n === 0) return -1;+ return prev < 0 ? 0 : (prev + 1) % n;+ });+ }, []);++ const goPrev = useCallback(() => {+ setActiveIndex((prev) => {+ const n = rangesRef.current.length;+ if (n === 0) return -1;+ return prev < 0 ? n - 1 : (prev - 1 + n) % n;+ });+ }, []);++ return {+ open,+ query,+ matchCount,+ activeIndex,+ supported,+ inputRef,+ setQuery,+ openFind,+ closeFind,+ goNext,+ goPrev,+ };+}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 3a441d989b..d126bf3331 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -228,8 +228,14 @@"pin_tooltip": "Pin to sidebar","unpin_tooltip": "Unpin from sidebar","sidebar_tooltip": "Toggle sidebar",- "cmdf_toast_title": "Find on page only covers what's visible",- "cmdf_toast_description": "The timeline is virtualized — ⌘F can't see off-screen comments. Full in-app search is coming.",+ "find": {+ "placeholder": "Find in issue...",+ "count": "{{current}}/{{total}}",+ "no_matches": "No matches",+ "previous": "Previous match",+ "next": "Next match",+ "close": "Close find"+ },"update_failed": "Failed to update issue","link_copied": "Link copied","link_copy_failed": "Failed to copy link",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 30fcaa7dd3..945399f26f 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -225,8 +225,14 @@"pin_tooltip": "サイドバーにピン留め","unpin_tooltip": "サイドバーのピン留めを解除","sidebar_tooltip": "サイドバーの開閉",- "cmdf_toast_title": "ページ内検索は表示中の内容のみが対象です",- "cmdf_toast_description": "タイムラインは仮想化されているため、画面外のコメントは ⌘F で見つかりません。アプリ全体の検索は近日提供予定です。",+ "find": {+ "placeholder": "イシュー内を検索...",+ "count": "{{current}}/{{total}}",+ "no_matches": "一致なし",+ "previous": "前の一致",+ "next": "次の一致",+ "close": "検索を閉じる"+ },"update_failed": "イシューを更新できませんでした","link_copied": "リンクをコピーしました","link_copy_failed": "リンクをコピーできませんでした",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 2ccb37d831..b212b2c49e 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -225,8 +225,14 @@"pin_tooltip": "사이드바에 고정","unpin_tooltip": "사이드바 고정 해제","sidebar_tooltip": "사이드바 열기/닫기",- "cmdf_toast_title": "페이지 내 찾기는 보이는 내용만 검색합니다",- "cmdf_toast_description": "타임라인은 가상화되어 있어 화면 밖 댓글은 ⌘F로 찾을 수 없습니다. 앱 전체 검색은 곧 제공됩니다.",+ "find": {+ "placeholder": "이슈에서 찾기...",+ "count": "{{current}}/{{total}}",+ "no_matches": "일치 항목 없음",+ "previous": "이전 일치",+ "next": "다음 일치",+ "close": "찾기 닫기"+ },"update_failed": "이슈를 업데이트하지 못했습니다","link_copied": "링크를 복사했습니다","link_copy_failed": "링크를 복사하지 못했습니다",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex afde482ab7..c9b10701a7 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -225,8 +225,14 @@"pin_tooltip": "固定到侧边栏","unpin_tooltip": "从侧边栏取消固定","sidebar_tooltip": "切换侧边栏",- "cmdf_toast_title": "页面内查找仅覆盖可见区",- "cmdf_toast_description": "评论列表已虚拟滚动,⌘F 找不到视口外的评论。完整应用内搜索即将推出。",+ "find": {+ "placeholder": "在 issue 中查找...",+ "count": "{{current}}/{{total}}",+ "no_matches": "无匹配结果",+ "previous": "上一个",+ "next": "下一个",+ "close": "关闭查找"+ },"update_failed": "更新 issue 失败","link_copied": "已复制链接","link_copy_failed": "复制链接失败",