AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix Android note search and keyboard handling
tianma-ifeede93e88b72
diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex ea4f25a0..8b75d8b0 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -24,6 +24,7 @@"@tiptap/extension-list": "3.27.1","@tiptap/extension-placeholder": "3.27.1","@tiptap/extension-table": "3.27.1",+ "@tiptap/pm": "3.27.1","@tiptap/react": "3.27.1","@tiptap/starter-kit": "3.27.1","beautiful-mermaid": "^1.1.3",diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsxindex 1c1caaca..1734bdcd 100644--- a/apps/mobile/src/components/LocalTiptapEditor.tsx+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx@@ -8,7 +8,7 @@ import CodeBlock from "@tiptap/extension-code-block";import Placeholder from "@tiptap/extension-placeholder";import { TaskItem, TaskList } from "@tiptap/extension-list";import { TableKit } from "@tiptap/extension-table";-import { EditorContent, useEditor, useEditorState } from "@tiptap/react";+import { EditorContent, Extension, useEditor, useEditorState, type Editor } from "@tiptap/react";import StarterKit from "@tiptap/starter-kit";import * as Clipboard from "expo-clipboard";import {@@ -60,6 +60,11 @@ import {stripMobileImageUploadPlaceholders,} from "../lib/mobile-image-upload-placeholder";import { getMobileAiSourceRange } from "../lib/mobile-ai-selection";+import {+ MOBILE_NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY,+ createMobileNoteSearchHighlightPlugin,+ getMobileNoteSearchMatches,+} from "../lib/mobile-note-search";import { toProtectedResourceLoadPath } from "../lib/mobile-protected-resources";type EditorDoc = TiptapDoc;@@ -89,7 +94,7 @@ type LocalTiptapEditorSharedProps = {onLoadResource: (source: string) => Promise<string | null>;onResourcePress?: (targetJson: string) => Promise<void>;onReady?: (startupMs: number) => Promise<void>;- onSearchResult?: (count: number, index: number) => Promise<void>;+ onSearchResult?: (count: number, index: number, query: string) => Promise<void>;ref: Ref<LocalTiptapEditorRef>;locale: "zh-CN" | "en-US";theme: "light" | "dark";@@ -423,6 +428,62 @@ const inlineMermaidSvgStyles = (svg: string) => {return serialized;};+const getEditorScrollContainer = (editor: Editor) =>+ editor.view.dom.closest<HTMLElement>(".edgeever-editor-scroll");++const updateEditorKeyboardInset = (editor: Editor) => {+ const scrollContainer = getEditorScrollContainer(editor);+ if (!scrollContainer) {+ return;+ }+ const visualViewport = window.visualViewport;+ const visibleBottom = visualViewport+ ? visualViewport.offsetTop + visualViewport.height+ : window.innerHeight;+ const keyboardInset = Math.max(0, window.innerHeight - visibleBottom);+ scrollContainer.style.setProperty("--edgeever-keyboard-inset", `${Math.round(keyboardInset)}px`);+};++const scrollEditorPositionIntoView = (+ editor: Editor,+ position: number,+ options: { behavior?: ScrollBehavior; center?: boolean } = {}+) => {+ const scrollContainer = getEditorScrollContainer(editor);+ if (!scrollContainer) {+ return;+ }+ try {+ const containerRect = scrollContainer.getBoundingClientRect();+ const positionRect = editor.view.coordsAtPos(position);+ const visualViewport = window.visualViewport;+ const visibleTop = Math.max(containerRect.top, visualViewport?.offsetTop ?? containerRect.top);+ const visibleBottom = Math.min(+ containerRect.bottom,+ visualViewport ? visualViewport.offsetTop + visualViewport.height : containerRect.bottom+ );+ const padding = 24;+ const isAbove = positionRect.top < visibleTop + padding;+ const isBelow = positionRect.bottom > visibleBottom - padding;+ if (!isAbove && !isBelow) {+ return;+ }+ const targetTop = options.center+ ? scrollContainer.scrollTop + positionRect.top - visibleTop+ - (visibleBottom - visibleTop - Math.max(positionRect.bottom - positionRect.top, 1)) / 2+ : scrollContainer.scrollTop + (isAbove+ ? positionRect.top - visibleTop - padding+ : positionRect.bottom - visibleBottom + padding);+ scrollContainer.scrollTo({+ behavior: options.behavior ?? "auto",+ top: Math.max(0, targetTop),+ });+ } catch {+ // The selection can disappear while content is being replaced. The next+ // selection/viewport update will retry with a valid document position.+ }+};+function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {const isViewer = props.mode === "viewer";const autoFocus = props.mode === "viewer" ? false : Boolean(props.autoFocus);@@ -454,6 +515,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {const onAiCancelRef = useRef(props.mode === "viewer" ? undefined : props.onAiCancel);const onReadyRef = useRef(props.onReady ?? (async () => undefined));const onSearchResultRef = useRef(props.onSearchResult ?? ignoreSearchResult);+ const searchStateRef = useRef({ activeIndex: -1, query: "" });const [aiPanel, setAiPanel] = useState<MobileAiPanelState | null>(null);const [aiSelectionHint, setAiSelectionHint] = useState(false);const aiSelectionHintTimerRef = useRef<number | null>(null);@@ -526,6 +588,18 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {() => createMobileCodeBlockExtension(props.locale, props.theme),[props.locale, props.theme]);+ const searchHighlightExtension = useMemo(+ () => Extension.create({+ name: "edgeeverMobileNoteSearchHighlight",+ addProseMirrorPlugins() {+ return [createMobileNoteSearchHighlightPlugin({+ getActiveIndex: () => searchStateRef.current.activeIndex,+ getQuery: () => searchStateRef.current.query,+ })];+ },+ }),+ []+ );const editor = useEditor({editable: !isViewer,@@ -538,6 +612,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {...createEdgeEverMathematics(),mermaidCodeBlockExtension,protectedImageExtension,+ searchHighlightExtension,TableKit.configure({table: { renderWrapper: true },}),@@ -607,24 +682,42 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {}, [editor, isViewer, props.baseUrl]);const search = useCallback((query: DOMValue, requestedIndex: DOMValue) => {- const matches = getEditorSearchMatches(editor, typeof query === "string" ? query : "");+ const normalizedQuery = typeof query === "string" ? query : "";+ const matches = editor && !editor.isDestroyed+ ? getMobileNoteSearchMatches(editor.state.doc, normalizedQuery)+ : [];const requestedMatchIndex = typeof requestedIndex === "number" ? requestedIndex : 0;const index = matches.length > 0- ? Math.min(Math.max(requestedMatchIndex, 0), matches.length - 1)+ ? requestedMatchIndex < 0+ ? -1+ : Math.min(Math.max(requestedMatchIndex, 0), matches.length - 1): 0;- const match = matches[index];- if (editor && !editor.isDestroyed && match) {- editor.commands.setTextSelection({ from: match.from, to: match.to });+ searchStateRef.current = {+ activeIndex: matches.length > 0 ? index : -1,+ query: normalizedQuery,+ };+ const match = index >= 0 ? matches[index] : undefined;+ if (editor && !editor.isDestroyed) {+ if (match) {+ editor.chain().setTextSelection({ from: match.from, to: match.to }).scrollIntoView().run();+ window.requestAnimationFrame(() => {+ scrollEditorPositionIntoView(editor, match.from, { behavior: "smooth", center: true });+ });+ } else {+ editor.view.dispatch(editor.state.tr.setMeta(MOBILE_NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY, true));+ }}- void onSearchResultRef.current(matches.length, index);+ void onSearchResultRef.current(matches.length, index, normalizedQuery);}, [editor]);const replaceAll = useCallback((query: DOMValue, replacement: DOMValue) => {const normalizedQuery = typeof query === "string" ? query : "";const normalizedReplacement = typeof replacement === "string" ? replacement : "";- const matches = getEditorSearchMatches(editor, normalizedQuery);+ const matches = editor && !editor.isDestroyed+ ? getMobileNoteSearchMatches(editor.state.doc, normalizedQuery)+ : [];if (!editor || editor.isDestroyed || matches.length === 0) {- void onSearchResultRef.current(0, 0);+ void onSearchResultRef.current(0, 0, normalizedQuery);return;}editor@@ -918,7 +1011,12 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {setContent,flush,focusEnd: () => {- if (!isViewer) editor?.commands.focus("end");+ if (!isViewer && editor && !editor.isDestroyed) {+ editor.commands.focus("end");+ window.requestAnimationFrame(() => {+ scrollEditorPositionIntoView(editor, editor.state.selection.head);+ });+ }},removeResource,renameResource,@@ -994,6 +1092,61 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {}}, [editor, isViewer, props.baseUrl, props.content]);+ useEffect(() => {+ if (!editor || editor.isDestroyed || isViewer) {+ return;+ }++ let scrollFrame = 0;+ let settledScrollTimer: number | null = null;+ const ensureSelectionVisible = () => {+ updateEditorKeyboardInset(editor);+ window.cancelAnimationFrame(scrollFrame);+ scrollFrame = window.requestAnimationFrame(() => {+ if (!editor.isDestroyed && editor.isFocused) {+ scrollEditorPositionIntoView(editor, editor.state.selection.head);+ }+ });+ if (settledScrollTimer !== null) {+ window.clearTimeout(settledScrollTimer);+ }+ // Android IMEs animate the visible viewport after focus. Recheck once the+ // animation settles so the last line stays above the keyboard.+ settledScrollTimer = window.setTimeout(() => {+ settledScrollTimer = null;+ if (!editor.isDestroyed && editor.isFocused) {+ updateEditorKeyboardInset(editor);+ scrollEditorPositionIntoView(editor, editor.state.selection.head);+ }+ }, 180);+ };++ const handleSelectionUpdate = () => {+ if (editor.isFocused) {+ ensureSelectionVisible();+ }+ };+ const visualViewport = window.visualViewport;+ window.addEventListener("resize", ensureSelectionVisible);+ visualViewport?.addEventListener("resize", ensureSelectionVisible);+ visualViewport?.addEventListener("scroll", ensureSelectionVisible);+ editor.on("focus", ensureSelectionVisible);+ editor.on("selectionUpdate", handleSelectionUpdate);+ updateEditorKeyboardInset(editor);++ return () => {+ window.cancelAnimationFrame(scrollFrame);+ if (settledScrollTimer !== null) {+ window.clearTimeout(settledScrollTimer);+ }+ window.removeEventListener("resize", ensureSelectionVisible);+ visualViewport?.removeEventListener("resize", ensureSelectionVisible);+ visualViewport?.removeEventListener("scroll", ensureSelectionVisible);+ editor.off("focus", ensureSelectionVisible);+ editor.off("selectionUpdate", handleSelectionUpdate);+ };+ }, [editor, isViewer]);+const toolbarState = useEditorState({editor,selector: ({ editor: activeEditor }) =>@@ -1340,43 +1493,6 @@ const MobileSelectionAiPanel = ({);};-type EditorSearchMatch = { from: number; to: number };--const getEditorSearchMatches = (editor: ReturnType<typeof useEditor>, query: string): EditorSearchMatch[] => {- const needle = query.trim().toLocaleLowerCase();- if (!editor || editor.isDestroyed || needle.length === 0) {- return [];- }-- const characters: Array<{ char: string; pos: number }> = [];- let previousTextEnd: number | null = null;- editor.state.doc.descendants((node, pos) => {- if (!node.isText || !node.text) {- return;- }- if (previousTextEnd !== null && pos > previousTextEnd) {- characters.push({ char: "\u0000", pos: -1 });- }- for (let index = 0; index < node.text.length; index += 1) {- characters.push({ char: node.text[index] ?? "", pos: pos + index });- }- previousTextEnd = pos + node.text.length;- });-- const haystack = characters.map((item) => item.char).join("").toLocaleLowerCase();- const matches: EditorSearchMatch[] = [];- let index = haystack.indexOf(needle);- while (index !== -1) {- const start = characters[index];- const end = characters[index + needle.length - 1];- if (start && end && start.pos >= 0 && end.pos >= 0) {- matches.push({ from: start.pos, to: end.pos + 1 });- }- index = haystack.indexOf(needle, index + needle.length);- }- return matches;-};-const EditorIcon = ({ children, size, strokeWidth }: { children: ReactNode; size: number; strokeWidth: number }) => (<svg aria-hidden="true" fill="none" height={size} stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} viewBox="0 0 24 24" width={size}>{children}@@ -2324,6 +2440,7 @@ const getEditorStyles = (theme: "light" | "dark", options?: { viewer?: boolean }.edgeever-editor-toolbar .edgeever-ai-toolbar-button { width: auto; gap: 4px; padding: 0 10px; border-color: ${theme === "dark" ? "#166534" : "#bbf7d0"}; background: ${theme === "dark" ? "#052e24" : "#ecfdf5"}; color: ${theme === "dark" ? "#6ee7b7" : "#047857"}; font-weight: 750; }.tiptap { min-height: 100%; max-width: 100%; min-width: 0; outline: none; }.edgeever-editor-scroll {+ --edgeever-keyboard-inset: 0px;min-height: 0;min-width: 0;flex: 1;@@ -2367,7 +2484,8 @@ const getEditorStyles = (theme: "light" | "dark", options?: { viewer?: boolean }min-height: 100%;max-width: 100%;min-width: 0;- padding: 18px 12px 32px;+ padding: 18px 12px calc(32px + var(--edgeever-keyboard-inset));+ scroll-padding-bottom: calc(32px + var(--edgeever-keyboard-inset));font-size: 1rem;line-height: var(--editor-body-line-height);overflow-wrap: anywhere;@@ -2375,6 +2493,15 @@ const getEditorStyles = (theme: "light" | "dark", options?: { viewer?: boolean }caret-color: ${options?.viewer ? "transparent" : "#0f766e"};}.edgeever-viewer-content { -webkit-user-select: text; user-select: text; cursor: text; }+ .edgeever-search-match {+ border-radius: 0.2rem;+ background-color: rgb(254 240 138 / 0.8);+ box-shadow: 0 0 0 1px rgb(234 179 8 / 0.25);+ }+ .edgeever-search-match-active {+ background-color: rgb(251 191 36 / 0.9);+ box-shadow: 0 0 0 2px rgb(217 119 6 / 0.45);+ }.edgeever-editor-content > :first-child { margin-top: 0; }.edgeever-editor-content p {margin: 0 0 var(--editor-paragraph-spacing) 0;diff --git a/apps/mobile/src/lib/mobile-note-search.test.ts b/apps/mobile/src/lib/mobile-note-search.test.tsnew file mode 100644index 00000000..a28974db--- /dev/null+++ b/apps/mobile/src/lib/mobile-note-search.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from "bun:test";+import { Schema } from "@tiptap/pm/model";+import { getMobileNoteSearchMatches, getNextMobileNoteSearchIndex } from "./mobile-note-search";++const schema = new Schema({+ nodes: {+ doc: { content: "block+" },+ paragraph: { content: "inline*", group: "block" },+ text: { group: "inline" },+ },+ marks: {+ strong: {},+ },+});++describe("mobile note search", () => {+ test("finds case-insensitive matches split across inline marks", () => {+ const strong = schema.marks.strong.create();+ const doc = schema.node("doc", null, [+ schema.node("paragraph", null, [+ schema.text("Edge"),+ schema.text("Ever", [strong]),+ schema.text(" edgeever"),+ ]),+ ]);++ expect(getMobileNoteSearchMatches(doc, "edgeever")).toEqual([+ { from: 1, to: 9 },+ { from: 10, to: 18 },+ ]);+ });++ test("does not create a match across block boundaries", () => {+ const doc = schema.node("doc", null, [+ schema.node("paragraph", null, schema.text("edge")),+ schema.node("paragraph", null, schema.text("ever")),+ ]);++ expect(getMobileNoteSearchMatches(doc, "edgeever")).toEqual([]);+ });++ test("wraps previous and next navigation", () => {+ expect(getNextMobileNoteSearchIndex(0, -1, 3)).toBe(2);+ expect(getNextMobileNoteSearchIndex(2, 1, 3)).toBe(0);+ expect(getNextMobileNoteSearchIndex(0, 1, 0)).toBe(0);+ });+});diff --git a/apps/mobile/src/lib/mobile-note-search.ts b/apps/mobile/src/lib/mobile-note-search.tsnew file mode 100644index 00000000..aa777cb5--- /dev/null+++ b/apps/mobile/src/lib/mobile-note-search.ts@@ -0,0 +1,78 @@+import type { Editor } from "@tiptap/react";+import { Plugin, PluginKey } from "@tiptap/pm/state";+import { Decoration, DecorationSet } from "@tiptap/pm/view";++export type MobileNoteSearchMatch = {+ from: number;+ to: number;+};++export const MOBILE_NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY = new PluginKey("edgeever-mobile-note-search-highlight");++export const getMobileNoteSearchMatches = (+ doc: Editor["state"]["doc"],+ query: string+): MobileNoteSearchMatch[] => {+ const needle = query.trim().toLocaleLowerCase();+ if (needle.length === 0) {+ return [];+ }++ const characters: Array<{ char: string; pos: number }> = [];+ let previousTextEnd: number | null = null;+ doc.descendants((node, pos) => {+ if (!node.isText || !node.text) {+ return;+ }+ if (previousTextEnd !== null && pos > previousTextEnd) {+ characters.push({ char: "\u0000", pos: -1 });+ }+ for (let index = 0; index < node.text.length; index += 1) {+ characters.push({ char: node.text[index] ?? "", pos: pos + index });+ }+ previousTextEnd = pos + node.text.length;+ });++ const haystack = characters.map((item) => item.char).join("").toLocaleLowerCase();+ const matches: MobileNoteSearchMatch[] = [];+ let index = haystack.indexOf(needle);+ while (index !== -1) {+ const start = characters[index];+ const end = characters[index + needle.length - 1];+ if (start && end && start.pos >= 0 && end.pos >= 0) {+ matches.push({ from: start.pos, to: end.pos + 1 });+ }+ index = haystack.indexOf(needle, index + needle.length);+ }+ return matches;+};++export const createMobileNoteSearchHighlightPlugin = (options: {+ getActiveIndex: () => number;+ getQuery: () => string;+}) => new Plugin({+ key: MOBILE_NOTE_SEARCH_HIGHLIGHT_PLUGIN_KEY,+ props: {+ decorations: (state) => {+ const matches = getMobileNoteSearchMatches(state.doc, options.getQuery());+ if (matches.length === 0) {+ return DecorationSet.empty;+ }+ const activeIndex = options.getActiveIndex();+ return DecorationSet.create(+ state.doc,+ matches.map((match, index) => Decoration.inline(match.from, match.to, {+ class: index === activeIndex+ ? "edgeever-search-match edgeever-search-match-active"+ : "edgeever-search-match",+ }))+ );+ },+ },+});++export const getNextMobileNoteSearchIndex = (+ current: number,+ direction: 1 | -1,+ matchCount: number+) => matchCount > 0 ? (current + direction + matchCount) % matchCount : 0;diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsxindex 63a1035b..b699700a 100644--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { DEFAULT_MEMO_TITLE, resolveMemoContentDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";import * as Clipboard from "expo-clipboard";-import { Image as RNImage, Platform, StyleSheet, View, type ImageStyle, type StyleProp } from "react-native";+import { Image as RNImage, Platform, StyleSheet, Text as RNText, View, type ImageStyle, type StyleProp, type TextStyle } from "react-native";import { Modal } from "react-native";import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";import { SvgXml } from "react-native-svg";@@ -11,6 +11,7 @@ import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/Locaimport { MobileAiAssistantModal } from "../components/MobileAiAssistantModal";import { MobileResourceActions } from "../components/MobileResourceActions";import { SAFE_DOM_WEBVIEW_PROPS } from "../lib/mobile-dom";+import { getNextMobileNoteSearchIndex } from "../lib/mobile-note-search";import { safeDomCall } from "../lib/safe-dom-call";import {getMobileImageTarget,@@ -30,6 +31,7 @@ import { useMobileTheme } from "../lib/mobile-theme";import { useSession } from "../lib/session";import { beginEditorStartup } from "../lib/startup-performance";import type { MobileSyncQueueItem } from "../lib/sync-queue";+import { getTextSearchMatches } from "./workspace-utils";import { styles } from "./workspace-styles";const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;@@ -292,7 +294,48 @@ const DetailActionButton = ({ children, disabled = false, label, onPress }: { ch</Pressable>);+const HighlightedMetadataText = ({+ activeIndex,+ matchOffset,+ matches,+ numberOfLines,+ style,+ text,+}: {+ activeIndex: number;+ matchOffset: number;+ matches: Array<{ end: number; start: number }>;+ numberOfLines?: number;+ style: StyleProp<TextStyle>;+ text: string;+}) => {+ if (matches.length === 0) {+ return <RNText numberOfLines={numberOfLines} selectable style={style}>{text}</RNText>;+ }+ const content: ReactNode[] = [];+ let cursor = 0;+ matches.forEach((match, index) => {+ if (match.start > cursor) {+ content.push(text.slice(cursor, match.start));+ }+ content.push(+ <RNText+ key={`${match.start}-${match.end}`}+ style={activeIndex === matchOffset + index ? styles.noteSearchHighlightActive : styles.noteSearchHighlight}+ >+ {text.slice(match.start, match.end)}+ </RNText>+ );+ cursor = match.end;+ });+ if (cursor < text.length) {+ content.push(text.slice(cursor));+ }+ return <RNText numberOfLines={numberOfLines} selectable style={style}>{content}</RNText>;+};+export const MemoDetailModal = ({+ initialSearchQuery,isDeleting,isLoading,isRestoring,@@ -317,6 +360,7 @@ export const MemoDetailModal = ({syncStatus,visible,}: {+ initialSearchQuery: string;isDeleting: boolean;isLoading: boolean;isRestoring: boolean;@@ -349,7 +393,7 @@ export const MemoDetailModal = ({const [aiAssistantOpen, setAiAssistantOpen] = useState(false);const [searchOpen, setSearchOpen] = useState(false);const [searchQuery, setSearchQuery] = useState("");- const [searchMatchCount, setSearchMatchCount] = useState(0);+ const [bodySearchMatchCount, setBodySearchMatchCount] = useState(0);const [activeMatchIndex, setActiveMatchIndex] = useState(0);const [imagePreview, setImagePreview] = useState<{ alt: string; source: string } | null>(null);const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);@@ -429,6 +473,14 @@ export const MemoDetailModal = ({}}, []);+ const memoTitle = memo?.title?.trim() || DEFAULT_MEMO_TITLE;+ const memoTagsText = memo?.tags.join(", ") ?? "";+ const metadataSearchMatches = useMemo(() => ({+ tags: getTextSearchMatches(memoTagsText, searchQuery),+ title: getTextSearchMatches(memoTitle, searchQuery),+ }), [memoTagsText, memoTitle, searchQuery]);+ const metadataSearchMatchCount = metadataSearchMatches.title.length + metadataSearchMatches.tags.length;+ const searchMatchCount = metadataSearchMatchCount + bodySearchMatchCount;const searchMatchLabel = searchQuery.trim()? `${searchMatchCount > 0 ? activeMatchIndex + 1 : 0}/${searchMatchCount}`: "0/0";@@ -467,28 +519,44 @@ export const MemoDetailModal = ({) + 16;useEffect(() => {+ const normalizedInitialSearchQuery = initialSearchQuery.trim();setViewerReady(false);- setSearchOpen(false);- setSearchQuery("");- setSearchMatchCount(0);+ setSearchOpen(Boolean(normalizedInitialSearchQuery));+ setSearchQuery(normalizedInitialSearchQuery);+ setBodySearchMatchCount(0);setActiveMatchIndex(0);setImagePreview(null);setResourceTarget(null);resourceDataUrlCacheRef.current.clear();- }, [memo?.id]);+ }, [initialSearchQuery, memo?.id]);useEffect(() => {if (!viewerReady || !searchOpen) {return;}- safeDomCall(() => viewerRef.current?.search(searchQuery, activeMatchIndex));- }, [activeMatchIndex, searchOpen, searchQuery, viewerReady]);+ const bodyMatchIndex = activeMatchIndex - metadataSearchMatchCount;+ const runSearch = () => {+ safeDomCall(() => viewerRef.current?.search(searchQuery, bodyMatchIndex >= 0 ? bodyMatchIndex : -1));+ };+ runSearch();+ // The first imperative call can land while Android is replacing the DOM+ // WebView after navigation. Short idempotent retries make that ready race+ // deterministic; stale callbacks are rejected by their query below.+ const retryTimers = [120, 360].map((delayMs) => setTimeout(runSearch, delayMs));+ return () => retryTimers.forEach(clearTimeout);+ }, [activeMatchIndex, metadataSearchMatchCount, searchOpen, searchQuery, viewerReady]);++ useEffect(() => {+ setActiveMatchIndex((current) => searchMatchCount > 0+ ? Math.min(current, searchMatchCount - 1)+ : 0);+ }, [searchMatchCount]);const moveSearchMatch = (direction: 1 | -1) => {if (searchMatchCount === 0) {return;}- setActiveMatchIndex((current) => (current + direction + searchMatchCount) % searchMatchCount);+ setActiveMatchIndex((current) => getNextMobileNoteSearchIndex(current, direction, searchMatchCount));};const closeActionsAndRun = (action: () => void) => {@@ -657,7 +725,13 @@ export const MemoDetailModal = ({) : memo ? (<View style={detailLayoutStyles.body}><View style={detailLayoutStyles.meta}>- <Text selectable style={styles.detailTitle}>{memo.title?.trim() || DEFAULT_MEMO_TITLE}</Text>+ <HighlightedMetadataText+ activeIndex={activeMatchIndex}+ matchOffset={0}+ matches={metadataSearchMatches.title}+ style={styles.detailTitle}+ text={memoTitle}+ /><View style={styles.detailMetaRow}><View style={styles.detailNotebookButton}><Text numberOfLines={1} selectable style={styles.detailNotebookName}>{notebookName}</Text>@@ -665,13 +739,14 @@ export const MemoDetailModal = ({</View><View style={styles.detailTagsGroup}><Tag color="#64748b" size={16} />- <Text+ <HighlightedMetadataText+ activeIndex={activeMatchIndex}+ matchOffset={metadataSearchMatches.title.length}+ matches={metadataSearchMatches.tags}numberOfLines={1}- selectablestyle={[styles.detailTagsInline, memo.tags.length === 0 && styles.detailTagsPlaceholder]}- >- {memo.tags.length ? memo.tags.join(", ") : "添加标签,用逗号分隔"}- </Text>+ text={memoTagsText || "添加标签,用逗号分隔"}+ /></View></View>{searchOpen ? (@@ -684,6 +759,7 @@ export const MemoDetailModal = ({autoCorrect={false}onChangeText={(value) => {setSearchQuery(value);+ setBodySearchMatchCount(0);setActiveMatchIndex(0);}}placeholder="在当前笔记内搜索"@@ -703,9 +779,9 @@ export const MemoDetailModal = ({<DetailActionButton label="关闭搜索" onPress={() => {setSearchOpen(false);setSearchQuery("");- setSearchMatchCount(0);+ setBodySearchMatchCount(0);setActiveMatchIndex(0);- safeDomCall(() => viewerRef.current?.search("", 0));+ safeDomCall(() => viewerRef.current?.search("", -1));}}><X color="#0f172a" size={16} /></DetailActionButton>@@ -738,9 +814,10 @@ export const MemoDetailModal = ({setViewerReady(true);}}onResourcePress={onResourcePress}- onSearchResult={async (count, index) => {- setSearchMatchCount(count);- setActiveMatchIndex(count > 0 ? index : 0);+ onSearchResult={async (count, _index, resultQuery) => {+ if (resultQuery === searchQuery) {+ setBodySearchMatchCount(count);+ }}}ref={viewerRef}theme={resolvedTheme}diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex 658968b7..e0f45675 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -46,6 +46,7 @@ import {Image as RNImage,type ImageStyle,InteractionManager,+ KeyboardAvoidingView,type LayoutChangeEvent,Linking,Modal,@@ -1336,6 +1337,7 @@ export const WorkspaceScreen = ({) : null}<MemoDetailModal+ initialSearchQuery={selectedMemoId ? searchText.trim() : ""}isDeleting={deleteMemoMutation.isPending}isLoading={memoDetailQuery.isLoading}isRestoring={restoreMemoMutation.isPending}@@ -2810,6 +2812,11 @@ const RichEditorModal = ({return (<SafeAreaView style={styles.richEditorSafeArea}>+ <KeyboardAvoidingView+ behavior="height"+ enabled={Platform.OS === "android"}+ style={styles.richEditorKeyboardAvoiding}+ ><View style={styles.createMemoHeader}><Pressable accessibilityLabel="返回" accessibilityRole="button" disabled={saving || uploading} onPress={() => void requestClose()} style={styles.createMemoBackButton}><ChevronLeft color={saving || uploading ? "#cbd5e1" : "#0f172a"} size={30} />@@ -2893,6 +2900,7 @@ const RichEditorModal = ({target={resourceTarget}/>{uploadSourcePicker}+ </KeyboardAvoidingView></SafeAreaView>);};diff --git a/apps/mobile/src/screens/workspace-styles.ts b/apps/mobile/src/screens/workspace-styles.tsindex e70d7e5f..23da381b 100644--- a/apps/mobile/src/screens/workspace-styles.ts+++ b/apps/mobile/src/screens/workspace-styles.ts@@ -1270,6 +1270,9 @@ const baseWorkspaceStyles = StyleSheet.create({backgroundColor: "#ffffff",flex: 1,},+ richEditorKeyboardAvoiding: {+ flex: 1,+ },richEditorHeaderStatus: {maxWidth: 76,},diff --git a/bun.lock b/bun.lockindex b320ff2b..569244e9 100644--- a/bun.lock+++ b/bun.lock@@ -120,6 +120,7 @@"@tiptap/extension-list": "3.27.1","@tiptap/extension-placeholder": "3.27.1","@tiptap/extension-table": "3.27.1",+ "@tiptap/pm": "3.27.1","@tiptap/react": "3.27.1","@tiptap/starter-kit": "3.27.1","beautiful-mermaid": "^1.1.3",diff --git a/tests/mobile-app-scope.test.ts b/tests/mobile-app-scope.test.tsindex 731a4072..0f5a64ff 100644--- a/tests/mobile-app-scope.test.ts+++ b/tests/mobile-app-scope.test.ts@@ -9,6 +9,10 @@ const memoDetailSource = readFileSync(new URL("../apps/mobile/src/screens/WorkspaceMemoDetail.tsx", import.meta.url),"utf8");+const localTiptapEditorSource = readFileSync(+ new URL("../apps/mobile/src/components/LocalTiptapEditor.tsx", import.meta.url),+ "utf8"+);const notesViewSource = readFileSync(new URL("../apps/mobile/src/screens/WorkspaceNotesView.tsx", import.meta.url),"utf8"@@ -71,6 +75,22 @@ describe("mobile app scope", () => {expect(memoDetailSource).not.toContain("react-native-markdown-display");});+ test("carries workspace search into note detail and scrolls active matches", () => {+ expect(workspaceSource).toContain('initialSearchQuery={selectedMemoId ? searchText.trim() : ""}');+ expect(memoDetailSource).toContain("metadataSearchMatchCount + bodySearchMatchCount");+ expect(memoDetailSource).toContain("const retryTimers = [120, 360]");+ expect(localTiptapEditorSource).toContain("createMobileNoteSearchHighlightPlugin");+ expect(localTiptapEditorSource).toContain("scrollEditorPositionIntoView(editor, match.from");+ });++ test("keeps the Android editor caret visible while the keyboard viewport changes", () => {+ expect(workspaceSource).toContain("KeyboardAvoidingView");+ expect(workspaceSource).toContain('enabled={Platform.OS === "android"}');+ expect(localTiptapEditorSource).toContain('visualViewport?.addEventListener("resize", ensureSelectionVisible)');+ expect(localTiptapEditorSource).toContain("--edgeever-keyboard-inset");+ expect(localTiptapEditorSource).toContain("scrollEditorPositionIntoView(editor, editor.state.selection.head)");+ });+test("keeps Android memo list motion and spring feedback", () => {expect(notesViewSource).toContain("FadeInDown.duration(260).springify().damping(18)");expect(notesViewSource).toContain("FadeOutUp.duration(220)");