Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(mobile): improve first sync and navigation safety

tianma-if36621220d009
diff --git a/apps/mobile/src/lib/local-mirror.test.ts b/apps/mobile/src/lib/local-mirror.test.ts
index 8add4616..bc7a15a0 100644
--- a/apps/mobile/src/lib/local-mirror.test.ts
+++ b/apps/mobile/src/lib/local-mirror.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test";
-import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged } from "./mobile-sync-protocol";
+import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized } from "./mobile-sync-protocol";
test("rebuilds the mobile mirror when the server change cursor rewinds", () => {
expect(hasMobileSyncCursorRewound(42, 7)).toBe(true);
@@ -19,3 +19,10 @@ test("rebuilds the mobile mirror when the server data identity changes", () => {
test("keeps compatibility with servers that do not report a data identity", () => {
expect(hasMobileSyncIdentityChanged("legacy")).toBe(false);
});
+
+test("waits for a complete local mirror before rendering an empty notebook", () => {
+ expect(isMobileSyncMetadataInitialized("42", "workspace-a")).toBe(true);
+ expect(isMobileSyncMetadataInitialized(null, "workspace-a")).toBe(false);
+ expect(isMobileSyncMetadataInitialized("42", null)).toBe(false);
+ expect(isMobileSyncMetadataInitialized("not-a-number", "workspace-a")).toBe(false);
+});
diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.ts
index 533d19a5..7be6b016 100644
--- a/apps/mobile/src/lib/local-mirror.ts
+++ b/apps/mobile/src/lib/local-mirror.ts
@@ -1,7 +1,7 @@
import type { createEdgeEverClient, ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";
import type { MemoDetail, MemoSummary, Notebook } from "@edgeever/shared";
import * as SQLite from "expo-sqlite";
-import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged } from "./mobile-sync-protocol";
+import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized } from "./mobile-sync-protocol";
const DATABASE_NAME = "edgeever-mobile.db";
const BOOTSTRAP_PAGE_SIZE = 200;
@@ -13,6 +13,7 @@ const syncPromises = new Map<string, Promise<number>>();
type StoredMemoRow = { data_json: string };
type StoredNotebookRow = { data_json: string; memo_count: number; last_memo_updated_at: string | null };
type CursorRow = { value: string };
+type SyncMetaRow = CursorRow & { key: string };
type IdMappingRow = { remote_id: string };
export type LocalMemoListParams = {
@@ -29,6 +30,18 @@ export type LocalMemoListParams = {
export const createMobileDataScope = (baseUrl: string, userId?: string | null) =>
`${baseUrl.trim().toLowerCase()}|${userId ?? "anonymous"}`;
+export const isMobileLocalMirrorInitialized = async (scope: string) => {
+ const db = await getDatabase();
+ const rows = await db.getAllAsync<SyncMetaRow>(
+ `SELECT key, value FROM mobile_sync_meta WHERE scope = ? AND key IN ('cursor', 'identity')`,
+ scope
+ );
+ const metadata = new Map(rows.map((row) => [row.key, row.value]));
+ const cursorValue = metadata.get("cursor");
+ const identityValue = metadata.get("identity");
+ return isMobileSyncMetadataInitialized(cursorValue, identityValue);
+};
+
export const listLocalNotebooks = async (scope: string): Promise<{ notebooks: Notebook[] }> => {
const db = await getDatabase();
const rows = await db.getAllAsync<StoredNotebookRow>(
diff --git a/apps/mobile/src/lib/mobile-sync-protocol.ts b/apps/mobile/src/lib/mobile-sync-protocol.ts
index d4876858..13856284 100644
--- a/apps/mobile/src/lib/mobile-sync-protocol.ts
+++ b/apps/mobile/src/lib/mobile-sync-protocol.ts
@@ -3,3 +3,8 @@ export const hasMobileSyncCursorRewound = (localCursor: number, serverCursor?: n
export const hasMobileSyncIdentityChanged = (localIdentity: string, serverIdentity?: string) =>
typeof serverIdentity === "string" && serverIdentity.length > 0 && serverIdentity !== localIdentity;
+
+export const isMobileSyncMetadataInitialized = (
+ cursorValue: string | null | undefined,
+ identityValue: string | null | undefined
+) => Boolean(identityValue?.trim()) && typeof cursorValue === "string" && cursorValue.trim().length > 0 && Number.isFinite(Number(cursorValue));
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 9cbd4175..a95df5a8 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -79,7 +79,7 @@ import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";
import Markdown, { type RenderRules } from "react-native-markdown-display";
import { SvgXml } from "react-native-svg";
import { buildRevisionDiffRows, createExcerpt, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, type ApiToken, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type ResourceListItem, type RevisionDiffRow, type TagSummary, type TiptapDoc } from "@edgeever/shared";
-import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";
+import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, getMobileNotebookSearchVisibleIds, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";
import { clearMobileMemoDraft, clearMobileNewMemoDraft, readMobileMemoDraft, readMobileNewMemoDraft, writeMobileMemoDraft, writeMobileNewMemoDraft, type MobileMemoDraft } from "../lib/mobile-drafts";
import {
readMobileImageCompressionEnabled,
@@ -105,6 +105,7 @@ import {
import {
createMobileDataScope,
getLocalMemo,
+ isMobileLocalMirrorInitialized,
listLocalMemos,
listLocalNotebooks,
replaceLocalMemoId,
@@ -126,6 +127,7 @@ const resolveEditableMemoTitle = (title?: string | null) => {
};
const MOBILE_APP_VERSION = Constants.expoConfig?.version ?? "0.1.2";
const GITHUB_REPOSITORY_URL = "https://github.com/tianma-if/edgeever";
+const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;
const formatExecutionEnvironment = (environment: string | null | undefined, localePreference: MobileLocaleMode = "system") => {
const english = isEnglishMobileLocale(localePreference);
@@ -268,12 +270,10 @@ export const WorkspaceScreen = () => {
throw new Error("Client is not ready");
}
- let local = await listLocalNotebooks(dataScope);
- if (local.notebooks.length === 0) {
+ if (!(await isMobileLocalMirrorInitialized(dataScope))) {
await syncMobileLocalMirror(client, dataScope);
- local = await listLocalNotebooks(dataScope);
}
- return local;
+ return listLocalNotebooks(dataScope);
},
enabled: Boolean(client),
});
@@ -293,6 +293,10 @@ export const WorkspaceScreen = () => {
throw new Error("Client is not ready");
}
+ if (pageParam === 0 && !(await isMobileLocalMirrorInitialized(dataScope))) {
+ await syncMobileLocalMirror(client, dataScope);
+ }
+
return listLocalMemos(dataScope, {
notebookIds: activeNotebookDescendantIds,
filter: memoFilterMode,
@@ -997,7 +1001,7 @@ export const WorkspaceScreen = () => {
{activeView === "notes" ? (
<NotesView
activeNotebook={activeNotebook}
- isLoading={searchActive ? searchQuery.isLoading : memosQuery.isLoading}
+ isLoading={notebooksQuery.isLoading || (searchActive ? searchQuery.isLoading : memosQuery.isLoading)}
isLoadingMore={searchActive ? searchQuery.isFetchingNextPage : memosQuery.isFetchingNextPage}
isRefreshing={isRefreshing}
memoFilterMode={memoFilterMode}
@@ -1030,8 +1034,8 @@ export const WorkspaceScreen = () => {
: memosQuery.data?.pages[0]?.totalCount ?? memos.length}
selectionMode={selectionMode}
selectedMemoIds={selectedMemoIds}
- error={searchActive ? searchQuery.error : memosQuery.error}
- isError={searchActive ? searchQuery.isError : memosQuery.isError}
+ error={notebooksQuery.error ?? (searchActive ? searchQuery.error : memosQuery.error)}
+ isError={notebooksQuery.isError || (searchActive ? searchQuery.isError : memosQuery.isError)}
/>
) : null}
@@ -1571,7 +1575,7 @@ const NotebookPickerModal = ({
const childNotebookIds = getNotebookParentIdSet(notebooks);
const activeNotebookAncestorIds = getNotebookAncestorIds(notebooks, activeNotebookId);
const visibleNotebookOptions = searchQuery
- ? filterNotebookOptions(notebookOptions, searchText)
+ ? filterNotebookOptionsById(notebookOptions, getMobileNotebookSearchVisibleIds(notebooks, searchText))
: filterCollapsedNotebookOptions(notebookOptions, collapsedNotebookIds);
const activeNotebookName = activeNotebookId === ALL_NOTES_ID
? "全部笔记"
@@ -3958,6 +3962,7 @@ const MemoDetailModal = ({
}) => {
const { session } = useSession();
const { resolvedTheme } = useMobileTheme();
+ const safeAreaInsets = useSafeAreaInsets();
const [actionsOpen, setActionsOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [searchReplaceOpen, setSearchReplaceOpen] = useState(false);
@@ -3983,6 +3988,10 @@ const MemoDetailModal = ({
const detailText = memo?.contentMarkdown || memo?.contentText || "没有正文内容";
const searchMatches = useMemo(() => getTextSearchMatches(detailText, searchQuery), [detailText, searchQuery]);
const searchMatchLabel = searchQuery.trim() ? `${searchMatches.length > 0 ? activeMatchIndex + 1 : 0}/${searchMatches.length}` : "0/0";
+ const editFabBottom = Math.max(
+ safeAreaInsets.bottom,
+ Platform.OS === "android" ? ANDROID_SYSTEM_NAVIGATION_FALLBACK : 0
+ ) + 16;
useEffect(() => {
setActiveMatchIndex(0);
@@ -4111,7 +4120,7 @@ const MemoDetailModal = ({
beginEditorStartup();
onRichEdit(memo);
}}
- style={styles.detailEditFab}
+ style={[styles.detailEditFab, { bottom: editFabBottom }]}
>
<Pencil color="#ffffff" size={20} />
</Pressable>
@@ -4586,8 +4595,12 @@ const MemoList = ({
}) => {
if (isLoading) {
return (
- <View style={styles.memoListStateWrap}>
- <Text style={styles.memoListLoadingText}>正在拉取最新笔记</Text>
+ <View accessibilityLabel="正在加载笔记" accessibilityLiveRegion="polite" style={styles.memoListStateWrap}>
+ <View style={styles.memoListLoadingCard}>
+ <ActivityIndicator color="#059669" size="large" />
+ <Text style={styles.memoListLoadingTitle}>正在加载笔记</Text>
+ <Text style={styles.memoListLoadingDescription}>正在同步笔记本和笔记,首次登录可能需要一点时间。</Text>
+ </View>
</View>
);
}
@@ -5209,6 +5222,9 @@ const filterNotebookOptions = (options: NotebookOption[], searchText: string) =>
return options.filter(({ notebook }) => notebook.name.toLowerCase().includes(query) || (notebook.slug || "").toLowerCase().includes(query));
};
+const filterNotebookOptionsById = (options: NotebookOption[], visibleIds: ReadonlySet<string>) =>
+ options.filter(({ notebook }) => visibleIds.has(notebook.id));
+
const getNotebookParentIdSet = (notebooks: Notebook[]) => {
const notebookIds = new Set(notebooks.map((notebook) => notebook.id));
const parentIds = new Set<string>();
@@ -6488,10 +6504,29 @@ const baseWorkspaceStyles = StyleSheet.create({
paddingHorizontal: 12,
paddingTop: 16,
},
- memoListLoadingText: {
+ memoListLoadingCard: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#a7f3d0",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ paddingHorizontal: 16,
+ paddingVertical: 34,
+ },
+ memoListLoadingTitle: {
+ color: "#0f172a",
+ fontSize: 16,
+ fontWeight: "800",
+ marginTop: 14,
+ },
+ memoListLoadingDescription: {
color: "#64748b",
- fontSize: 14,
- paddingHorizontal: 8,
+ fontSize: 13,
+ lineHeight: 20,
+ marginTop: 7,
+ maxWidth: 300,
+ textAlign: "center",
},
memoListErrorCard: {
alignItems: "center",
@@ -7394,7 +7429,6 @@ const baseWorkspaceStyles = StyleSheet.create({
alignItems: "center",
backgroundColor: "#10b981",
borderRadius: 24,
- bottom: 16,
elevation: 6,
height: 48,
justifyContent: "center",
diff --git a/apps/web/src/lib/app-helpers.ts b/apps/web/src/lib/app-helpers.ts
index 62826129..e342b273 100644
--- a/apps/web/src/lib/app-helpers.ts
+++ b/apps/web/src/lib/app-helpers.ts
@@ -1,5 +1,6 @@
import type { MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";
import { DEFAULT_MEMO_TITLE } from "@edgeever/shared";
+import { getMobileNotebookSearchVisibleIds } from "@edgeever/shared/mobile-ui";
import { buildNotebookTree, type NotebookNode, type NotebookNodeComparator } from "./utils";
import * as React from "react";
import type { ReactNode } from "react";
@@ -117,30 +118,24 @@ export const getExpandableNotebookIds = (nodes: NotebookNode[]) => {
};
export const filterNotebookTree = (nodes: NotebookNode[], search: string): NotebookNode[] => {
- const query = search.trim().toLocaleLowerCase("zh-CN");
-
- if (!query) {
+ if (!search.trim()) {
return nodes;
}
- const walk = (items: NotebookNode[]): NotebookNode[] => {
- const filteredNodes: NotebookNode[] = [];
-
+ const notebooks: Notebook[] = [];
+ const collectNotebooks = (items: NotebookNode[]) => {
for (const node of items) {
- const children = walk(node.children);
- const matched = node.name.toLocaleLowerCase("zh-CN").includes(query);
-
- if (matched) {
- filteredNodes.push({ ...node, children: node.children });
- continue;
- }
-
- if (children.length > 0) {
- filteredNodes.push({ ...node, children });
- }
+ notebooks.push(node);
+ collectNotebooks(node.children);
}
+ };
+ collectNotebooks(nodes);
+ const visibleIds = getMobileNotebookSearchVisibleIds(notebooks, search);
- return filteredNodes;
+ const walk = (items: NotebookNode[]): NotebookNode[] => {
+ return items
+ .filter((node) => visibleIds.has(node.id))
+ .map((node) => ({ ...node, children: walk(node.children) }));
};
return walk(nodes);
diff --git a/packages/shared/src/mobile-ui.test.mjs b/packages/shared/src/mobile-ui.test.mjs
index cd3d31d5..d4d47afe 100644
--- a/packages/shared/src/mobile-ui.test.mjs
+++ b/packages/shared/src/mobile-ui.test.mjs
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "./mobile-ui.ts";
+import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, getMobileNotebookSearchVisibleIds, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "./mobile-ui.ts";
describe("mobile UI contract", () => {
test("keeps core touch targets and navigation metrics stable", () => {
@@ -27,4 +27,18 @@ describe("mobile UI contract", () => {
expect(getMobileCenteredScrollOffset(600, 48, 400)).toBe(424);
expect(getMobileCenteredScrollOffset(80, 48, 400)).toBe(0);
});
+
+ test("keeps notebook hierarchy context while searching", () => {
+ const notebooks = [
+ { id: "projects", name: "工作项目", parentId: null },
+ { id: "edgeever", name: "EdgeEver", parentId: "projects" },
+ { id: "demo", name: "功能演示", parentId: "projects" },
+ { id: "personal", name: "生活个人", parentId: null },
+ ];
+
+ expect(Array.from(getMobileNotebookSearchVisibleIds(notebooks, "edge"))).toEqual(["edgeever", "projects"]);
+ expect(Array.from(getMobileNotebookSearchVisibleIds(notebooks, "工作"))).toEqual(["projects", "edgeever", "demo"]);
+ expect(Array.from(getMobileNotebookSearchVisibleIds(notebooks, "没有"))).toEqual([]);
+ expect(Array.from(getMobileNotebookSearchVisibleIds(notebooks, ""))).toEqual(["projects", "edgeever", "demo", "personal"]);
+ });
});
diff --git a/packages/shared/src/mobile-ui.ts b/packages/shared/src/mobile-ui.ts
index c5a49439..615da978 100644
--- a/packages/shared/src/mobile-ui.ts
+++ b/packages/shared/src/mobile-ui.ts
@@ -33,3 +33,60 @@ export const getMobileCenteredScrollOffset = (
rowHeight: number,
viewportHeight: number
): number => Math.max(0, rowTop - Math.max(0, viewportHeight - rowHeight) / 2);
+
+export type MobileNotebookSearchItem = {
+ id: string;
+ name: string;
+ parentId?: string | null;
+};
+
+export const getMobileNotebookSearchVisibleIds = (
+ notebooks: ReadonlyArray<MobileNotebookSearchItem>,
+ searchText: string
+): Set<string> => {
+ const query = searchText.trim().toLocaleLowerCase("zh-CN");
+ const notebookById = new Map(notebooks.map((notebook) => [notebook.id, notebook]));
+
+ if (!query) {
+ return new Set(notebookById.keys());
+ }
+
+ const childrenByParentId = new Map<string, string[]>();
+ for (const notebook of notebooks) {
+ if (!notebook.parentId || !notebookById.has(notebook.parentId)) {
+ continue;
+ }
+ const children = childrenByParentId.get(notebook.parentId) ?? [];
+ children.push(notebook.id);
+ childrenByParentId.set(notebook.parentId, children);
+ }
+
+ const visibleIds = new Set<string>();
+ const includeDescendants = (notebookId: string, visited: Set<string>) => {
+ if (visited.has(notebookId)) {
+ return;
+ }
+ visited.add(notebookId);
+ visibleIds.add(notebookId);
+ for (const childId of childrenByParentId.get(notebookId) ?? []) {
+ includeDescendants(childId, visited);
+ }
+ };
+
+ for (const notebook of notebooks) {
+ if (!notebook.name.toLocaleLowerCase("zh-CN").includes(query)) {
+ continue;
+ }
+
+ includeDescendants(notebook.id, new Set());
+ const visitedAncestors = new Set<string>([notebook.id]);
+ let parentId = notebook.parentId ?? null;
+ while (parentId && !visitedAncestors.has(parentId)) {
+ visitedAncestors.add(parentId);
+ visibleIds.add(parentId);
+ parentId = notebookById.get(parentId)?.parentId ?? null;
+ }
+ }
+
+ return visibleIds;
+};