Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 修复查找框自匹配和焦点恢复 (#3791)

Dash683d63024d2f
diff --git a/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx b/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx
index 72f73a5f19..aef8e725e6 100644
--- a/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx
+++ b/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx
@@ -6,17 +6,442 @@ import { cn } from '@/lib/utils';
import { useAppShortcut } from '@/hooks/useAppShortcut';
import { isFindInPageClaimed } from './findInPageOwnership';
+const MATCH_HIGHLIGHT_NAME = 'cindy-find-in-page-match';
+const ACTIVE_HIGHLIGHT_NAME = 'cindy-find-in-page-active';
+const SEARCH_MATCH_BACKGROUND = 'hsl(var(--search-match-bg))';
+const SEARCH_MATCH_FOREGROUND = 'hsl(var(--search-match-fg))';
+const SEARCH_REFRESH_DEBOUNCE_MS = 120;
+
+interface TextMatch {
+ range: Range;
+}
+
+function getHighlightRegistry(): HighlightRegistry | null {
+ if (typeof CSS === 'undefined' || !CSS.highlights || typeof Highlight === 'undefined') {
+ return null;
+ }
+ return CSS.highlights;
+}
+
+function clearFindHighlights() {
+ const registry = getHighlightRegistry();
+ if (!registry) return;
+ registry.delete(MATCH_HIGHLIGHT_NAME);
+ registry.delete(ACTIVE_HIGHLIGHT_NAME);
+}
+
+function applyFindHighlights(matches: readonly TextMatch[], activeIndex: number) {
+ const registry = getHighlightRegistry();
+ if (!registry) return;
+
+ registry.delete(MATCH_HIGHLIGHT_NAME);
+ registry.delete(ACTIVE_HIGHLIGHT_NAME);
+ if (matches.length === 0) return;
+
+ const matchHighlight = new Highlight();
+ for (const match of matches) matchHighlight.add(match.range);
+ registry.set(MATCH_HIGHLIGHT_NAME, matchHighlight);
+ const activeMatch = matches[activeIndex];
+ if (activeMatch) {
+ const activeHighlight = new Highlight();
+ activeHighlight.add(activeMatch.range);
+ registry.set(ACTIVE_HIGHLIGHT_NAME, activeHighlight);
+ }
+}
+
+function findMatchOffsets(
+ value: string,
+ query: string,
+ whiteSpace = 'normal',
+): Array<[number, number]> {
+ if (!value || !query) return [];
+
+ const collapseWhitespace = ['normal', 'nowrap', 'pre-line'].includes(whiteSpace);
+ const sourceStarts: number[] = [];
+ const sourceEnds: number[] = [];
+ let searchableValue = '';
+ for (let index = 0; index < value.length; index += 1) {
+ if (collapseWhitespace && /\s/.test(value[index])) {
+ const runStart = index;
+ while (index + 1 < value.length && /\s/.test(value[index + 1])) index += 1;
+ const runEnd = index + 1;
+ const hasSegmentBreak = /[\r\n\f]/.test(value.slice(runStart, runEnd));
+ const previousCharacter = getCodePointBefore(value, runStart);
+ const nextCharacter = getCodePointAt(value, runEnd);
+ if (hasSegmentBreak && isCjkCharacter(previousCharacter) && isCjkCharacter(nextCharacter)) {
+ continue;
+ }
+ if (searchableValue.at(-1) !== ' ') {
+ searchableValue += ' ';
+ sourceStarts.push(runStart);
+ sourceEnds.push(runEnd);
+ } else {
+ sourceEnds[sourceEnds.length - 1] = runEnd;
+ }
+ continue;
+ }
+ searchableValue += value[index];
+ sourceStarts.push(index);
+ sourceEnds.push(index + 1);
+ }
+
+ const searchableQuery = collapseWhitespace ? query.replace(/\s+/g, ' ') : query;
+ const normalizedQuery = unicodeCaseFold(searchableQuery.normalize('NFC'));
+ const offsets: Array<[number, number]> = [];
+
+ const foldedValue = foldSearchValue(
+ normalizeSearchValue(searchableValue, sourceStarts, sourceEnds),
+ );
+ let start = 0;
+ while (start <= foldedValue.value.length - normalizedQuery.length) {
+ const matchStart = foldedValue.value.indexOf(normalizedQuery, start);
+ if (matchStart < 0) break;
+ const matchEnd = matchStart + normalizedQuery.length - 1;
+ offsets.push([foldedValue.starts[matchStart], foldedValue.ends[matchEnd]]);
+ start = matchStart + normalizedQuery.length;
+ }
+ return offsets;
+}
+
+function unicodeCaseFold(value: string): string {
+ // Keep case-insensitive matching locale-independent without maintaining a
+ // second Unicode full-fold table. Final sigma is the one contextual form
+ // that JavaScript lower-casing does not make equivalent in both directions.
+ return value.toLowerCase().replace(/\u03c2/g, '\u03c3');
+}
+
+function normalizeSearchValue(
+ value: string,
+ sourceStarts: readonly number[],
+ sourceEnds: readonly number[],
+): { value: string; starts: number[]; ends: number[] } {
+ const characters: Array<{ value: string; start: number; end: number }> = [];
+ for (let index = 0; index < value.length; ) {
+ const character = getCodePointAt(value, index);
+ const end = index + character.length;
+ characters.push({
+ value: character,
+ start: sourceStarts[index],
+ end: sourceEnds[end - 1],
+ });
+ index = end;
+ }
+
+ let normalizedValue = '';
+ const normalizedStarts: number[] = [];
+ const normalizedEnds: number[] = [];
+ for (let index = 0; index < characters.length; ) {
+ let end = index + 1;
+ if (
+ isHangulLeadingJamo(characters[index].value) &&
+ isHangulVowelJamo(characters[end]?.value)
+ ) {
+ end += 1;
+ if (isHangulTrailingJamo(characters[end]?.value)) end += 1;
+ } else if (
+ isHangulLvSyllable(characters[index].value) &&
+ isHangulTrailingJamo(characters[end]?.value)
+ ) {
+ end += 1;
+ }
+ while (end < characters.length && isCombiningMark(characters[end].value)) end += 1;
+
+ const normalizedChunk = characters
+ .slice(index, end)
+ .map((character) => character.value)
+ .join('')
+ .normalize('NFC');
+ const sourceStart = characters[index].start;
+ const sourceEnd = characters[end - 1].end;
+ normalizedValue += normalizedChunk;
+ for (let offset = 0; offset < normalizedChunk.length; offset += 1) {
+ normalizedStarts.push(sourceStart);
+ normalizedEnds.push(sourceEnd);
+ }
+ index = end;
+ }
+
+ return { value: normalizedValue, starts: normalizedStarts, ends: normalizedEnds };
+}
+
+function isCombiningMark(value: string): boolean {
+ return /^\p{M}$/u.test(value);
+}
+
+function getCodePoint(value: string | undefined): number | undefined {
+ return value?.codePointAt(0);
+}
+
+function isHangulLeadingJamo(value: string | undefined): boolean {
+ const codePoint = getCodePoint(value);
+ if (codePoint === undefined) return false;
+ return codePoint >= 0x1100 && codePoint <= 0x1112;
+}
+
+function isHangulVowelJamo(value: string | undefined): boolean {
+ const codePoint = getCodePoint(value);
+ if (codePoint === undefined) return false;
+ return codePoint >= 0x1161 && codePoint <= 0x1175;
+}
+
+function isHangulTrailingJamo(value: string | undefined): boolean {
+ const codePoint = getCodePoint(value);
+ if (codePoint === undefined) return false;
+ return codePoint >= 0x11a8 && codePoint <= 0x11c2;
+}
+
+function isHangulLvSyllable(value: string | undefined): boolean {
+ const codePoint = getCodePoint(value);
+ return (
+ codePoint !== undefined &&
+ codePoint >= 0xac00 &&
+ codePoint <= 0xd7a3 &&
+ (codePoint - 0xac00) % 28 === 0
+ );
+}
+
+function foldSearchValue(
+ normalizedValue: { value: string; starts: number[]; ends: number[] },
+): { value: string; starts: number[]; ends: number[] } {
+ let foldedValue = '';
+ const starts: number[] = [];
+ const ends: number[] = [];
+ for (let index = 0; index < normalizedValue.value.length; ) {
+ const character = getCodePointAt(normalizedValue.value, index);
+ const end = index + character.length;
+ const foldedCharacter = unicodeCaseFold(character);
+ const sourceStart = normalizedValue.starts[index];
+ const sourceEnd = normalizedValue.ends[end - 1];
+ foldedValue += foldedCharacter;
+ for (let offset = 0; offset < foldedCharacter.length; offset += 1) {
+ starts.push(sourceStart);
+ ends.push(sourceEnd);
+ }
+ index = end;
+ }
+ return { value: foldedValue, starts, ends };
+}
+
+function getCodePointBefore(value: string, index: number): string {
+ if (index <= 0) return '';
+ let start = index - 1;
+ const codeUnit = value.charCodeAt(start);
+ if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff && start > 0) {
+ const previousCodeUnit = value.charCodeAt(start - 1);
+ if (previousCodeUnit >= 0xd800 && previousCodeUnit <= 0xdbff) start -= 1;
+ }
+ return value.slice(start, index);
+}
+
+function getCodePointAt(value: string, index: number): string {
+ if (index < 0 || index >= value.length) return '';
+ const codeUnit = value.charCodeAt(index);
+ if (
+ codeUnit >= 0xd800 &&
+ codeUnit <= 0xdbff &&
+ index + 1 < value.length &&
+ value.charCodeAt(index + 1) >= 0xdc00 &&
+ value.charCodeAt(index + 1) <= 0xdfff
+ ) {
+ return value.slice(index, index + 2);
+ }
+ return value[index];
+}
+
+function isVisuallyClipped(style: CSSStyleDeclaration): boolean {
+ const clip = style.clip.trim().toLowerCase();
+ const clipPath = style.clipPath.trim().toLowerCase();
+ const hasZeroRectClip = /^rect\(\s*0(?:px)?[ ,]+0(?:px)?[ ,]+0(?:px)?[ ,]+0(?:px)?\s*\)$/.test(
+ clip,
+ );
+ if (hasZeroRectClip) return true;
+ if (clipPath === 'none' || clipPath === '') return false;
+
+ const width = Number.parseFloat(style.width);
+ const height = Number.parseFloat(style.height);
+ const isTiny = Number.isFinite(width) && Number.isFinite(height) && width <= 1 && height <= 1;
+ return isTiny && (style.position === 'absolute' || style.position === 'fixed');
+}
+
+function isCjkCharacter(value: string): boolean {
+ if (!value) return false;
+ const codePoint = value.codePointAt(0);
+ if (codePoint === undefined) return false;
+ return (
+ (codePoint >= 0x2e80 && codePoint <= 0x2fff) ||
+ (codePoint >= 0x3000 && codePoint <= 0x30ff) ||
+ (codePoint >= 0x3400 && codePoint <= 0x9fff) ||
+ (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
+ (codePoint >= 0x20000 && codePoint <= 0x2ffff)
+ );
+}
+
+function getCachedComputedStyle(
+ element: HTMLElement,
+ styleCache: WeakMap<HTMLElement, CSSStyleDeclaration>,
+): CSSStyleDeclaration {
+ const cachedStyle = styleCache.get(element);
+ if (cachedStyle) return cachedStyle;
+ const style = window.getComputedStyle(element);
+ styleCache.set(element, style);
+ return style;
+}
+
+function isExcludedTextNode(
+ node: Text,
+ excludedRoot: HTMLElement | null,
+ visibilityCache: WeakMap<HTMLElement, boolean>,
+ styleCache: WeakMap<HTMLElement, CSSStyleDeclaration>,
+): boolean {
+ let element = node.parentElement;
+ while (element) {
+ if (element === excludedRoot) return true;
+ const tagName = element.tagName.toLowerCase();
+ if (
+ tagName === 'script' ||
+ tagName === 'style' ||
+ tagName === 'noscript' ||
+ tagName === 'template'
+ ) {
+ return true;
+ }
+ if (tagName === 'option') {
+ const select = element.closest('select');
+ const option = element as HTMLOptionElement;
+ if (select && !select.multiple && select.size <= 1 && !option.selected) return true;
+ }
+ if (tagName === 'details' && !element.hasAttribute('open')) {
+ const summary = Array.from(element.children).find(
+ (child) => child.tagName.toLowerCase() === 'summary',
+ );
+ if (!summary || !summary.contains(node)) return true;
+ }
+ if (element.hidden) return true;
+ const cachedHidden = visibilityCache.get(element);
+ if (cachedHidden !== undefined) {
+ if (cachedHidden) return true;
+ } else {
+ const style = getCachedComputedStyle(element, styleCache);
+ const hiddenByStyle =
+ style.display === 'none' ||
+ style.visibility === 'hidden' ||
+ style.visibility === 'collapse' ||
+ style.opacity === '0' ||
+ isVisuallyClipped(style);
+ visibilityCache.set(element, hiddenByStyle);
+ if (hiddenByStyle) return true;
+ }
+ element = element.parentElement;
+ }
+ return false;
+}
+
+function collectTextMatches(query: string, excludedRoot: HTMLElement | null): TextMatch[] {
+ if (!query) return [];
+
+ const matches: TextMatch[] = [];
+ const visibilityCache = new WeakMap<HTMLElement, boolean>();
+ const styleCache = new WeakMap<HTMLElement, CSSStyleDeclaration>();
+ // Keep off-screen and scrollable content searchable. Geometry-based clipping
+ // guesses cannot distinguish a closed drawer from history outside a scroll
+ // viewport, so only explicit hidden styles are excluded here.
+ const walker = document.createTreeWalker(document.body, 4);
+ let node = walker.nextNode();
+ while (node) {
+ const textNode = node as Text;
+ if (!isExcludedTextNode(textNode, excludedRoot, visibilityCache, styleCache)) {
+ const parentElement = textNode.parentElement;
+ const parentStyle = parentElement ? getCachedComputedStyle(parentElement, styleCache) : null;
+ const whiteSpace = parentStyle?.whiteSpace || 'normal';
+ for (const [start, end] of findMatchOffsets(textNode.data, query, whiteSpace)) {
+ const range = document.createRange();
+ range.setStart(textNode, start);
+ range.setEnd(textNode, end);
+ matches.push({ range });
+ }
+ }
+ node = walker.nextNode();
+ }
+ return matches;
+}
+
+function isInsideRoot(node: Node, root: HTMLElement | null): boolean {
+ return Boolean(root && (node === root || root.contains(node)));
+}
+
+function getRangeRect(range: Range): DOMRect | null {
+ const rects = typeof range.getClientRects === 'function' ? range.getClientRects() : [];
+ const rect =
+ rects[0] ??
+ (typeof range.getBoundingClientRect === 'function' ? range.getBoundingClientRect() : null);
+ if (!rect) return null;
+ if (rect.width === 0 && rect.height === 0 && rect.top === 0 && rect.bottom === 0) return null;
+ return rect;
+}
+
+function scrollRangeIntoView(range: Range) {
+ const element = range.startContainer.parentElement;
+ if (!element) return;
+
+ let ancestor: HTMLElement | null = element;
+ while (ancestor) {
+ const style = window.getComputedStyle(ancestor);
+ const canScrollY =
+ /(auto|scroll|overlay|hidden)/.test(style.overflowY) &&
+ ancestor.scrollHeight > ancestor.clientHeight;
+ const canScrollX =
+ /(auto|scroll|overlay|hidden)/.test(style.overflowX) &&
+ ancestor.scrollWidth > ancestor.clientWidth;
+ if (!canScrollY && !canScrollX) {
+ ancestor = ancestor.parentElement;
+ continue;
+ }
+
+ const rect = getRangeRect(range);
+ const containerRect = ancestor.getBoundingClientRect();
+ if (!rect) return;
+ if (canScrollY) {
+ if (rect.top < containerRect.top) ancestor.scrollTop -= containerRect.top - rect.top;
+ else if (rect.bottom > containerRect.bottom)
+ ancestor.scrollTop += rect.bottom - containerRect.bottom;
+ }
+ if (canScrollX) {
+ if (rect.left < containerRect.left) ancestor.scrollLeft -= containerRect.left - rect.left;
+ else if (rect.right > containerRect.right)
+ ancestor.scrollLeft += rect.right - containerRect.right;
+ }
+ ancestor = ancestor.parentElement;
+ }
+
+ const rect = getRangeRect(range);
+ if (!rect || typeof window.scrollBy !== 'function') return;
+ const viewportHeight = window.innerHeight;
+ const viewportWidth = window.innerWidth;
+ if (rect.top < 0 || rect.bottom > viewportHeight) {
+ window.scrollBy({
+ top: rect.top < 0 ? rect.top : rect.bottom - viewportHeight,
+ behavior: 'auto',
+ });
+ }
+ if (rect.left < 0 || rect.right > viewportWidth) {
+ window.scrollBy({
+ left: rect.left < 0 ? rect.left : rect.right - viewportWidth,
+ behavior: 'auto',
+ });
+ }
+}
+
/**
* F-FIP-1 — Find in Page overlay (Ctrl/Cmd+F).
*
- * Drives Chromium's native `webContents.findInPage` via IPC and surfaces
- * match counts in a small floating bar pinned to the top-right of the
- * window. Esc closes; Enter / Shift+Enter walk forward / backward.
+ * Searches renderer text nodes directly, excluding this bar's subtree and
+ * hidden/non-content nodes. Matches are painted with CSS Custom Highlight so
+ * the query input stays a normal editable control throughout the search.
+ * Enter / Shift+Enter and the arrow buttons walk the collected ranges.
*
- * Why a single global instance (mounted once in App.tsx):
- * `findInPage` is per-WebContents — every press of Ctrl+F should drive
- * the SAME native search session, otherwise the highlighted matches
- * bounce around or get orphaned. One bar = one source of truth.
+ * Search intentionally does not join text across element boundaries. That
+ * keeps matching synchronous and avoids the native find-in-page focus and
+ * font-metric races that made CJK/proportional-font input unreliable.
*/
export function FindInPageBar() {
const { t } = useTranslation();
@@ -24,54 +449,192 @@ export function FindInPageBar() {
const [text, setText] = useState('');
const [matches, setMatches] = useState(0);
const [active, setActive] = useState(0);
+ const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
+ const rangesRef = useRef<TextMatch[]>([]);
+ const activeRef = useRef(0);
+ const pendingScrollFrameRef = useRef<number | null>(null);
+ const pendingRefreshTimerRef = useRef<number | null>(null);
const isComposingRef = useRef(false);
- // Chromium may emit the final input/change after compositionend. Remember
- // that value so the committed IME text starts exactly one native search.
const compositionCommitRef = useRef<string | null>(null);
- // Track the requestId returned by `findInPage` so we can ignore stale
- // result events from an earlier query (Chromium fires `found-in-page`
- // multiple times per request as the search progresses).
- const lastRequestIdRef = useRef<number | null>(null);
-
- // Subscribe to result events while the bar is open. The fan-out subscriber
- // returns an unsubscribe function — calling it on close releases the
- // underlying ipcRenderer binding (see preload.ts createIpcFanOut).
- useEffect(() => {
- if (!open) return;
- const unsub = window.electronAPI.onFindInPageResult((result) => {
- // Discard results that don't belong to our most recent request.
- if (lastRequestIdRef.current !== null && result.requestId !== lastRequestIdRef.current) {
- return;
+
+ const clearSearchResults = useCallback(() => {
+ rangesRef.current = [];
+ activeRef.current = 0;
+ setMatches(0);
+ setActive(0);
+ clearFindHighlights();
+ }, []);
+
+ const cancelPendingScroll = useCallback(() => {
+ const frame = pendingScrollFrameRef.current;
+ pendingScrollFrameRef.current = null;
+ if (frame !== null && typeof cancelAnimationFrame === 'function') {
+ cancelAnimationFrame(frame);
+ }
+ }, []);
+
+ const scrollToMatch = useCallback(
+ (range: Range | undefined) => {
+ cancelPendingScroll();
+ if (!range) return;
+ const element = range.startContainer.parentElement;
+ if (!element || isInsideRoot(element, rootRef.current)) return;
+ scrollRangeIntoView(range);
+ if (typeof requestAnimationFrame === 'function') {
+ pendingScrollFrameRef.current = requestAnimationFrame(() => {
+ pendingScrollFrameRef.current = null;
+ if (
+ range.startContainer.isConnected &&
+ rangesRef.current[activeRef.current]?.range === range
+ ) {
+ scrollRangeIntoView(range);
+ }
+ });
}
- setMatches(result.matches);
- setActive(result.activeMatchOrdinal);
- });
- return () => {
- unsub();
- };
- }, [open]);
+ },
+ [cancelPendingScroll],
+ );
+
+ const applySearch = useCallback(
+ (query: string, requestedActive = 0, shouldScroll = false) => {
+ const nextRanges = collectTextMatches(query, rootRef.current);
+ rangesRef.current = nextRanges;
+ const nextActive = nextRanges.length
+ ? ((requestedActive % nextRanges.length) + nextRanges.length) % nextRanges.length
+ : 0;
+ activeRef.current = nextActive;
+ setMatches(nextRanges.length);
+ setActive(nextActive);
+ applyFindHighlights(nextRanges, nextActive);
+ if (shouldScroll) scrollToMatch(nextRanges[nextActive]?.range);
+ },
+ [scrollToMatch],
+ );
+
+ const moveActive = useCallback(
+ (direction: 1 | -1) => {
+ const hadMatches = rangesRef.current.length > 0;
+ if (text) applySearch(text, activeRef.current);
+ const ranges = rangesRef.current;
+ if (ranges.length === 0) return;
+ const nextActive = hadMatches
+ ? (activeRef.current + direction + ranges.length) % ranges.length
+ : direction === 1
+ ? 0
+ : ranges.length - 1;
+ activeRef.current = nextActive;
+ setActive(nextActive);
+ applyFindHighlights(ranges, nextActive);
+ scrollToMatch(ranges[nextActive]?.range);
+ },
+ [applySearch, scrollToMatch, text],
+ );
const close = useCallback(() => {
+ cancelPendingScroll();
setOpen(false);
setText('');
- setMatches(0);
- setActive(0);
isComposingRef.current = false;
compositionCommitRef.current = null;
- lastRequestIdRef.current = null;
- window.electronAPI.stopFindInPage('clearSelection');
- }, []);
+ clearSearchResults();
+ }, [cancelPendingScroll, clearSearchResults]);
+
+ useEffect(() => () => clearFindHighlights(), []);
+
+ useEffect(() => {
+ if (!open || !text) return;
+
+ const refreshSearch = () => {
+ if (isComposingRef.current) return;
+ applySearch(text, activeRef.current);
+ };
+ const scheduleRefresh = () => {
+ if (isComposingRef.current) return;
+ const pendingTimer = pendingRefreshTimerRef.current;
+ if (pendingTimer !== null) window.clearTimeout(pendingTimer);
+
+ pendingRefreshTimerRef.current = window.setTimeout(() => {
+ pendingRefreshTimerRef.current = null;
+ refreshSearch();
+ }, SEARCH_REFRESH_DEBOUNCE_MS);
+ };
+ const handleResize = () => scheduleRefresh();
+ const handleChange = (event: Event) => {
+ if (event.target instanceof HTMLSelectElement) refreshSearch();
+ };
+ const handleTransitionEnd = (event: Event) => {
+ const target = event.target;
+ const propertyName = (event as TransitionEvent).propertyName;
+ if (
+ !(target instanceof Node) ||
+ isInsideRoot(target, rootRef.current) ||
+ ![
+ 'opacity',
+ 'visibility',
+ 'width',
+ 'height',
+ 'max-width',
+ 'max-height',
+ 'transform',
+ ].includes(propertyName)
+ ) {
+ return;
+ }
+ scheduleRefresh();
+ };
+ const handlePotentialVisibilityChange = (event: Event) => {
+ const target = event.target;
+ if (!(target instanceof Node) || isInsideRoot(target, rootRef.current)) return;
+ scheduleRefresh();
+ };
+ const observer =
+ typeof MutationObserver === 'function'
+ ? new MutationObserver((records) => {
+ const root = rootRef.current;
+ if (!root || records.every((record) => isInsideRoot(record.target, root))) return;
+ scheduleRefresh();
+ })
+ : null;
+
+ window.addEventListener('resize', handleResize);
+ document.addEventListener('change', handleChange);
+ document.addEventListener('transitionend', handleTransitionEnd);
+ document.addEventListener('mouseover', handlePotentialVisibilityChange);
+ document.addEventListener('mouseout', handlePotentialVisibilityChange);
+ document.addEventListener('focusin', handlePotentialVisibilityChange);
+ document.addEventListener('focusout', handlePotentialVisibilityChange);
+ observer?.observe(document.body, {
+ childList: true,
+ characterData: true,
+ attributes: true,
+ attributeFilter: ['class', 'style', 'hidden', 'open'],
+ subtree: true,
+ });
+ return () => {
+ window.removeEventListener('resize', handleResize);
+ document.removeEventListener('change', handleChange);
+ document.removeEventListener('transitionend', handleTransitionEnd);
+ document.removeEventListener('mouseover', handlePotentialVisibilityChange);
+ document.removeEventListener('mouseout', handlePotentialVisibilityChange);
+ document.removeEventListener('focusin', handlePotentialVisibilityChange);
+ document.removeEventListener('focusout', handlePotentialVisibilityChange);
+ observer?.disconnect();
+ const timer = pendingRefreshTimerRef.current;
+ pendingRefreshTimerRef.current = null;
+ if (timer !== null) {
+ window.clearTimeout(timer);
+ }
+ };
+ }, [applySearch, open, text]);
// Global find-in-page shortcut (registry 默认 Ctrl/Cmd+F, 用户可改绑) →
- // open + focus. Capture phase so editable inputs (TipTap, plain inputs,
- // contenteditable) don't swallow the chord first.
+ // open + focus. Capture phase means editable page controls do not swallow
+ // the chord before the global bar sees it.
useAppShortcut('find-in-page', () => {
- // 有局部接管者(如 doc 模式的 FileBodyView)时让位 —— 不消费事件,
- // 让接管者自己的 handler 处理。注册顺序此时无所谓。
+ // 局部接管者(如 doc 模式的 FileBodyView)存在时让位。
if (isFindInPageClaimed()) return false;
setOpen(true);
- // Defer focus to next tick so the input is mounted & visible.
queueMicrotask(() => {
inputRef.current?.focus();
inputRef.current?.select();
@@ -79,33 +642,11 @@ export function FindInPageBar() {
return true;
});
- // Electron uses `findNext=true` to start a new request and false to continue
- // walking the current search session.
- const runSearch = useCallback(
- async (nextText: string, opts: { forward?: boolean; findNext?: boolean } = {}) => {
- if (!nextText) {
- setMatches(0);
- setActive(0);
- lastRequestIdRef.current = null;
- window.electronAPI.stopFindInPage('clearSelection');
- return;
- }
- const id = await window.electronAPI.findInPage({
- text: nextText,
- forward: opts.forward ?? true,
- findNext: opts.findNext ?? true,
- });
- if (typeof id === 'number') {
- lastRequestIdRef.current = id;
- }
- },
- [],
- );
-
if (!open) return null;
return (
<div
+ ref={rootRef}
className={cn(
// Title bar is 46px tall — sit just below it so it never overlaps.
'fixed right-4 top-[54px] z-50',
@@ -122,66 +663,85 @@ export function FindInPageBar() {
role="dialog"
aria-label={t('findInPage.dialogAriaLabel')}
>
- <input
- ref={inputRef}
- type="text"
- value={text}
- placeholder={t('findInPage.placeholder')}
- onChange={(e) => {
- const next = e.target.value;
- const nativeIsComposing =
- 'isComposing' in e.nativeEvent && e.nativeEvent.isComposing === true;
- setText(next);
- if (isComposingRef.current || nativeIsComposing) return;
- if (compositionCommitRef.current !== null) {
- const committed = compositionCommitRef.current;
+ <style>{`
+ ::highlight(${MATCH_HIGHLIGHT_NAME}) {
+ background-color: ${SEARCH_MATCH_BACKGROUND};
+ color: ${SEARCH_MATCH_FOREGROUND};
+ }
+ ::highlight(${ACTIVE_HIGHLIGHT_NAME}) {
+ background-color: ${SEARCH_MATCH_BACKGROUND};
+ color: ${SEARCH_MATCH_FOREGROUND};
+ text-decoration: underline;
+ text-decoration-color: ${SEARCH_MATCH_FOREGROUND};
+ text-decoration-thickness: 2px;
+ }
+ `}</style>
+ <div className="relative flex-1 min-w-0 overflow-hidden">
+ <input
+ ref={inputRef}
+ type="text"
+ role="searchbox"
+ aria-label={t('findInPage.placeholder')}
+ autoComplete="off"
+ value={text}
+ placeholder={t('findInPage.placeholder')}
+ onChange={(e) => {
+ const next = e.target.value;
+ const nativeIsComposing =
+ 'isComposing' in e.nativeEvent && e.nativeEvent.isComposing === true;
+ setText(next);
+ if (compositionCommitRef.current === next) {
+ compositionCommitRef.current = null;
+ return;
+ }
compositionCommitRef.current = null;
- if (next === committed) return;
- }
- void runSearch(next, { forward: true, findNext: true });
- }}
- onCompositionStart={() => {
- isComposingRef.current = true;
- compositionCommitRef.current = null;
- }}
- onCompositionEnd={(e) => {
- const committed = e.currentTarget.value;
- isComposingRef.current = false;
- compositionCommitRef.current = committed;
- setText(committed);
- void runSearch(committed, { forward: true, findNext: true });
- }}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.preventDefault();
- close();
- } else if (
- e.key === 'Enter' &&
- !e.nativeEvent.isComposing &&
- e.nativeEvent.keyCode !== 229
- ) {
- e.preventDefault();
- if (text) void runSearch(text, { forward: !e.shiftKey, findNext: false });
- }
- }}
- className={cn(
- 'flex-1 min-w-0',
- 'bg-transparent outline-none',
- 'text-sm',
- 'placeholder:text-muted-foreground',
- )}
- />
+ if (isComposingRef.current || nativeIsComposing) return;
+ applySearch(next, 0, true);
+ }}
+ onCompositionStart={() => {
+ isComposingRef.current = true;
+ compositionCommitRef.current = null;
+ clearSearchResults();
+ }}
+ onCompositionEnd={(e) => {
+ const committed = e.currentTarget.value;
+ isComposingRef.current = false;
+ compositionCommitRef.current = committed;
+ setText(committed);
+ applySearch(committed, 0, true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ close();
+ } else if (
+ e.key === 'Enter' &&
+ !e.nativeEvent.isComposing &&
+ e.nativeEvent.keyCode !== 229
+ ) {
+ e.preventDefault();
+ moveActive(e.shiftKey ? -1 : 1);
+ }
+ }}
+ className={cn(
+ 'w-full min-w-0',
+ 'bg-transparent outline-none',
+ 'text-sm',
+ 'placeholder:text-muted-foreground',
+ )}
+ />
+ </div>
<span
className="text-xs tabular-nums text-muted-foreground select-none whitespace-nowrap px-1"
aria-live="polite"
>
- {text ? (matches > 0 ? `${active}/${matches}` : '0/0') : ''}
+ {text ? (matches > 0 ? `${active + 1}/${matches}` : '0/0') : ''}
</span>
<button
type="button"
aria-label={t('findInPage.previous')}
- disabled={!text || matches === 0}
- onClick={() => void runSearch(text, { forward: false, findNext: false })}
+ disabled={!text}
+ onClick={() => moveActive(-1)}
className={cn(
'flex h-6 w-6 items-center justify-center rounded',
'hover:bg-titlebar-button-hover',
@@ -194,8 +754,8 @@ export function FindInPageBar() {
<button
type="button"
aria-label={t('findInPage.next')}
- disabled={!text || matches === 0}
- onClick={() => void runSearch(text, { forward: true, findNext: false })}
+ disabled={!text}
+ onClick={() => moveActive(1)}
className={cn(
'flex h-6 w-6 items-center justify-center rounded',
'hover:bg-titlebar-button-hover',
diff --git a/apps/desktop/src/renderer/components/find-in-page/__tests__/FindInPageBar.test.tsx b/apps/desktop/src/renderer/components/find-in-page/__tests__/FindInPageBar.test.tsx
index 5eac837fdd..99d518b567 100644
--- a/apps/desktop/src/renderer/components/find-in-page/__tests__/FindInPageBar.test.tsx
+++ b/apps/desktop/src/renderer/components/find-in-page/__tests__/FindInPageBar.test.tsx
@@ -1,118 +1,997 @@
// @vitest-environment jsdom
-import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const shortcut = vi.hoisted(() => ({ handler: null as null | (() => boolean) }));
+const MATCH_HIGHLIGHT_NAME = 'cindy-find-in-page-match';
+const ACTIVE_HIGHLIGHT_NAME = 'cindy-find-in-page-active';
-vi.mock('@/hooks/useAppShortcut', () => ({
- useAppShortcut: (_id: string, handler: () => boolean) => {
- shortcut.handler = handler;
- },
+const mocks = vi.hoisted(() => ({
+ shortcutHandler: null as ((event: KeyboardEvent) => boolean) | null,
}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
+vi.mock('@/hooks/useAppShortcut', () => ({
+ useAppShortcut: (_id: string, handler: (event: KeyboardEvent) => boolean) => {
+ mocks.shortcutHandler = handler;
+ },
+}));
+
+vi.mock('@/components/find-in-page/findInPageOwnership', () => ({
+ isFindInPageClaimed: () => false,
+}));
+
import { FindInPageBar } from '../FindInPageBar';
-describe('FindInPageBar', () => {
- const findInPage = vi.fn<(params: {
- text: string;
- forward?: boolean;
- findNext?: boolean;
- }) => Promise<number>>();
- const stopFindInPage = vi.fn();
+class MockHighlight {
+ readonly ranges: AbstractRange[];
+
+ constructor(...ranges: AbstractRange[]) {
+ this.ranges = [...ranges];
+ }
+
+ add(range: AbstractRange) {
+ this.ranges.push(range);
+ return this;
+ }
+}
+
+let highlights: Map<string, MockHighlight>;
+async function openFindBar(page?: HTMLElement): Promise<HTMLInputElement> {
+ if (page) document.body.append(page);
+ render(<FindInPageBar />);
+ await act(async () => {
+ expect(mocks.shortcutHandler?.(new KeyboardEvent('keydown'))).toBe(true);
+ await Promise.resolve();
+ });
+ return screen.getByRole('searchbox') as HTMLInputElement;
+}
+
+function getHighlight(name: string): MockHighlight | undefined {
+ return highlights.get(name);
+}
+
+describe('FindInPageBar', () => {
beforeEach(() => {
- findInPage.mockReset();
- findInPage.mockResolvedValue(1);
- stopFindInPage.mockReset();
- shortcut.handler = null;
- (window as unknown as { electronAPI: unknown }).electronAPI = {
- findInPage,
- stopFindInPage,
- onFindInPageResult: vi.fn(() => vi.fn()),
- };
- });
-
- afterEach(cleanup);
-
- async function openFindBar() {
- const view = render(<FindInPageBar />);
- expect(shortcut.handler).not.toBeNull();
- await act(async () => {
- shortcut.handler?.();
+ vi.clearAllMocks();
+ mocks.shortcutHandler = null;
+ highlights = new Map();
+ vi.stubGlobal('Highlight', MockHighlight);
+ vi.stubGlobal('CSS', {
+ highlights: {
+ set: vi.fn((name: string, highlight: MockHighlight) => highlights.set(name, highlight)),
+ delete: vi.fn((name: string) => highlights.delete(name)),
+ },
});
- return { view, input: view.getByRole('textbox') as HTMLInputElement };
- }
+ });
- it('waits for IME composition to finish before searching the committed text', async () => {
- const { input } = await openFindBar();
+ afterEach(() => {
+ cleanup();
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+ });
- fireEvent.compositionStart(input);
- fireEvent.change(input, { target: { value: 'n' } });
- fireEvent.change(input, { target: { value: 'ni' } });
- expect(findInPage).not.toHaveBeenCalled();
+ it('searches visible page text without matching the query input or hidden content', async () => {
+ const page = document.createElement('main');
+ page.append('foo');
+ const ariaHidden = document.createElement('span');
+ ariaHidden.setAttribute('aria-hidden', 'true');
+ ariaHidden.textContent = 'foo';
+ page.append(ariaHidden);
+ const cssHidden = document.createElement('span');
+ cssHidden.style.display = 'none';
+ cssHidden.textContent = 'foo';
+ page.append(cssHidden);
+ const script = document.createElement('script');
+ script.textContent = '// foo';
+ page.append(script);
+ const select = document.createElement('select');
+ const selectedOption = document.createElement('option');
+ selectedOption.textContent = 'bar';
+ selectedOption.selected = true;
+ const unselectedOption = document.createElement('option');
+ unselectedOption.textContent = 'foo';
+ select.append(selectedOption, unselectedOption);
+ page.append(select);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(2);
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('foo');
+ expect(getHighlight(ACTIVE_HIGHLIGHT_NAME)?.ranges).toHaveLength(1);
+ });
+
+ it('matches case-insensitively and keeps element-boundary matches explicit', async () => {
+ const page = document.createElement('main');
+ page.append('Foo foo 中文中文');
+ const first = document.createElement('span');
+ first.textContent = '中';
+ const second = document.createElement('span');
+ second.textContent = '文';
+ page.append(first, second);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '中文' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(2);
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ '中文',
+ '中文',
+ ]);
+ });
+
+ it('matches context-sensitive Greek sigma case-insensitively', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'ΟΣ Σ';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'Σ' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ 'Σ',
+ 'Σ',
+ ]);
+ });
+
+ it('case-folds Greek final sigma in either the page or the query', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'σ ς Σ';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'σ' } });
+
+ expect(screen.getByText('1/3')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ 'σ',
+ 'ς',
+ 'Σ',
+ ]);
+ });
+
+ it('keeps ASCII case folding independent of the runtime locale', async () => {
+ const localeLowerCaseSpy = vi
+ .spyOn(String.prototype, 'toLocaleLowerCase')
+ .mockImplementation(function (this: string) {
+ return this.toLowerCase().replace(/i/g, 'ı');
+ });
+ const page = document.createElement('main');
+ page.textContent = 'I';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'i' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(localeLowerCaseSpy).not.toHaveBeenCalled();
+ localeLowerCaseSpy.mockRestore();
+ });
+
+ it('maps case-folded characters that expand back to the source range', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'İ';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'i\u0307' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('İ');
+ });
+
+ it('matches an expanded case fold when the query uses the original character', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'i\u0307';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'İ' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('i\u0307');
+ });
+
+ it('matches canonically equivalent Unicode forms and maps the source range', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'e\u0301 x é';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'é' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ 'e\u0301',
+ 'é',
+ ]);
+
+ fireEvent.change(input, { target: { value: 'e\u0301' } });
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ 'e\u0301',
+ 'é',
+ ]);
+ });
- fireEvent.change(input, { target: { value: '你' } });
- fireEvent.compositionEnd(input);
+ it('keeps separate Hangul Jamo syllable ranges after normalization', async () => {
+ const page = document.createElement('main');
+ page.textContent = '가가';
- await waitFor(() => {
- expect(findInPage).toHaveBeenCalledTimes(1);
- expect(findInPage).toHaveBeenCalledWith({ text: '你', forward: true, findNext: true });
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '가' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ '가',
+ '가',
+ ]);
+ });
+
+ it('combines a precomposed Hangul LV syllable with its trailing Jamo', async () => {
+ const page = document.createElement('main');
+ page.textContent = '각 각';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '각' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges.map((range) => range.toString())).toEqual([
+ '각',
+ '각',
+ ]);
+ });
+
+ it('does not merge non-composing Hangul Jamo extensions into a source range', async () => {
+ const page = document.createElement('main');
+ page.textContent = '가\uD7CB';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '가' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('가');
+ });
+
+ it('does not expand one visible character into duplicate navigation matches', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'ß';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 's' } });
+
+ expect(screen.getByText('0/0')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)).toBeUndefined();
+
+ fireEvent.change(input, { target: { value: 'ß' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('ß');
+ });
+
+ it('matches whitespace collapsed by normal text layout', async () => {
+ const page = document.createElement('main');
+ page.style.whiteSpace = 'normal';
+ page.textContent = 'foo\nbar';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo bar' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('foo\nbar');
+ });
+
+ it('removes normal-layout segment breaks between CJK characters', async () => {
+ const page = document.createElement('main');
+ page.style.whiteSpace = 'normal';
+ page.textContent = '你\n好';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '你好' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('你\n好');
+ });
+
+ it('keeps normal-layout segment breaks between Korean syllables', async () => {
+ const page = document.createElement('main');
+ page.style.whiteSpace = 'normal';
+ page.textContent = '한\n글';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '한 글' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('한\n글');
+ });
+
+ it('removes normal-layout segment breaks around supplementary-plane CJK characters', async () => {
+ const page = document.createElement('main');
+ page.style.whiteSpace = 'normal';
+ page.textContent = '𠮷\n野';
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: '𠮷野' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges[0].toString()).toBe('𠮷\n野');
+ });
+
+ it('walks matches with Enter, Shift+Enter, and the navigation buttons', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'foo foo foo';
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/3')).toBeTruthy();
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(screen.getByText('2/3')).toBeTruthy();
+ fireEvent.keyDown(input, { key: 'Enter', shiftKey: true });
+ expect(screen.getByText('1/3')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.previous' }));
+ expect(screen.getByText('3/3')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.next' }));
+ expect(screen.getByText('1/3')).toBeTruthy();
+ });
+
+ it('refreshes stale ranges before navigating after page text changes', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'foo';
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ page.textContent = 'bar';
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(screen.getByText('0/0')).toBeTruthy();
+ });
+
+ it('refreshes matches when page text changes while the bar is open', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'foo';
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ page.textContent = 'foo foo';
+ await waitFor(() => expect(screen.getByText('1/2')).toBeTruthy());
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(2);
+ });
+
+ it('refreshes matches when page visibility attributes change', async () => {
+ const page = document.createElement('main');
+ const responsive = document.createElement('span');
+ responsive.textContent = 'foo';
+ page.append(responsive);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ responsive.hidden = true;
+ await waitFor(() => expect(screen.getByText('0/0')).toBeTruthy());
+
+ responsive.hidden = false;
+ await waitFor(() => expect(screen.getByText('1/1')).toBeTruthy());
+ });
+
+ it('refreshes matches when a visibility transition ends', async () => {
+ const page = document.createElement('main');
+ const responsive = document.createElement('span');
+ responsive.textContent = 'foo';
+ page.append(responsive);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ await act(async () => {
+ responsive.style.opacity = '0';
+ const transitionEnd = new Event('transitionend', { bubbles: true });
+ Object.defineProperty(transitionEnd, 'propertyName', { value: 'opacity' });
+ responsive.dispatchEvent(transitionEnd);
});
+ await waitFor(() => expect(screen.getByText('0/0')).toBeTruthy());
+ });
+
+ it('refreshes matches after hover and focus visibility changes', async () => {
+ const page = document.createElement('main');
+ const responsive = document.createElement('button');
+ responsive.textContent = 'foo';
+ page.append(responsive);
- // Some Chromium versions emit one final change after compositionend.
- fireEvent.change(input, { target: { value: '你' } });
- expect(findInPage).toHaveBeenCalledTimes(1);
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ const walkerSpy = vi.spyOn(document, 'createTreeWalker');
+ const initialSearchCount = walkerSpy.mock.calls.length;
+
+ fireEvent.mouseOver(responsive);
+ await waitFor(() =>
+ expect(walkerSpy.mock.calls.length).toBeGreaterThan(initialSearchCount),
+ );
+ const hoverSearchCount = walkerSpy.mock.calls.length;
+
+ fireEvent.focusIn(responsive);
+ await waitFor(() => expect(walkerSpy.mock.calls.length).toBeGreaterThan(hoverSearchCount));
+ walkerSpy.mockRestore();
+ });
+
+ it('refreshes matches when details sections expand or collapse', async () => {
+ const page = document.createElement('main');
+ const details = document.createElement('details');
+ details.innerHTML = '<summary>More</summary><span>foo</span>';
+ page.append(details);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('0/0')).toBeTruthy();
+
+ details.open = true;
+ await waitFor(() => expect(screen.getByText('1/1')).toBeTruthy());
+
+ details.open = false;
+ await waitFor(() => expect(screen.getByText('0/0')).toBeTruthy());
});
- it('keeps IME composition intact after an earlier search', async () => {
- const { input } = await openFindBar();
+ it('clears highlights when the query is cleared or the bar closes', async () => {
+ const page = document.createElement('main');
+ page.textContent = 'foo';
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
- fireEvent.change(input, { target: { value: 'a' } });
- await waitFor(() => expect(findInPage).toHaveBeenCalledTimes(1));
- findInPage.mockClear();
+ fireEvent.change(input, { target: { value: '' } });
+ expect(screen.queryByText('1/1')).toBeNull();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)).toBeUndefined();
+ expect(getHighlight(ACTIVE_HIGHLIGHT_NAME)).toBeUndefined();
+
+ fireEvent.change(input, { target: { value: 'foo' } });
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.close' }));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)).toBeUndefined();
+ });
+
+ it('waits for compositionend before searching committed IME text', async () => {
+ const page = document.createElement('main');
+ page.textContent = '中文';
+ const input = await openFindBar(page);
+ const walkerSpy = vi.spyOn(document, 'createTreeWalker');
fireEvent.compositionStart(input);
- fireEvent.change(input, { target: { value: 'z' } });
- fireEvent.change(input, { target: { value: 'zhong' } });
- expect(findInPage).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: '中' } });
- fireEvent.compositionEnd(input);
+ expect(screen.queryByText('1/1')).toBeNull();
- await waitFor(() =>
- expect(findInPage).toHaveBeenCalledWith({ text: '中', forward: true, findNext: true }),
+ fireEvent.compositionEnd(input, { target: { value: '中文' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+ const searchCount = walkerSpy.mock.calls.length;
+ fireEvent.change(input, { target: { value: '中文' } });
+ expect(walkerSpy).toHaveBeenCalledTimes(searchCount);
+ walkerSpy.mockRestore();
+ });
+
+ it('refreshes matches when a single-select option changes', async () => {
+ const page = document.createElement('main');
+ const select = document.createElement('select');
+ const first = document.createElement('option');
+ first.value = 'first';
+ first.textContent = 'first';
+ const second = document.createElement('option');
+ second.value = 'second';
+ second.textContent = 'second';
+ select.append(first, second);
+ page.append(select);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'second' } });
+ expect(screen.getByText('0/0')).toBeTruthy();
+
+ select.value = 'second';
+ fireEvent.change(select);
+ expect(screen.getByText('1/1')).toBeTruthy();
+ });
+
+ it('refreshes after a controlled select restores its submitted value', async () => {
+ const page = document.createElement('main');
+ const select = document.createElement('select');
+ const first = document.createElement('option');
+ first.value = 'first';
+ first.textContent = 'first';
+ const second = document.createElement('option');
+ second.value = 'second';
+ second.textContent = 'second';
+ select.append(first, second);
+ select.addEventListener('change', () => {
+ select.value = 'first';
+ });
+ page.append(select);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'second' } });
+ expect(screen.getByText('0/0')).toBeTruthy();
+
+ select.value = 'second';
+ fireEvent.change(select);
+ expect(screen.getByText('0/0')).toBeTruthy();
+ });
+
+ it('refreshes matches when responsive visibility changes on resize', async () => {
+ const page = document.createElement('main');
+ const responsive = document.createElement('span');
+ responsive.textContent = 'foo';
+ page.append(responsive);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+ const walkerSpy = vi.spyOn(document, 'createTreeWalker');
+ const initialWalkCount = walkerSpy.mock.calls.length;
+
+ responsive.style.display = 'none';
+ fireEvent(window, new Event('resize'));
+ fireEvent(window, new Event('resize'));
+ expect(walkerSpy).toHaveBeenCalledTimes(initialWalkCount);
+ await waitFor(() => expect(screen.getByText('0/0')).toBeTruthy());
+
+ responsive.style.display = '';
+ fireEvent(window, new Event('resize'));
+ fireEvent(window, new Event('resize'));
+ await waitFor(() => expect(screen.getByText('1/1')).toBeTruthy());
+ walkerSpy.mockRestore();
+ });
+
+ it('allows arrow navigation to rescan after a zero-result search', async () => {
+ const page = document.createElement('main');
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('0/0')).toBeTruthy();
+ const nextButton = screen.getByRole('button', { name: 'findInPage.next' });
+ expect((nextButton as HTMLButtonElement).disabled).toBe(false);
+
+ page.textContent = 'foo';
+ fireEvent.click(nextButton);
+ expect(screen.getByText('1/1')).toBeTruthy();
+ });
+
+ it('starts at the first or last match when navigation rescans from zero results', async () => {
+ const page = document.createElement('main');
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ page.textContent = 'foo foo';
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.next' }));
+ expect(screen.getByText('1/2')).toBeTruthy();
+
+ page.textContent = '';
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.next' }));
+ expect(screen.getByText('0/0')).toBeTruthy();
+
+ page.textContent = 'foo foo';
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.previous' }));
+ expect(screen.getByText('2/2')).toBeTruthy();
+ });
+
+ it('excludes content hidden by zero opacity', async () => {
+ const page = document.createElement('main');
+ const visible = document.createElement('span');
+ visible.textContent = 'foo';
+ const transparent = document.createElement('span');
+ transparent.textContent = 'foo';
+ transparent.style.opacity = '0';
+ page.append(visible, transparent);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ transparent.style.opacity = '';
+ fireEvent(window, new Event('resize'));
+ await waitFor(() => expect(screen.getByText('1/2')).toBeTruthy());
+ });
+
+ it('excludes clipping-based screen-reader-only text', async () => {
+ const page = document.createElement('main');
+ const visible = document.createElement('span');
+ visible.textContent = 'foo';
+ const srOnly = document.createElement('span');
+ srOnly.textContent = 'foo';
+ Object.assign(srOnly.style, {
+ position: 'absolute',
+ width: '1px',
+ height: '1px',
+ overflow: 'hidden',
+ clip: 'rect(0px, 0px, 0px, 0px)',
+ whiteSpace: 'nowrap',
+ });
+ page.append(visible, srOnly);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(1);
+ });
+
+ it('keeps text searchable when a line clamp clips its layout', async () => {
+ const rangeRectDescriptor = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
+ const elementRectDescriptor = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'getBoundingClientRect',
+ );
+ const page = document.createElement('main');
+ const visible = document.createElement('span');
+ visible.textContent = 'foo';
+ const clamped = document.createElement('span');
+ clamped.textContent = 'foo';
+ clamped.style.display = '-webkit-box';
+ clamped.style.overflow = 'hidden';
+ clamped.style.setProperty('-webkit-line-clamp', '1');
+ page.append(visible, clamped);
+
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value(this: Range) {
+ return [{ top: 20, bottom: 30, left: 0, right: 100 }];
+ },
+ });
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value(this: Element) {
+ if (this === clamped) return { top: 0, bottom: 10, left: 0, right: 100 };
+ return { top: 0, bottom: 100, left: 0, right: 100 };
+ },
+ });
+
+ try {
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(2);
+ } finally {
+ if (rangeRectDescriptor) {
+ Object.defineProperty(Range.prototype, 'getClientRects', rangeRectDescriptor);
+ } else {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ }
+ if (elementRectDescriptor) {
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', elementRectDescriptor);
+ } else {
+ delete (Element.prototype as { getBoundingClientRect?: unknown }).getBoundingClientRect;
+ }
+ }
+ });
+
+ it('keeps text searchable through an overflow-hidden ancestor', async () => {
+ const rangeRectDescriptor = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
+ const elementRectDescriptor = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'getBoundingClientRect',
);
+ const page = document.createElement('main');
+ const visible = document.createElement('span');
+ visible.textContent = 'foo';
+ const clippedContainer = document.createElement('div');
+ clippedContainer.style.overflow = 'hidden';
+ const clipped = document.createElement('span');
+ clipped.textContent = 'foo';
+ clippedContainer.append(clipped);
+ page.append(visible, clippedContainer);
+ let clipBottom = 10;
+
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value(this: Range) {
+ const parent = this.startContainer.parentElement;
+ const top = parent === clipped ? 20 : 0;
+ return [{ top, bottom: top + 10, left: 0, right: 100 }];
+ },
+ });
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value(this: Element) {
+ if (this === clippedContainer) return { top: 0, bottom: clipBottom, left: 0, right: 100 };
+ return { top: 0, bottom: 100, left: 0, right: 100 };
+ },
+ });
+
+ try {
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/2')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(2);
+
+ clipBottom = 100;
+ const transitionEnd = new Event('transitionend', { bubbles: true });
+ Object.defineProperty(transitionEnd, 'propertyName', { value: 'height' });
+ clippedContainer.dispatchEvent(transitionEnd);
+ await waitFor(() => expect(screen.getByText('1/2')).toBeTruthy());
+ } finally {
+ if (rangeRectDescriptor) {
+ Object.defineProperty(Range.prototype, 'getClientRects', rangeRectDescriptor);
+ } else {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ }
+ if (elementRectDescriptor) {
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', elementRectDescriptor);
+ } else {
+ delete (Element.prototype as { getBoundingClientRect?: unknown }).getBoundingClientRect;
+ }
+ }
});
- it('continues the current Electron search session for Enter navigation', async () => {
- const { input } = await openFindBar();
+ it('keeps ranges outside the root viewport eligible for navigation', async () => {
+ const rangeRectDescriptor = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
+ const elementRectDescriptor = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'getBoundingClientRect',
+ );
+ const root = document.createElement('div');
+ root.id = 'root';
+ root.style.overflow = 'hidden';
+ const page = document.createElement('main');
+ page.textContent = 'foo';
+ root.append(page);
+ document.body.append(root);
- fireEvent.change(input, { target: { value: 'term' } });
- await waitFor(() => expect(findInPage).toHaveBeenCalledTimes(1));
- findInPage.mockClear();
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value() {
+ return [{ top: 20, bottom: 30, left: 0, right: 100 }];
+ },
+ });
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value(this: Element) {
+ if (this === root) return { top: 0, bottom: 10, left: 0, right: 100 };
+ return { top: 0, bottom: 100, left: 0, right: 100 };
+ },
+ });
- fireEvent.keyDown(input, { key: 'Enter' });
- expect(findInPage).toHaveBeenCalledWith({ text: 'term', forward: true, findNext: false });
- fireEvent.keyDown(input, { key: 'Enter', shiftKey: true });
- expect(findInPage).toHaveBeenLastCalledWith({
- text: 'term',
- forward: false,
- findNext: false,
+ try {
+ const input = await openFindBar();
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(1);
+ } finally {
+ if (rangeRectDescriptor) {
+ Object.defineProperty(Range.prototype, 'getClientRects', rangeRectDescriptor);
+ } else {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ }
+ if (elementRectDescriptor) {
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', elementRectDescriptor);
+ } else {
+ delete (Element.prototype as { getBoundingClientRect?: unknown }).getBoundingClientRect;
+ }
+ }
+ });
+
+ it('keeps scrollable content searchable through a flexible overflow-hidden layout shell', async () => {
+ const rangeRectDescriptor = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
+ const elementRectDescriptor = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'getBoundingClientRect',
+ );
+ const layoutShell = document.createElement('div');
+ layoutShell.style.display = 'flex';
+ layoutShell.style.flexGrow = '1';
+ layoutShell.style.overflow = 'hidden';
+ const scrollContainer = document.createElement('div');
+ scrollContainer.style.overflowY = 'auto';
+ const page = document.createElement('main');
+ page.textContent = 'foo';
+ scrollContainer.append(page);
+ layoutShell.append(scrollContainer);
+ document.body.append(layoutShell);
+
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value() {
+ return [{ top: 20, bottom: 30, left: 0, right: 100 }];
+ },
+ });
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value(this: Element) {
+ if (this === layoutShell) return { top: 0, bottom: 10, left: 0, right: 100 };
+ return { top: 0, bottom: 100, left: 0, right: 100 };
+ },
+ });
+
+ try {
+ const input = await openFindBar();
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+ expect(getHighlight(MATCH_HIGHLIGHT_NAME)?.ranges).toHaveLength(1);
+ } finally {
+ if (rangeRectDescriptor) {
+ Object.defineProperty(Range.prototype, 'getClientRects', rangeRectDescriptor);
+ } else {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ }
+ if (elementRectDescriptor) {
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', elementRectDescriptor);
+ } else {
+ delete (Element.prototype as { getBoundingClientRect?: unknown }).getBoundingClientRect;
+ }
+ }
+ });
+
+ it('keeps transformed drawer text searchable while it is outside the viewport', async () => {
+ const rangeRectDescriptor = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
+ const elementRectDescriptor = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'getBoundingClientRect',
+ );
+ const drawer = document.createElement('aside');
+ drawer.style.position = 'fixed';
+ drawer.style.transform = 'translateX(100%)';
+ drawer.textContent = 'foo';
+ document.body.append(drawer);
+ let rangeRect = { top: 0, bottom: 10, left: -100, right: -90 };
+
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value() {
+ return [rangeRect];
+ },
+ });
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value() {
+ return { top: 0, bottom: 100, left: 0, right: 100 };
+ },
});
+
+ try {
+ const input = await openFindBar();
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ drawer.style.transform = 'none';
+ rangeRect = { top: 0, bottom: 10, left: 0, right: 10 };
+ const transitionEnd = new Event('transitionend', { bubbles: true });
+ Object.defineProperty(transitionEnd, 'propertyName', { value: 'transform' });
+ drawer.dispatchEvent(transitionEnd);
+ await waitFor(() => expect(screen.getByText('1/1')).toBeTruthy());
+ } finally {
+ if (rangeRectDescriptor) {
+ Object.defineProperty(Range.prototype, 'getClientRects', rangeRectDescriptor);
+ } else {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ }
+ if (elementRectDescriptor) {
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', elementRectDescriptor);
+ } else {
+ delete (Element.prototype as { getBoundingClientRect?: unknown }).getBoundingClientRect;
+ }
+ }
+ });
+
+ it('keeps scrollable content searchable regardless of overflow clipping', async () => {
+ const rangeRectDescriptor = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
+ const elementRectDescriptor = Object.getOwnPropertyDescriptor(
+ Element.prototype,
+ 'getBoundingClientRect',
+ );
+ const page = document.createElement('main');
+ const scrollContainer = document.createElement('div');
+ scrollContainer.style.overflowX = 'hidden';
+ scrollContainer.style.overflowY = 'auto';
+ const match = document.createElement('span');
+ match.textContent = 'foo';
+ scrollContainer.append(match);
+ page.append(scrollContainer);
+ let rangeRect = { top: 20, bottom: 30, left: 0, right: 100 };
+
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value() {
+ return [rangeRect];
+ },
+ });
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value(this: Element) {
+ if (this === scrollContainer) return { top: 0, bottom: 10, left: 0, right: 100 };
+ return { top: 0, bottom: 100, left: 0, right: 100 };
+ },
+ });
+
+ try {
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ rangeRect = { top: 0, bottom: 10, left: -20, right: -10 };
+ const transitionEnd = new Event('transitionend', { bubbles: true });
+ Object.defineProperty(transitionEnd, 'propertyName', { value: 'width' });
+ scrollContainer.dispatchEvent(transitionEnd);
+ await waitFor(() => expect(screen.getByText('1/1')).toBeTruthy());
+ } finally {
+ if (rangeRectDescriptor) {
+ Object.defineProperty(Range.prototype, 'getClientRects', rangeRectDescriptor);
+ } else {
+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;
+ }
+ if (elementRectDescriptor) {
+ Object.defineProperty(Element.prototype, 'getBoundingClientRect', elementRectDescriptor);
+ } else {
+ delete (Element.prototype as { getBoundingClientRect?: unknown }).getBoundingClientRect;
+ }
+ }
});
- it('does not treat a Windows IME confirmation key as find-next', async () => {
- const { input } = await openFindBar();
+ it('cancels a delayed scroll when the bar closes', async () => {
+ let nextFrame = 1;
+ const pendingFrames = new Map<number, FrameRequestCallback>();
+ const cancelAnimationFrameMock = vi.fn((frame: number) => {
+ pendingFrames.delete(frame);
+ });
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ const frame = nextFrame;
+ nextFrame += 1;
+ pendingFrames.set(frame, callback);
+ return frame;
+ });
+ vi.stubGlobal('cancelAnimationFrame', cancelAnimationFrameMock);
+
+ const page = document.createElement('main');
+ page.textContent = 'foo';
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
- fireEvent.change(input, { target: { value: 'term' } });
- await waitFor(() => expect(findInPage).toHaveBeenCalledTimes(1));
- findInPage.mockClear();
+ expect(pendingFrames.size).toBe(1);
+ fireEvent.click(screen.getByRole('button', { name: 'findInPage.close' }));
+
+ expect(cancelAnimationFrameMock).toHaveBeenCalledTimes(1);
+ expect(pendingFrames.size).toBe(0);
+ });
+
+ it('does not refresh responsive visibility while composing with IME', async () => {
+ const page = document.createElement('main');
+ const responsive = document.createElement('span');
+ responsive.textContent = 'foo';
+ page.append(responsive);
+
+ const input = await openFindBar(page);
+ fireEvent.change(input, { target: { value: 'foo' } });
+ expect(screen.getByText('1/1')).toBeTruthy();
+
+ const walkerSpy = vi.spyOn(document, 'createTreeWalker');
+ fireEvent.compositionStart(input);
+ fireEvent.change(input, { target: { value: 'bar' } });
+ const searchCount = walkerSpy.mock.calls.length;
+
+ responsive.style.display = 'none';
+ fireEvent(window, new Event('resize'));
+ expect(walkerSpy).toHaveBeenCalledTimes(searchCount);
+
+ fireEvent.compositionEnd(input, { target: { value: 'bar' } });
+ expect(screen.getByText('0/0')).toBeTruthy();
+ walkerSpy.mockRestore();
+ });
+
+ it('reopens the bar and selects the whole query', async () => {
+ const input = await openFindBar();
+ fireEvent.change(input, { target: { value: 'foobar' } });
+ input.setSelectionRange(2, 2);
+
+ await act(async () => {
+ expect(mocks.shortcutHandler?.(new KeyboardEvent('keydown'))).toBe(true);
+ await Promise.resolve();
+ });
- fireEvent.keyDown(input, { key: 'Enter', keyCode: 229 });
- expect(findInPage).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(input);
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe(input.value.length);
});
});
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 4442dbda4f..c484921a00 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -29,7 +29,7 @@
| `desktop.native.system-notification` | desktop | 系统通知 | notificationService(系统通知出口) | notificationService | apps/desktop/src/main/notificationService.ts | 0 | 0 | 0 |
| `desktop.native.tray` | desktop | 系统托盘 | windowsTrayLifecycle(Windows 托盘菜单) | windowsTrayLifecycle | apps/desktop/src/main/windowsTrayLifecycle.ts | 0 | 0 | 0 |
| `desktop.overlay.confirm` | desktop | 确认弹窗 | ConfirmDialogProvider 及插件确认宿主 | ConfirmDialogProvider, ForgeOidcInstallConfirmHost, GhostConfirmDialogHost, PluginPublisherConfirmHost | apps/desktop/src/renderer/cindy-brain/ForgeOidcInstallConfirmHost.tsx, apps/desktop/src/renderer/cindy-brain/GhostConfirmDialogHost.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/features/plugin/PluginPublisherConfirmHost.tsx | 21 | 0 | 6 |
-| `desktop.overlay.find-in-page` | desktop | 页内查找条 | App → FindInPageBar | FindInPageBar | apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx, apps/desktop/src/renderer/components/find-in-page/findInPageOwnership.ts | 0 | 0 | 4 |
+| `desktop.overlay.find-in-page` | desktop | 页内查找条 | App → FindInPageBar | FindInPageBar | apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx, apps/desktop/src/renderer/components/find-in-page/findInPageOwnership.ts | 2 | 0 | 4 |
| `desktop.overlay.interaction-portal` | desktop | 交互提问卡片 | components/interaction-portal(AskUser / 权限类卡片出口) | InteractionPromptCardShell, InteractionPromptHost | apps/desktop/src/renderer/components/interaction-portal/InteractionPromptCardShell.tsx, apps/desktop/src/renderer/components/interaction-portal/InteractionPromptHost.tsx, apps/desktop/src/renderer/components/interaction-portal/InteractionPromptSlot.tsx, apps/desktop/src/renderer/components/interaction-portal/index.ts, apps/desktop/src/renderer/components/interaction-portal/store.ts | 10 | 0 | 4 |
| `desktop.overlay.permission-prompt` | desktop | 权限询问 | PermissionPrompt(会话内权限卡;DS-6 迁移前置) | AskUserQuestionPrompt, PermissionPrompt, PermissionSelector | apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx | 51 | 4 | 27 |
| `desktop.overlay.route-error` | desktop | 路由错误页 | router errorElement → RouteErrorFallback / TopLevelErrorBoundary | AppCrashScreen, RouteErrorFallback, TopLevelErrorBoundary | apps/desktop/src/renderer/components/error/AppCrashScreen.tsx, apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx, apps/desktop/src/renderer/components/error/RouteErrorFallback.tsx, apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx, apps/desktop/src/renderer/components/error/localDbFatalView.ts | 11 | 0 | 6 |