Skip to content

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

refactor: modularize cross-platform workspace architecture

tianma-if2253653a4733
diff --git a/apps/api/src/api-context.ts b/apps/api/src/api-context.ts
new file mode 100644
index 00000000..52664220
--- /dev/null
+++ b/apps/api/src/api-context.ts
@@ -0,0 +1,50 @@
+import type { Context } from "hono";
+import type { CloudflareStorageBindings, StorageAdapter } from "./storage-contract";
+
+export type Bindings = CloudflareStorageBindings & {
+ /** The only persistence dependency exposed to application code. */
+ storage: StorageAdapter;
+ EDGE_EVER_AUTH_USERNAME?: string;
+ EDGE_EVER_RUNTIME?: string;
+ EDGE_EVER_AUTH_PASSWORD?: string;
+ EDGE_EVER_AUTH_PASSWORD_HASH?: string;
+ EDGE_EVER_SESSION_TTL_DAYS?: string;
+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS?: string;
+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS?: string;
+ EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS?: string;
+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS?: string;
+ EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS?: string;
+ EDGE_EVER_R2_BUCKET_NAME?: string;
+ EDGE_EVER_DEMO_MODE?: string;
+ EDGE_EVER_LOCAL_DEMO_SEED?: string;
+ EDGE_EVER_ALLOW_UNAUTHENTICATED?: string;
+};
+
+export type WorkerBindings = Omit<Bindings, "storage">;
+
+export type AuthContext = {
+ kind: "user" | "agent";
+ actorType: "user" | "agent";
+ actorId: string | null;
+ username: string;
+ displayName: string | null;
+ scopes: string[];
+ workspaceId: string;
+ role: "owner" | "member";
+ sessionId?: string;
+ tokenId?: string;
+};
+
+export type AuditActor = {
+ actorType: "user" | "agent";
+ actorId: string | null;
+};
+
+export type AppEnv = {
+ Bindings: Bindings;
+ Variables: {
+ auth: AuthContext;
+ };
+};
+
+export type AppContext = Context<AppEnv>;
diff --git a/apps/api/src/app-error.ts b/apps/api/src/app-error.ts
new file mode 100644
index 00000000..690a93c7
--- /dev/null
+++ b/apps/api/src/app-error.ts
@@ -0,0 +1,11 @@
+export class AppError extends Error {
+ code: string;
+ status: number;
+
+ constructor(code: string, message: string, status = 400) {
+ super(message);
+ this.name = "AppError";
+ this.code = code;
+ this.status = status;
+ }
+}
diff --git a/apps/api/src/audit.ts b/apps/api/src/audit.ts
new file mode 100644
index 00000000..5c8a49d5
--- /dev/null
+++ b/apps/api/src/audit.ts
@@ -0,0 +1,29 @@
+import type { DatabaseAdapter } from "./storage-contract";
+import { createId, isoNow } from "./entity-utils";
+
+export const audit = async (
+ db: DatabaseAdapter,
+ actorType: "user" | "agent" | "system",
+ actorId: string | null,
+ action: string,
+ entityType: string,
+ entityId: string,
+ metadata: unknown
+) => auditStatement(db, actorType, actorId, action, entityType, entityId, metadata).run();
+
+export const auditStatement = (
+ db: DatabaseAdapter,
+ actorType: "user" | "agent" | "system",
+ actorId: string | null,
+ action: string,
+ entityType: string,
+ entityId: string,
+ metadata: unknown
+) =>
+ db
+ .prepare(
+ `INSERT INTO audit_events (
+ id, actor_type, actor_id, action, entity_type, entity_id, metadata_json, created_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
+ )
+ .bind(createId("audit"), actorType, actorId, action, entityType, entityId, JSON.stringify(metadata ?? {}), isoNow());
diff --git a/apps/api/src/auth-crypto.test.mjs b/apps/api/src/auth-crypto.test.mjs
new file mode 100644
index 00000000..eb8ee872
--- /dev/null
+++ b/apps/api/src/auth-crypto.test.mjs
@@ -0,0 +1,24 @@
+import { describe, expect, test } from "bun:test";
+import { hashPassword, randomToken, verifyPassword } from "./auth-crypto";
+
+describe("API authentication crypto", () => {
+ test("round trips a password without accepting another password", async () => {
+ const hash = await hashPassword("correct horse battery staple");
+
+ expect(hash).toMatch(/^pbkdf2-sha256\$100000\$/);
+ expect(await verifyPassword("correct horse battery staple", hash)).toBe(true);
+ expect(await verifyPassword("incorrect", hash)).toBe(false);
+ });
+
+ test("rejects malformed or intentionally weak hashes", async () => {
+ expect(await verifyPassword("password", "plaintext")).toBe(false);
+ expect(await verifyPassword("password", "pbkdf2-sha256$99999$c2FsdA$aGFzaA")).toBe(false);
+ });
+
+ test("creates URL-safe tokens with the requested entropy length", () => {
+ const token = randomToken(32);
+
+ expect(token).toMatch(/^[A-Za-z0-9_-]+$/);
+ expect(token.length).toBe(43);
+ });
+});
diff --git a/apps/api/src/auth-crypto.ts b/apps/api/src/auth-crypto.ts
new file mode 100644
index 00000000..e5ed9634
--- /dev/null
+++ b/apps/api/src/auth-crypto.ts
@@ -0,0 +1,101 @@
+const PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";
+const PASSWORD_HASH_ITERATIONS = 100_000;
+const PASSWORD_HASH_BYTES = 32;
+const PASSWORD_SALT_BYTES = 16;
+
+export const SESSION_TOKEN_BYTES = 32;
+
+export const hashPassword = async (password: string) => {
+ const salt = crypto.getRandomValues(new Uint8Array(PASSWORD_SALT_BYTES));
+ const hash = await derivePasswordHash(password, salt, PASSWORD_HASH_ITERATIONS);
+
+ return [
+ PASSWORD_HASH_ALGORITHM,
+ PASSWORD_HASH_ITERATIONS,
+ base64UrlEncode(salt),
+ base64UrlEncode(hash),
+ ].join("$");
+};
+
+export const verifyPassword = async (password: string, passwordHash: string) => {
+ const [algorithm, iterationsRaw, saltRaw, hashRaw] = passwordHash.split("$");
+ const iterations = Number(iterationsRaw);
+
+ if (
+ algorithm !== PASSWORD_HASH_ALGORITHM ||
+ !Number.isInteger(iterations) ||
+ iterations < PASSWORD_HASH_ITERATIONS ||
+ !saltRaw ||
+ !hashRaw
+ ) {
+ return false;
+ }
+
+ try {
+ const expected = base64UrlDecode(hashRaw);
+ const salt = base64UrlDecode(saltRaw);
+ const actual = await derivePasswordHash(password, salt, iterations);
+
+ return timingSafeEqual(actual, expected);
+ } catch {
+ return false;
+ }
+};
+
+const derivePasswordHash = async (password: string, salt: Uint8Array, iterations: number) => {
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, [
+ "deriveBits",
+ ]);
+ const saltBuffer = salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength) as ArrayBuffer;
+ const bits = await crypto.subtle.deriveBits(
+ {
+ name: "PBKDF2",
+ hash: "SHA-256",
+ salt: saltBuffer,
+ iterations,
+ },
+ key,
+ PASSWORD_HASH_BYTES * 8
+ );
+
+ return new Uint8Array(bits);
+};
+
+export const randomToken = (bytes: number) => {
+ const token = crypto.getRandomValues(new Uint8Array(bytes));
+ return base64UrlEncode(token);
+};
+
+const base64UrlEncode = (bytes: Uint8Array) => {
+ let binary = "";
+
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
+};
+
+const base64UrlDecode = (value: string) => {
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
+ const binary = atob(padded);
+ const bytes = new Uint8Array(binary.length);
+
+ for (let index = 0; index < binary.length; index += 1) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+
+ return bytes;
+};
+
+const timingSafeEqual = (left: Uint8Array, right: Uint8Array) => {
+ const length = Math.max(left.length, right.length);
+ let diff = left.length ^ right.length;
+
+ for (let index = 0; index < length; index += 1) {
+ diff |= (left[index % left.length] ?? 0) ^ (right[index % right.length] ?? 0);
+ }
+
+ return diff === 0;
+};
diff --git a/apps/api/src/entity-utils.ts b/apps/api/src/entity-utils.ts
new file mode 100644
index 00000000..f3edfc0b
--- /dev/null
+++ b/apps/api/src/entity-utils.ts
@@ -0,0 +1,21 @@
+export const createId = (prefix: string) => `${prefix}_${crypto.randomUUID().replace(/-/g, "")}`;
+
+export const isoNow = () => new Date().toISOString();
+
+export const parseJsonArray = (json: string): string[] => {
+ try {
+ const value = JSON.parse(json);
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
+ } catch {
+ return [];
+ }
+};
+
+export const slugify = (value: string) =>
+ value
+ .trim()
+ .toLowerCase()
+ .replace(/['"]/g, "")
+ .replace(/[^\p{L}\p{N}]+/gu, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 80);
diff --git a/apps/api/src/http-errors.ts b/apps/api/src/http-errors.ts
new file mode 100644
index 00000000..65afbd1e
--- /dev/null
+++ b/apps/api/src/http-errors.ts
@@ -0,0 +1,43 @@
+import type { Context } from "hono";
+
+export const apiError = (c: Context, code: string, message: string, status: number) =>
+ c.json(
+ {
+ error: {
+ code,
+ message,
+ },
+ },
+ status as 400
+ );
+
+export const notFound = (c: Context, message: string) =>
+ apiError(c, "not_found", message, 404);
+
+export const badRequest = (c: Context, message: string) =>
+ apiError(c, "bad_request", message, 400);
+
+export const authNotConfigured = (c: Context) =>
+ apiError(
+ c,
+ "auth_not_configured",
+ "Authentication is not configured. Set EDGE_EVER_AUTH_PASSWORD as a Worker Secret and redeploy.",
+ 503,
+ );
+
+export const databaseNotReady = (c: Context) =>
+ apiError(
+ c,
+ "database_not_ready",
+ "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",
+ 503,
+ );
+
+export const conflict = (c: Context, code: string, message: string) =>
+ apiError(c, code, message, 409);
+
+export const unauthorized = (c: Context, message: string) =>
+ apiError(c, "unauthorized", message, 401);
+
+export const forbidden = (c: Context, message: string) =>
+ apiError(c, "forbidden", message, 403);
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index c0c3a054..0a52058e 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -21,11 +21,8 @@ import {
MergeMemosSchema,
MoveMemosSchema,
normalizeTags,
- TagRenameSchema,
UserCreateSchema,
UserUpdateSchema,
- NotebookCreateSchema,
- NotebookUpdateSchema,
RestoreJsonMemosSchema,
RestoreJsonNotebooksSchema,
type ApiToken,
@@ -41,12 +38,9 @@ import {
type JsonBackupNotebook,
type JsonBackupResource,
type JsonBackupRevision,
- type Notebook,
- type NotebookCreateInput,
type Resource,
type ResourceListItem,
type ResourceStorageSummary,
- type TagSummary,
type TiptapDoc,
type InstanceUser,
} from "@edgeever/shared";
@@ -91,11 +85,73 @@ import {
import { createCloudflareStorageAdapter } from "./cloudflare-storage-adapter";
import type {
BlobStoreAdapter,
- CloudflareStorageBindings,
DatabaseAdapter,
PreparedStatementAdapter,
- StorageAdapter,
} from "./storage-contract";
+import type { AppContext, AppEnv, AuditActor, AuthContext, Bindings, WorkerBindings } from "./api-context";
+import { AppError } from "./app-error";
+import { hashPassword, randomToken, SESSION_TOKEN_BYTES, verifyPassword } from "./auth-crypto";
+import {
+ apiError,
+ authNotConfigured,
+ badRequest,
+ conflict,
+ databaseNotReady,
+ forbidden,
+ notFound,
+ unauthorized,
+} from "./http-errors";
+import {
+ asRecord,
+ decodeBase64Data,
+ escapeMarkdownImageAlt,
+ escapeMarkdownLinkLabel,
+ getJsonRpcId,
+ getOptionalString,
+ getOptionalStringArray,
+ getRequiredString,
+ getRequiredStringArray,
+ jsonRpcError,
+ jsonRpcResult,
+ mapMcpToolError,
+ type JsonRpcHandlerResult,
+ type JsonRpcRequest,
+} from "./mcp-json-rpc";
+import { MCP_TOOLS } from "./mcp-tools";
+import { audit, auditStatement } from "./audit";
+import { createId, isoNow, parseJsonArray } from "./entity-utils";
+import {
+ createNotebookRecord,
+ findNotebooks,
+ getNotebook,
+ listNotebooks,
+ mapNotebook,
+ notebookSelectSql,
+ resolveNotebookPath,
+ updateNotebookRecord,
+ type NotebookRow,
+} from "./notebook-service";
+import {
+ listTagSummaries,
+ previewTagRename,
+ updateTagAcrossMemos,
+ updateTagsForMemos,
+} from "./tag-service";
+import {
+ ALL_TOKEN_SCOPES,
+ assertScope,
+ getActorLabel,
+ getAuditActor,
+ getWorkspaceId,
+ hasScopes,
+ normalizeTokenScopes,
+ requireOwner,
+ requireScopes,
+ requireUser,
+ type TokenScope,
+} from "./request-auth";
+import { registerTagRoutes } from "./tag-routes";
+import { registerNotebookRoutes } from "./notebook-routes";
// Compatibility aliases keep the existing SQL-heavy implementation small
// while routing its dependency through the platform-neutral contract above.
@@ -104,59 +160,6 @@ type D1Database = DatabaseAdapter;
type D1PreparedStatement = PreparedStatementAdapter;
type R2Bucket = BlobStoreAdapter;
-type Bindings = CloudflareStorageBindings & {
- /** The only persistence dependency exposed to application code. */
- storage: StorageAdapter;
- EDGE_EVER_AUTH_USERNAME?: string;
- EDGE_EVER_RUNTIME?: string;
- EDGE_EVER_AUTH_PASSWORD?: string;
- EDGE_EVER_AUTH_PASSWORD_HASH?: string;
- EDGE_EVER_SESSION_TTL_DAYS?: string;
- EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS?: string;
- EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS?: string;
- EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS?: string;
- EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS?: string;
- EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS?: string;
- EDGE_EVER_R2_BUCKET_NAME?: string;
- EDGE_EVER_DEMO_MODE?: string;
- EDGE_EVER_LOCAL_DEMO_SEED?: string;
- EDGE_EVER_ALLOW_UNAUTHENTICATED?: string;
-};
-
-type WorkerBindings = Omit<Bindings, "storage">;
-
-type AuthContext = {
- kind: "user" | "agent";
- actorType: "user" | "agent";
- actorId: string | null;
- username: string;
- displayName: string | null;
- scopes: string[];
- workspaceId: string;
- role: "owner" | "member";
- sessionId?: string;
- tokenId?: string;
-};
-
-type AuditActor = {
- actorType: "user" | "agent";
- actorId: string | null;
-};
-
-type NotebookRow = {
- id: string;
- parent_id: string | null;
- name: string;
- slug: string | null;
- icon: string | null;
- color: string | null;
- sort_order: number;
- memo_count: number | null;
- last_memo_updated_at: string | null;
- created_at: string;
- updated_at: string;
-};
-
type MemoSummaryRow = {
id: string;
notebook_id: string;
@@ -292,19 +295,6 @@ type MemoImportSourceRow = {
source_updated_at: string | null;
};
-type TagSummaryRow = {
- name: string;
- memo_count: number;
- updated_at: string | null;
-};
-
-type MemoTagUpdateRow = {
- id: string;
- title: string | null;
- tags_json: string;
- content_text: string;
-};
-
type ResourceRow = {
id: string;
memo_id: string;
@@ -335,18 +325,11 @@ type ResourceStatsRow = {
attachment_count: number;
};
-type AppContext = Context<{ Bindings: Bindings; Variables: { auth: AuthContext } }>;
-
const SESSION_COOKIE = "edgeever_session";
const DEFAULT_WORKSPACE_ID = "ws_default";
const DEFAULT_MEMO_LIST_LIMIT = 100;
const MAX_MEMO_LIST_LIMIT = 200;
const UNTITLED_MEMO_TITLE = "无标题笔记";
-const PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";
-const PASSWORD_HASH_ITERATIONS = 100_000;
-const PASSWORD_HASH_BYTES = 32;
-const PASSWORD_SALT_BYTES = 16;
-const SESSION_TOKEN_BYTES = 32;
const DEFAULT_SESSION_TTL_DAYS = 400;
const MAX_SESSION_TTL_DAYS = 400;
const DEFAULT_R2_BUCKET_NAME = "edgeever-resources";
@@ -433,17 +416,6 @@ const MAX_ATTACHMENT_UPLOAD_BYTES = 100 * 1024 * 1024;
const REVISION_SNAPSHOT_INTERVAL_MS = 5 * 60 * 1000;
const API_TOKEN_BYTES = 32;
const API_TOKEN_PREFIX = "eev";
-const ALL_TOKEN_SCOPES = [
- "read:notebooks",
- "write:notebooks",
- "read:memos",
- "write:memos",
- "read:resources",
- "write:resources",
- "read:tags",
- "write:tags",
-] as const;
-type TokenScope = (typeof ALL_TOKEN_SCOPES)[number];
const SUPPORTED_IMAGE_MIME_TYPES = new Set([
"image/png",
"image/jpeg",
@@ -452,7 +424,7 @@ const SUPPORTED_IMAGE_MIME_TYPES = new Set([
"image/avif",
]);
-const app = new Hono<{ Bindings: Bindings; Variables: { auth: AuthContext } }>();
+const app = new Hono<AppEnv>();
app.use(
"/api/*",
@@ -1004,26 +976,8 @@ app.delete("/api/v1/api-tokens/:id", async (c) => {
return c.json({ ok: true });
});
-app.get("/api/v1/notebooks", async (c) => {
- const denied = requireScopes(c, "read:notebooks");
-
- if (denied) {
- return denied;
- }
-
- if (isDemoMode(c.env)) {
- await ensureDemoSeed(c.env);
- }
-
- const rows = await c.env.storage.db.prepare(
- notebookSelectSql(
- `WHERE n.workspace_id = ? AND n.is_deleted = 0
- GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at
- ORDER BY n.parent_id IS NOT NULL, n.sort_order ASC, n.name ASC`
- )
- ).bind(getWorkspaceId(c)).all<NotebookRow>();
-
- return c.json({ notebooks: rows.results.map(mapNotebook) });
+registerNotebookRoutes(app, async (env) => {
+ if (isDemoMode(env)) await ensureDemoSeed(env);
});
app.get("/api/v1/sync/bootstrap", async (c) => {
@@ -1155,161 +1109,7 @@ app.get("/api/v1/sync/changes", async (c) => {
});
});
-app.post("/api/v1/notebooks", zValidator("json", NotebookCreateSchema), async (c) => {
- const denied = requireScopes(c, "write:notebooks");
-
- if (denied) {
- return denied;
- }
-
- const input = c.req.valid("json");
- const actor = getAuditActor(c);
-
- try {
- const notebook = await createNotebookRecord(c.env.storage.db, getWorkspaceId(c), input, actor);
- return c.json({ notebook }, 201);
- } catch (error) {
- if (error instanceof AppError) {
- return apiError(c, error.code, error.message, error.status);
- }
-
- throw error;
- }
-});
-
-app.patch("/api/v1/notebooks/:id", zValidator("json", NotebookUpdateSchema), async (c) => {
- const denied = requireScopes(c, "write:notebooks");
-
- if (denied) {
- return denied;
- }
-
- const id = c.req.param("id");
- const input = c.req.valid("json");
- const actor = getAuditActor(c);
-
- try {
- const notebook = await updateNotebookRecord(c.env.storage.db, getWorkspaceId(c), id, input, actor);
- return c.json({ notebook });
- } catch (error) {
- if (error instanceof AppError) {
- return apiError(c, error.code, error.message, error.status);
- }
-
- throw error;
- }
-});
-
-app.delete("/api/v1/notebooks/:id", async (c) => {
- const denied = requireScopes(c, "write:notebooks");
-
- if (denied) {
- return denied;
- }
-
- const id = c.req.param("id");
- const actor = getAuditActor(c);
- const now = isoNow();
- const workspaceId = getWorkspaceId(c);
- const current = await getNotebook(c.env.storage.db, workspaceId, id);
-
- if (!current) {
- return notFound(c, "Notebook not found");
- }
-
- if (id === "nb_inbox" || current.slug === "inbox") {
- return badRequest(c, "等待分类不能删除。");
- }
-
- const [childCount, memoCount] = await Promise.all([
- c.env.storage.db.prepare(`SELECT COUNT(*) AS count FROM notebooks WHERE workspace_id = ? AND parent_id = ? AND is_deleted = 0`)
- .bind(workspaceId, id)
- .first<{ count: number }>(),
- c.env.storage.db.prepare(`SELECT COUNT(*) AS count FROM memos WHERE workspace_id = ? AND notebook_id = ? AND is_deleted = 0`)
- .bind(workspaceId, id)
- .first<{ count: number }>(),
- ]);
-
- if ((childCount?.count ?? 0) > 0 || (memoCount?.count ?? 0) > 0) {
- return conflict(c, "notebook_not_empty", "Move or delete child notebooks and memos before deleting this notebook.");
- }
-
- await c.env.storage.db.prepare(
- `UPDATE notebooks
- SET is_deleted = 1, deleted_at = ?, updated_at = ?
- WHERE id = ? AND workspace_id = ? AND slug <> 'inbox'`
- )
- .bind(now, now, id, workspaceId)
- .run();
-
- await audit(c.env.storage.db, actor.actorType, actor.actorId, "notebook.delete", "notebook", id, {});
- return c.json({ ok: true });
-});
-
-app.post("/api/v1/notebooks/:id/restore", async (c) => {
- const denied = requireScopes(c, "write:notebooks");
- if (denied) return denied;
-
- const id = c.req.param("id");
- const workspaceId = getWorkspaceId(c);
- const actor = getAuditActor(c);
- const current = await c.env.storage.db.prepare(
- `SELECT id FROM notebooks WHERE id = ? AND workspace_id = ? AND is_deleted = 1`
- ).bind(id, workspaceId).first<{ id: string }>();
- if (!current) return notFound(c, "Deleted notebook not found");
-
- const now = isoNow();
- await c.env.storage.db.batch([
- c.env.storage.db.prepare(
- `UPDATE notebooks SET is_deleted = 0, deleted_at = NULL, updated_at = ? WHERE id = ? AND workspace_id = ?`
- ).bind(now, id, workspaceId),
- auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "notebook.restore", "notebook", id, {}),
- ]);
- const notebook = await getNotebook(c.env.storage.db, workspaceId, id);
- if (!notebook) return notFound(c, "Notebook not found after restore");
- return c.json({ notebook });
-});
-
-app.get("/api/v1/tags", async (c) => {
- const denied = requireScopes(c, "read:tags");
-
- if (denied) {
- return denied;
- }
-
- return c.json({ tags: await listTagSummaries(c.env.storage.db, getWorkspaceId(c)) });
-});
-
-app.patch("/api/v1/tags/:tag", zValidator("json", TagRenameSchema), async (c) => {
- const denied = requireScopes(c, "write:tags");
-
- if (denied) {
- return denied;
- }
-
- const oldTag = decodeTagParam(c.req.param("tag"));
- const input = c.req.valid("json");
- const actor = getAuditActor(c);
- const actorLabel = getActorLabel(c);
- const updated = await updateTagAcrossMemos(c.env.storage.db, getWorkspaceId(c), oldTag, input.name, actor, actorLabel);
-
- return c.json({ ok: true, updated });
-});
-
-app.delete("/api/v1/tags/:tag", async (c) => {
- const denied = requireScopes(c, "write:tags");
-
- if (denied) {
- return denied;
- }
-
- const tag = decodeTagParam(c.req.param("tag"));
- const actor = getAuditActor(c);
- const actorLabel = getActorLabel(c);
- const updated = await updateTagAcrossMemos(c.env.storage.db, getWorkspaceId(c), tag, null, actor, actorLabel);
-
- return c.json({ ok: true, updated });
-});
+registerTagRoutes(app);
app.get("/api/v1/templates", async (c) => {
const rows = await c.env.storage.db.prepare(
@@ -2973,31 +2773,6 @@ app.onError((error, c) => {
export default worker;
-type JsonRpcRequest = {
- jsonrpc?: string;
- id?: string | number | null;
- method?: string;
- params?: unknown;
-};
-
-type JsonRpcId = string | number | null;
-type JsonRpcHandlerResult = {
- body: unknown;
- status: number;
-};
-
-class AppError extends Error {
- code: string;
- status: number;
-
- constructor(code: string, message: string, status = 400) {
- super(message);
- this.name = "AppError";
- this.code = code;
- this.status = status;
- }
-}
-
const MCP_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] as const;
type McpProtocolVersion = (typeof MCP_PROTOCOL_VERSIONS)[number];
const MCP_PROTOCOL_VERSION: McpProtocolVersion = MCP_PROTOCOL_VERSIONS[0];
@@ -3122,583 +2897,69 @@ const handleMcpMessage = async (c: AppContext, payload: unknown): Promise<JsonRp
return { body: jsonRpcError(request.id ?? null, -32601, "Method not found"), status: 404 };
};
-const mapMcpToolError = (error: unknown) => {
- if (error instanceof AppError) {
- const rpcCode =
- error.status === 401
- ? -32001
- : error.status === 403
- ? -32003
- : error.status === 404
- ? -32004
- : error.status === 409
- ? -32009
- : -32602;
+const callMcpTool = async (
+ c: AppContext,
+ auth: AuthContext,
+ name: string,
+ args: Record<string, unknown>
+) => {
+ switch (name) {
+ case "get_current_user": {
+ return await getCurrentWorkspaceIdentity(c.env.storage.db, auth);
+ }
+ case "search_memos": {
+ assertScope(auth, "read:memos");
+ return {
+ memos: await searchMemoSummaries(c.env.storage.db, {
+ workspaceId: auth.workspaceId,
+ query: getOptionalString(args.query),
+ notebookId: getOptionalString(args.notebookId),
+ tags: getOptionalStringArray(args.tags),
+ createdAfter: getOptionalString(args.createdAfter),
+ createdBefore: getOptionalString(args.createdBefore),
+ updatedAfter: getOptionalString(args.updatedAfter),
+ updatedBefore: getOptionalString(args.updatedBefore),
+ isPinned: typeof args.isPinned === "boolean" ? args.isPinned : null,
+ hasResources: typeof args.hasResources === "boolean" ? args.hasResources : null,
+ limit: clampNumber(Number(args.limit ?? 20), 1, 50),
+ }),
+ };
+ }
+ case "list_memos": {
+ assertScope(auth, "read:memos");
+ return await listMemosForMcp(c.env.storage.db, {
+ workspaceId: auth.workspaceId,
+ notebookId: getOptionalString(args.notebookId),
+ limit: clampNumber(Number(args.limit ?? 50), 1, 100),
+ offset: clampNumber(Number(args.offset ?? 0), 0, 100_000),
+ includeContent: args.includeContent === true,
+ includeDeleted: args.includeDeleted === true,
+ });
+ }
+ case "get_memo": {
+ assertScope(auth, "read:memos");
+ const memoId = getRequiredString(args.memoId, "memoId");
+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId, args.includeDeleted === true);
- return {
- rpcCode,
- status: error.status,
- message: error.message,
- data: {
- code: error.code,
- },
- };
- }
+ if (!memo) {
+ throw new Error("Memo not found");
+ }
- return {
- rpcCode: -32000,
- status: 400,
- message: error instanceof Error ? error.message : "Tool call failed",
- data: undefined,
- };
-};
-
-const MCP_TOOL_DEFINITIONS = [
- {
- name: "get_current_user",
- description:
- "Identify the EdgeEver user and personal workspace authorized by the current session or API token. Use this before imports when the destination account must be confirmed.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {},
- },
- },
- {
- name: "search_memos",
- description: "Search active EdgeEver memos by text, tag, notebook, time range, pin state, or resource presence.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {
- query: { type: "string" },
- notebookId: { type: "string" },
- tags: { type: "array", items: { type: "string" } },
- createdAfter: { type: "string", format: "date-time" },
- createdBefore: { type: "string", format: "date-time" },
- updatedAfter: { type: "string", format: "date-time" },
- updatedBefore: { type: "string", format: "date-time" },
- isPinned: { type: "boolean" },
- hasResources: { type: "boolean" },
- limit: { type: "integer", minimum: 1, maximum: 50 },
- },
- },
- },
- {
- name: "list_memos",
- description: "List EdgeEver memos with pagination. Use includeContent when full Markdown is needed.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {
- notebookId: { type: "string" },
- limit: { type: "integer", minimum: 1, maximum: 100 },
- offset: { type: "integer", minimum: 0 },
- includeContent: { type: "boolean" },
- includeDeleted: { type: "boolean" },
- },
- },
- },
- {
- name: "get_memo",
- description: "Read a memo with Markdown content.",
- inputSchema: {
- type: "object",
- required: ["memoId"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- includeDeleted: { type: "boolean" },
- },
- },
- },
- {
- name: "create_memo",
- description: "Create a memo in a notebook.",
- inputSchema: {
- type: "object",
- required: ["notebookId"],
- additionalProperties: false,
- properties: {
- notebookId: { type: "string" },
- title: { type: "string" },
- contentMarkdown: { type: "string" },
- tags: { type: "array", items: { type: "string" } },
- createdAt: { type: "string", format: "date-time" },
- updatedAt: { type: "string", format: "date-time" },
- },
- },
- },
- {
- name: "import_memos",
- description:
- "Import up to 25 memos from an external service with database-backed idempotency. Reusing the same source and externalId returns skipped instead of creating a duplicate. Results are reported per item.",
- inputSchema: {
- type: "object",
- required: ["source", "notebookId", "items"],
- additionalProperties: false,
- properties: {
- source: {
- type: "string",
- minLength: 1,
- maxLength: 80,
- pattern: "^[A-Za-z0-9._-]+$",
- description: "Stable source identifier such as flomo, notion, memos, or evernote.",
- },
- notebookId: { type: "string", description: "Destination notebook for every item in this batch." },
- dryRun: { type: "boolean", description: "Validate and report existing items without creating memos." },
- items: {
- type: "array",
- minItems: 1,
- maxItems: 25,
- items: {
- type: "object",
- required: ["externalId"],
- additionalProperties: false,
- properties: {
- externalId: {
- type: "string",
- minLength: 1,
- maxLength: 512,
- description: "Stable ID from the source system. It is the idempotency key within source and workspace.",
- },
- title: { type: "string", maxLength: 160 },
- contentMarkdown: { type: "string" },
- tags: { type: "array", maxItems: 100, items: { type: "string" } },
- createdAt: { type: "string", format: "date-time" },
- updatedAt: { type: "string", format: "date-time" },
- },
- },
- },
- },
- },
- },
- {
- name: "update_memo",
- description: "Update memo title, Markdown, tags, notebook, or pinned state.",
- inputSchema: {
- type: "object",
- required: ["memoId"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- title: { type: "string" },
- isPinned: { type: "boolean" },
- contentMarkdown: { type: "string" },
- tags: { type: "array", items: { type: "string" } },
- notebookId: { type: "string" },
- expectedRevision: { type: "integer", minimum: 0 },
- createdAt: { type: "string", format: "date-time" },
- updatedAt: { type: "string", format: "date-time" },
- },
- },
- },
- {
- name: "trash_memos",
- description: "Move one or more active memos to trash. Use dryRun to preview affected memos.",
- inputSchema: {
- type: "object",
- required: ["memoIds"],
- additionalProperties: false,
- properties: {
- memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "restore_memos",
- description: "Restore one or more trashed memos. If the original notebook is gone, memos are restored to the default inbox.",
- inputSchema: {
- type: "object",
- required: ["memoIds"],
- additionalProperties: false,
- properties: {
- memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "move_memos",
- description: "Move one or more active memos to another notebook. Use dryRun to preview affected memos.",
- inputSchema: {
- type: "object",
- required: ["memoIds", "notebookId"],
- additionalProperties: false,
- properties: {
- memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
- notebookId: { type: "string" },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "add_tags_to_memos",
- description: "Add tags to one or more active memos. Use dryRun to preview changed tags.",
- inputSchema: {
- type: "object",
- required: ["memoIds", "tags"],
- additionalProperties: false,
- properties: {
- memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
- tags: { type: "array", minItems: 1, maxItems: 20, items: { type: "string" } },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "remove_tags_from_memos",
- description: "Remove tags from one or more active memos. Use dryRun to preview changed tags.",
- inputSchema: {
- type: "object",
- required: ["memoIds", "tags"],
- additionalProperties: false,
- properties: {
- memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
- tags: { type: "array", minItems: 1, maxItems: 20, items: { type: "string" } },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "rename_tag",
- description: "Rename a tag across all active memos. This merges into an existing tag with the same normalized name.",
- inputSchema: {
- type: "object",
- required: ["from", "to"],
- additionalProperties: false,
- properties: {
- from: { type: "string" },
- to: { type: "string" },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "delete_tag",
- description: "Remove a tag from all active memos.",
- inputSchema: {
- type: "object",
- required: ["tag"],
- additionalProperties: false,
- properties: {
- tag: { type: "string" },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "merge_memos",
- description: "Merge multiple active memos into a new memo and soft-delete the sources.",
- inputSchema: {
- type: "object",
- required: ["memoIds"],
- additionalProperties: false,
- properties: {
- memoIds: { type: "array", minItems: 2, maxItems: 50, items: { type: "string" } },
- notebookId: { type: "string" },
- title: { type: "string" },
- },
- },
- },
- {
- name: "upload_memo_image",
- description:
- "Upload a base64-encoded image resource to a memo and return Markdown that can be inserted into memo content. Images are stored as provided; server-side compression is disabled to avoid Cloudflare Images quota usage.",
- inputSchema: {
- type: "object",
- required: ["memoId", "mimeType", "dataBase64"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- filename: { type: "string" },
- mimeType: { type: "string", enum: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"] },
- dataBase64: { type: "string" },
- alt: { type: "string" },
- },
- },
- },
- {
- name: "upload_memo_attachment",
- description: "Upload a base64-encoded attachment resource to a memo and return Markdown link text that can be inserted into memo content.",
- inputSchema: {
- type: "object",
- required: ["memoId", "filename", "mimeType", "dataBase64"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- filename: { type: "string" },
- mimeType: { type: "string" },
- dataBase64: { type: "string" },
- label: { type: "string" },
- },
- },
- },
- {
- name: "list_memo_resources",
- description: "List active resources attached to a memo.",
- inputSchema: {
- type: "object",
- required: ["memoId"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- },
- },
- },
- {
- name: "list_resources",
- description: "List active workspace resources with storage summary.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {
- limit: { type: "integer", minimum: 1, maximum: 500 },
- },
- },
- },
- {
- name: "list_memo_revisions",
- description: "List revision history for a memo.",
- inputSchema: {
- type: "object",
- required: ["memoId"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- limit: { type: "integer", minimum: 1, maximum: 100 },
- },
- },
- },
- {
- name: "restore_memo_revision",
- description: "Restore a memo to a previous revision. Use dryRun to preview the target revision.",
- inputSchema: {
- type: "object",
- required: ["memoId", "revisionId"],
- additionalProperties: false,
- properties: {
- memoId: { type: "string" },
- revisionId: { type: "string" },
- dryRun: { type: "boolean" },
- },
- },
- },
- {
- name: "move_notebook",
- description: "Move a notebook under another notebook or root and update its sort order.",
- inputSchema: {
- type: "object",
- required: ["notebookId"],
- additionalProperties: false,
- properties: {
- notebookId: { type: "string" },
- parentId: { type: ["string", "null"] },
- sortOrder: { type: "integer" },
- },
- },
- },
- {
- name: "create_notebook",
- description: "Create a notebook at the root or under another notebook.",
- inputSchema: {
- type: "object",
- required: ["name"],
- additionalProperties: false,
- properties: {
- name: { type: "string", minLength: 1, maxLength: 80 },
- parentId: { type: ["string", "null"] },
- sortOrder: { type: "integer" },
- },
- },
- },
- {
- name: "get_notebook",
- description: "Get one active notebook by ID from the authenticated user's workspace.",
- inputSchema: {
- type: "object",
- required: ["notebookId"],
- additionalProperties: false,
- properties: {
- notebookId: { type: "string", description: "The exact EdgeEver notebook ID." },
- },
- },
- },
- {
- name: "find_notebooks",
- description: "Find active notebooks by name, optionally restricted to a parent notebook or the workspace root.",
- inputSchema: {
- type: "object",
- required: ["name"],
- additionalProperties: false,
- properties: {
- name: { type: "string", minLength: 1, description: "Full or partial notebook name, matched case-insensitively." },
- parentId: {
- type: ["string", "null"],
- description: "Parent notebook ID. Pass null to search only root notebooks; omit to search all levels.",
- },
- exact: { type: "boolean", description: "Require an exact name match. Defaults to false." },
- limit: { type: "integer", minimum: 1, maximum: 50 },
- },
- },
- },
- {
- name: "resolve_notebook_path",
- description:
- "Resolve a slash-separated notebook path such as 'Imports/Flomo' to one exact notebook. Returns a diagnostic result instead of guessing when a segment is missing or ambiguous.",
- inputSchema: {
- type: "object",
- required: ["path"],
- additionalProperties: false,
- properties: {
- path: { type: "string", minLength: 1, description: "Slash-separated notebook names from the workspace root." },
- },
- },
- },
- {
- name: "list_notebooks",
- description:
- "List active notebooks in the authenticated user's workspace. Every returned notebook is owned by that workspace; notebooks from other users are never returned.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {},
- },
- },
- {
- name: "list_tags",
- description: "List tags and memo counts.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {},
- },
- },
- {
- name: "get_workspace_stats",
- description: "Get notebook, memo, tag, and resource counts for workspace diagnostics.",
- inputSchema: {
- type: "object",
- additionalProperties: false,
- properties: {},
- },
- },
-];
-
-const READ_ONLY_MCP_TOOLS = new Set([
- "get_current_user",
- "search_memos",
- "list_memos",
- "get_memo",
- "list_memo_resources",
- "list_resources",
- "list_memo_revisions",
- "get_notebook",
- "find_notebooks",
- "resolve_notebook_path",
- "list_notebooks",
- "list_tags",
- "get_workspace_stats",
-]);
-const NON_DESTRUCTIVE_MCP_TOOLS = new Set([
- "create_memo",
- "import_memos",
- "restore_memos",
- "move_memos",
- "add_tags_to_memos",
- "upload_memo_image",
- "upload_memo_attachment",
- "move_notebook",
- "create_notebook",
-]);
-const IDEMPOTENT_MCP_TOOLS = new Set([
- "restore_memos",
- "move_memos",
- "add_tags_to_memos",
- "remove_tags_from_memos",
- "import_memos",
- "move_notebook",
-]);
-
-const MCP_TOOLS = MCP_TOOL_DEFINITIONS.map((tool) => {
- const readOnly = READ_ONLY_MCP_TOOLS.has(tool.name);
- return {
- ...tool,
- title: tool.name.split("_").map((part) => part[0]?.toUpperCase() + part.slice(1)).join(" "),
- outputSchema: { type: "object" },
- annotations: {
- readOnlyHint: readOnly,
- destructiveHint: readOnly ? false : !NON_DESTRUCTIVE_MCP_TOOLS.has(tool.name),
- idempotentHint: readOnly || IDEMPOTENT_MCP_TOOLS.has(tool.name),
- openWorldHint: false,
- },
- };
-});
-
-const callMcpTool = async (
- c: AppContext,
- auth: AuthContext,
- name: string,
- args: Record<string, unknown>
-) => {
- switch (name) {
- case "get_current_user": {
- return await getCurrentWorkspaceIdentity(c.env.storage.db, auth);
- }
- case "search_memos": {
- assertScope(auth, "read:memos");
- return {
- memos: await searchMemoSummaries(c.env.storage.db, {
- workspaceId: auth.workspaceId,
- query: getOptionalString(args.query),
- notebookId: getOptionalString(args.notebookId),
- tags: getOptionalStringArray(args.tags),
- createdAfter: getOptionalString(args.createdAfter),
- createdBefore: getOptionalString(args.createdBefore),
- updatedAfter: getOptionalString(args.updatedAfter),
- updatedBefore: getOptionalString(args.updatedBefore),
- isPinned: typeof args.isPinned === "boolean" ? args.isPinned : null,
- hasResources: typeof args.hasResources === "boolean" ? args.hasResources : null,
- limit: clampNumber(Number(args.limit ?? 20), 1, 50),
- }),
- };
- }
- case "list_memos": {
- assertScope(auth, "read:memos");
- return await listMemosForMcp(c.env.storage.db, {
- workspaceId: auth.workspaceId,
- notebookId: getOptionalString(args.notebookId),
- limit: clampNumber(Number(args.limit ?? 50), 1, 100),
- offset: clampNumber(Number(args.offset ?? 0), 0, 100_000),
- includeContent: args.includeContent === true,
- includeDeleted: args.includeDeleted === true,
- });
- }
- case "get_memo": {
- assertScope(auth, "read:memos");
- const memoId = getRequiredString(args.memoId, "memoId");
- const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId, args.includeDeleted === true);
-
- if (!memo) {
- throw new Error("Memo not found");
- }
-
- return { memo };
- }
- case "create_memo": {
- assertScope(auth, "write:memos");
- const notebookId = getRequiredString(args.notebookId, "notebookId");
- const actor = getAuditActor(c);
- const actorLabel = getActorLabel(c);
- const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {
- notebookId,
- title: getOptionalString(args.title) ?? undefined,
- contentMarkdown: getOptionalString(args.contentMarkdown) ?? "",
- tags: getOptionalStringArray(args.tags),
- createdAt: getOptionalString(args.createdAt) ?? undefined,
- updatedAt: getOptionalString(args.updatedAt) ?? undefined,
- }, actor, actorLabel);
+ return { memo };
+ }
+ case "create_memo": {
+ assertScope(auth, "write:memos");
+ const notebookId = getRequiredString(args.notebookId, "notebookId");
+ const actor = getAuditActor(c);
+ const actorLabel = getActorLabel(c);
+ const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {
+ notebookId,
+ title: getOptionalString(args.title) ?? undefined,
+ contentMarkdown: getOptionalString(args.contentMarkdown) ?? "",
+ tags: getOptionalStringArray(args.tags),
+ createdAt: getOptionalString(args.createdAt) ?? undefined,
+ updatedAt: getOptionalString(args.updatedAt) ?? undefined,
+ }, actor, actorLabel);
return { memo };
}
@@ -4028,81 +3289,6 @@ const callMcpTool = async (
}
};
-const jsonRpcResult = (id: JsonRpcId, result: unknown) => ({
- jsonrpc: "2.0",
- id,
- result,
-});
-
-const jsonRpcError = (id: JsonRpcId, code: number, message: string, data?: unknown) => ({
- jsonrpc: "2.0",
- id,
- error: {
- code,
- message,
- ...(data === undefined ? {} : { data }),
- },
-});
-
-const getJsonRpcId = (request: unknown): JsonRpcId => {
- if (!request || typeof request !== "object" || !("id" in request)) {
- return null;
- }
-
- const id = (request as { id?: unknown }).id;
- return typeof id === "string" || typeof id === "number" || id === null ? id : null;
-};
-
-const asRecord = (value: unknown): Record<string, unknown> =>
- value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
-
-const getOptionalString = (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : null);
-
-const getRequiredString = (value: unknown, name: string) => {
- const parsed = getOptionalString(value);
-
- if (!parsed) {
- throw new AppError("invalid_params", `${name} is required`, 400);
- }
-
- return parsed;
-};
-
-const getOptionalStringArray = (value: unknown) =>
- Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
-
-const getRequiredStringArray = (value: unknown, name: string) => {
- const items = getOptionalStringArray(value);
-
- if (items.length === 0) {
- throw new AppError("invalid_params", `${name} must include at least one item`, 400);
- }
-
- return items;
-};
-
-const decodeBase64Data = async (value: string) => {
- const [, dataUrlPayload] = value.match(/^data:[^;]+;base64,(.+)$/i) ?? [];
- const base64 = (dataUrlPayload ?? value).replace(/\s/g, "");
-
- if (!base64) {
- throw new AppError("invalid_params", "dataBase64 is required", 400);
- }
-
- try {
- const response = await fetch("data:application/octet-stream;base64," + base64);
- if (!response.ok) {
- throw new Error("failed to decode base64");
- }
- return new Uint8Array(await response.arrayBuffer());
- } catch (error) {
- throw new AppError("invalid_params", "dataBase64 must be valid base64 data: " + (error as Error).message, 400);
- }
-};
-
-const escapeMarkdownImageAlt = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
-const escapeMarkdownLinkLabel = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
-
const getInstanceAuthMode = async (env: Bindings): Promise<InstanceAuthMode> => {
if (!env.storage.db || typeof env.storage.db.prepare !== "function") {
throw new AppError(
@@ -4481,211 +3667,11 @@ const getBearerToken = (c: AppContext) => {
return scheme.toLowerCase() === "bearer" && token ? token : null;
};
-const getAuditActor = (c: AppContext) => {
- const auth = c.get("auth");
-
- return {
- actorType: auth?.actorType ?? "user",
- actorId: auth?.actorId ?? null,
- };
-};
-
-const getActorLabel = (c: AppContext) => {
- const auth = c.get("auth");
- return auth?.actorId ? `${auth.actorType}:${auth.actorId}` : auth?.username ?? "user";
-};
-
-const getWorkspaceId = (c: AppContext) => c.get("auth").workspaceId;
-
-const requireOwner = (c: AppContext) => {
- const auth = c.get("auth");
- return auth?.kind === "user" && auth.role === "owner"
- ? null
- : forbidden(c, "Only the instance owner can manage users.");
-};
-
-const requireUser = (c: AppContext) => {
- const auth = c.get("auth");
-
- if (auth?.kind === "user") {
- return null;
- }
-
- return forbidden(c, "Only an interactive user session can manage this resource.");
-};
-
-const requireScopes = (c: AppContext, ...scopes: TokenScope[]) => {
- const auth = c.get("auth");
-
- if (!auth) {
- return unauthorized(c, "Authentication required.");
- }
-
- if (hasScopes(auth, scopes)) {
- return null;
- }
-
- return forbidden(c, `Missing required scope: ${scopes.join(", ")}`);
-};
-
-const assertScope = (auth: AuthContext, scope: TokenScope) => {
- if (!hasScopes(auth, [scope])) {
- throw new AppError("forbidden", `Missing required scope: ${scope}`, 403);
- }
-};
-
-const hasScopes = (auth: AuthContext, scopes: TokenScope[]) => {
- if (auth.kind === "user") {
- return true;
- }
-
- return scopes.every((scope) => auth.scopes.includes(scope));
-};
-
-const normalizeTokenScopes = (scopes: string[]) => {
- const normalized = Array.from(new Set(scopes.map((scope) => scope.trim()).filter(Boolean)));
-
- if (normalized.some((scope) => !isTokenScope(scope))) {
- return null;
- }
-
- return normalized as TokenScope[];
-};
-
-const isTokenScope = (scope: string): scope is TokenScope =>
- (ALL_TOKEN_SCOPES as readonly string[]).includes(scope);
-
const getSessionMaxAge = (env: Bindings) => {
const days = clampNumber(Number(env.EDGE_EVER_SESSION_TTL_DAYS ?? DEFAULT_SESSION_TTL_DAYS), 1, MAX_SESSION_TTL_DAYS);
return days * 24 * 60 * 60;
};
-const hashPassword = async (password: string) => {
- const salt = crypto.getRandomValues(new Uint8Array(PASSWORD_SALT_BYTES));
- const hash = await derivePasswordHash(password, salt, PASSWORD_HASH_ITERATIONS);
-
- return [
- PASSWORD_HASH_ALGORITHM,
- PASSWORD_HASH_ITERATIONS,
- base64UrlEncode(salt),
- base64UrlEncode(hash),
- ].join("$");
-};
-
-const verifyPassword = async (password: string, passwordHash: string) => {
- const [algorithm, iterationsRaw, saltRaw, hashRaw] = passwordHash.split("$");
- const iterations = Number(iterationsRaw);
-
- if (
- algorithm !== PASSWORD_HASH_ALGORITHM ||
- !Number.isInteger(iterations) ||
- iterations < 100_000 ||
- !saltRaw ||
- !hashRaw
- ) {
- return false;
- }
-
- try {
- const expected = base64UrlDecode(hashRaw);
- const salt = base64UrlDecode(saltRaw);
- const actual = await derivePasswordHash(password, salt, iterations);
-
- return timingSafeEqual(actual, expected);
- } catch {
- return false;
- }
-};
-
-const derivePasswordHash = async (password: string, salt: Uint8Array, iterations: number) => {
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, [
- "deriveBits",
- ]);
- const saltBuffer = salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength) as ArrayBuffer;
- const bits = await crypto.subtle.deriveBits(
- {
- name: "PBKDF2",
- hash: "SHA-256",
- salt: saltBuffer,
- iterations,
- },
- key,
- PASSWORD_HASH_BYTES * 8
- );
-
- return new Uint8Array(bits);
-};
-
-const randomToken = (bytes: number) => {
- const token = crypto.getRandomValues(new Uint8Array(bytes));
- return base64UrlEncode(token);
-};
-
-const base64UrlEncode = (bytes: Uint8Array) => {
- let binary = "";
-
- for (const byte of bytes) {
- binary += String.fromCharCode(byte);
- }
-
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
-};
-
-const base64UrlDecode = (value: string) => {
- const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
- const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
- const binary = atob(padded);
- const bytes = new Uint8Array(binary.length);
-
- for (let index = 0; index < binary.length; index += 1) {
- bytes[index] = binary.charCodeAt(index);
- }
-
- return bytes;
-};
-
-const timingSafeEqual = (left: Uint8Array, right: Uint8Array) => {
- const length = Math.max(left.length, right.length);
- let diff = left.length ^ right.length;
-
- for (let index = 0; index < length; index += 1) {
- diff |= (left[index % left.length] ?? 0) ^ (right[index % right.length] ?? 0);
- }
-
- return diff === 0;
-};
-
-const mapNotebook = (row: NotebookRow): Notebook => ({
- id: row.id,
- parentId: row.parent_id,
- name: row.name,
- slug: row.slug,
- icon: row.icon,
- color: row.color,
- sortOrder: row.sort_order,
- memoCount: row.memo_count ?? 0,
- lastMemoUpdatedAt: row.last_memo_updated_at,
- createdAt: row.created_at,
- updatedAt: row.updated_at,
-});
-
-const notebookSelectSql = (tail: string) => `
- SELECT n.id,
- n.parent_id,
- n.name,
- n.slug,
- n.icon,
- n.color,
- n.sort_order,
- COUNT(m.id) AS memo_count,
- MAX(m.updated_at) AS last_memo_updated_at,
- n.created_at,
- n.updated_at
- FROM notebooks n
- LEFT JOIN memos m ON m.notebook_id = n.id AND m.is_deleted = 0
- ${tail}
-`;
-
const mapMemoSummary = (row: MemoSummaryRow): MemoSummary => ({
id: row.id,
notebookId: row.notebook_id,
@@ -4932,430 +3918,105 @@ const assertIdsAvailableInWorkspace = async (
const assertNotebookIdsInWorkspace = async (db: D1Database, workspaceId: string, ids: string[]) => {
const uniqueIds = Array.from(new Set(ids));
if (uniqueIds.length === 0) return;
- const placeholders = uniqueIds.map(() => "?").join(", ");
- const rows = await db.prepare(
- `SELECT id FROM notebooks WHERE workspace_id = ? AND id IN (${placeholders})`
- ).bind(workspaceId, ...uniqueIds).all<{ id: string }>();
- if (rows.results.length !== uniqueIds.length) {
- throw new AppError("invalid_backup_workspace", "Backup references a notebook outside the current workspace.", 400);
- }
-};
-
-const mapResource = (row: ResourceRow): Resource => ({
- id: row.id,
- memoId: row.memo_id,
- originalMemoId: row.original_memo_id,
- kind: row.kind,
- mimeType: row.mime_type,
- filename: row.filename,
- byteSize: row.byte_size,
- sha256: row.sha256,
- width: row.width,
- height: row.height,
- createdAt: row.created_at,
- updatedAt: row.updated_at,
- url: `/api/v1/resources/${row.id}/blob`,
-});
-
-const mapResourceListItem = (row: ResourceListRow): ResourceListItem => ({
- ...mapResource(row),
- memoTitle: row.memo_title,
- memoExcerpt: row.memo_excerpt,
- memoDeleted: Boolean(row.memo_is_deleted),
-});
-
-const mapResourceStorageSummary = (row: ResourceStatsRow | null): ResourceStorageSummary => ({
- totalCount: row?.total_count ?? 0,
- totalBytes: row?.total_bytes ?? 0,
- imageCount: row?.image_count ?? 0,
- attachmentCount: row?.attachment_count ?? 0,
-});
-
-const mapApiToken = (row: ApiTokenRow): ApiToken => ({
- id: row.id,
- name: row.name,
- token: row.token_value,
- scopes: parseJsonArray(row.scopes_json),
- lastUsedAt: row.last_used_at,
- expiresAt: row.expires_at,
- isRevoked: Boolean(row.is_revoked),
- createdAt: row.created_at,
-});
-
-const mapTagSummary = (row: TagSummaryRow): TagSummary => ({
- name: row.name,
- memoCount: row.memo_count,
- updatedAt: row.updated_at,
-});
-
-const getApiTokenRow = async (db: D1Database, id: string, workspaceId: string): Promise<ApiTokenRow | null> =>
- db
- .prepare(
- `SELECT id, name, token_value, scopes_json, last_used_at, expires_at, is_revoked, created_at, workspace_id
- FROM api_tokens
- WHERE id = ? AND workspace_id = ?`
- )
- .bind(id, workspaceId)
- .first<ApiTokenRow>();
-
-const getCurrentWorkspaceIdentity = async (db: D1Database, auth: AuthContext) => {
- const row = await db.prepare(
- `SELECT w.id AS workspace_id, w.name AS workspace_name, w.is_personal,
- u.id AS user_id, u.username, u.display_name, wm.role
- FROM workspaces w
- INNER JOIN workspace_members wm ON wm.workspace_id = w.id
- INNER JOIN users u ON u.id = wm.user_id
- WHERE w.id = ?
- ORDER BY CASE WHEN u.id = ? THEN 0 ELSE 1 END, wm.created_at ASC
- LIMIT 1`
- ).bind(auth.workspaceId, auth.kind === "user" ? auth.actorId : null).first<WorkspaceIdentityRow>();
-
- if (!row) {
- throw new AppError("workspace_identity_not_found", "The authenticated workspace has no associated user.", 404);
- }
-
- return {
- user: {
- id: row.user_id,
- username: row.username,
- displayName: row.display_name,
- role: row.role,
- },
- workspace: {
- id: row.workspace_id,
- name: row.workspace_name,
- isPersonal: row.is_personal === 1,
- },
- authorization: {
- kind: auth.kind === "agent" ? "api_token" : "user_session",
- ...(auth.kind === "agent" ? { tokenName: auth.username, scopes: auth.scopes } : {}),
- },
- dataIsolation: {
- workspaceScoped: true,
- statement:
- "Every notebook and memo returned by this MCP server belongs to this workspace; data from other users is excluded.",
- },
- };
-};
-
-const listNotebooks = async (db: D1Database, workspaceId: string): Promise<Notebook[]> => {
- const rows = await db
- .prepare(
- notebookSelectSql(
- `WHERE n.workspace_id = ? AND n.is_deleted = 0
- GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at
- ORDER BY n.parent_id IS NOT NULL, n.sort_order ASC, n.name ASC`
- )
- )
- .bind(workspaceId).all<NotebookRow>();
-
- return rows.results.map(mapNotebook);
-};
-
-const normalizeNotebookLookupName = (value: string) => value.trim().toLocaleLowerCase("en-US");
-
-const findNotebooks = async (
- db: D1Database,
- workspaceId: string,
- options: { name: string; parentId?: string | null; exact: boolean; limit: number },
-) => {
- const query = normalizeNotebookLookupName(options.name);
- const notebooks = await listNotebooks(db, workspaceId);
- return notebooks
- .filter((notebook) => {
- if (options.parentId !== undefined && notebook.parentId !== options.parentId) {
- return false;
- }
- const name = normalizeNotebookLookupName(notebook.name);
- return options.exact ? name === query : name.includes(query);
- })
- .slice(0, options.limit);
-};
-
-const resolveNotebookPath = async (db: D1Database, workspaceId: string, path: string) => {
- const segments = path.split("/").map((segment) => segment.trim()).filter(Boolean);
- if (segments.length === 0) {
- throw new AppError("invalid_params", "path must contain at least one notebook name", 400);
- }
-
- const notebooks = await listNotebooks(db, workspaceId);
- const matched: Notebook[] = [];
- let parentId: string | null = null;
-
- for (const [index, segment] of segments.entries()) {
- const normalizedSegment = normalizeNotebookLookupName(segment);
- const candidates = notebooks.filter(
- (notebook) => notebook.parentId === parentId && normalizeNotebookLookupName(notebook.name) === normalizedSegment,
- );
-
- if (candidates.length !== 1) {
- return {
- resolved: false,
- path,
- segments,
- matched,
- failedAt: index,
- failedSegment: segment,
- reason: candidates.length === 0 ? "not_found" : "ambiguous",
- candidates,
- };
- }
-
- matched.push(candidates[0]);
- parentId = candidates[0].id;
- }
-
- return {
- resolved: true,
- path,
- segments,
- notebook: matched.at(-1),
- matched,
- };
-};
-
-const listTagSummaries = async (db: D1Database, workspaceId: string): Promise<TagSummary[]> => {
- const rows = await db
- .prepare(
- `SELECT json_each.value AS name,
- COUNT(DISTINCT m.id) AS memo_count,
- MAX(m.updated_at) AS updated_at
- FROM memos m, json_each(m.tags_json)
- WHERE m.workspace_id = ? AND m.is_deleted = 0
- AND trim(json_each.value) <> ''
- GROUP BY json_each.value
- ORDER BY lower(json_each.value) ASC`
- )
- .bind(workspaceId).all<TagSummaryRow>();
-
- return rows.results
- .filter((row) => typeof row.name === "string" && row.name.trim())
- .map(mapTagSummary);
-};
-
-const updateTagAcrossMemos = async (
- db: D1Database,
- workspaceId: string,
- oldTag: string,
- nextTag: string | null,
- actor: { actorType: "user" | "agent"; actorId: string | null },
- actorLabel: string
-) => {
- const normalizedOld = normalizeTags([oldTag])[0];
- const normalizedNext = nextTag === null ? null : normalizeTags([nextTag])[0];
-
- if (!normalizedOld || normalizedOld === normalizedNext) {
- return 0;
- }
-
- const rows = await db
- .prepare(
- `SELECT m.id, m.title, m.tags_json, c.content_text
- FROM memos m
- INNER JOIN memo_contents c ON c.memo_id = m.id
- WHERE m.workspace_id = ? AND m.is_deleted = 0
- AND EXISTS (
- SELECT 1
- FROM json_each(m.tags_json)
- WHERE json_each.value = ?
- )`
- )
- .bind(workspaceId, normalizedOld)
- .all<MemoTagUpdateRow>();
-
- const now = isoNow();
- const statements: D1PreparedStatement[] = [];
- let updated = 0;
-
- for (const row of rows.results) {
- const currentTags = parseJsonArray(row.tags_json);
-
- if (!currentTags.includes(normalizedOld)) {
- continue;
- }
-
- const nextTags = normalizeTags(
- currentTags.flatMap((tag) => {
- if (tag !== normalizedOld) {
- return [tag];
- }
-
- return normalizedNext ? [normalizedNext] : [];
- })
- );
-
- statements.push(
- db
- .prepare(
- `UPDATE memos
- SET tags_json = ?, updated_by = ?, updated_at = ?
- WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
- )
- .bind(JSON.stringify(nextTags), actorLabel, now, row.id, workspaceId),
- db.prepare(`DELETE FROM memos_fts WHERE memo_id = ?`).bind(row.id),
- db
- .prepare(
- `INSERT INTO memos_fts (memo_id, title, content_text, tags)
- VALUES (?, ?, ?, ?)`
- )
- .bind(row.id, row.title, row.content_text, nextTags.join(" ")),
- auditStatement(db, actor.actorType, actor.actorId, normalizedNext ? "tag.rename" : "tag.delete", "memo", row.id, {
- from: normalizedOld,
- to: normalizedNext,
- })
- );
- updated += 1;
- }
-
- if (statements.length > 0) {
- await db.batch(statements);
- }
-
- return updated;
-};
-
-const previewTagRename = async (db: D1Database, workspaceId: string, oldTag: string, nextTag: string | null) => {
- const normalizedOld = normalizeTags([oldTag])[0];
- const normalizedNext = nextTag === null ? null : normalizeTags([nextTag])[0];
-
- if (!normalizedOld || normalizedOld === normalizedNext) {
- return { dryRun: true, updated: 0, changes: [] };
- }
-
- const rows = await getMemoRowsByTag(db, workspaceId, normalizedOld);
- const changes = rows.map((row) => {
- const currentTags = parseJsonArray(row.tags_json);
- const nextTags = normalizeTags(
- currentTags.flatMap((tag) => {
- if (tag !== normalizedOld) {
- return [tag];
- }
-
- return normalizedNext ? [normalizedNext] : [];
- })
- );
-
- return {
- memoId: row.id,
- title: row.title,
- currentTags,
- nextTags,
- };
- });
-
- return { dryRun: true, updated: changes.length, changes };
-};
-
-const getMemoRowsByTag = async (db: D1Database, workspaceId: string, tag: string) => {
- const rows = await db
- .prepare(
- `SELECT m.id, m.title, m.tags_json, c.content_text
- FROM memos m
- INNER JOIN memo_contents c ON c.memo_id = m.id
- WHERE m.workspace_id = ? AND m.is_deleted = 0
- AND EXISTS (
- SELECT 1
- FROM json_each(m.tags_json)
- WHERE json_each.value = ?
- )`
- )
- .bind(workspaceId, tag)
- .all<MemoTagUpdateRow>();
-
- return rows.results;
-};
-
-const updateTagsForMemos = async (
- db: D1Database,
- input: {
- workspaceId: string;
- memoIds: string[];
- tags: string[];
- mode: "add" | "remove";
- dryRun: boolean;
- actor: { actorType: "user" | "agent"; actorId: string | null };
- actorLabel: string;
- }
-) => {
- const memoIds = Array.from(new Set(input.memoIds));
- const tags = normalizeTags(input.tags);
-
- if (memoIds.length === 0 || tags.length === 0) {
- throw new AppError("invalid_params", "memoIds and tags must include at least one item", 400);
+ const placeholders = uniqueIds.map(() => "?").join(", ");
+ const rows = await db.prepare(
+ `SELECT id FROM notebooks WHERE workspace_id = ? AND id IN (${placeholders})`
+ ).bind(workspaceId, ...uniqueIds).all<{ id: string }>();
+ if (rows.results.length !== uniqueIds.length) {
+ throw new AppError("invalid_backup_workspace", "Backup references a notebook outside the current workspace.", 400);
}
+};
- const placeholders = memoIds.map(() => "?").join(", ");
- const rows = await db
- .prepare(
- `SELECT m.id, m.title, m.tags_json, c.content_text
- FROM memos m
- INNER JOIN memo_contents c ON c.memo_id = m.id
- WHERE m.workspace_id = ? AND m.is_deleted = 0 AND m.id IN (${placeholders})`
- )
- .bind(input.workspaceId, ...memoIds)
- .all<MemoTagUpdateRow>();
+const mapResource = (row: ResourceRow): Resource => ({
+ id: row.id,
+ memoId: row.memo_id,
+ originalMemoId: row.original_memo_id,
+ kind: row.kind,
+ mimeType: row.mime_type,
+ filename: row.filename,
+ byteSize: row.byte_size,
+ sha256: row.sha256,
+ width: row.width,
+ height: row.height,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ url: `/api/v1/resources/${row.id}/blob`,
+});
- if (rows.results.length !== memoIds.length) {
- throw new AppError("missing_memos", "One or more memos cannot be updated.", 400);
- }
+const mapResourceListItem = (row: ResourceListRow): ResourceListItem => ({
+ ...mapResource(row),
+ memoTitle: row.memo_title,
+ memoExcerpt: row.memo_excerpt,
+ memoDeleted: Boolean(row.memo_is_deleted),
+});
- const changes = rows.results
- .map((row) => {
- const currentTags = parseJsonArray(row.tags_json);
- const nextTags =
- input.mode === "add"
- ? normalizeTags([...currentTags, ...tags])
- : currentTags.filter((tag) => !tags.includes(tag));
+const mapResourceStorageSummary = (row: ResourceStatsRow | null): ResourceStorageSummary => ({
+ totalCount: row?.total_count ?? 0,
+ totalBytes: row?.total_bytes ?? 0,
+ imageCount: row?.image_count ?? 0,
+ attachmentCount: row?.attachment_count ?? 0,
+});
- return {
- memoId: row.id,
- title: row.title,
- currentTags,
- nextTags,
- contentText: row.content_text,
- };
- })
- .filter((change) => JSON.stringify(change.currentTags) !== JSON.stringify(change.nextTags));
+const mapApiToken = (row: ApiTokenRow): ApiToken => ({
+ id: row.id,
+ name: row.name,
+ token: row.token_value,
+ scopes: parseJsonArray(row.scopes_json),
+ lastUsedAt: row.last_used_at,
+ expiresAt: row.expires_at,
+ isRevoked: Boolean(row.is_revoked),
+ createdAt: row.created_at,
+});
- if (input.dryRun) {
- return {
- dryRun: true,
- updated: changes.length,
- changes: changes.map(({ contentText: _contentText, ...change }) => change),
- };
- }
- if (changes.length === 0) {
- return { ok: true, updated: 0 };
- }
+const getApiTokenRow = async (db: D1Database, id: string, workspaceId: string): Promise<ApiTokenRow | null> =>
+ db
+ .prepare(
+ `SELECT id, name, token_value, scopes_json, last_used_at, expires_at, is_revoked, created_at, workspace_id
+ FROM api_tokens
+ WHERE id = ? AND workspace_id = ?`
+ )
+ .bind(id, workspaceId)
+ .first<ApiTokenRow>();
- const now = isoNow();
- const statements: D1PreparedStatement[] = [];
+const getCurrentWorkspaceIdentity = async (db: D1Database, auth: AuthContext) => {
+ const row = await db.prepare(
+ `SELECT w.id AS workspace_id, w.name AS workspace_name, w.is_personal,
+ u.id AS user_id, u.username, u.display_name, wm.role
+ FROM workspaces w
+ INNER JOIN workspace_members wm ON wm.workspace_id = w.id
+ INNER JOIN users u ON u.id = wm.user_id
+ WHERE w.id = ?
+ ORDER BY CASE WHEN u.id = ? THEN 0 ELSE 1 END, wm.created_at ASC
+ LIMIT 1`
+ ).bind(auth.workspaceId, auth.kind === "user" ? auth.actorId : null).first<WorkspaceIdentityRow>();
- for (const change of changes) {
- statements.push(
- db
- .prepare(
- `UPDATE memos
- SET tags_json = ?, updated_by = ?, updated_at = ?
- WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
- )
- .bind(JSON.stringify(change.nextTags), input.actorLabel, now, change.memoId, input.workspaceId),
- db.prepare(`DELETE FROM memos_fts WHERE memo_id = ?`).bind(change.memoId),
- db
- .prepare(
- `INSERT INTO memos_fts (memo_id, title, content_text, tags)
- VALUES (?, ?, ?, ?)`
- )
- .bind(change.memoId, change.title, change.contentText, change.nextTags.join(" ")),
- auditStatement(db, input.actor.actorType, input.actor.actorId, input.mode === "add" ? "tag.add" : "tag.remove", "memo", change.memoId, {
- tags,
- })
- );
+ if (!row) {
+ throw new AppError("workspace_identity_not_found", "The authenticated workspace has no associated user.", 404);
}
- await db.batch(statements);
- return { ok: true, updated: changes.length };
+ return {
+ user: {
+ id: row.user_id,
+ username: row.username,
+ displayName: row.display_name,
+ role: row.role,
+ },
+ workspace: {
+ id: row.workspace_id,
+ name: row.workspace_name,
+ isPersonal: row.is_personal === 1,
+ },
+ authorization: {
+ kind: auth.kind === "agent" ? "api_token" : "user_session",
+ ...(auth.kind === "agent" ? { tokenName: auth.username, scopes: auth.scopes } : {}),
+ },
+ dataIsolation: {
+ workspaceScoped: true,
+ statement:
+ "Every notebook and memo returned by this MCP server belongs to this workspace; data from other users is excluded.",
+ },
+ };
};
const searchMemoSummaries = async (
@@ -5546,139 +4207,6 @@ const listMemosForMcp = async (
};
};
-const getNotebook = async (db: D1Database, workspaceId: string, id: string): Promise<Notebook | null> => {
- const row = await db
- .prepare(
- notebookSelectSql(
- `WHERE n.id = ? AND n.workspace_id = ? AND n.is_deleted = 0
- GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at`
- )
- )
- .bind(id, workspaceId)
- .first<NotebookRow>();
-
- return row ? mapNotebook(row) : null;
-};
-
-const createNotebookRecord = async (
- db: D1Database,
- workspaceId: string,
- input: NotebookCreateInput & { sortOrder?: number },
- actor: { actorType: "user" | "agent"; actorId: string | null }
-) => {
- const parentId = input.parentId ?? null;
-
- if (parentId && !(await getNotebook(db, workspaceId, parentId))) {
- throw new AppError("not_found", "Parent notebook not found", 404);
- }
-
- const id = createId("nb");
- const now = isoNow();
- const sortOrder = input.sortOrder ?? Date.now();
-
- await db.batch([
- db
- .prepare(
- `INSERT INTO notebooks (id, workspace_id, parent_id, name, slug, sort_order, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
- )
- .bind(id, workspaceId, parentId, input.name, slugify(input.name), sortOrder, now, now),
- auditStatement(db, actor.actorType, actor.actorId, "notebook.create", "notebook", id, {
- name: input.name,
- parentId,
- sortOrder,
- }),
- ]);
-
- const notebook = await getNotebook(db, workspaceId, id);
-
- if (!notebook) {
- throw new AppError("not_found", "Notebook not found after create", 404);
- }
-
- return notebook;
-};
-
-const updateNotebookRecord = async (
- db: D1Database,
- workspaceId: string,
- id: string,
- input: { name?: string; parentId?: string | null; sortOrder?: number },
- actor: { actorType: "user" | "agent"; actorId: string | null }
-) => {
- const current = await getNotebook(db, workspaceId, id);
-
- if (!current) {
- throw new AppError("not_found", "Notebook not found", 404);
- }
-
- const nextName = input.name ?? current.name;
- const nextParentId = input.parentId === undefined ? current.parentId : input.parentId;
- const nextSortOrder = input.sortOrder ?? current.sortOrder;
- const now = isoNow();
-
- if (nextParentId === id) {
- throw new AppError("bad_request", "Notebook cannot be its own parent", 400);
- }
-
- if (nextParentId) {
- const parent = await getNotebook(db, workspaceId, nextParentId);
-
- if (!parent) {
- throw new AppError("not_found", "Parent notebook not found", 404);
- }
-
- if (await isNotebookDescendant(db, workspaceId, nextParentId, id)) {
- throw new AppError("notebook_cycle", "Notebook cannot be moved into its own descendant.", 409);
- }
- }
-
- await db.batch([
- db
- .prepare(
- `UPDATE notebooks
- SET name = ?, slug = ?, parent_id = ?, sort_order = ?, updated_at = ?
- WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
- )
- .bind(nextName, slugify(nextName), nextParentId ?? null, nextSortOrder, now, id, workspaceId),
- auditStatement(db, actor.actorType, actor.actorId, "notebook.update", "notebook", id, input),
- ]);
-
- const notebook = await getNotebook(db, workspaceId, id);
-
- if (!notebook) {
- throw new AppError("not_found", "Notebook not found after update", 404);
- }
-
- return notebook;
-};
-
-const isNotebookDescendant = async (db: D1Database, workspaceId: string, candidateId: string, ancestorId: string) => {
- const row = await db
- .prepare(
- `WITH RECURSIVE descendants(id) AS (
- SELECT id
- FROM notebooks
- WHERE workspace_id = ? AND parent_id = ? AND is_deleted = 0
-
- UNION ALL
-
- SELECT n.id
- FROM notebooks n
- INNER JOIN descendants d ON n.parent_id = d.id
- WHERE n.workspace_id = ? AND n.is_deleted = 0
- )
- SELECT id
- FROM descendants
- WHERE id = ?
- LIMIT 1`
- )
- .bind(workspaceId, ancestorId, workspaceId, candidateId)
- .first<{ id: string }>();
-
- return Boolean(row);
-};
-
const getMemoDetailRow = async (
db: D1Database,
workspaceId: string,
@@ -7177,15 +5705,6 @@ const getWorkspaceStats = async (db: D1Database, workspaceId: string) => {
};
};
-const parseJsonArray = (json: string): string[] => {
- try {
- const value = JSON.parse(json);
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
- } catch {
- return [];
- }
-};
-
const parseDoc = (json: string): TiptapDoc => {
try {
const value = JSON.parse(json);
@@ -7195,46 +5714,6 @@ const parseDoc = (json: string): TiptapDoc => {
}
};
-const audit = async (
- db: D1Database,
- actorType: "user" | "agent" | "system",
- actorId: string | null,
- action: string,
- entityType: string,
- entityId: string,
- metadata: unknown
-) => auditStatement(db, actorType, actorId, action, entityType, entityId, metadata).run();
-
-const auditStatement = (
- db: D1Database,
- actorType: "user" | "agent" | "system",
- actorId: string | null,
- action: string,
- entityType: string,
- entityId: string,
- metadata: unknown
-) =>
- db
- .prepare(
- `INSERT INTO audit_events (
- id, actor_type, actor_id, action, entity_type, entity_id, metadata_json, created_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
- )
- .bind(createId("audit"), actorType, actorId, action, entityType, entityId, JSON.stringify(metadata ?? {}), isoNow());
-
-const createId = (prefix: string) => `${prefix}_${crypto.randomUUID().replace(/-/g, "")}`;
-
-const isoNow = () => new Date().toISOString();
-
-const slugify = (value: string) =>
- value
- .trim()
- .toLowerCase()
- .replace(/['"]/g, "")
- .replace(/[^\p{L}\p{N}]+/gu, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 80);
-
const normalizeMemoTitle = (value: string | null | undefined) => {
const title = value?.trim();
return title || DEFAULT_MEMO_TITLE;
@@ -7394,93 +5873,3 @@ const contentDispositionAttachment = (filename: string | null) => {
const fallback = normalizeFilename(filename).replace(/"/g, "'");
return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
};
-
-const decodeTagParam = (value: string) => {
- try {
- return decodeURIComponent(value).trim();
- } catch {
- return value.trim();
- }
-};
-
-const notFound = (c: Context, message: string) =>
- c.json(
- {
- error: {
- code: "not_found",
- message,
- },
- },
- 404
- );
-
-const badRequest = (c: Context, message: string) =>
- c.json(
- {
- error: {
- code: "bad_request",
- message,
- },
- },
- 400
- );
-
-const apiError = (c: Context, code: string, message: string, status: number) =>
- c.json(
- {
- error: {
- code,
- message,
- },
- },
- status as 400
- );
-
-const authNotConfigured = (c: Context) =>
- apiError(
- c,
- "auth_not_configured",
- "Authentication is not configured. Set EDGE_EVER_AUTH_PASSWORD as a Worker Secret and redeploy.",
- 503,
- );
-
-const databaseNotReady = (c: Context) =>
- apiError(
- c,
- "database_not_ready",
- "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",
- 503,
- );
-
-const conflict = (c: Context, code: string, message: string) =>
- c.json(
- {
- error: {
- code,
- message,
- },
- },
- 409
- );
-
-const unauthorized = (c: Context, message: string) =>
- c.json(
- {
- error: {
- code: "unauthorized",
- message,
- },
- },
- 401
- );
-
-const forbidden = (c: Context, message: string) =>
- c.json(
- {
- error: {
- code: "forbidden",
- message,
- },
- },
- 403
- );
diff --git a/apps/api/src/mcp-json-rpc.test.mjs b/apps/api/src/mcp-json-rpc.test.mjs
new file mode 100644
index 00000000..bc494cba
--- /dev/null
+++ b/apps/api/src/mcp-json-rpc.test.mjs
@@ -0,0 +1,52 @@
+import { describe, expect, test } from "bun:test";
+import { AppError } from "./app-error";
+import {
+ asRecord,
+ decodeBase64Data,
+ escapeMarkdownImageAlt,
+ getJsonRpcId,
+ getRequiredString,
+ getRequiredStringArray,
+ jsonRpcError,
+ jsonRpcResult,
+ mapMcpToolError,
+} from "./mcp-json-rpc";
+
+describe("MCP JSON-RPC helpers", () => {
+ test("builds protocol results and errors", () => {
+ expect(jsonRpcResult(1, { ok: true })).toEqual({ jsonrpc: "2.0", id: 1, result: { ok: true } });
+ expect(jsonRpcError("request", -32602, "Invalid params", { field: "memoId" })).toEqual({
+ jsonrpc: "2.0",
+ id: "request",
+ error: { code: -32602, message: "Invalid params", data: { field: "memoId" } },
+ });
+ });
+
+ test("accepts only valid IDs, records, and required values", () => {
+ expect(getJsonRpcId({ id: 0 })).toBe(0);
+ expect(getJsonRpcId({ id: false })).toBeNull();
+ expect(asRecord(["not", "a", "record"])).toEqual({});
+ expect(getRequiredString(" memo_1 ", "memoId")).toBe("memo_1");
+ expect(getRequiredStringArray(["one", 2, "two"], "items")).toEqual(["one", "two"]);
+ expect(() => getRequiredString(" ", "memoId")).toThrow(AppError);
+ });
+
+ test("decodes raw and data URL base64 payloads", async () => {
+ expect(new TextDecoder().decode(await decodeBase64Data("RWRnZUV2ZXI="))).toBe("EdgeEver");
+ expect(new TextDecoder().decode(await decodeBase64Data("data:text/plain;base64,RWRnZUV2ZXI="))).toBe("EdgeEver");
+ });
+
+ test("escapes Markdown image labels", () => {
+ expect(escapeMarkdownImageAlt("[cover] \\ draft")).toBe("\\[cover\\] \\\\ draft");
+ });
+
+ test("maps application errors to stable MCP error codes", () => {
+ expect(mapMcpToolError(new AppError("memo_missing", "Memo not found", 404))).toEqual({
+ rpcCode: -32004,
+ status: 404,
+ message: "Memo not found",
+ data: { code: "memo_missing" },
+ });
+ expect(mapMcpToolError(new Error("boom"))).toMatchObject({ rpcCode: -32000, status: 400, message: "boom" });
+ });
+});
diff --git a/apps/api/src/mcp-json-rpc.ts b/apps/api/src/mcp-json-rpc.ts
new file mode 100644
index 00000000..6b77a351
--- /dev/null
+++ b/apps/api/src/mcp-json-rpc.ts
@@ -0,0 +1,122 @@
+import { AppError } from "./app-error";
+
+export type JsonRpcRequest = {
+ jsonrpc?: string;
+ id?: string | number | null;
+ method?: string;
+ params?: unknown;
+};
+
+export type JsonRpcId = string | number | null;
+
+export type JsonRpcHandlerResult = {
+ body: unknown;
+ status: number;
+};
+
+export const jsonRpcResult = (id: JsonRpcId, result: unknown) => ({
+ jsonrpc: "2.0",
+ id,
+ result,
+});
+
+export const jsonRpcError = (id: JsonRpcId, code: number, message: string, data?: unknown) => ({
+ jsonrpc: "2.0",
+ id,
+ error: {
+ code,
+ message,
+ ...(data === undefined ? {} : { data }),
+ },
+});
+
+export const getJsonRpcId = (request: unknown): JsonRpcId => {
+ if (!request || typeof request !== "object" || !("id" in request)) {
+ return null;
+ }
+
+ const id = (request as { id?: unknown }).id;
+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;
+};
+
+export const asRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
+
+export const getOptionalString = (value: unknown) =>
+ typeof value === "string" && value.trim() ? value.trim() : null;
+
+export const getRequiredString = (value: unknown, name: string) => {
+ const parsed = getOptionalString(value);
+
+ if (!parsed) {
+ throw new AppError("invalid_params", `${name} is required`, 400);
+ }
+
+ return parsed;
+};
+
+export const getOptionalStringArray = (value: unknown) =>
+ Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
+
+export const getRequiredStringArray = (value: unknown, name: string) => {
+ const items = getOptionalStringArray(value);
+
+ if (items.length === 0) {
+ throw new AppError("invalid_params", `${name} must include at least one item`, 400);
+ }
+
+ return items;
+};
+
+export const decodeBase64Data = async (value: string) => {
+ const [, dataUrlPayload] = value.match(/^data:[^;]+;base64,(.+)$/i) ?? [];
+ const base64 = (dataUrlPayload ?? value).replace(/\s/g, "");
+
+ if (!base64) {
+ throw new AppError("invalid_params", "dataBase64 is required", 400);
+ }
+
+ try {
+ const response = await fetch("data:application/octet-stream;base64," + base64);
+ if (!response.ok) {
+ throw new Error("failed to decode base64");
+ }
+ return new Uint8Array(await response.arrayBuffer());
+ } catch (error) {
+ throw new AppError("invalid_params", "dataBase64 must be valid base64 data: " + (error as Error).message, 400);
+ }
+};
+
+export const escapeMarkdownImageAlt = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
+export const escapeMarkdownLinkLabel = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
+
+export const mapMcpToolError = (error: unknown) => {
+ if (error instanceof AppError) {
+ const rpcCode =
+ error.status === 401
+ ? -32001
+ : error.status === 403
+ ? -32003
+ : error.status === 404
+ ? -32004
+ : error.status === 409
+ ? -32009
+ : -32602;
+
+ return {
+ rpcCode,
+ status: error.status,
+ message: error.message,
+ data: {
+ code: error.code,
+ },
+ };
+ }
+
+ return {
+ rpcCode: -32000,
+ status: 400,
+ message: error instanceof Error ? error.message : "Tool call failed",
+ data: undefined,
+ };
+};
diff --git a/apps/api/src/mcp-tools.test.mjs b/apps/api/src/mcp-tools.test.mjs
new file mode 100644
index 00000000..f11a359b
--- /dev/null
+++ b/apps/api/src/mcp-tools.test.mjs
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "bun:test";
+import { MCP_TOOLS } from "./mcp-tools";
+
+describe("MCP tool catalog", () => {
+ test("keeps tool names unique and schemas object-shaped", () => {
+ const names = MCP_TOOLS.map((tool) => tool.name);
+
+ expect(new Set(names).size).toBe(names.length);
+ expect(MCP_TOOLS.length).toBeGreaterThan(20);
+ for (const tool of MCP_TOOLS) {
+ expect(tool.inputSchema.type).toBe("object");
+ expect(tool.outputSchema).toEqual({ type: "object" });
+ expect(tool.annotations.openWorldHint).toBe(false);
+ }
+ });
+
+ test("marks reads and destructive writes consistently", () => {
+ const byName = new Map(MCP_TOOLS.map((tool) => [tool.name, tool]));
+
+ expect(byName.get("get_memo")?.annotations).toMatchObject({
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ });
+ expect(byName.get("trash_memos")?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: false,
+ });
+ expect(byName.get("move_memos")?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: true,
+ });
+ });
+});
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
new file mode 100644
index 00000000..c43c9b15
--- /dev/null
+++ b/apps/api/src/mcp-tools.ts
@@ -0,0 +1,482 @@
+const MCP_TOOL_DEFINITIONS = [
+ {
+ name: "get_current_user",
+ description:
+ "Identify the EdgeEver user and personal workspace authorized by the current session or API token. Use this before imports when the destination account must be confirmed.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {},
+ },
+ },
+ {
+ name: "search_memos",
+ description: "Search active EdgeEver memos by text, tag, notebook, time range, pin state, or resource presence.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ query: { type: "string" },
+ notebookId: { type: "string" },
+ tags: { type: "array", items: { type: "string" } },
+ createdAfter: { type: "string", format: "date-time" },
+ createdBefore: { type: "string", format: "date-time" },
+ updatedAfter: { type: "string", format: "date-time" },
+ updatedBefore: { type: "string", format: "date-time" },
+ isPinned: { type: "boolean" },
+ hasResources: { type: "boolean" },
+ limit: { type: "integer", minimum: 1, maximum: 50 },
+ },
+ },
+ },
+ {
+ name: "list_memos",
+ description: "List EdgeEver memos with pagination. Use includeContent when full Markdown is needed.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ notebookId: { type: "string" },
+ limit: { type: "integer", minimum: 1, maximum: 100 },
+ offset: { type: "integer", minimum: 0 },
+ includeContent: { type: "boolean" },
+ includeDeleted: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "get_memo",
+ description: "Read a memo with Markdown content.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ includeDeleted: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "create_memo",
+ description: "Create a memo in a notebook.",
+ inputSchema: {
+ type: "object",
+ required: ["notebookId"],
+ additionalProperties: false,
+ properties: {
+ notebookId: { type: "string" },
+ title: { type: "string" },
+ contentMarkdown: { type: "string" },
+ tags: { type: "array", items: { type: "string" } },
+ createdAt: { type: "string", format: "date-time" },
+ updatedAt: { type: "string", format: "date-time" },
+ },
+ },
+ },
+ {
+ name: "import_memos",
+ description:
+ "Import up to 25 memos from an external service with database-backed idempotency. Reusing the same source and externalId returns skipped instead of creating a duplicate. Results are reported per item.",
+ inputSchema: {
+ type: "object",
+ required: ["source", "notebookId", "items"],
+ additionalProperties: false,
+ properties: {
+ source: {
+ type: "string",
+ minLength: 1,
+ maxLength: 80,
+ pattern: "^[A-Za-z0-9._-]+$",
+ description: "Stable source identifier such as flomo, notion, memos, or evernote.",
+ },
+ notebookId: { type: "string", description: "Destination notebook for every item in this batch." },
+ dryRun: { type: "boolean", description: "Validate and report existing items without creating memos." },
+ items: {
+ type: "array",
+ minItems: 1,
+ maxItems: 25,
+ items: {
+ type: "object",
+ required: ["externalId"],
+ additionalProperties: false,
+ properties: {
+ externalId: {
+ type: "string",
+ minLength: 1,
+ maxLength: 512,
+ description: "Stable ID from the source system. It is the idempotency key within source and workspace.",
+ },
+ title: { type: "string", maxLength: 160 },
+ contentMarkdown: { type: "string" },
+ tags: { type: "array", maxItems: 100, items: { type: "string" } },
+ createdAt: { type: "string", format: "date-time" },
+ updatedAt: { type: "string", format: "date-time" },
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ name: "update_memo",
+ description: "Update memo title, Markdown, tags, notebook, or pinned state.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ title: { type: "string" },
+ isPinned: { type: "boolean" },
+ contentMarkdown: { type: "string" },
+ tags: { type: "array", items: { type: "string" } },
+ notebookId: { type: "string" },
+ expectedRevision: { type: "integer", minimum: 0 },
+ createdAt: { type: "string", format: "date-time" },
+ updatedAt: { type: "string", format: "date-time" },
+ },
+ },
+ },
+ {
+ name: "trash_memos",
+ description: "Move one or more active memos to trash. Use dryRun to preview affected memos.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "restore_memos",
+ description: "Restore one or more trashed memos. If the original notebook is gone, memos are restored to the default inbox.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "move_memos",
+ description: "Move one or more active memos to another notebook. Use dryRun to preview affected memos.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds", "notebookId"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
+ notebookId: { type: "string" },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "add_tags_to_memos",
+ description: "Add tags to one or more active memos. Use dryRun to preview changed tags.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds", "tags"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
+ tags: { type: "array", minItems: 1, maxItems: 20, items: { type: "string" } },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "remove_tags_from_memos",
+ description: "Remove tags from one or more active memos. Use dryRun to preview changed tags.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds", "tags"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
+ tags: { type: "array", minItems: 1, maxItems: 20, items: { type: "string" } },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "rename_tag",
+ description: "Rename a tag across all active memos. This merges into an existing tag with the same normalized name.",
+ inputSchema: {
+ type: "object",
+ required: ["from", "to"],
+ additionalProperties: false,
+ properties: {
+ from: { type: "string" },
+ to: { type: "string" },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "delete_tag",
+ description: "Remove a tag from all active memos.",
+ inputSchema: {
+ type: "object",
+ required: ["tag"],
+ additionalProperties: false,
+ properties: {
+ tag: { type: "string" },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "merge_memos",
+ description: "Merge multiple active memos into a new memo and soft-delete the sources.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 2, maxItems: 50, items: { type: "string" } },
+ notebookId: { type: "string" },
+ title: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "upload_memo_image",
+ description:
+ "Upload a base64-encoded image resource to a memo and return Markdown that can be inserted into memo content. Images are stored as provided; server-side compression is disabled to avoid Cloudflare Images quota usage.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId", "mimeType", "dataBase64"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ filename: { type: "string" },
+ mimeType: { type: "string", enum: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"] },
+ dataBase64: { type: "string" },
+ alt: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "upload_memo_attachment",
+ description: "Upload a base64-encoded attachment resource to a memo and return Markdown link text that can be inserted into memo content.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId", "filename", "mimeType", "dataBase64"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ filename: { type: "string" },
+ mimeType: { type: "string" },
+ dataBase64: { type: "string" },
+ label: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "list_memo_resources",
+ description: "List active resources attached to a memo.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "list_resources",
+ description: "List active workspace resources with storage summary.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ limit: { type: "integer", minimum: 1, maximum: 500 },
+ },
+ },
+ },
+ {
+ name: "list_memo_revisions",
+ description: "List revision history for a memo.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ limit: { type: "integer", minimum: 1, maximum: 100 },
+ },
+ },
+ },
+ {
+ name: "restore_memo_revision",
+ description: "Restore a memo to a previous revision. Use dryRun to preview the target revision.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId", "revisionId"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string" },
+ revisionId: { type: "string" },
+ dryRun: { type: "boolean" },
+ },
+ },
+ },
+ {
+ name: "move_notebook",
+ description: "Move a notebook under another notebook or root and update its sort order.",
+ inputSchema: {
+ type: "object",
+ required: ["notebookId"],
+ additionalProperties: false,
+ properties: {
+ notebookId: { type: "string" },
+ parentId: { type: ["string", "null"] },
+ sortOrder: { type: "integer" },
+ },
+ },
+ },
+ {
+ name: "create_notebook",
+ description: "Create a notebook at the root or under another notebook.",
+ inputSchema: {
+ type: "object",
+ required: ["name"],
+ additionalProperties: false,
+ properties: {
+ name: { type: "string", minLength: 1, maxLength: 80 },
+ parentId: { type: ["string", "null"] },
+ sortOrder: { type: "integer" },
+ },
+ },
+ },
+ {
+ name: "get_notebook",
+ description: "Get one active notebook by ID from the authenticated user's workspace.",
+ inputSchema: {
+ type: "object",
+ required: ["notebookId"],
+ additionalProperties: false,
+ properties: {
+ notebookId: { type: "string", description: "The exact EdgeEver notebook ID." },
+ },
+ },
+ },
+ {
+ name: "find_notebooks",
+ description: "Find active notebooks by name, optionally restricted to a parent notebook or the workspace root.",
+ inputSchema: {
+ type: "object",
+ required: ["name"],
+ additionalProperties: false,
+ properties: {
+ name: { type: "string", minLength: 1, description: "Full or partial notebook name, matched case-insensitively." },
+ parentId: {
+ type: ["string", "null"],
+ description: "Parent notebook ID. Pass null to search only root notebooks; omit to search all levels.",
+ },
+ exact: { type: "boolean", description: "Require an exact name match. Defaults to false." },
+ limit: { type: "integer", minimum: 1, maximum: 50 },
+ },
+ },
+ },
+ {
+ name: "resolve_notebook_path",
+ description:
+ "Resolve a slash-separated notebook path such as 'Imports/Flomo' to one exact notebook. Returns a diagnostic result instead of guessing when a segment is missing or ambiguous.",
+ inputSchema: {
+ type: "object",
+ required: ["path"],
+ additionalProperties: false,
+ properties: {
+ path: { type: "string", minLength: 1, description: "Slash-separated notebook names from the workspace root." },
+ },
+ },
+ },
+ {
+ name: "list_notebooks",
+ description:
+ "List active notebooks in the authenticated user's workspace. Every returned notebook is owned by that workspace; notebooks from other users are never returned.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {},
+ },
+ },
+ {
+ name: "list_tags",
+ description: "List tags and memo counts.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {},
+ },
+ },
+ {
+ name: "get_workspace_stats",
+ description: "Get notebook, memo, tag, and resource counts for workspace diagnostics.",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {},
+ },
+ },
+];
+
+const READ_ONLY_MCP_TOOLS = new Set([
+ "get_current_user",
+ "search_memos",
+ "list_memos",
+ "get_memo",
+ "list_memo_resources",
+ "list_resources",
+ "list_memo_revisions",
+ "get_notebook",
+ "find_notebooks",
+ "resolve_notebook_path",
+ "list_notebooks",
+ "list_tags",
+ "get_workspace_stats",
+]);
+const NON_DESTRUCTIVE_MCP_TOOLS = new Set([
+ "create_memo",
+ "import_memos",
+ "restore_memos",
+ "move_memos",
+ "add_tags_to_memos",
+ "upload_memo_image",
+ "upload_memo_attachment",
+ "move_notebook",
+ "create_notebook",
+]);
+const IDEMPOTENT_MCP_TOOLS = new Set([
+ "restore_memos",
+ "move_memos",
+ "add_tags_to_memos",
+ "remove_tags_from_memos",
+ "import_memos",
+ "move_notebook",
+]);
+
+export const MCP_TOOLS = MCP_TOOL_DEFINITIONS.map((tool) => {
+ const readOnly = READ_ONLY_MCP_TOOLS.has(tool.name);
+ return {
+ ...tool,
+ title: tool.name.split("_").map((part) => part[0]?.toUpperCase() + part.slice(1)).join(" "),
+ outputSchema: { type: "object" },
+ annotations: {
+ readOnlyHint: readOnly,
+ destructiveHint: readOnly ? false : !NON_DESTRUCTIVE_MCP_TOOLS.has(tool.name),
+ idempotentHint: readOnly || IDEMPOTENT_MCP_TOOLS.has(tool.name),
+ openWorldHint: false,
+ },
+ };
+});
diff --git a/apps/api/src/notebook-routes.ts b/apps/api/src/notebook-routes.ts
new file mode 100644
index 00000000..350f8ebb
--- /dev/null
+++ b/apps/api/src/notebook-routes.ts
@@ -0,0 +1,96 @@
+import { NotebookCreateSchema, NotebookUpdateSchema } from "@edgeever/shared";
+import { zValidator } from "@hono/zod-validator";
+import type { Hono } from "hono";
+import type { AppEnv, Bindings } from "./api-context";
+import { AppError } from "./app-error";
+import { apiError } from "./http-errors";
+import {
+ createNotebookRecord,
+ deleteNotebookRecord,
+ listNotebooks,
+ restoreNotebookRecord,
+ updateNotebookRecord,
+} from "./notebook-service";
+import { getAuditActor, getWorkspaceId, requireScopes } from "./request-auth";
+
+const respondWithAppError = (c: Parameters<typeof apiError>[0], error: unknown) => {
+ if (error instanceof AppError) return apiError(c, error.code, error.message, error.status);
+ throw error;
+};
+
+export const registerNotebookRoutes = (
+ app: Hono<AppEnv>,
+ prepareDemoData: (env: Bindings) => Promise<void>
+) => {
+ app.get("/api/v1/notebooks", async (c) => {
+ const denied = requireScopes(c, "read:notebooks");
+ if (denied) return denied;
+
+ await prepareDemoData(c.env);
+ return c.json({ notebooks: await listNotebooks(c.env.storage.db, getWorkspaceId(c)) });
+ });
+
+ app.post("/api/v1/notebooks", zValidator("json", NotebookCreateSchema), async (c) => {
+ const denied = requireScopes(c, "write:notebooks");
+ if (denied) return denied;
+
+ try {
+ const notebook = await createNotebookRecord(
+ c.env.storage.db,
+ getWorkspaceId(c),
+ c.req.valid("json"),
+ getAuditActor(c)
+ );
+ return c.json({ notebook }, 201);
+ } catch (error) {
+ return respondWithAppError(c, error);
+ }
+ });
+
+ app.patch("/api/v1/notebooks/:id", zValidator("json", NotebookUpdateSchema), async (c) => {
+ const denied = requireScopes(c, "write:notebooks");
+ if (denied) return denied;
+
+ try {
+ const notebook = await updateNotebookRecord(
+ c.env.storage.db,
+ getWorkspaceId(c),
+ c.req.param("id"),
+ c.req.valid("json"),
+ getAuditActor(c)
+ );
+ return c.json({ notebook });
+ } catch (error) {
+ return respondWithAppError(c, error);
+ }
+ });
+
+ app.delete("/api/v1/notebooks/:id", async (c) => {
+ const denied = requireScopes(c, "write:notebooks");
+ if (denied) return denied;
+
+ try {
+ await deleteNotebookRecord(c.env.storage.db, getWorkspaceId(c), c.req.param("id"), getAuditActor(c));
+ return c.json({ ok: true });
+ } catch (error) {
+ return respondWithAppError(c, error);
+ }
+ });
+
+ app.post("/api/v1/notebooks/:id/restore", async (c) => {
+ const denied = requireScopes(c, "write:notebooks");
+ if (denied) return denied;
+
+ try {
+ const notebook = await restoreNotebookRecord(
+ c.env.storage.db,
+ getWorkspaceId(c),
+ c.req.param("id"),
+ getAuditActor(c)
+ );
+ return c.json({ notebook });
+ } catch (error) {
+ return respondWithAppError(c, error);
+ }
+ });
+};
diff --git a/apps/api/src/notebook-service.ts b/apps/api/src/notebook-service.ts
new file mode 100644
index 00000000..aef91b01
--- /dev/null
+++ b/apps/api/src/notebook-service.ts
@@ -0,0 +1,327 @@
+import type { Notebook, NotebookCreateInput } from "@edgeever/shared";
+import type { AuditActor } from "./api-context";
+import { AppError } from "./app-error";
+import { audit, auditStatement } from "./audit";
+import { createId, isoNow, slugify } from "./entity-utils";
+import type { DatabaseAdapter } from "./storage-contract";
+
+export type NotebookRow = {
+ id: string;
+ parent_id: string | null;
+ name: string;
+ slug: string | null;
+ icon: string | null;
+ color: string | null;
+ sort_order: number;
+ memo_count: number | null;
+ last_memo_updated_at: string | null;
+ created_at: string;
+ updated_at: string;
+};
+
+export const mapNotebook = (row: NotebookRow): Notebook => ({
+ id: row.id,
+ parentId: row.parent_id,
+ name: row.name,
+ slug: row.slug,
+ icon: row.icon,
+ color: row.color,
+ sortOrder: row.sort_order,
+ memoCount: row.memo_count ?? 0,
+ lastMemoUpdatedAt: row.last_memo_updated_at,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+});
+
+export const notebookSelectSql = (tail: string) => `
+ SELECT n.id,
+ n.parent_id,
+ n.name,
+ n.slug,
+ n.icon,
+ n.color,
+ n.sort_order,
+ COUNT(m.id) AS memo_count,
+ MAX(m.updated_at) AS last_memo_updated_at,
+ n.created_at,
+ n.updated_at
+ FROM notebooks n
+ LEFT JOIN memos m ON m.notebook_id = n.id AND m.is_deleted = 0
+ ${tail}
+`;
+
+export const listNotebooks = async (db: DatabaseAdapter, workspaceId: string): Promise<Notebook[]> => {
+ const rows = await db
+ .prepare(
+ notebookSelectSql(
+ `WHERE n.workspace_id = ? AND n.is_deleted = 0
+ GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at
+ ORDER BY n.parent_id IS NOT NULL, n.sort_order ASC, n.name ASC`
+ )
+ )
+ .bind(workspaceId).all<NotebookRow>();
+
+ return rows.results.map(mapNotebook);
+};
+
+const normalizeNotebookLookupName = (value: string) => value.trim().toLocaleLowerCase("en-US");
+
+export const findNotebooks = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ options: { name: string; parentId?: string | null; exact: boolean; limit: number },
+) => {
+ const query = normalizeNotebookLookupName(options.name);
+ const notebooks = await listNotebooks(db, workspaceId);
+ return notebooks
+ .filter((notebook) => {
+ if (options.parentId !== undefined && notebook.parentId !== options.parentId) {
+ return false;
+ }
+ const name = normalizeNotebookLookupName(notebook.name);
+ return options.exact ? name === query : name.includes(query);
+ })
+ .slice(0, options.limit);
+};
+
+export const resolveNotebookPath = async (db: DatabaseAdapter, workspaceId: string, path: string) => {
+ const segments = path.split("/").map((segment) => segment.trim()).filter(Boolean);
+ if (segments.length === 0) {
+ throw new AppError("invalid_params", "path must contain at least one notebook name", 400);
+ }
+
+ const notebooks = await listNotebooks(db, workspaceId);
+ const matched: Notebook[] = [];
+ let parentId: string | null = null;
+
+ for (const [index, segment] of segments.entries()) {
+ const normalizedSegment = normalizeNotebookLookupName(segment);
+ const candidates = notebooks.filter(
+ (notebook) => notebook.parentId === parentId && normalizeNotebookLookupName(notebook.name) === normalizedSegment,
+ );
+
+ if (candidates.length !== 1) {
+ return {
+ resolved: false,
+ path,
+ segments,
+ matched,
+ failedAt: index,
+ failedSegment: segment,
+ reason: candidates.length === 0 ? "not_found" : "ambiguous",
+ candidates,
+ };
+ }
+
+ matched.push(candidates[0]);
+ parentId = candidates[0].id;
+ }
+
+ return {
+ resolved: true,
+ path,
+ segments,
+ notebook: matched.at(-1),
+ matched,
+ };
+};
+
+export const getNotebook = async (db: DatabaseAdapter, workspaceId: string, id: string): Promise<Notebook | null> => {
+ const row = await db
+ .prepare(
+ notebookSelectSql(
+ `WHERE n.id = ? AND n.workspace_id = ? AND n.is_deleted = 0
+ GROUP BY n.id, n.parent_id, n.name, n.slug, n.icon, n.color, n.sort_order, n.created_at, n.updated_at`
+ )
+ )
+ .bind(id, workspaceId)
+ .first<NotebookRow>();
+
+ return row ? mapNotebook(row) : null;
+};
+
+export const createNotebookRecord = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ input: NotebookCreateInput & { sortOrder?: number },
+ actor: AuditActor
+) => {
+ const parentId = input.parentId ?? null;
+
+ if (parentId && !(await getNotebook(db, workspaceId, parentId))) {
+ throw new AppError("not_found", "Parent notebook not found", 404);
+ }
+
+ const id = createId("nb");
+ const now = isoNow();
+ const sortOrder = input.sortOrder ?? Date.now();
+
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO notebooks (id, workspace_id, parent_id, name, slug, sort_order, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
+ )
+ .bind(id, workspaceId, parentId, input.name, slugify(input.name), sortOrder, now, now),
+ auditStatement(db, actor.actorType, actor.actorId, "notebook.create", "notebook", id, {
+ name: input.name,
+ parentId,
+ sortOrder,
+ }),
+ ]);
+
+ const notebook = await getNotebook(db, workspaceId, id);
+
+ if (!notebook) {
+ throw new AppError("not_found", "Notebook not found after create", 404);
+ }
+
+ return notebook;
+};
+
+export const updateNotebookRecord = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ id: string,
+ input: { name?: string; parentId?: string | null; sortOrder?: number },
+ actor: AuditActor
+) => {
+ const current = await getNotebook(db, workspaceId, id);
+
+ if (!current) {
+ throw new AppError("not_found", "Notebook not found", 404);
+ }
+
+ const nextName = input.name ?? current.name;
+ const nextParentId = input.parentId === undefined ? current.parentId : input.parentId;
+ const nextSortOrder = input.sortOrder ?? current.sortOrder;
+ const now = isoNow();
+
+ if (nextParentId === id) {
+ throw new AppError("bad_request", "Notebook cannot be its own parent", 400);
+ }
+
+ if (nextParentId) {
+ const parent = await getNotebook(db, workspaceId, nextParentId);
+
+ if (!parent) {
+ throw new AppError("not_found", "Parent notebook not found", 404);
+ }
+
+ if (await isNotebookDescendant(db, workspaceId, nextParentId, id)) {
+ throw new AppError("notebook_cycle", "Notebook cannot be moved into its own descendant.", 409);
+ }
+ }
+
+ await db.batch([
+ db
+ .prepare(
+ `UPDATE notebooks
+ SET name = ?, slug = ?, parent_id = ?, sort_order = ?, updated_at = ?
+ WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
+ )
+ .bind(nextName, slugify(nextName), nextParentId ?? null, nextSortOrder, now, id, workspaceId),
+ auditStatement(db, actor.actorType, actor.actorId, "notebook.update", "notebook", id, input),
+ ]);
+
+ const notebook = await getNotebook(db, workspaceId, id);
+
+ if (!notebook) {
+ throw new AppError("not_found", "Notebook not found after update", 404);
+ }
+
+ return notebook;
+};
+
+export const deleteNotebookRecord = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ id: string,
+ actor: AuditActor
+) => {
+ const current = await getNotebook(db, workspaceId, id);
+ if (!current) throw new AppError("not_found", "Notebook not found", 404);
+ if (id === "nb_inbox" || current.slug === "inbox") {
+ throw new AppError("bad_request", "等待分类不能删除。", 400);
+ }
+
+ const [childCount, memoCount] = await Promise.all([
+ db.prepare(`SELECT COUNT(*) AS count FROM notebooks WHERE workspace_id = ? AND parent_id = ? AND is_deleted = 0`)
+ .bind(workspaceId, id)
+ .first<{ count: number }>(),
+ db.prepare(`SELECT COUNT(*) AS count FROM memos WHERE workspace_id = ? AND notebook_id = ? AND is_deleted = 0`)
+ .bind(workspaceId, id)
+ .first<{ count: number }>(),
+ ]);
+
+ if ((childCount?.count ?? 0) > 0 || (memoCount?.count ?? 0) > 0) {
+ throw new AppError(
+ "notebook_not_empty",
+ "Move or delete child notebooks and memos before deleting this notebook.",
+ 409
+ );
+ }
+
+ const now = isoNow();
+ await db.prepare(
+ `UPDATE notebooks
+ SET is_deleted = 1, deleted_at = ?, updated_at = ?
+ WHERE id = ? AND workspace_id = ? AND slug <> 'inbox'`
+ ).bind(now, now, id, workspaceId).run();
+ await audit(db, actor.actorType, actor.actorId, "notebook.delete", "notebook", id, {});
+};
+
+export const restoreNotebookRecord = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ id: string,
+ actor: AuditActor
+) => {
+ const current = await db.prepare(
+ `SELECT id FROM notebooks WHERE id = ? AND workspace_id = ? AND is_deleted = 1`
+ ).bind(id, workspaceId).first<{ id: string }>();
+ if (!current) throw new AppError("not_found", "Deleted notebook not found", 404);
+
+ const now = isoNow();
+ await db.batch([
+ db.prepare(
+ `UPDATE notebooks SET is_deleted = 0, deleted_at = NULL, updated_at = ? WHERE id = ? AND workspace_id = ?`
+ ).bind(now, id, workspaceId),
+ auditStatement(db, actor.actorType, actor.actorId, "notebook.restore", "notebook", id, {}),
+ ]);
+
+ const notebook = await getNotebook(db, workspaceId, id);
+ if (!notebook) throw new AppError("not_found", "Notebook not found after restore", 404);
+ return notebook;
+};
+
+export const isNotebookDescendant = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ candidateId: string,
+ ancestorId: string
+) => {
+ const row = await db
+ .prepare(
+ `WITH RECURSIVE descendants(id) AS (
+ SELECT id
+ FROM notebooks
+ WHERE workspace_id = ? AND parent_id = ? AND is_deleted = 0
+
+ UNION ALL
+
+ SELECT n.id
+ FROM notebooks n
+ INNER JOIN descendants d ON n.parent_id = d.id
+ WHERE n.workspace_id = ? AND n.is_deleted = 0
+ )
+ SELECT id
+ FROM descendants
+ WHERE id = ?
+ LIMIT 1`
+ )
+ .bind(workspaceId, ancestorId, workspaceId, candidateId)
+ .first<{ id: string }>();
+
+ return Boolean(row);
+};
diff --git a/apps/api/src/request-auth.ts b/apps/api/src/request-auth.ts
new file mode 100644
index 00000000..fb19b5b5
--- /dev/null
+++ b/apps/api/src/request-auth.ts
@@ -0,0 +1,70 @@
+import type { AppContext, AuditActor, AuthContext } from "./api-context";
+import { AppError } from "./app-error";
+import { forbidden, unauthorized } from "./http-errors";
+
+export const ALL_TOKEN_SCOPES = [
+ "read:notebooks",
+ "write:notebooks",
+ "read:memos",
+ "write:memos",
+ "read:resources",
+ "write:resources",
+ "read:tags",
+ "write:tags",
+] as const;
+
+export type TokenScope = (typeof ALL_TOKEN_SCOPES)[number];
+
+export const getAuditActor = (c: AppContext): AuditActor => {
+ const auth = c.get("auth");
+ return {
+ actorType: auth?.actorType ?? "user",
+ actorId: auth?.actorId ?? null,
+ };
+};
+
+export const getActorLabel = (c: AppContext) => {
+ const auth = c.get("auth");
+ return auth?.actorId ? `${auth.actorType}:${auth.actorId}` : auth?.username ?? "user";
+};
+
+export const getWorkspaceId = (c: AppContext) => c.get("auth").workspaceId;
+
+export const requireOwner = (c: AppContext) => {
+ const auth = c.get("auth");
+ return auth?.kind === "user" && auth.role === "owner"
+ ? null
+ : forbidden(c, "Only the instance owner can manage users.");
+};
+
+export const requireUser = (c: AppContext) => {
+ const auth = c.get("auth");
+ return auth?.kind === "user"
+ ? null
+ : forbidden(c, "Only an interactive user session can manage this resource.");
+};
+
+export const hasScopes = (auth: AuthContext, scopes: TokenScope[]) =>
+ auth.kind === "user" || scopes.every((scope) => auth.scopes.includes(scope));
+
+export const requireScopes = (c: AppContext, ...scopes: TokenScope[]) => {
+ const auth = c.get("auth");
+ if (!auth) return unauthorized(c, "Authentication required.");
+ return hasScopes(auth, scopes)
+ ? null
+ : forbidden(c, `Missing required scope: ${scopes.join(", ")}`);
+};
+
+export const assertScope = (auth: AuthContext, scope: TokenScope) => {
+ if (!hasScopes(auth, [scope])) {
+ throw new AppError("forbidden", `Missing required scope: ${scope}`, 403);
+ }
+};
+
+export const isTokenScope = (scope: string): scope is TokenScope =>
+ (ALL_TOKEN_SCOPES as readonly string[]).includes(scope);
+
+export const normalizeTokenScopes = (scopes: string[]) => {
+ const normalized = Array.from(new Set(scopes.map((scope) => scope.trim()).filter(Boolean)));
+ return normalized.some((scope) => !isTokenScope(scope)) ? null : normalized as TokenScope[];
+};
diff --git a/apps/api/src/tag-routes.ts b/apps/api/src/tag-routes.ts
new file mode 100644
index 00000000..538385e6
--- /dev/null
+++ b/apps/api/src/tag-routes.ts
@@ -0,0 +1,61 @@
+import { TagRenameSchema } from "@edgeever/shared";
+import { zValidator } from "@hono/zod-validator";
+import type { Hono } from "hono";
+import type { AppEnv } from "./api-context";
+import {
+ getActorLabel,
+ getAuditActor,
+ getWorkspaceId,
+ requireScopes,
+} from "./request-auth";
+import {
+ listTagSummaries,
+ updateTagAcrossMemos,
+} from "./tag-service";
+
+const decodeTagParam = (value: string) => {
+ try {
+ return decodeURIComponent(value).trim();
+ } catch {
+ return value.trim();
+ }
+};
+
+export const registerTagRoutes = (app: Hono<AppEnv>) => {
+ app.get("/api/v1/tags", async (c) => {
+ const denied = requireScopes(c, "read:tags");
+ if (denied) return denied;
+
+ return c.json({ tags: await listTagSummaries(c.env.storage.db, getWorkspaceId(c)) });
+ });
+
+ app.patch("/api/v1/tags/:tag", zValidator("json", TagRenameSchema), async (c) => {
+ const denied = requireScopes(c, "write:tags");
+ if (denied) return denied;
+
+ const updated = await updateTagAcrossMemos(
+ c.env.storage.db,
+ getWorkspaceId(c),
+ decodeTagParam(c.req.param("tag")),
+ c.req.valid("json").name,
+ getAuditActor(c),
+ getActorLabel(c)
+ );
+ return c.json({ ok: true, updated });
+ });
+
+ app.delete("/api/v1/tags/:tag", async (c) => {
+ const denied = requireScopes(c, "write:tags");
+ if (denied) return denied;
+
+ const updated = await updateTagAcrossMemos(
+ c.env.storage.db,
+ getWorkspaceId(c),
+ decodeTagParam(c.req.param("tag")),
+ null,
+ getAuditActor(c),
+ getActorLabel(c)
+ );
+ return c.json({ ok: true, updated });
+ });
+};
diff --git a/apps/api/src/tag-service.ts b/apps/api/src/tag-service.ts
new file mode 100644
index 00000000..6d7f8d11
--- /dev/null
+++ b/apps/api/src/tag-service.ts
@@ -0,0 +1,231 @@
+import { normalizeTags, type TagSummary } from "@edgeever/shared";
+import type { AuditActor } from "./api-context";
+import { AppError } from "./app-error";
+import { auditStatement } from "./audit";
+import { isoNow, parseJsonArray } from "./entity-utils";
+import type { DatabaseAdapter, PreparedStatementAdapter } from "./storage-contract";
+
+type TagSummaryRow = {
+ name: string;
+ memo_count: number;
+ updated_at: string | null;
+};
+
+type MemoTagUpdateRow = {
+ id: string;
+ title: string | null;
+ tags_json: string;
+ content_text: string;
+};
+
+const mapTagSummary = (row: TagSummaryRow): TagSummary => ({
+ name: row.name,
+ memoCount: row.memo_count,
+ updatedAt: row.updated_at,
+});
+
+const getMemoRowsByTag = async (db: DatabaseAdapter, workspaceId: string, tag: string) => {
+ const rows = await db
+ .prepare(
+ `SELECT m.id, m.title, m.tags_json, c.content_text
+ FROM memos m
+ INNER JOIN memo_contents c ON c.memo_id = m.id
+ WHERE m.workspace_id = ? AND m.is_deleted = 0
+ AND EXISTS (
+ SELECT 1
+ FROM json_each(m.tags_json)
+ WHERE json_each.value = ?
+ )`
+ )
+ .bind(workspaceId, tag)
+ .all<MemoTagUpdateRow>();
+
+ return rows.results;
+};
+
+const replaceTag = (currentTags: string[], oldTag: string, nextTag: string | null) =>
+ normalizeTags(
+ currentTags.flatMap((tag) => {
+ if (tag !== oldTag) return [tag];
+ return nextTag ? [nextTag] : [];
+ })
+ );
+
+export const listTagSummaries = async (db: DatabaseAdapter, workspaceId: string): Promise<TagSummary[]> => {
+ const rows = await db
+ .prepare(
+ `SELECT json_each.value AS name,
+ COUNT(DISTINCT m.id) AS memo_count,
+ MAX(m.updated_at) AS updated_at
+ FROM memos m, json_each(m.tags_json)
+ WHERE m.workspace_id = ? AND m.is_deleted = 0
+ AND trim(json_each.value) <> ''
+ GROUP BY json_each.value
+ ORDER BY lower(json_each.value) ASC`
+ )
+ .bind(workspaceId)
+ .all<TagSummaryRow>();
+
+ return rows.results
+ .filter((row) => typeof row.name === "string" && row.name.trim())
+ .map(mapTagSummary);
+};
+
+export const updateTagAcrossMemos = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ oldTag: string,
+ nextTag: string | null,
+ actor: AuditActor,
+ actorLabel: string
+) => {
+ const normalizedOld = normalizeTags([oldTag])[0];
+ const normalizedNext = nextTag === null ? null : normalizeTags([nextTag])[0];
+
+ if (!normalizedOld || normalizedOld === normalizedNext) return 0;
+
+ const rows = await getMemoRowsByTag(db, workspaceId, normalizedOld);
+ const now = isoNow();
+ const statements: PreparedStatementAdapter[] = [];
+ let updated = 0;
+
+ for (const row of rows) {
+ const currentTags = parseJsonArray(row.tags_json);
+ if (!currentTags.includes(normalizedOld)) continue;
+
+ const nextTags = replaceTag(currentTags, normalizedOld, normalizedNext);
+ statements.push(
+ db
+ .prepare(
+ `UPDATE memos
+ SET tags_json = ?, updated_by = ?, updated_at = ?
+ WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
+ )
+ .bind(JSON.stringify(nextTags), actorLabel, now, row.id, workspaceId),
+ db.prepare(`DELETE FROM memos_fts WHERE memo_id = ?`).bind(row.id),
+ db
+ .prepare(`INSERT INTO memos_fts (memo_id, title, content_text, tags) VALUES (?, ?, ?, ?)`)
+ .bind(row.id, row.title, row.content_text, nextTags.join(" ")),
+ auditStatement(db, actor.actorType, actor.actorId, normalizedNext ? "tag.rename" : "tag.delete", "memo", row.id, {
+ from: normalizedOld,
+ to: normalizedNext,
+ })
+ );
+ updated += 1;
+ }
+
+ if (statements.length > 0) await db.batch(statements);
+ return updated;
+};
+
+export const previewTagRename = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ oldTag: string,
+ nextTag: string | null
+) => {
+ const normalizedOld = normalizeTags([oldTag])[0];
+ const normalizedNext = nextTag === null ? null : normalizeTags([nextTag])[0];
+
+ if (!normalizedOld || normalizedOld === normalizedNext) {
+ return { dryRun: true, updated: 0, changes: [] };
+ }
+
+ const rows = await getMemoRowsByTag(db, workspaceId, normalizedOld);
+ const changes = rows.map((row) => {
+ const currentTags = parseJsonArray(row.tags_json);
+ return {
+ memoId: row.id,
+ title: row.title,
+ currentTags,
+ nextTags: replaceTag(currentTags, normalizedOld, normalizedNext),
+ };
+ });
+
+ return { dryRun: true, updated: changes.length, changes };
+};
+
+export const updateTagsForMemos = async (
+ db: DatabaseAdapter,
+ input: {
+ workspaceId: string;
+ memoIds: string[];
+ tags: string[];
+ mode: "add" | "remove";
+ dryRun: boolean;
+ actor: AuditActor;
+ actorLabel: string;
+ }
+) => {
+ const memoIds = Array.from(new Set(input.memoIds));
+ const tags = normalizeTags(input.tags);
+
+ if (memoIds.length === 0 || tags.length === 0) {
+ throw new AppError("invalid_params", "memoIds and tags must include at least one item", 400);
+ }
+
+ const placeholders = memoIds.map(() => "?").join(", ");
+ const rows = await db
+ .prepare(
+ `SELECT m.id, m.title, m.tags_json, c.content_text
+ FROM memos m
+ INNER JOIN memo_contents c ON c.memo_id = m.id
+ WHERE m.workspace_id = ? AND m.is_deleted = 0 AND m.id IN (${placeholders})`
+ )
+ .bind(input.workspaceId, ...memoIds)
+ .all<MemoTagUpdateRow>();
+
+ if (rows.results.length !== memoIds.length) {
+ throw new AppError("missing_memos", "One or more memos cannot be updated.", 400);
+ }
+
+ const changes = rows.results
+ .map((row) => {
+ const currentTags = parseJsonArray(row.tags_json);
+ const nextTags = input.mode === "add"
+ ? normalizeTags([...currentTags, ...tags])
+ : currentTags.filter((tag) => !tags.includes(tag));
+ return { memoId: row.id, title: row.title, currentTags, nextTags, contentText: row.content_text };
+ })
+ .filter((change) => JSON.stringify(change.currentTags) !== JSON.stringify(change.nextTags));
+
+ if (input.dryRun) {
+ return {
+ dryRun: true,
+ updated: changes.length,
+ changes: changes.map(({ contentText: _contentText, ...change }) => change),
+ };
+ }
+
+ if (changes.length === 0) return { ok: true, updated: 0 };
+
+ const now = isoNow();
+ const statements: PreparedStatementAdapter[] = [];
+ for (const change of changes) {
+ statements.push(
+ db
+ .prepare(
+ `UPDATE memos
+ SET tags_json = ?, updated_by = ?, updated_at = ?
+ WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
+ )
+ .bind(JSON.stringify(change.nextTags), input.actorLabel, now, change.memoId, input.workspaceId),
+ db.prepare(`DELETE FROM memos_fts WHERE memo_id = ?`).bind(change.memoId),
+ db
+ .prepare(`INSERT INTO memos_fts (memo_id, title, content_text, tags) VALUES (?, ?, ?, ?)`)
+ .bind(change.memoId, change.title, change.contentText, change.nextTags.join(" ")),
+ auditStatement(
+ db,
+ input.actor.actorType,
+ input.actor.actorId,
+ input.mode === "add" ? "tag.add" : "tag.remove",
+ "memo",
+ change.memoId,
+ { tags }
+ )
+ );
+ }
+
+ await db.batch(statements);
+ return { ok: true, updated: changes.length };
+};
diff --git a/apps/mobile/src/hooks/useDebouncedValue.ts b/apps/mobile/src/hooks/useDebouncedValue.ts
new file mode 100644
index 00000000..e777de30
--- /dev/null
+++ b/apps/mobile/src/hooks/useDebouncedValue.ts
@@ -0,0 +1,12 @@
+import { useEffect, useState } from "react";
+
+export const useDebouncedValue = <T,>(value: T, delay: number) => {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ useEffect(() => {
+ const timeout = setTimeout(() => setDebouncedValue(value), delay);
+ return () => clearTimeout(timeout);
+ }, [delay, value]);
+
+ return debouncedValue;
+};
diff --git a/apps/mobile/src/hooks/useMobileAutomaticSync.ts b/apps/mobile/src/hooks/useMobileAutomaticSync.ts
new file mode 100644
index 00000000..db0dc494
--- /dev/null
+++ b/apps/mobile/src/hooks/useMobileAutomaticSync.ts
@@ -0,0 +1,141 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { AppState, type AppStateStatus } from "react-native";
+import { useQueryClient } from "@tanstack/react-query";
+import type { createEdgeEverClient } from "@edgeever/client";
+import type { MemoDetail } from "@edgeever/shared";
+import {
+ getMobileSyncRetryDelay,
+ listMobileSyncQueueItems,
+ loadMobileSyncQueueSummary,
+ syncMobileQueuedChanges,
+ type MobileSyncQueueItem,
+} from "../lib/sync-queue";
+import { replaceLocalMemoId, upsertLocalMemo } from "../lib/local-mirror";
+
+type MobileClient = ReturnType<typeof createEdgeEverClient>;
+
+export const useMobileAutomaticSync = ({
+ client,
+ dataScope,
+ onMemoIdRemapped,
+ syncQueueScope,
+}: {
+ client: MobileClient | null;
+ dataScope: string;
+ onMemoIdRemapped: (temporaryId: string, memo: MemoDetail) => void;
+ syncQueueScope: string;
+}) => {
+ const queryClient = useQueryClient();
+ const [syncQueueItems, setSyncQueueItems] = useState<MobileSyncQueueItem[]>([]);
+ const runningRef = useRef(false);
+ const requestedRef = useRef(false);
+ const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const runRef = useRef<() => Promise<void>>(async () => undefined);
+
+ const refreshSyncQueueItems = useCallback(async () => {
+ const items = await listMobileSyncQueueItems(syncQueueScope);
+ setSyncQueueItems(items);
+ return items;
+ }, [syncQueueScope]);
+
+ const invalidateSyncedWorkspace = useCallback(async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memo"] }),
+ ]);
+ }, [queryClient]);
+
+ const runAutomaticSync = useCallback(async () => {
+ if (!client) {
+ return;
+ }
+
+ if (runningRef.current) {
+ requestedRef.current = true;
+ return;
+ }
+
+ if (retryTimerRef.current) {
+ clearTimeout(retryTimerRef.current);
+ retryTimerRef.current = null;
+ }
+
+ runningRef.current = true;
+
+ try {
+ const summary = await loadMobileSyncQueueSummary(syncQueueScope);
+ if (summary.pending + summary.error + summary.syncing === 0) {
+ return;
+ }
+
+ await syncMobileQueuedChanges(client, syncQueueScope, {
+ onSynced: async (memo, item) => {
+ if (item.kind === "memo.create") {
+ await replaceLocalMemoId(dataScope, item.memoId, memo);
+ onMemoIdRemapped(item.memoId, memo);
+ } else {
+ await upsertLocalMemo(dataScope, memo);
+ }
+ queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], { memo });
+ queryClient.setQueryData(["mobile", "memo", "trash", memo.id], { memo });
+ },
+ });
+
+ const nextSummary = await loadMobileSyncQueueSummary(syncQueueScope);
+ if (nextSummary.total === 0) {
+ await invalidateSyncedWorkspace();
+ }
+ } catch {
+ // Queue metadata remains durable; the scheduled pass resumes it.
+ } finally {
+ await refreshSyncQueueItems();
+ runningRef.current = false;
+
+ if (requestedRef.current) {
+ requestedRef.current = false;
+ void runRef.current();
+ return;
+ }
+
+ const retryDelay = await getMobileSyncRetryDelay(syncQueueScope);
+ if (retryDelay !== null) {
+ retryTimerRef.current = setTimeout(() => {
+ retryTimerRef.current = null;
+ void runRef.current();
+ }, retryDelay);
+ }
+ }
+ }, [client, dataScope, invalidateSyncedWorkspace, onMemoIdRemapped, queryClient, refreshSyncQueueItems, syncQueueScope]);
+
+ runRef.current = runAutomaticSync;
+
+ useEffect(() => {
+ if (!client) {
+ return;
+ }
+
+ void runRef.current();
+
+ const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
+ if (nextState === "active") {
+ void runRef.current();
+ }
+ });
+
+ return () => {
+ subscription.remove();
+ if (retryTimerRef.current) {
+ clearTimeout(retryTimerRef.current);
+ retryTimerRef.current = null;
+ }
+ };
+ }, [client, syncQueueScope]);
+
+ return {
+ refreshSyncQueueItems,
+ runAutomaticSync,
+ syncQueueItems,
+ };
+};
diff --git a/apps/mobile/src/hooks/useMobileLocalMirrorSync.ts b/apps/mobile/src/hooks/useMobileLocalMirrorSync.ts
new file mode 100644
index 00000000..7b9f5880
--- /dev/null
+++ b/apps/mobile/src/hooks/useMobileLocalMirrorSync.ts
@@ -0,0 +1,96 @@
+import { useCallback, useEffect, useState } from "react";
+import { AppState, type AppStateStatus } from "react-native";
+import { useQueryClient } from "@tanstack/react-query";
+import type { createEdgeEverClient } from "@edgeever/client";
+import {
+ isMobileLocalMirrorInitialized,
+ syncMobileLocalMirror,
+ type MobileBootstrapProgress,
+} from "../lib/local-mirror";
+
+type MobileClient = ReturnType<typeof createEdgeEverClient>;
+
+export const useMobileLocalMirrorSync = ({
+ client,
+ dataScope,
+}: {
+ client: MobileClient | null;
+ dataScope: string;
+}) => {
+ const queryClient = useQueryClient();
+ const [isInitialStatusPending, setIsInitialStatusPending] = useState(true);
+ const [initialSyncProgress, setInitialSyncProgress] = useState<MobileBootstrapProgress | null>(null);
+ const [initialSyncError, setInitialSyncError] = useState<unknown>(null);
+ const [syncAttempt, setSyncAttempt] = useState(0);
+ const retryInitialSync = useCallback(() => setSyncAttempt((attempt) => attempt + 1), []);
+
+ useEffect(() => {
+ if (!client) {
+ return;
+ }
+
+ let active = true;
+ const syncMirror = async () => {
+ let isInitialSync = false;
+ let refreshedNotebooksDuringBootstrap = false;
+ try {
+ isInitialSync = !(await isMobileLocalMirrorInitialized(dataScope));
+ if (active) {
+ setIsInitialStatusPending(false);
+ setInitialSyncError(null);
+ setInitialSyncProgress(isInitialSync ? { loadedCount: 0, totalCount: 0 } : null);
+ }
+ await syncMobileLocalMirror(client, dataScope, {
+ onBootstrapProgress: isInitialSync ? async (progress) => {
+ if (!active) {
+ return;
+ }
+ setInitialSyncProgress(progress);
+ const invalidations = [
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
+ ];
+ if (!refreshedNotebooksDuringBootstrap) {
+ refreshedNotebooksDuringBootstrap = true;
+ invalidations.push(queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }));
+ }
+ await Promise.all(invalidations);
+ } : undefined,
+ });
+ if (active) {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
+ ]);
+ setInitialSyncProgress(null);
+ }
+ } catch (error) {
+ if (active && isInitialSync) {
+ setInitialSyncProgress(null);
+ setInitialSyncError(error);
+ }
+ // An initialized local mirror remains readable while offline.
+ }
+ };
+
+ void syncMirror();
+ const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
+ if (nextState === "active") {
+ void syncMirror();
+ }
+ });
+
+ return () => {
+ active = false;
+ subscription.remove();
+ };
+ }, [client, dataScope, queryClient, syncAttempt]);
+
+ return {
+ initialSyncError,
+ initialSyncProgress,
+ isInitialStatusPending,
+ retryInitialSync,
+ };
+};
diff --git a/apps/mobile/src/lib/mobile-locale.test.mjs b/apps/mobile/src/lib/mobile-locale.test.mjs
new file mode 100644
index 00000000..0df0d40a
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-locale.test.mjs
@@ -0,0 +1,17 @@
+import { describe, expect, test } from "bun:test";
+import { translateMobileText } from "./mobile-locale.tsx";
+
+describe("mobile locale translation", () => {
+ test("keeps Chinese copy unchanged for the Chinese locale", () => {
+ expect(translateMobileText("正在同步笔记", "zh-CN")).toBe("正在同步笔记");
+ });
+
+ test("translates mobile-only static copy", () => {
+ expect(translateMobileText("正在同步笔记", "en-US")).toBe("Syncing your notes");
+ });
+
+ test("interpolates mobile-only template copy", () => {
+ expect(translateMobileText("已加载 12 / 40 条笔记", "en-US")).toBe("Loaded 12 of 40 notes");
+ expect(translateMobileText("筛选:Pinned · 3 条", "en-US")).toBe("Filter: Pinned · 3 notes");
+ });
+});
diff --git a/apps/mobile/src/lib/mobile-locale.tsx b/apps/mobile/src/lib/mobile-locale.tsx
index 3a4626f9..77ee2955 100644
--- a/apps/mobile/src/lib/mobile-locale.tsx
+++ b/apps/mobile/src/lib/mobile-locale.tsx
@@ -86,6 +86,22 @@ const mobileOnlyTranslations = new Map<string, string>([
["最近一次本地编辑器启动", "Latest local editor startup"],
["暂不可用", "Unavailable"],
["尚未记录", "Not recorded"],
+ ["正在搜索", "Searching"],
+ ["退出搜索", "Exit search"],
+ ["重置", "Reset"],
+ ["置顶", "Pinned"],
+ ["有标签", "Tagged"],
+ ["无标签", "Untagged"],
+ ["正在同步笔记", "Syncing your notes"],
+ ["正在准备首次同步…", "Preparing your notes for the first sync…"],
+ ["正在加载笔记", "Loading notes"],
+ ["正在加载笔记本和笔记…", "Loading notebooks and notes…"],
+ ["同步已暂停", "Sync paused"],
+ ["已加载的笔记仍可使用,请检查网络后重试。", "Loaded notes remain available. Check your connection and retry."],
+ ["已选择 {{count}} 条", "{{count}} selected"],
+ ["{{count}} 条结果", "Results: {{count}}"],
+ ["筛选:{{filter}} · {{count}} 条", "Filter: {{filter}} · {{count}} notes"],
+ ["已加载 {{loaded}} / {{total}} 条笔记", "Loaded {{loaded}} of {{total}} notes"],
]);
const flattenStrings = (value: unknown, prefix = "", output = new Map<string, string>()) => {
@@ -121,6 +137,16 @@ const translationPairs: TranslationPair[] = Array.from(zhStrings.entries())
.sort((left, right) => right.source.length - left.source.length);
const exactTranslations = new Map(translationPairs.filter((pair) => !pair.pattern).map((pair) => [pair.source, pair.target]));
const templateTranslations = translationPairs.filter((pair) => pair.pattern);
+const mobileTemplateTranslations: TranslationPair[] = Array.from(mobileOnlyTranslations.entries())
+ .filter(([source]) => source.includes("{{"))
+ .map(([source, target]) => {
+ const placeholders: string[] = [];
+ const patternSource = escapeRegExp(source).replace(/\\\{\\\{(\w+)\\\}\\\}/g, (_match, placeholder: string) => {
+ placeholders.push(placeholder);
+ return "(.+?)";
+ });
+ return { source, target, pattern: new RegExp(`^${patternSource}$`), placeholders };
+ });
const resolveSystemLocale = (): SupportedMobileLocale =>
(Intl.DateTimeFormat().resolvedOptions().locale || "zh-CN").toLowerCase().startsWith("en") ? "en-US" : "zh-CN";
@@ -133,7 +159,7 @@ export const translateMobileText = (value: string, locale: SupportedMobileLocale
if (exact) {
return exact;
}
- for (const pair of templateTranslations) {
+ for (const pair of [...mobileTemplateTranslations, ...templateTranslations]) {
const match = pair.pattern?.exec(value);
if (!match) {
continue;
diff --git a/apps/mobile/src/lib/sync-queue.ts b/apps/mobile/src/lib/sync-queue.ts
index 078601b3..c9b23998 100644
--- a/apps/mobile/src/lib/sync-queue.ts
+++ b/apps/mobile/src/lib/sync-queue.ts
@@ -1,6 +1,15 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { ApiRequestError, type createEdgeEverClient } from "@edgeever/client";
-import type { MemoDetail } from "@edgeever/shared";
+import {
+ createEmptySyncQueueSummary,
+ createEmptySyncRunResult,
+ getNextSyncQueueRetryDelay,
+ getSyncRetryAt,
+ summarizeSyncQueue,
+ type MemoDetail,
+ type SyncQueueSummary,
+ type SyncRunResult,
+} from "@edgeever/shared";
const LEGACY_SYNC_QUEUE_KEY = "edgeever.mobile.syncQueue.v1";
const SYNC_QUEUE_KEY_PREFIX = "edgeever.mobile.syncQueue.v2";
@@ -50,28 +59,10 @@ export type MobileSyncQueueItem = MobileMemoUpdateSyncQueueItem | MobileMemoCrea
let syncQueueWriteChain: Promise<void> = Promise.resolve();
-export type MobileSyncQueueSummary = {
- total: number;
- pending: number;
- syncing: number;
- conflict: number;
- error: number;
-};
-
-export type MobileSyncRunResult = {
- attempted: number;
- synced: number;
- failed: number;
- conflicted: number;
-};
+export type MobileSyncQueueSummary = SyncQueueSummary;
+export type MobileSyncRunResult = SyncRunResult;
-export const emptyMobileSyncQueueSummary = (): MobileSyncQueueSummary => ({
- total: 0,
- pending: 0,
- syncing: 0,
- conflict: 0,
- error: 0,
-});
+export const emptyMobileSyncQueueSummary = createEmptySyncQueueSummary;
export const getMobileMemoUpdateQueueId = (memoId: string) => `memo.update:${memoId}`;
export const getMobileMemoCreateQueueId = (memoId: string) => `memo.create:${memoId}`;
@@ -143,19 +134,8 @@ export const queueMobileMemoUpdate = async (scope: string, payload: MobileMemoUp
export const loadMobileSyncQueueSummary = async (scope: string) => summarizeMobileSyncQueue(await readMobileSyncQueue(scope));
-export const getMobileSyncRetryDelay = async (scope: string) => {
- const now = Date.now();
- const retryTimes = (await readMobileSyncQueue(scope))
- .filter((item) => item.status === "pending" || item.status === "error" || item.status === "syncing")
- .map((item) => (item.nextAttemptAt ? Date.parse(item.nextAttemptAt) : now))
- .filter(Number.isFinite);
-
- if (retryTimes.length === 0) {
- return null;
- }
-
- return Math.max(250, Math.min(...retryTimes) - now);
-};
+export const getMobileSyncRetryDelay = async (scope: string) =>
+ getNextSyncQueueRetryDelay(await readMobileSyncQueue(scope));
export const listMobileSyncQueueItems = async (scope: string) =>
(await readMobileSyncQueue(scope)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
@@ -172,12 +152,7 @@ export const syncMobileQueuedChanges = async (
onSynced?: (memo: MemoDetail, item: MobileSyncQueueItem) => void | Promise<void>;
} = {}
): Promise<MobileSyncRunResult> => {
- const result: MobileSyncRunResult = {
- attempted: 0,
- synced: 0,
- failed: 0,
- conflicted: 0,
- };
+ const result = createEmptySyncRunResult();
const now = new Date();
const items = (await readMobileSyncQueue(scope))
.filter((item) => item.status === "pending" || item.status === "error" || item.status === "syncing")
@@ -213,7 +188,7 @@ export const syncMobileQueuedChanges = async (
status,
attemptCount,
lastError: getErrorMessage(error),
- nextAttemptAt: status === "error" ? nextRetryAt(attemptCount) : null,
+ nextAttemptAt: status === "error" ? getSyncRetryAt(attemptCount) : null,
updatedAt: new Date().toISOString(),
}, itemVersion);
@@ -397,11 +372,7 @@ const mutateMobileSyncQueue = async (scope: string, mutate: (items: MobileSyncQu
const getSyncQueueStorageKey = (scope: string) => `${SYNC_QUEUE_KEY_PREFIX}:${encodeURIComponent(scope.trim().toLowerCase())}`;
const summarizeMobileSyncQueue = (items: MobileSyncQueueItem[]) =>
- items.reduce((summary, item) => {
- summary.total += 1;
- summary[item.status] += 1;
- return summary;
- }, emptyMobileSyncQueueSummary());
+ summarizeSyncQueue(items);
const isMobileSyncQueueItem = (value: unknown): value is MobileSyncQueueItem => {
if (!value || typeof value !== "object") {
@@ -415,8 +386,3 @@ const isMobileSyncQueueItem = (value: unknown): value is MobileSyncQueueItem =>
const isRevisionConflict = (error: unknown) => error instanceof ApiRequestError && error.code === "revision_conflict";
const getErrorMessage = (error: unknown) => (error instanceof Error ? error.message : "Sync failed");
-
-const nextRetryAt = (attemptCount: number) => {
- const delayMs = Math.min(5 * 60_000, 2 ** Math.min(attemptCount, 6) * 1000);
- return new Date(Date.now() + delayMs).toISOString();
-};
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
new file mode 100644
index 00000000..ca46c9f2
--- /dev/null
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -0,0 +1,640 @@
+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import type { MemoDetail } from "@edgeever/shared";
+import { ActivityIndicator, Image as RNImage, Platform, ScrollView, StyleSheet, Text as RNText, useWindowDimensions, View, type ImageStyle, type StyleProp, type ViewStyle } from "react-native";
+import { Modal } from "react-native";
+import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
+import Markdown, { type ASTNode, type RenderRules } from "react-native-markdown-display";
+import { SvgXml } from "react-native-svg";
+import { ChevronDown, ChevronLeft, ChevronRight, History, MoreHorizontal, Pencil, RotateCcw, Search, Tag, Trash2, X } from "../components/icons";
+import { Pressable, Text, TextInput } from "../components/LocalizedText";
+import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";
+import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";
+import { useMobileLocale } from "../lib/mobile-locale";
+import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";
+import { useSession } from "../lib/session";
+import { beginEditorStartup } from "../lib/startup-performance";
+import type { MobileSyncQueueItem } from "../lib/sync-queue";
+import { formatDate, getTextSearchMatches } from "./workspace-utils";
+import { styles } from "./workspace-styles";
+
+const DETAIL_CONTENT_HORIZONTAL_PADDING = 16;
+const DETAIL_TABLE_FIT_COLUMN_COUNT = 3;
+const DETAIL_TABLE_MIN_COLUMN_WIDTH = 132;
+const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;
+const DEFAULT_MEMO_TITLE = "无标题笔记";
+const useMobileLocalePreference = () => useMobileLocale().preference;
+
+const getAuthenticatedResourceSource = (
+ source: string,
+ session: { baseUrl: string; token: string } | null
+) => {
+ const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
+ const uri = source.startsWith("/") && baseUrl ? `${baseUrl}${source}` : source;
+ const isProtectedResource = source.startsWith("/api/v1/resources/") || Boolean(baseUrl && uri.startsWith(`${baseUrl}/api/v1/resources/`));
+
+ return {
+ uri,
+ ...(session?.token && isProtectedResource ? { headers: { Authorization: `Bearer ${session.token}` } } : {}),
+ };
+};
+
+type CachedSvgResource = {
+ aspectRatio: number | null;
+ xml: string;
+};
+
+const AUTHENTICATED_SVG_CACHE_LIMIT = 24;
+const authenticatedSvgCache = new Map<string, Promise<CachedSvgResource | null>>();
+const getAuthenticatedSvgCacheKey = (source: ReturnType<typeof getAuthenticatedResourceSource>) =>
+ `${source.uri}\n${source.headers?.Authorization ?? ""}`;
+const loadAuthenticatedSvg = (source: ReturnType<typeof getAuthenticatedResourceSource>) => {
+ const cacheKey = getAuthenticatedSvgCacheKey(source);
+ const cached = authenticatedSvgCache.get(cacheKey);
+ if (cached) {
+ return cached;
+ }
+ if (authenticatedSvgCache.size >= AUTHENTICATED_SVG_CACHE_LIMIT) {
+ const oldestKey = authenticatedSvgCache.keys().next().value;
+ if (oldestKey) {
+ authenticatedSvgCache.delete(oldestKey);
+ }
+ }
+ const pending = fetch(source.uri, { headers: source.headers })
+ .then(async (response) => {
+ if (!response.ok) {
+ throw new Error(`Resource request failed with ${response.status}`);
+ }
+ if (!response.headers.get("Content-Type")?.toLowerCase().includes("svg")) {
+ return null;
+ }
+ const xml = await response.text();
+ const viewBox = xml.match(/viewBox=["']\s*[\d.-]+\s+[\d.-]+\s+([\d.]+)\s+([\d.]+)\s*["']/i);
+ const width = Number(viewBox?.[1]);
+ const height = Number(viewBox?.[2]);
+ return {
+ aspectRatio: width > 0 && height > 0 ? width / height : null,
+ xml,
+ };
+ })
+ .catch(() => {
+ authenticatedSvgCache.delete(cacheKey);
+ return null;
+ });
+ authenticatedSvgCache.set(cacheKey, pending);
+ return pending;
+};
+
+const AuthenticatedResourceImage = ({
+ alt,
+ fitAspect = false,
+ resizeMode = "cover",
+ source,
+ style,
+}: {
+ alt: string;
+ fitAspect?: boolean;
+ resizeMode?: "center" | "contain" | "cover" | "repeat" | "stretch";
+ source: ReturnType<typeof getAuthenticatedResourceSource>;
+ style: StyleProp<ImageStyle>;
+}) => {
+ const [aspectRatio, setAspectRatio] = useState(16 / 9);
+ const [svgXml, setSvgXml] = useState<string | null>(null);
+ const svgRequestStartedRef = useRef(false);
+ const svgSourceKeyRef = useRef("");
+ const svgSourceKey = getAuthenticatedSvgCacheKey(source);
+ const imageStyle = fitAspect ? [style, { aspectRatio, height: undefined, width: "100%" as const }] : style;
+
+ useEffect(() => {
+ setSvgXml(null);
+ setAspectRatio(16 / 9);
+ svgRequestStartedRef.current = false;
+ svgSourceKeyRef.current = svgSourceKey;
+ const cached = authenticatedSvgCache.get(svgSourceKey);
+ if (cached) {
+ svgRequestStartedRef.current = true;
+ void cached.then((result) => {
+ if (!result || svgSourceKeyRef.current !== svgSourceKey) {
+ return;
+ }
+ if (result.aspectRatio) {
+ setAspectRatio(result.aspectRatio);
+ }
+ setSvgXml(result.xml);
+ });
+ }
+ return () => {
+ if (svgSourceKeyRef.current === svgSourceKey) {
+ svgSourceKeyRef.current = "";
+ }
+ };
+ }, [svgSourceKey]);
+
+ const loadSvgFallback = () => {
+ if (svgRequestStartedRef.current) {
+ return;
+ }
+ svgRequestStartedRef.current = true;
+ void loadAuthenticatedSvg(source)
+ .then((result) => {
+ if (!result || svgSourceKeyRef.current !== svgSourceKey) {
+ return;
+ }
+ if (result.aspectRatio) {
+ setAspectRatio(result.aspectRatio);
+ }
+ setSvgXml(result.xml);
+ });
+ };
+
+ if (svgXml) {
+ return (
+ <View accessibilityLabel={alt || undefined} accessible={Boolean(alt)} style={imageStyle}>
+ <SvgXml height="100%" width="100%" xml={svgXml} />
+ </View>
+ );
+ }
+
+ return (
+ <RNImage
+ accessibilityLabel={alt || undefined}
+ accessible={Boolean(alt)}
+ fadeDuration={Platform.OS === "android" ? 0 : undefined}
+ onLoad={(event) => {
+ const { height, width } = event.nativeEvent.source;
+ if (height > 0 && width > 0) {
+ setAspectRatio(width / height);
+ }
+ }}
+ onError={loadSvgFallback}
+ resizeMethod={Platform.OS === "android" ? "resize" : "auto"}
+ resizeMode={resizeMode}
+ source={source}
+ style={imageStyle}
+ />
+ );
+};
+
+
+const DetailActionSheetItem = ({ danger = false, disabled = false, icon, label, onPress }: { danger?: boolean; disabled?: boolean; icon: ReactNode; label: string; onPress: () => void }) => (
+ <Pressable accessibilityRole="button" disabled={disabled} onPress={onPress} style={[styles.actionSheetItem, disabled && styles.buttonDisabled]}>
+ {icon}
+ <Text style={[styles.actionSheetItemText, danger && styles.actionSheetItemTextDanger]}>{label}</Text>
+ </Pressable>
+);
+
+const DetailActionButton = ({ children, disabled = false, label, onPress }: { children: ReactNode; disabled?: boolean; label: string; onPress: () => void }) => (
+ <Pressable disabled={disabled} onPress={onPress} style={[styles.actionButton, disabled && styles.buttonDisabled]}>
+ {children}
+ <Text style={styles.actionButtonText}>{label}</Text>
+ </Pressable>
+);
+
+export const MemoDetailModal = ({
+ isDeleting,
+ isLoading,
+ isRestoring,
+ isSaving,
+ memo,
+ notebookName,
+ onClose,
+ onDelete,
+ onRichEdit,
+ onOpenRevisions,
+ onResolveSyncConflict,
+ onRestore,
+ syncStatus,
+ visible,
+}: {
+ isDeleting: boolean;
+ isLoading: boolean;
+ isRestoring: boolean;
+ isSaving: boolean;
+ memo: MemoDetail | null;
+ notebookName: string;
+ onClose: () => void;
+ onDelete: (memo: MemoDetail) => void;
+ onRichEdit: (memo: MemoDetail) => void;
+ onOpenRevisions: (memo: MemoDetail) => void;
+ onResolveSyncConflict: (memo: MemoDetail) => void;
+ onRestore: (memo: MemoDetail) => void;
+ syncStatus: MobileSyncQueueItem["status"] | null;
+ visible: boolean;
+}) => {
+ const { session } = useSession();
+ const { resolvedTheme } = useMobileTheme();
+ const { resolvedLocale } = useMobileLocale();
+ const { width: viewportWidth } = useWindowDimensions();
+ const safeAreaInsets = useSafeAreaInsets();
+ const [actionsOpen, setActionsOpen] = useState(false);
+ const [searchOpen, setSearchOpen] = useState(false);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [activeMatchIndex, setActiveMatchIndex] = useState(0);
+ const localePreference = useMobileLocalePreference();
+ const themedDetailMarkdownStyles = useMemo(
+ () => resolveMobileThemeStyles(detailMarkdownStyles, resolvedTheme),
+ [resolvedTheme]
+ );
+ const detailMarkdownRules = useMemo<RenderRules>(() => {
+ const availableTableWidth = Math.max(0, viewportWidth - DETAIL_CONTENT_HORIZONTAL_PADDING * 2);
+ const getTableColumnCount = (node: ASTNode, parents: ASTNode[]) => {
+ const table = node.type === "table" ? node : parents.find((parent) => parent.type === "table");
+ const tableSection = table?.children.find((child) => child.type === "thead" || child.type === "tbody");
+ const firstRow = tableSection?.children.find((child) => child.type === "tr");
+ return Math.max(1, firstRow?.children.filter((child) => child.type === "th" || child.type === "td").length ?? 1);
+ };
+ const renderTableCell = (node: ASTNode, children: ReactNode[], parents: ASTNode[], markdownStyles: Record<string, StyleProp<ViewStyle>>, isHeader: boolean) => {
+ const columnCount = getTableColumnCount(node, parents);
+ const row = parents.find((parent) => parent.type === "tr");
+ const cellIndex = row?.children.findIndex((child) => child.key === node.key) ?? -1;
+ const isLastCell = cellIndex === (row?.children.length ?? 0) - 1;
+ const wideCellStyle = columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT
+ ? { flex: 0, width: DETAIL_TABLE_MIN_COLUMN_WIDTH }
+ : undefined;
+
+ return (
+ <View
+ key={node.key}
+ style={[
+ markdownStyles[isHeader ? "_VIEW_SAFE_th" : "_VIEW_SAFE_td"],
+ wideCellStyle,
+ !isLastCell && markdownStyles._VIEW_SAFE_tableCellDivider,
+ ]}
+ >
+ {children}
+ </View>
+ );
+ };
+
+ return {
+ fence: (node, _children, _parents, markdownStyles, inheritedStyles = {}) => {
+ const language = getMobileMarkdownFenceLanguage((node as ASTNode & { sourceInfo?: string }).sourceInfo);
+ const content = trimMobileMarkdownFenceContent(node.content);
+ if (language === "mermaid") {
+ return (
+ <MobileMermaidDiagram
+ key={node.key}
+ locale={resolvedLocale}
+ source={content}
+ theme={resolvedTheme}
+ />
+ );
+ }
+ return <RNText key={node.key} style={[inheritedStyles, markdownStyles.fence]}>{content}</RNText>;
+ },
+ image: (node, _children, _parents, markdownStyles) => (
+ <AuthenticatedResourceImage
+ alt={String(node.attributes.alt ?? "")}
+ fitAspect
+ key={node.key}
+ resizeMode="contain"
+ source={getAuthenticatedResourceSource(String(node.attributes.src ?? ""), session)}
+ style={markdownStyles._VIEW_SAFE_image}
+ />
+ ),
+ table: (node, children, parents, markdownStyles) => {
+ const columnCount = getTableColumnCount(node, parents);
+ const tableWidth = columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT
+ ? columnCount * DETAIL_TABLE_MIN_COLUMN_WIDTH
+ : availableTableWidth;
+
+ return (
+ <ScrollView
+ contentContainerStyle={markdownStyles._VIEW_SAFE_tableScrollContent}
+ horizontal
+ key={node.key}
+ nestedScrollEnabled
+ showsHorizontalScrollIndicator={columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT}
+ style={markdownStyles._VIEW_SAFE_tableScroll}
+ >
+ <View style={[markdownStyles._VIEW_SAFE_table, { width: tableWidth }]}>{children}</View>
+ </ScrollView>
+ );
+ },
+ td: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, false),
+ th: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, true),
+ };
+ }, [resolvedLocale, resolvedTheme, session, viewportWidth]);
+ 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 syncStatusLabel = isSaving || syncStatus === "syncing"
+ ? "保存中"
+ : syncStatus === "conflict"
+ ? "同步冲突"
+ : syncStatus === "error"
+ ? "同步失败"
+ : syncStatus === "pending"
+ ? "待同步"
+ : "已同步";
+ const editFabBottom = Math.max(
+ safeAreaInsets.bottom,
+ Platform.OS === "android" ? ANDROID_SYSTEM_NAVIGATION_FALLBACK : 0
+ ) + 16;
+
+ useEffect(() => {
+ setActiveMatchIndex(0);
+ }, [detailText, searchQuery]);
+
+ const moveSearchMatch = (direction: 1 | -1) => {
+ if (searchMatches.length === 0) {
+ return;
+ }
+
+ setActiveMatchIndex((current) => (current + direction + searchMatches.length) % searchMatches.length);
+ };
+
+ const closeActionsAndRun = (action: () => void) => {
+ setActionsOpen(false);
+ action();
+ };
+
+ return (
+ <Modal animationType="slide" onRequestClose={onClose} presentationStyle="fullScreen" visible={visible}>
+ <SafeAreaView style={styles.modalSafeArea}>
+ <View style={styles.detailHeader}>
+ <Pressable accessibilityLabel="返回列表" accessibilityRole="button" onPress={onClose} style={styles.detailHeaderButton}>
+ <ChevronLeft color="#475569" size={21} />
+ </Pressable>
+ <View style={styles.detailHeaderActions}>
+ <Pressable
+ accessibilityHint={syncStatus === "conflict" ? "查看并处理同步冲突" : undefined}
+ accessibilityLabel={syncStatusLabel}
+ accessibilityRole={syncStatus === "conflict" ? "button" : "text"}
+ disabled={syncStatus !== "conflict" || !memo}
+ onPress={() => memo && onResolveSyncConflict(memo)}
+ >
+ <Text
+ numberOfLines={1}
+ style={[styles.detailSyncStatus, syncStatus === "conflict" && styles.detailSyncStatusConflict]}
+ >
+ {syncStatusLabel}
+ </Text>
+ </Pressable>
+ {memo && !memo.isDeleted ? (
+ <Pressable
+ accessibilityLabel="版本历史"
+ accessibilityRole="button"
+ onPress={() => onOpenRevisions(memo)}
+ style={styles.detailHeaderIconButton}
+ >
+ <History color="#475569" size={20} />
+ </Pressable>
+ ) : null}
+ {memo?.isDeleted ? (
+ <Pressable accessibilityLabel="笔记操作" accessibilityRole="button" onPress={() => setActionsOpen(true)} style={styles.detailHeaderIconButton}>
+ <MoreHorizontal color="#475569" size={21} />
+ </Pressable>
+ ) : null}
+ </View>
+ </View>
+
+ {isLoading ? (
+ <View style={styles.centerState}>
+ <ActivityIndicator color="#0f172a" />
+ </View>
+ ) : memo ? (
+ <ScrollView contentContainerStyle={styles.detailContent}>
+ <Text style={styles.detailTitle}>{memo.title?.trim() || DEFAULT_MEMO_TITLE}</Text>
+ <View style={styles.detailMetaRow}>
+ <View style={styles.detailNotebookButton}>
+ <Text numberOfLines={1} style={styles.detailNotebookName}>{notebookName}</Text>
+ <ChevronDown color="#94a3b8" size={14} />
+ </View>
+ <View style={styles.detailTagsGroup}>
+ <Tag color="#64748b" size={16} />
+ <Text
+ numberOfLines={1}
+ style={[styles.detailTagsInline, memo.tags.length === 0 && styles.detailTagsPlaceholder]}
+ >
+ {memo.tags.length ? memo.tags.join(", ") : "添加标签,用逗号分隔"}
+ </Text>
+ </View>
+ </View>
+ {searchOpen ? (
+ <View style={styles.noteSearchPanel}>
+ <View style={styles.searchBox}>
+ <Search color="#64748b" size={18} />
+ <TextInput
+ accessibilityLabel="在当前笔记内搜索"
+ autoCapitalize="none"
+ autoCorrect={false}
+ onChangeText={setSearchQuery}
+ placeholder="在当前笔记内搜索"
+ placeholderTextColor="#94a3b8"
+ style={styles.searchInput}
+ value={searchQuery}
+ />
+ <Text style={[styles.noteSearchCount, searchQuery.trim() && searchMatches.length === 0 && styles.noteSearchCountEmpty]}>{searchMatchLabel}</Text>
+ </View>
+ <View style={styles.richEditorSearchActions}>
+ <DetailActionButton disabled={searchMatches.length === 0} label="上一个搜索结果" onPress={() => moveSearchMatch(-1)}>
+ <ChevronLeft color={searchMatches.length === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
+ </DetailActionButton>
+ <DetailActionButton disabled={searchMatches.length === 0} label="下一个搜索结果" onPress={() => moveSearchMatch(1)}>
+ <ChevronRight color={searchMatches.length === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
+ </DetailActionButton>
+ <DetailActionButton label="关闭搜索" onPress={() => {
+ setSearchOpen(false);
+ setSearchQuery("");
+ }}>
+ <X color="#0f172a" size={16} />
+ </DetailActionButton>
+ </View>
+ </View>
+ ) : null}
+ <View style={styles.detailDivider} />
+ {searchOpen && searchQuery.trim() ? (
+ <HighlightedDetailText activeIndex={activeMatchIndex} matches={searchMatches} text={detailText} />
+ ) : (
+ <MobileMermaidProvider theme={resolvedTheme}>
+ <Markdown rules={detailMarkdownRules} style={themedDetailMarkdownStyles}>{detailText}</Markdown>
+ </MobileMermaidProvider>
+ )}
+ </ScrollView>
+ ) : (
+ <View style={styles.centerState}>
+ <Text style={styles.errorText}>笔记加载失败</Text>
+ </View>
+ )}
+ {memo && !memo.isDeleted ? (
+ <Pressable
+ accessibilityLabel="编辑笔记"
+ accessibilityRole="button"
+ onPress={() => {
+ beginEditorStartup();
+ onRichEdit(memo);
+ }}
+ style={[styles.detailEditFab, { bottom: editFabBottom }]}
+ >
+ <Pencil color="#ffffff" size={20} />
+ </Pressable>
+ ) : null}
+ {memo?.isDeleted ? (
+ <Modal animationType="fade" onRequestClose={() => setActionsOpen(false)} transparent visible={actionsOpen}>
+ <Pressable onPress={() => setActionsOpen(false)} style={styles.actionSheetBackdrop}>
+ <Pressable style={styles.actionSheet}>
+ <View style={styles.actionSheetHandle} />
+ <Text style={styles.actionSheetTitle}>笔记操作</Text>
+ <DetailActionSheetItem icon={<Search color="#0f172a" size={18} />} label="搜索当前笔记" onPress={() => closeActionsAndRun(() => {
+ setSearchOpen(true);
+ })} />
+ <DetailActionSheetItem icon={<History color="#0f172a" size={18} />} label="版本历史" onPress={() => closeActionsAndRun(() => onOpenRevisions(memo))} />
+ <DetailActionSheetItem disabled={isRestoring} icon={<RotateCcw color="#0f172a" size={18} />} label={isRestoring ? "恢复中" : "恢复笔记"} onPress={() => closeActionsAndRun(() => onRestore(memo))} />
+ <View style={styles.listActionDivider} />
+ <DetailActionSheetItem danger disabled={isDeleting} icon={<Trash2 color="#b91c1c" size={18} />} label={isDeleting ? "删除中" : "彻底删除"} onPress={() => closeActionsAndRun(() => onDelete(memo))} />
+ </Pressable>
+ </Pressable>
+ </Modal>
+ ) : null}
+ </SafeAreaView>
+ </Modal>
+ );
+};
+
+const HighlightedDetailText = ({
+ activeIndex,
+ matches,
+ text,
+}: {
+ activeIndex: number;
+ matches: Array<{ end: number; start: number }>;
+ text: string;
+}) => {
+ if (matches.length === 0) {
+ return <Text style={styles.detailMarkdown}>{text}</Text>;
+ }
+
+ const segments: ReactNode[] = [];
+ let cursor = 0;
+
+ matches.forEach((match, index) => {
+ if (match.start > cursor) {
+ segments.push(text.slice(cursor, match.start));
+ }
+
+ segments.push(
+ <Text key={`${match.start}-${match.end}`} style={index === activeIndex ? styles.noteSearchHighlightActive : styles.noteSearchHighlight}>
+ {text.slice(match.start, match.end)}
+ </Text>
+ );
+ cursor = match.end;
+ });
+
+ if (cursor < text.length) {
+ segments.push(text.slice(cursor));
+ }
+
+ return <Text style={styles.detailMarkdown}>{segments}</Text>;
+};
+
+
+const detailMarkdownStyles = StyleSheet.create({
+ body: {
+ color: "#0f172a",
+ fontSize: 17,
+ lineHeight: 27,
+ },
+ blockquote: {
+ backgroundColor: "#f8fafc",
+ borderLeftColor: "#94a3b8",
+ borderLeftWidth: 3,
+ marginVertical: 10,
+ paddingHorizontal: 14,
+ paddingVertical: 8,
+ },
+ bullet_list: {
+ marginVertical: 8,
+ },
+ code_inline: {
+ backgroundColor: "#f1f5f9",
+ borderRadius: 4,
+ color: "#334155",
+ fontSize: 15,
+ },
+ fence: {
+ backgroundColor: "#0f172a",
+ borderColor: "#0f172a",
+ borderRadius: 8,
+ color: "#e2e8f0",
+ fontSize: 14,
+ marginVertical: 10,
+ padding: 12,
+ },
+ heading1: {
+ color: "#0f172a",
+ fontSize: 26,
+ fontWeight: "800",
+ lineHeight: 34,
+ marginBottom: 10,
+ marginTop: 14,
+ },
+ heading2: {
+ color: "#0f172a",
+ fontSize: 21,
+ fontWeight: "800",
+ lineHeight: 29,
+ marginBottom: 8,
+ marginTop: 18,
+ },
+ heading3: {
+ color: "#0f172a",
+ fontSize: 18,
+ fontWeight: "800",
+ lineHeight: 26,
+ marginBottom: 6,
+ marginTop: 14,
+ },
+ link: {
+ color: "#059669",
+ },
+ list_item: {
+ marginVertical: 3,
+ },
+ ordered_list: {
+ marginVertical: 8,
+ },
+ paragraph: {
+ marginBottom: 10,
+ marginTop: 0,
+ },
+ strong: {
+ fontWeight: "800",
+ },
+ table: {
+ backgroundColor: "#ffffff",
+ borderColor: "#d8d8d8",
+ borderRadius: 2,
+ borderWidth: 1,
+ overflow: "hidden",
+ },
+ tableCellDivider: {
+ borderRightColor: "#dedede",
+ borderRightWidth: 1,
+ },
+ tableScroll: {
+ marginBottom: 10,
+ marginTop: 10,
+ maxWidth: "100%",
+ },
+ tableScrollContent: {
+ flexGrow: 1,
+ },
+ td: {
+ flex: 1,
+ minWidth: 0,
+ paddingHorizontal: 10,
+ paddingVertical: 7,
+ },
+ th: {
+ backgroundColor: "#f2f2f2",
+ flex: 1,
+ minWidth: 0,
+ paddingHorizontal: 10,
+ paddingVertical: 7,
+ },
+ tr: {
+ borderBottomColor: "#dedede",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ },
+});
diff --git a/apps/mobile/src/screens/WorkspaceNotesView.tsx b/apps/mobile/src/screens/WorkspaceNotesView.tsx
new file mode 100644
index 00000000..7b897c46
--- /dev/null
+++ b/apps/mobile/src/screens/WorkspaceNotesView.tsx
@@ -0,0 +1,471 @@
+import { memo, type ReactNode } from "react";
+import type { MemoFilterMode } from "@edgeever/client";
+import type { MemoSummary, Notebook } from "@edgeever/shared";
+import { MOBILE_UI_METRICS, toggleMobileMemoFilterMode } from "@edgeever/shared/mobile-ui";
+import { ActivityIndicator, FlatList, Platform, RefreshControl, View } from "react-native";
+import Animated, { FadeInDown, FadeOutUp, LinearTransition, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
+import { Check, ChevronDown, ChevronLeft, MoreHorizontal, Plus, RotateCcw, Search, Sparkles, Tag, X } from "../components/icons";
+import { Pressable, Text, TextInput } from "../components/LocalizedText";
+import type { MobileBootstrapProgress } from "../lib/local-mirror";
+import { useMobileLocale } from "../lib/mobile-locale";
+import { useMobileTheme } from "../lib/mobile-theme";
+import type { MobileMemoListDensity } from "../lib/preferences";
+import { formatMemoPreviewDate } from "./workspace-utils";
+import { styles } from "./workspace-styles";
+
+const DEFAULT_MEMO_TITLE = "无标题笔记";
+type MemoView = "notebook" | "trash";
+
+export const NotesView = ({
+ activeNotebook,
+ error,
+ initialSyncProgress,
+ isError,
+ isLoading,
+ isLoadingMore,
+ isRefreshing,
+ memoFilterMode,
+ memoListDensity,
+ memoView,
+ memos,
+ notebooks,
+ onCreate,
+ onClearSelection,
+ onFilterModeChange,
+ onOpenActions,
+ onOpenNotebookPicker,
+ onMemoLongPress,
+ onMemoPress,
+ onLoadMore,
+ onRefresh,
+ onRetry,
+ onSearchTextChange,
+ onSetMemoView,
+ searchText,
+ totalMemoCount,
+ selectedMemoIds,
+ selectionMode,
+}: {
+ activeNotebook: Notebook | null;
+ error: unknown;
+ initialSyncProgress: MobileBootstrapProgress | null;
+ isError: boolean;
+ isLoading: boolean;
+ isLoadingMore: boolean;
+ isRefreshing: boolean;
+ memoFilterMode: MemoFilterMode;
+ memoListDensity: MobileMemoListDensity;
+ memoView: MemoView;
+ memos: MemoSummary[];
+ notebooks: Notebook[];
+ onCreate: () => void;
+ onClearSelection: () => void;
+ onFilterModeChange: (filterMode: MemoFilterMode) => void;
+ onOpenActions: () => void;
+ onOpenNotebookPicker: () => void;
+ onMemoLongPress: (memo: MemoSummary) => void;
+ onMemoPress: (memoId: string) => void;
+ onLoadMore: () => void;
+ onRefresh: () => void;
+ onRetry: () => void;
+ onSearchTextChange: (value: string) => void;
+ onSetMemoView: (memoView: MemoView) => void;
+ searchText: string;
+ totalMemoCount: number;
+ selectionMode: boolean;
+ selectedMemoIds: Set<string>;
+}) => {
+ const { resolvedTheme } = useMobileTheme();
+ const { preference: localePreference, translate } = useMobileLocale();
+ const searchActive = searchText.trim().length > 0;
+ const filterActive = memoFilterMode !== "all";
+ const searchStatusLabel = translate("正在搜索");
+ const searchResultLabel = translate(`${totalMemoCount} 条结果`);
+ const exitSearchLabel = translate("退出搜索");
+ const activeFilterLabel = memoFilterMode === "pinned"
+ ? translate("置顶")
+ : memoFilterMode === "tagged"
+ ? translate("有标签")
+ : translate("无标签");
+ const filterResultLabel = translate(`筛选:${activeFilterLabel} · ${totalMemoCount} 条`);
+ const resetFilterLabel = translate("重置");
+
+ return (
+ <View style={styles.viewBody}>
+ <View style={styles.mobileListHeader}>
+ {selectionMode ? (
+ <View style={styles.mobileSelectionHeader}>
+ <Pressable accessibilityLabel="取消选择" accessibilityRole="button" onPress={onClearSelection} style={styles.mobileSelectionClose}>
+ <X color="#64748b" size={19} />
+ </Pressable>
+ <Text style={styles.mobileSelectionTitle}>{selectedMemoIds.size > 0 ? translate(`已选择 ${selectedMemoIds.size} 条`) : "选择笔记"}</Text>
+ <View style={styles.iconButtonPlaceholder} />
+ </View>
+ ) : null}
+ <View style={styles.mobileListTitleRow}>
+ <Pressable
+ accessibilityLabel={memoView === "trash" ? "返回笔记列表" : "切换笔记本"}
+ accessibilityRole="button"
+ onPress={memoView === "trash" ? () => onSetMemoView("notebook") : onOpenNotebookPicker}
+ style={styles.mobileNotebookTitleButton}
+ >
+ {memoView === "trash" ? <ChevronLeft color="#475569" size={18} /> : null}
+ <Text numberOfLines={1} style={styles.mobileNotebookTitle}>
+ {memoView === "trash" ? "回收站" : activeNotebook?.name ?? "全部笔记"}
+ </Text>
+ {memoView === "notebook" ? <ChevronDown color="#64748b" size={16} /> : null}
+ </Pressable>
+ <Pressable accessibilityLabel={selectionMode ? "批量操作" : "列表选项"} accessibilityRole="button" onPress={onOpenActions} style={styles.mobileMoreButton}>
+ <MoreHorizontal color="#475569" size={20} />
+ </Pressable>
+ </View>
+
+ <>
+ <View style={styles.mobileSearchRow}>
+ <View style={[styles.mobileSearchButton, searchActive && styles.mobileSearchButtonActive, searchActive && resolvedTheme === "dark" && styles.mobileSearchButtonActiveDark]}>
+ <Search color={searchActive && resolvedTheme === "dark" ? "rgb(5, 150, 105)" : searchActive ? "#059669" : "#64748b"} size={17} />
+ <TextInput
+ accessibilityLabel="搜索笔记"
+ autoCapitalize="none"
+ autoCorrect={false}
+ onChangeText={onSearchTextChange}
+ placeholder="搜索笔记"
+ placeholderTextColor="#94a3b8"
+ returnKeyType="search"
+ style={[styles.mobileSearchInput, searchActive && resolvedTheme === "dark" && styles.mobileSearchInputActiveDark]}
+ value={searchText}
+ />
+ {searchText ? (
+ <Pressable accessibilityLabel="清空搜索" accessibilityRole="button" onPress={() => onSearchTextChange("")} style={styles.mobileSearchClearButton}>
+ <X color={resolvedTheme === "dark" ? "rgb(100, 116, 139)" : "#64748b"} size={14} />
+ </Pressable>
+ ) : null}
+ </View>
+ <MobileFilterButton
+ active={memoFilterMode === "pinned"}
+ icon={<Sparkles color={memoFilterMode === "pinned" ? "#ffffff" : "#475569"} size={18} />}
+ label="置顶"
+ onPress={() => onFilterModeChange(toggleMobileMemoFilterMode(memoFilterMode, "pinned"))}
+ />
+ <MobileFilterButton
+ active={memoFilterMode === "tagged"}
+ icon={<Tag color={memoFilterMode === "tagged" ? "#ffffff" : "#475569"} size={18} />}
+ label="有标签"
+ onPress={() => onFilterModeChange(toggleMobileMemoFilterMode(memoFilterMode, "tagged"))}
+ />
+ <MobileFilterButton
+ active={memoFilterMode === "untagged"}
+ icon={<Tag color={memoFilterMode === "untagged" ? "#ffffff" : "#475569"} size={18} />}
+ label="无标签"
+ onPress={() => onFilterModeChange(toggleMobileMemoFilterMode(memoFilterMode, "untagged"))}
+ />
+ </View>
+ {searchActive || filterActive ? (
+ <View accessibilityLiveRegion="polite" style={[styles.mobileListConstraint, !searchActive && styles.mobileListConstraintFilter]}>
+ {searchActive ? (
+ <View style={styles.mobileSearchStatusPill}>
+ <Search color="#ffffff" size={12} />
+ <Text style={styles.mobileSearchStatusPillText}>{searchStatusLabel}</Text>
+ </View>
+ ) : null}
+ <Text numberOfLines={1} style={[styles.mobileListConstraintText, !searchActive && styles.mobileListConstraintTextFilter]}>
+ {searchActive ? searchResultLabel : filterResultLabel}
+ </Text>
+ <Pressable
+ accessibilityLabel={searchActive ? exitSearchLabel : resetFilterLabel}
+ accessibilityRole="button"
+ onPress={searchActive ? () => onSearchTextChange("") : () => onFilterModeChange("all")}
+ >
+ <Text style={[styles.mobileListConstraintAction, !searchActive && styles.mobileListConstraintActionFilter]}>
+ {searchActive ? exitSearchLabel : resetFilterLabel}
+ </Text>
+ </Pressable>
+ </View>
+ ) : null}
+ </>
+ </View>
+
+ <MemoList
+ emptyAction={memoView === "notebook" && notebooks.length > 0 ? { label: "新建笔记", onPress: onCreate } : undefined}
+ emptyDescription={searchActive ? "换个关键词再试" : memoFilterMode !== "all" ? "试试切换筛选条件,或调整搜索关键词。" : memoView === "trash" ? "删除的笔记会显示在这里。" : "先创建一条笔记,之后可以在这里快速预览、搜索和批量整理。"}
+ emptyTitle={searchActive ? "没有找到匹配笔记" : memoFilterMode !== "all" ? "没有符合筛选的笔记" : memoView === "trash" ? "回收站为空" : "暂无笔记"}
+ error={error}
+ initialSyncProgress={initialSyncProgress}
+ isError={isError}
+ isLoading={isLoading}
+ isLoadingMore={isLoadingMore}
+ isRefreshing={isRefreshing}
+ listDensity={memoListDensity}
+ memos={memos}
+ onMemoLongPress={onMemoLongPress}
+ onMemoPress={onMemoPress}
+ onLoadMore={onLoadMore}
+ onRefresh={onRefresh}
+ onRetry={onRetry}
+ selectionMode={selectionMode}
+ selectedMemoIds={selectedMemoIds}
+ />
+ </View>
+ );
+};
+
+
+const MemoList = ({
+ emptyAction,
+ emptyDescription,
+ emptyTitle,
+ error,
+ isError,
+ initialSyncProgress,
+ isLoading,
+ isLoadingMore = false,
+ isRefreshing,
+ listDensity,
+ memos,
+ onMemoLongPress,
+ onMemoPress,
+ onLoadMore,
+ onRefresh,
+ onRetry,
+ selectionMode = false,
+ selectedMemoIds = new Set(),
+}: {
+ emptyAction?: { label: string; onPress: () => void };
+ emptyDescription: string;
+ emptyTitle: string;
+ error?: unknown;
+ isError: boolean;
+ initialSyncProgress: MobileBootstrapProgress | null;
+ isLoading: boolean;
+ isLoadingMore?: boolean;
+ isRefreshing: boolean;
+ listDensity: MobileMemoListDensity;
+ memos: MemoSummary[];
+ onMemoLongPress?: (memo: MemoSummary) => void;
+ onMemoPress: (memoId: string) => void;
+ onLoadMore?: () => void;
+ onRefresh: () => void;
+ onRetry?: () => void;
+ selectionMode?: boolean;
+ selectedMemoIds?: Set<string>;
+}) => {
+ const { preference: localePreference, translate } = useMobileLocale();
+ const hasInitialSyncProgress = initialSyncProgress !== null;
+ const loadedCount = initialSyncProgress?.loadedCount ?? 0;
+ const totalCount = initialSyncProgress?.totalCount ?? 0;
+ const progressPercent = totalCount > 0 ? Math.min(100, Math.round((loadedCount / totalCount) * 100)) : 0;
+ const progressTitle = translate("正在同步笔记");
+ const progressDescription = totalCount > 0
+ ? translate(`已加载 ${loadedCount} / ${totalCount} 条笔记`)
+ : translate("正在准备首次同步…");
+ const loadingTitle = hasInitialSyncProgress ? progressTitle : translate("正在加载笔记");
+ const loadingDescription = hasInitialSyncProgress
+ ? progressDescription
+ : translate("正在加载笔记本和笔记…");
+
+ if ((isLoading || hasInitialSyncProgress) && memos.length === 0) {
+ return (
+ <View accessibilityLabel={loadingTitle} accessibilityLiveRegion="polite" style={styles.memoListStateWrap}>
+ <View style={styles.memoListLoadingCard}>
+ <ActivityIndicator color="#059669" size="large" />
+ <Text style={styles.memoListLoadingTitle}>{loadingTitle}</Text>
+ <Text style={styles.memoListLoadingDescription}>{loadingDescription}</Text>
+ {totalCount > 0 ? (
+ <View style={styles.memoSyncProgressTrack}>
+ <View style={[styles.memoSyncProgressFill, { width: `${progressPercent}%` }]} />
+ </View>
+ ) : null}
+ </View>
+ </View>
+ );
+ }
+
+ if (isError && memos.length === 0) {
+ return (
+ <View style={styles.memoListStateWrap}>
+ <View style={styles.memoListErrorCard}>
+ <Text style={styles.memoListErrorTitle}>暂时没有拉到笔记</Text>
+ <Text style={styles.memoListErrorDescription}>网络或 PWA 后台恢复可能短暂中断了同步。这里不会把它当作空笔记本。</Text>
+ {onRetry ? (
+ <Pressable accessibilityLabel="重试加载" accessibilityRole="button" onPress={onRetry} style={styles.memoListRetryButton}>
+ <RotateCcw color="#92400e" size={17} />
+ <Text style={styles.memoListRetryText}>重试</Text>
+ </Pressable>
+ ) : null}
+ </View>
+ </View>
+ );
+ }
+
+ return (
+ <FlatList
+ contentContainerStyle={memos.length === 0 ? styles.emptyList : styles.list}
+ data={memos}
+ initialNumToRender={10}
+ keyExtractor={(memo) => memo.id}
+ maxToRenderPerBatch={8}
+ onEndReached={onLoadMore}
+ onEndReachedThreshold={0.35}
+ removeClippedSubviews={Platform.OS === "android"}
+ refreshControl={<RefreshControl onRefresh={onRefresh} refreshing={isRefreshing} tintColor="#0f172a" />}
+ style={styles.memoList}
+ renderItem={({ item }) => (
+ <MemoCard
+ memo={item}
+ listDensity={listDensity}
+ onLongPress={!selectionMode && onMemoLongPress ? () => onMemoLongPress(item) : undefined}
+ onPress={() => onMemoPress(item.id)}
+ selected={selectedMemoIds.has(item.id)}
+ selectionMode={selectionMode}
+ />
+ )}
+ ListEmptyComponent={
+ <View style={styles.memoListEmptyCard}>
+ <Text style={styles.emptyTitle}>{emptyTitle}</Text>
+ <Text style={styles.mutedText}>{emptyDescription}</Text>
+ {emptyAction ? (
+ <Pressable accessibilityRole="button" onPress={emptyAction.onPress} style={styles.emptyActionButton}>
+ <Plus color="#ffffff" size={18} />
+ <Text style={styles.emptyActionButtonText}>{emptyAction.label}</Text>
+ </Pressable>
+ ) : null}
+ </View>
+ }
+ ListHeaderComponent={hasInitialSyncProgress ? (
+ <View accessibilityLiveRegion="polite" style={styles.memoSyncBanner}>
+ <ActivityIndicator color="#059669" size="small" />
+ <View style={styles.memoSyncBannerContent}>
+ <Text style={styles.memoSyncBannerTitle}>{progressTitle}</Text>
+ <Text style={styles.memoSyncBannerDescription}>{progressDescription}</Text>
+ <View style={styles.memoSyncProgressTrack}>
+ <View style={[styles.memoSyncProgressFill, { width: `${progressPercent}%` }]} />
+ </View>
+ </View>
+ </View>
+ ) : isError ? (
+ <View accessibilityLiveRegion="polite" style={styles.memoSyncErrorBanner}>
+ <View style={styles.memoSyncBannerContent}>
+ <Text style={styles.memoSyncErrorBannerTitle}>{translate("同步已暂停")}</Text>
+ <Text style={styles.memoSyncErrorBannerDescription}>
+ {translate("已加载的笔记仍可使用,请检查网络后重试。")}
+ </Text>
+ </View>
+ {onRetry ? (
+ <Pressable accessibilityRole="button" onPress={onRetry} style={styles.memoSyncErrorRetryButton}>
+ <RotateCcw color="#92400e" size={15} />
+ <Text style={styles.memoListRetryText}>{translate("重试")}</Text>
+ </Pressable>
+ ) : null}
+ </View>
+ ) : null}
+ ListFooterComponent={isLoadingMore ? <ActivityIndicator color="#0f172a" style={styles.listLoadingFooter} /> : null}
+ updateCellsBatchingPeriod={32}
+ windowSize={7}
+ />
+ );
+};
+
+
+const MobileFilterButton = ({ active, icon, label, onPress }: { active: boolean; icon: ReactNode; label: string; onPress: () => void }) => (
+ <Pressable
+ accessibilityLabel={label}
+ accessibilityRole="button"
+ accessibilityState={{ selected: active }}
+ onPress={onPress}
+ style={[styles.mobileFilterButton, active && styles.mobileFilterButtonActive]}
+ >
+ {icon}
+ </Pressable>
+);
+
+const MemoCard = memo(function MemoCard({
+ listDensity,
+ memo,
+ onLongPress,
+ onPress,
+ selected = false,
+ selectionMode = false,
+}: {
+ listDensity: MobileMemoListDensity;
+ memo: MemoSummary;
+ onLongPress?: () => void;
+ onPress: () => void;
+ selected?: boolean;
+ selectionMode?: boolean;
+}) {
+ const localePreference = useMobileLocale().preference;
+ const memoTitle = memo.title?.trim() || DEFAULT_MEMO_TITLE;
+ const pressScale = useSharedValue(1);
+ const pressAnimatedStyle = useAnimatedStyle(() => ({
+ transform: [{ scale: pressScale.value }],
+ }));
+
+ return (
+ <Animated.View
+ entering={FadeInDown.duration(260).springify().damping(18)}
+ exiting={FadeOutUp.duration(220)}
+ layout={LinearTransition.duration(220)}
+ style={[
+ styles.memoCard,
+ listDensity === "compact" && styles.memoCardCompact,
+ selected && styles.memoCardSelected,
+ pressAnimatedStyle,
+ ]}
+ >
+ {selectionMode ? (
+ <Pressable
+ accessibilityLabel={`${selected ? "取消选择" : "选择"} ${memoTitle}`}
+ accessibilityRole="button"
+ accessibilityState={{ selected }}
+ onPress={onPress}
+ style={styles.memoSelectionButton}
+ >
+ <View style={[styles.selectionIndicator, selected && styles.selectionIndicatorActive]}>
+ {selected ? <Check color="#ffffff" size={14} /> : null}
+ </View>
+ </Pressable>
+ ) : null}
+ <Pressable
+ accessibilityLabel={memoTitle}
+ accessibilityRole="button"
+ delayLongPress={520}
+ onLongPress={onLongPress}
+ onPress={onPress}
+ onPressIn={() => {
+ pressScale.value = withTiming(0.985, { duration: 100 });
+ }}
+ onPressOut={() => {
+ pressScale.value = withTiming(1, { duration: 160 });
+ }}
+ style={[styles.memoCardContent, listDensity === "compact" && styles.memoCardContentCompact, selectionMode && styles.memoCardContentWithSelection]}
+ >
+ <View style={styles.memoCardTop}>
+ {memo.isPinned ? (
+ <Text accessibilityElementsHidden importantForAccessibility="no-hide-descendants" style={styles.memoPinnedStar}>★</Text>
+ ) : null}
+ <Text numberOfLines={1} style={styles.memoTitle}>
+ {memoTitle}
+ </Text>
+ </View>
+ {listDensity === "preview" ? (
+ <Text numberOfLines={2} style={styles.memoExcerpt}>
+ {memo.excerpt || "空笔记"}
+ </Text>
+ ) : null}
+ <View style={[styles.memoMeta, listDensity === "compact" && styles.memoMetaCompact]}>
+ <Text style={styles.memoDate}>{formatMemoPreviewDate(memo.updatedAt, localePreference)}</Text>
+ {memo.tags.slice(0, 3).map((tag) => (
+ <Text key={tag} style={styles.tag}>
+ #{tag}
+ </Text>
+ ))}
+ </View>
+ </Pressable>
+ </Animated.View>
+ );
+}, (previous, next) =>
+ previous.memo === next.memo &&
+ previous.listDensity === next.listDensity &&
+ previous.selected === next.selected &&
+ previous.selectionMode === next.selectionMode
+);
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 1f049ce2..f581a50d 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -1,5 +1,5 @@
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentRef, type ReactNode } from "react";
-import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData, type QueryClient, type UseMutationResult } from "@tanstack/react-query";
+import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
import * as Clipboard from "expo-clipboard";
import Constants from "expo-constants";
import { File as ExpoFile } from "expo-file-system";
@@ -42,8 +42,6 @@ import {
import {
ActivityIndicator,
BackHandler,
- AppState,
- type AppStateStatus,
FlatList,
Image as RNImage,
type ImageStyle,
@@ -84,21 +82,16 @@ import { useMobileLocale } from "../lib/mobile-locale";
import { useSession } from "../lib/session";
import {
deleteMobileSyncQueueItem,
- getMobileSyncRetryDelay,
listMobileSyncQueueItems,
- loadMobileSyncQueueSummary,
queueMobileMemoCreate,
queueMobileMemoUpdate,
- syncMobileQueuedChanges,
type MobileSyncQueueItem,
} from "../lib/sync-queue";
import {
createMobileDataScope,
getLocalMemo,
- isMobileLocalMirrorInitialized,
listLocalMemos,
listLocalNotebooks,
- replaceLocalMemoId,
resolveLocalMemo,
syncMobileLocalMirror,
upsertLocalMemo,
@@ -111,7 +104,7 @@ import EditorRuntimePrewarm from "../components/EditorRuntimePrewarm";
import MobileWebClipCapture from "../components/MobileWebClipCapture";
import { showEdgeEverKeyboard } from "../../modules/edgeever-keyboard";
import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";
-import { resolveMobileThemeStyles, useMobileTheme, type MobileResolvedTheme } from "../lib/mobile-theme";
+import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";
import { useMobileUpdate } from "../lib/mobile-update";
import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";
import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";
@@ -124,55 +117,49 @@ import {
type MobileSharedPayload,
type MobileWebClipDraft,
} from "../lib/mobile-web-clip";
+import { useDebouncedValue } from "../hooks/useDebouncedValue";
+import { useMobileAutomaticSync } from "../hooks/useMobileAutomaticSync";
+import { useMobileLocalMirrorSync } from "../hooks/useMobileLocalMirrorSync";
+import {
+ filterCollapsedNotebookOptions,
+ filterNotebookOptions,
+ filterNotebookOptionsById,
+ flattenNotebooks,
+ formatDate,
+ formatMemoPreviewDate,
+ formatRevisionActor,
+ getNotebookAncestorIds,
+ getNotebookParentIdSet,
+ getResolvedMobileLocale,
+ getTextSearchMatches,
+ isEnglishMobileLocale,
+ parseTags,
+ type NotebookOption,
+} from "./workspace-utils";
+import {
+ applyOptimisticMemoToCache,
+ createOptimisticMemo,
+ findCachedMemoDetail,
+ type MobileMemoUpdatePayload,
+} from "./workspace-memo-cache";
+import { refreshWorkspaceThemeStyles, styles } from "./workspace-styles";
+import { NotesView } from "./WorkspaceNotesView";
+import { SettingsView, type MobileLocaleMode } from "./WorkspaceSettingsView";
+import { MemoDetailModal } from "./WorkspaceMemoDetail";
const ALL_NOTES_ID = "all";
const DEFAULT_MEMO_TITLE = "无标题笔记";
-const resolveEditableMemoTitle = (title?: string | null) => {
- const trimmedTitle = title?.trim() ?? "";
- return trimmedTitle === DEFAULT_MEMO_TITLE ? "" : trimmedTitle;
-};
-const MOBILE_APP_VERSION = Constants.expoConfig?.version ?? "0.1.2";
const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;
const DETAIL_CONTENT_HORIZONTAL_PADDING = 16;
const DETAIL_TABLE_FIT_COLUMN_COUNT = 3;
const DETAIL_TABLE_MIN_COLUMN_WIDTH = 132;
-
-const formatExecutionEnvironment = (environment: string | null | undefined, localePreference: MobileLocaleMode = "system") => {
- const english = isEnglishMobileLocale(localePreference);
-
- switch (environment) {
- case "standalone":
- return english ? "Standalone app" : "独立安装包";
- case "storeClient":
- return english ? "Expo Go / development client" : "Expo Go / 开发客户端";
- case "bare":
- return "Bare React Native";
- default:
- return environment || getMobileSystemInfoText(localePreference).unknown;
- }
+const resolveEditableMemoTitle = (title?: string | null) => {
+ const trimmedTitle = title?.trim() ?? "";
+ return trimmedTitle === DEFAULT_MEMO_TITLE ? "" : trimmedTitle;
};
-const MOBILE_LOCALE_OPTIONS: Array<{ label: string; value: MobileLocalePreference }> = [
- { label: "跟随系统", value: "system" },
- { label: "简体中文", value: "zh-CN" },
- { label: "English", value: "en-US" },
-];
+const useMobileLocalePreference = () => useMobileLocale().preference;
type MobileView = "notes" | "settings";
-type SettingsTab = "general" | "account" | "system";
type MemoView = "notebook" | "trash";
-type NotebookOption = {
- notebook: Notebook;
- depth: number;
-};
-type MobileLocaleMode = MobileLocalePreference;
-const useMobileLocalePreference = () => useMobileLocale().preference;
-type MobileMemoUpdatePayload = {
- title?: string;
- contentJson?: TiptapDoc;
- contentMarkdown?: string;
- isPinned?: boolean;
- notebookId?: string;
- tags?: string[];
-};
type RichEditingSession = {
draft: MobileMemoDraft | null;
memo: MemoDetail;
@@ -217,26 +204,31 @@ export const WorkspaceScreen = ({
const [selectedMemoIds, setSelectedMemoIds] = useState<Set<string>>(() => new Set());
const [selectionMoveOpen, setSelectionMoveOpen] = useState(false);
const [selectionMoreOpen, setSelectionMoreOpen] = useState(false);
- const [isInitialMirrorStatusPending, setIsInitialMirrorStatusPending] = useState(true);
- const [initialMirrorSyncProgress, setInitialMirrorSyncProgress] = useState<MobileBootstrapProgress | null>(null);
- const [initialMirrorSyncError, setInitialMirrorSyncError] = useState<unknown>(null);
- const [mirrorSyncAttempt, setMirrorSyncAttempt] = useState(0);
- const autoSyncRunningRef = useRef(false);
- const autoSyncRequestedRef = useRef(false);
- const autoSyncRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const memoDraftPrefetchRef = useRef(new Map<string, Promise<MobileMemoDraft | null>>());
const processedShareUrlRef = useRef<string | null>(null);
const onIncomingShareHandledRef = useRef(onIncomingShareHandled);
onIncomingShareHandledRef.current = onIncomingShareHandled;
- const [syncQueueItems, setSyncQueueItems] = useState<MobileSyncQueueItem[]>([]);
const debouncedSearchText = useDebouncedValue(searchText.trim(), 250);
const incomingShareUrl = useMemo(() => getSharedWebUrl(incomingSharePayloads), [incomingSharePayloads]);
-
- const refreshSyncQueueItems = useCallback(async () => {
- const items = await listMobileSyncQueueItems(syncQueueScope);
- setSyncQueueItems(items);
- return items;
- }, [syncQueueScope]);
+ const handleMemoIdRemapped = useCallback((temporaryId: string, memo: MemoDetail) => {
+ setSelectedMemoId((current) => current === temporaryId ? memo.id : current);
+ }, []);
+ const {
+ refreshSyncQueueItems,
+ runAutomaticSync,
+ syncQueueItems,
+ } = useMobileAutomaticSync({
+ client,
+ dataScope,
+ onMemoIdRemapped: handleMemoIdRemapped,
+ syncQueueScope,
+ });
+ const {
+ initialSyncError: initialMirrorSyncError,
+ initialSyncProgress: initialMirrorSyncProgress,
+ isInitialStatusPending: isInitialMirrorStatusPending,
+ retryInitialSync,
+ } = useMobileLocalMirrorSync({ client, dataScope });
const notebooksQuery = useQuery({
queryKey: ["mobile", "notebooks"],
@@ -969,149 +961,6 @@ export const WorkspaceScreen = ({
setSelectedMemoIds(new Set([memoId]));
};
- const runAutomaticSync = async () => {
- if (!client) {
- return;
- }
-
- if (autoSyncRunningRef.current) {
- autoSyncRequestedRef.current = true;
- return;
- }
-
- if (autoSyncRetryTimerRef.current) {
- clearTimeout(autoSyncRetryTimerRef.current);
- autoSyncRetryTimerRef.current = null;
- }
-
- autoSyncRunningRef.current = true;
-
- const summary = await loadMobileSyncQueueSummary(syncQueueScope);
- if (summary.pending + summary.error + summary.syncing === 0) {
- await refreshSyncQueueItems();
- autoSyncRunningRef.current = false;
- return;
- }
-
- try {
- await syncMobileQueuedChanges(client, syncQueueScope, {
- onSynced: async (memo, item) => {
- if (item.kind === "memo.create") {
- await replaceLocalMemoId(dataScope, item.memoId, memo);
- setSelectedMemoId((current) => current === item.memoId ? memo.id : current);
- } else {
- await upsertLocalMemo(dataScope, memo);
- }
- queryClient.setQueryData(["mobile", "memo", "notebook", memo.id], { memo });
- queryClient.setQueryData(["mobile", "memo", "trash", memo.id], { memo });
- },
- });
- const nextSummary = await loadMobileSyncQueueSummary(syncQueueScope);
- if (nextSummary.total === 0) {
- await invalidateWorkspace();
- }
- } catch {
- // The queue keeps its retry metadata; the next scheduled pass resumes it.
- } finally {
- await refreshSyncQueueItems();
- autoSyncRunningRef.current = false;
- if (autoSyncRequestedRef.current) {
- autoSyncRequestedRef.current = false;
- void runAutomaticSync();
- } else {
- const retryDelay = await getMobileSyncRetryDelay(syncQueueScope);
- if (retryDelay !== null) {
- autoSyncRetryTimerRef.current = setTimeout(() => {
- autoSyncRetryTimerRef.current = null;
- void runAutomaticSync();
- }, retryDelay);
- }
- }
- }
- };
-
- useEffect(() => {
- if (!client) {
- return;
- }
-
- void runAutomaticSync();
-
- const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
- if (nextState === "active") {
- void runAutomaticSync();
- }
- });
-
- return () => {
- subscription.remove();
- if (autoSyncRetryTimerRef.current) {
- clearTimeout(autoSyncRetryTimerRef.current);
- autoSyncRetryTimerRef.current = null;
- }
- };
- }, [client, syncQueueScope]);
-
- useEffect(() => {
- if (!client) {
- return;
- }
- let active = true;
- const syncMirror = async () => {
- let isInitialSync = false;
- let refreshedNotebooksDuringBootstrap = false;
- try {
- isInitialSync = !(await isMobileLocalMirrorInitialized(dataScope));
- if (active) {
- setIsInitialMirrorStatusPending(false);
- setInitialMirrorSyncError(null);
- setInitialMirrorSyncProgress(isInitialSync ? { loadedCount: 0, totalCount: 0 } : null);
- }
- await syncMobileLocalMirror(client, dataScope, {
- onBootstrapProgress: isInitialSync ? async (progress) => {
- if (!active) {
- return;
- }
- setInitialMirrorSyncProgress(progress);
- const invalidations = [
- queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
- queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
- ];
- if (!refreshedNotebooksDuringBootstrap) {
- refreshedNotebooksDuringBootstrap = true;
- invalidations.push(queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }));
- }
- await Promise.all(invalidations);
- } : undefined,
- });
- if (active) {
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: ["mobile", "notebooks"] }),
- queryClient.invalidateQueries({ queryKey: ["mobile", "memos"] }),
- queryClient.invalidateQueries({ queryKey: ["mobile", "search"] }),
- ]);
- setInitialMirrorSyncProgress(null);
- }
- } catch (error) {
- if (active && isInitialSync) {
- setInitialMirrorSyncProgress(null);
- setInitialMirrorSyncError(error);
- }
- // An initialized local mirror remains readable while the device is offline.
- }
- };
- void syncMirror();
- const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
- if (nextState === "active") {
- void syncMirror();
- }
- });
- return () => {
- active = false;
- subscription.remove();
- };
- }, [client, dataScope, mirrorSyncAttempt, queryClient]);
-
if (richEditingSession) {
return <RichEditorModal
baseUrl={session?.baseUrl ?? ""}
@@ -1166,11 +1015,7 @@ export const WorkspaceScreen = ({
selectedMemoIds={selectedMemoIds}
error={initialMirrorSyncError ?? notebooksQuery.error ?? (searchActive ? searchQuery.error : memosQuery.error)}
isError={Boolean(initialMirrorSyncError) || notebooksQuery.isError || (searchActive ? searchQuery.isError : memosQuery.isError)}
- onRetry={() => {
- setIsInitialMirrorStatusPending(true);
- setInitialMirrorSyncError(null);
- setMirrorSyncAttempt((attempt) => attempt + 1);
- }}
+ onRetry={retryInitialSync}
/>
) : null}
@@ -1372,202 +1217,6 @@ export const WorkspaceScreen = ({
);
};
-const NotesView = ({
- activeNotebook,
- error,
- initialSyncProgress,
- isError,
- isLoading,
- isLoadingMore,
- isRefreshing,
- memoFilterMode,
- memoListDensity,
- memoView,
- memos,
- notebooks,
- onCreate,
- onClearSelection,
- onFilterModeChange,
- onOpenActions,
- onOpenNotebookPicker,
- onMemoLongPress,
- onMemoPress,
- onLoadMore,
- onRefresh,
- onRetry,
- onSearchTextChange,
- onSetMemoView,
- searchText,
- totalMemoCount,
- selectedMemoIds,
- selectionMode,
-}: {
- activeNotebook: Notebook | null;
- error: unknown;
- initialSyncProgress: MobileBootstrapProgress | null;
- isError: boolean;
- isLoading: boolean;
- isLoadingMore: boolean;
- isRefreshing: boolean;
- memoFilterMode: MemoFilterMode;
- memoListDensity: MobileMemoListDensity;
- memoView: MemoView;
- memos: MemoSummary[];
- notebooks: Notebook[];
- onCreate: () => void;
- onClearSelection: () => void;
- onFilterModeChange: (filterMode: MemoFilterMode) => void;
- onOpenActions: () => void;
- onOpenNotebookPicker: () => void;
- onMemoLongPress: (memo: MemoSummary) => void;
- onMemoPress: (memoId: string) => void;
- onLoadMore: () => void;
- onRefresh: () => void;
- onRetry: () => void;
- onSearchTextChange: (value: string) => void;
- onSetMemoView: (memoView: MemoView) => void;
- searchText: string;
- totalMemoCount: number;
- selectionMode: boolean;
- selectedMemoIds: Set<string>;
-}) => {
- const { resolvedTheme } = useMobileTheme();
- const localePreference = useMobileLocalePreference();
- const searchActive = searchText.trim().length > 0;
- const filterActive = memoFilterMode !== "all";
- const englishLocale = isEnglishMobileLocale(localePreference);
- const searchStatusLabel = englishLocale ? "Searching" : "正在搜索";
- const searchResultLabel = englishLocale ? `${totalMemoCount} ${totalMemoCount === 1 ? "result" : "results"}` : `${totalMemoCount} 条结果`;
- const exitSearchLabel = englishLocale ? "Exit search" : "退出搜索";
- const activeFilterLabel = memoFilterMode === "pinned"
- ? (englishLocale ? "Pinned" : "置顶")
- : memoFilterMode === "tagged"
- ? (englishLocale ? "Tagged" : "有标签")
- : (englishLocale ? "Untagged" : "无标签");
- const filterResultLabel = englishLocale
- ? `Filter: ${activeFilterLabel} · ${totalMemoCount} ${totalMemoCount === 1 ? "note" : "notes"}`
- : `筛选:${activeFilterLabel} · ${totalMemoCount} 条`;
- const resetFilterLabel = englishLocale ? "Reset" : "重置";
-
- return (
- <View style={styles.viewBody}>
- <View style={styles.mobileListHeader}>
- {selectionMode ? (
- <View style={styles.mobileSelectionHeader}>
- <Pressable accessibilityLabel="取消选择" accessibilityRole="button" onPress={onClearSelection} style={styles.mobileSelectionClose}>
- <X color="#64748b" size={19} />
- </Pressable>
- <Text style={styles.mobileSelectionTitle}>{selectedMemoIds.size > 0 ? `已选择 ${selectedMemoIds.size} 条` : "选择笔记"}</Text>
- <View style={styles.iconButtonPlaceholder} />
- </View>
- ) : null}
- <View style={styles.mobileListTitleRow}>
- <Pressable
- accessibilityLabel={memoView === "trash" ? "返回笔记列表" : "切换笔记本"}
- accessibilityRole="button"
- onPress={memoView === "trash" ? () => onSetMemoView("notebook") : onOpenNotebookPicker}
- style={styles.mobileNotebookTitleButton}
- >
- {memoView === "trash" ? <ChevronLeft color="#475569" size={18} /> : null}
- <Text numberOfLines={1} style={styles.mobileNotebookTitle}>
- {memoView === "trash" ? "回收站" : activeNotebook?.name ?? "全部笔记"}
- </Text>
- {memoView === "notebook" ? <ChevronDown color="#64748b" size={16} /> : null}
- </Pressable>
- <Pressable accessibilityLabel={selectionMode ? "批量操作" : "列表选项"} accessibilityRole="button" onPress={onOpenActions} style={styles.mobileMoreButton}>
- <MoreHorizontal color="#475569" size={20} />
- </Pressable>
- </View>
-
- <>
- <View style={styles.mobileSearchRow}>
- <View style={[styles.mobileSearchButton, searchActive && styles.mobileSearchButtonActive, searchActive && resolvedTheme === "dark" && styles.mobileSearchButtonActiveDark]}>
- <Search color={searchActive && resolvedTheme === "dark" ? "rgb(5, 150, 105)" : searchActive ? "#059669" : "#64748b"} size={17} />
- <TextInput
- accessibilityLabel="搜索笔记"
- autoCapitalize="none"
- autoCorrect={false}
- onChangeText={onSearchTextChange}
- placeholder="搜索笔记"
- placeholderTextColor="#94a3b8"
- returnKeyType="search"
- style={[styles.mobileSearchInput, searchActive && resolvedTheme === "dark" && styles.mobileSearchInputActiveDark]}
- value={searchText}
- />
- {searchText ? (
- <Pressable accessibilityLabel="清空搜索" accessibilityRole="button" onPress={() => onSearchTextChange("")} style={styles.mobileSearchClearButton}>
- <X color={resolvedTheme === "dark" ? "rgb(100, 116, 139)" : "#64748b"} size={14} />
- </Pressable>
- ) : null}
- </View>
- <MobileFilterButton
- active={memoFilterMode === "pinned"}
- icon={<Sparkles color={memoFilterMode === "pinned" ? "#ffffff" : "#475569"} size={18} />}
- label="置顶"
- onPress={() => onFilterModeChange(toggleMobileMemoFilterMode(memoFilterMode, "pinned"))}
- />
- <MobileFilterButton
- active={memoFilterMode === "tagged"}
- icon={<Tag color={memoFilterMode === "tagged" ? "#ffffff" : "#475569"} size={18} />}
- label="有标签"
- onPress={() => onFilterModeChange(toggleMobileMemoFilterMode(memoFilterMode, "tagged"))}
- />
- <MobileFilterButton
- active={memoFilterMode === "untagged"}
- icon={<Tag color={memoFilterMode === "untagged" ? "#ffffff" : "#475569"} size={18} />}
- label="无标签"
- onPress={() => onFilterModeChange(toggleMobileMemoFilterMode(memoFilterMode, "untagged"))}
- />
- </View>
- {searchActive || filterActive ? (
- <View accessibilityLiveRegion="polite" style={[styles.mobileListConstraint, !searchActive && styles.mobileListConstraintFilter]}>
- {searchActive ? (
- <View style={styles.mobileSearchStatusPill}>
- <Search color="#ffffff" size={12} />
- <Text style={styles.mobileSearchStatusPillText}>{searchStatusLabel}</Text>
- </View>
- ) : null}
- <Text numberOfLines={1} style={[styles.mobileListConstraintText, !searchActive && styles.mobileListConstraintTextFilter]}>
- {searchActive ? searchResultLabel : filterResultLabel}
- </Text>
- <Pressable
- accessibilityLabel={searchActive ? exitSearchLabel : resetFilterLabel}
- accessibilityRole="button"
- onPress={searchActive ? () => onSearchTextChange("") : () => onFilterModeChange("all")}
- >
- <Text style={[styles.mobileListConstraintAction, !searchActive && styles.mobileListConstraintActionFilter]}>
- {searchActive ? exitSearchLabel : resetFilterLabel}
- </Text>
- </Pressable>
- </View>
- ) : null}
- </>
- </View>
-
- <MemoList
- emptyAction={memoView === "notebook" && notebooks.length > 0 ? { label: "新建笔记", onPress: onCreate } : undefined}
- emptyDescription={searchActive ? "换个关键词再试" : memoFilterMode !== "all" ? "试试切换筛选条件,或调整搜索关键词。" : memoView === "trash" ? "删除的笔记会显示在这里。" : "先创建一条笔记,之后可以在这里快速预览、搜索和批量整理。"}
- emptyTitle={searchActive ? "没有找到匹配笔记" : memoFilterMode !== "all" ? "没有符合筛选的笔记" : memoView === "trash" ? "回收站为空" : "暂无笔记"}
- error={error}
- initialSyncProgress={initialSyncProgress}
- isError={isError}
- isLoading={isLoading}
- isLoadingMore={isLoadingMore}
- isRefreshing={isRefreshing}
- listDensity={memoListDensity}
- memos={memos}
- onMemoLongPress={onMemoLongPress}
- onMemoPress={onMemoPress}
- onLoadMore={onLoadMore}
- onRefresh={onRefresh}
- onRetry={onRetry}
- selectionMode={selectionMode}
- selectedMemoIds={selectedMemoIds}
- />
- </View>
- );
-};
-
const NotesActionsModal = ({
bottomOffset,
canEnterSelection,
@@ -1868,224 +1517,6 @@ const ActionSheetItem = ({ compact = false, danger = false, disabled = false, ic
</Pressable>
);
-const SettingsView = ({
- currentUser,
- imageCompressionEnabled,
- localePreference,
- onClose,
- onImageCompressionChange,
- onLocalePreferenceChange,
- onSignOut,
-}: {
- currentUser: AuthUser | null;
- imageCompressionEnabled: boolean;
- localePreference: MobileLocaleMode;
- onClose: () => void;
- onImageCompressionChange: (enabled: boolean) => void;
- onLocalePreferenceChange: (locale: MobileLocaleMode) => void;
- onSignOut: () => void;
-}) => {
- const { resolvedTheme, toggleTheme } = useMobileTheme();
- const { translate } = useMobileLocale();
- const [activeTab, setActiveTab] = useState<SettingsTab | null>(null);
- const [localePickerOpen, setLocalePickerOpen] = useState(false);
- const [localePickerAnchor, setLocalePickerAnchor] = useState<{ left: number; top: number; width: number } | null>(null);
- const localeSelectRef = useRef<ComponentRef<typeof Pressable>>(null);
- const tabs: Array<{ key: SettingsTab; label: string; icon: ReactNode }> = [
- { key: "general", label: "常规设置", icon: <SlidersHorizontal color="#059669" size={17} /> },
- { key: "account", label: "登录设置", icon: <ShieldCheck color="#059669" size={17} /> },
- ];
- const systemInfoCopy = getMobileSystemInfoText(localePreference);
- const activeTabItem = activeTab === "system"
- ? { label: systemInfoCopy.title, icon: <Info color="#059669" size={17} /> }
- : tabs.find((tab) => tab.key === activeTab);
- const title = activeTabItem?.label ?? "我的";
- const activeLocaleLabel = MOBILE_LOCALE_OPTIONS.find((option) => option.value === localePreference)?.label ?? "跟随系统";
- const openLocalePicker = () => {
- localeSelectRef.current?.measureInWindow((left, top, width, height) => {
- setLocalePickerAnchor({ left, top: top + height + 4, width });
- setLocalePickerOpen(true);
- });
- };
- const openFeedback = () => {
- void Linking.openURL(buildMobileFeedbackUrl(localePreference));
- };
-
- useEffect(() => {
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
- if (activeTab) {
- setActiveTab(null);
- } else {
- onClose();
- }
- return true;
- });
-
- return () => subscription.remove();
- }, [activeTab, onClose]);
-
- const renderContent = () => {
- if (activeTab === "system") {
- return (
- <View style={styles.settingsDetailList}>
- <SystemInfoCard defaultExpanded />
- </View>
- );
- }
- if (activeTab === "general") {
- return (
- <View style={styles.settingsDetailList}>
- <SettingsGroup title="偏好设置" icon={<ImageIcon color="#047857" size={16} />}>
- <View style={styles.settingsContentRow}>
- <View style={styles.preferenceStack}>
- <View style={styles.preferenceText}>
- <Text style={styles.settingsRowTitle}>界面语言</Text>
- <Text style={styles.settingsRowDescription}>切换产品界面的显示语言。</Text>
- </View>
- <Pressable accessibilityLabel="界面语言" accessibilityRole="button" onPress={openLocalePicker} ref={localeSelectRef} style={styles.settingsSelect}>
- <Text style={styles.settingsSelectText}>{activeLocaleLabel}</Text>
- <ChevronDown color="#64748b" size={18} />
- </Pressable>
- </View>
- </View>
- <View style={styles.settingsContentRow}>
- <View style={styles.preferenceStack}>
- <View style={styles.preferenceText}>
- <Text style={styles.settingsRowTitle}>压缩笔记内图片</Text>
- <Text style={styles.settingsRowDescription}>上传大图时在本地压缩,节省资源占用。</Text>
- </View>
- <View style={styles.settingsSwitchStart}>
- <Switch accessibilityLabel={translate("是否压缩笔记内图片")} onValueChange={onImageCompressionChange} value={imageCompressionEnabled} />
- </View>
- </View>
- </View>
- </SettingsGroup>
- </View>
- );
- }
- return (
- <View style={styles.settingsDetailList}>
- <View style={styles.accountSummaryCard}>
- <View style={styles.accountSummaryIcon}>
- <UserRound color="#047857" size={19} />
- </View>
- <View style={styles.accountSummaryContent}>
- <Text style={styles.accountSummaryTitle}>{translate("当前账户")}</Text>
- <Text style={styles.accountSummaryName}>{currentUser?.displayName || currentUser?.username || "—"}</Text>
- <Text style={styles.accountSummaryHelp}>
- @{currentUser?.username ?? "—"} · {currentUser?.role === "owner" ? translate("实例管理员") : translate("成员")}
- </Text>
- </View>
- </View>
- <View style={styles.settingsGroup}>
- <AccountSecurityPanel active />
- </View>
- <View style={styles.settingsLogoutCard}>
- <Pressable onPress={onSignOut} style={styles.settingsLogoutButton}>
- <LogOut color="#ffffff" size={17} />
- <Text style={styles.settingsLogoutText}>退出登录</Text>
- </Pressable>
- </View>
- </View>
- );
- };
-
- return (
- <View style={styles.settingsScreen}>
- <View style={styles.settingsHeader}>
- <Pressable accessibilityLabel="返回" onPress={() => activeTab ? setActiveTab(null) : onClose()} style={styles.settingsBackButton}>
- <ChevronLeft color="#64748b" size={21} />
- </Pressable>
- <View style={styles.settingsHeaderTitle}>
- {activeTab ? activeTabItem?.icon : <UserRound color="#047857" size={17} />}
- <Text numberOfLines={1} style={styles.settingsTitle}>{title}</Text>
- </View>
- <Pressable
- accessibilityLabel={resolvedTheme === "dark" ? "切换到浅色模式" : "切换到深色模式"}
- accessibilityRole="button"
- onPress={toggleTheme}
- style={styles.settingsThemeButton}
- >
- {resolvedTheme === "dark" ? <Sun color="#64748b" size={19} /> : <Moon color="#64748b" size={19} />}
- <Text numberOfLines={1} style={styles.settingsThemeText}>{resolvedTheme === "dark" ? "切换到浅色模式" : "切换到深色模式"}</Text>
- </Pressable>
- </View>
- <ScrollView contentContainerStyle={styles.settingsScrollContent} style={styles.viewBody}>
- {activeTab === null ? (
- <View style={styles.settingsDetailList}>
- <View style={styles.settingsMenu}>
- {tabs.map((tab, index) => (
- <Pressable key={tab.key} onPress={() => setActiveTab(tab.key)} style={[styles.settingsMenuRow, index > 0 && styles.settingsMenuRowBorder]}>
- <View style={styles.settingsMenuLabel}>
- <View style={styles.settingsMenuIcon}>{tab.icon}</View>
- <Text style={styles.settingsMenuText}>{tab.label}</Text>
- </View>
- <ChevronRight color="#94a3b8" size={17} />
- </Pressable>
- ))}
- </View>
- <View style={styles.settingsMenu}>
- <Pressable accessibilityRole="button" onPress={() => setActiveTab("system")} style={styles.settingsMenuRow}>
- <View style={styles.settingsMenuLabel}>
- <View style={styles.settingsMenuIcon}><Info color="#059669" size={17} /></View>
- <View style={styles.settingsFeedbackCopy}>
- <Text style={styles.settingsMenuText}>{systemInfoCopy.title}</Text>
- <Text style={styles.settingsFeedbackDescription}>{systemInfoCopy.description}</Text>
- </View>
- </View>
- <ChevronRight color="#94a3b8" size={17} />
- </Pressable>
- <Pressable accessibilityRole="link" onPress={openFeedback} style={[styles.settingsMenuRow, styles.settingsMenuRowBorder]}>
- <View style={styles.settingsMenuLabel}>
- <View style={[styles.settingsMenuIcon, styles.settingsFeedbackIcon]}><MessageSquare color="#64748b" size={17} /></View>
- <View style={styles.settingsFeedbackCopy}>
- <Text style={styles.settingsMenuText}>意见反馈</Text>
- <Text style={styles.settingsFeedbackDescription}>报告问题或提出功能建议</Text>
- </View>
- </View>
- <ExternalLink color="#94a3b8" size={17} />
- </Pressable>
- </View>
- </View>
- ) : renderContent()}
- </ScrollView>
- <Modal animationType="fade" onRequestClose={() => setLocalePickerOpen(false)} statusBarTranslucent transparent visible={localePickerOpen && Boolean(localePickerAnchor)}>
- <Pressable onPress={() => setLocalePickerOpen(false)} style={styles.localePickerBackdrop}>
- {localePickerAnchor ? (
- <View style={[styles.localePickerMenu, localePickerAnchor]}>
- {MOBILE_LOCALE_OPTIONS.map((option) => {
- const active = localePreference === option.value;
- return (
- <Pressable
- accessibilityRole="radio"
- accessibilityState={{ checked: active }}
- key={option.value}
- onPress={() => {
- onLocalePreferenceChange(option.value);
- setLocalePickerOpen(false);
- }}
- style={[styles.localePickerOption, active && styles.localePickerOptionActive]}
- >
- <Text style={[styles.localePickerOptionText, active && styles.localePickerOptionTextActive]}>{option.label}</Text>
- {active ? <Check color="#047857" size={16} /> : null}
- </Pressable>
- );
- })}
- </View>
- ) : null}
- </Pressable>
- </Modal>
- </View>
- );
-};
-
-const SettingsGroup = ({ children, icon, title }: { children: ReactNode; icon?: ReactNode; title?: string }) => (
- <View style={styles.settingsGroup}>
- {title ? <View style={styles.settingsGroupHeader}>{icon}<Text style={styles.settingsGroupTitle}>{title}</Text></View> : null}
- {children}
- </View>
-);
-
const CreateMemoModal = ({
baseUrl,
dataScope,
@@ -2543,75 +1974,6 @@ const CreateMemoModal = ({
);
};
-const SystemInfoCard = ({ defaultExpanded = false }: { defaultExpanded?: boolean }) => {
- const [copied, setCopied] = useState(false);
- const [expanded, setExpanded] = useState(defaultExpanded);
- const { checkForUpdate, hasUpdate, status } = useMobileUpdate();
- const localePreference = useMobileLocalePreference();
- const copy = getMobileSystemInfoText(localePreference);
- const infoItems = getMobileSystemInfoItems(localePreference);
-
- const copySystemInfo = async () => {
- await Clipboard.setStringAsync(infoItems.map((item) => `${item.label}: ${item.value}`).join("\n"));
- setCopied(true);
- setTimeout(() => setCopied(false), 1600);
- };
-
- return (
- <View style={styles.settingsGroup}>
- <Pressable accessibilityState={{ expanded }} onPress={() => setExpanded((value) => !value)} style={styles.settingsAccordionHeader}>
- <View style={styles.settingsLinkCopy}>
- <View style={styles.settingsGroupHeader}>
- <Info color="#047857" size={16} />
- <Text style={styles.settingsGroupTitle}>{copy.title}</Text>
- {hasUpdate ? <View accessibilityLabel="有新版本" style={styles.updateDot} /> : null}
- </View>
- <Text style={styles.settingsLinkDescription}>{copy.description}</Text>
- </View>
- {expanded ? <ChevronDown color="#94a3b8" size={17} /> : <ChevronRight color="#94a3b8" size={17} />}
- </Pressable>
- {expanded ? (
- <View style={styles.settingsAccordionContent}>
- <ActionButton label={copied ? "已复制" : "复制信息"} onPress={copySystemInfo}>
- {copied ? <ShieldCheck color="#047857" size={16} /> : <Copy color="#0f172a" size={16} />}
- </ActionButton>
- <ActionButton
- disabled={status === "checking"}
- label={status === "checking" ? "正在检查…" : hasUpdate ? "发现新版本" : "检查更新"}
- onPress={() => void checkForUpdate()}
- >
- {status === "checking" ? <ActivityIndicator color="#047857" size="small" /> : <RefreshCw color="#047857" size={16} />}
- </ActionButton>
- <View style={styles.systemInfoRows}>
- {Array.from({ length: Math.ceil(infoItems.length / 3) }, (_, rowIndex) => {
- const rowItems = infoItems.slice(rowIndex * 3, rowIndex * 3 + 3);
-
- return (
- <View
- key={`system-info-row-${rowIndex}`}
- style={[styles.systemInfoRow, rowIndex === Math.ceil(infoItems.length / 3) - 1 && styles.systemInfoRowLast]}
- >
- {rowItems.map((item, itemIndex) => (
- <View
- key={item.label}
- style={[styles.systemInfoCell, itemIndex < rowItems.length - 1 && styles.systemInfoCellDivider]}
- >
- <Text numberOfLines={1} style={styles.panelLabel}>{item.label}</Text>
- <Text numberOfLines={1} selectable style={styles.systemInfoListValue}>
- {item.value}
- </Text>
- </View>
- ))}
- </View>
- );
- })}
- </View>
- </View>
- ) : null}
- </View>
- );
-};
-
const RevisionHistoryModal = ({
memo,
onClose,
@@ -2766,510 +2128,22 @@ const RevisionHistoryModal = ({
);
};
-const getAuthenticatedResourceSource = (
- source: string,
- session: { baseUrl: string; token: string } | null
-) => {
- const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
- const uri = source.startsWith("/") && baseUrl ? `${baseUrl}${source}` : source;
- const isProtectedResource = source.startsWith("/api/v1/resources/") || Boolean(baseUrl && uri.startsWith(`${baseUrl}/api/v1/resources/`));
-
- return {
- uri,
- ...(session?.token && isProtectedResource ? { headers: { Authorization: `Bearer ${session.token}` } } : {}),
- };
-};
-
-type CachedSvgResource = {
- aspectRatio: number | null;
- xml: string;
-};
-
-const AUTHENTICATED_SVG_CACHE_LIMIT = 24;
-const authenticatedSvgCache = new Map<string, Promise<CachedSvgResource | null>>();
-const getAuthenticatedSvgCacheKey = (source: ReturnType<typeof getAuthenticatedResourceSource>) =>
- `${source.uri}\n${source.headers?.Authorization ?? ""}`;
-const loadAuthenticatedSvg = (source: ReturnType<typeof getAuthenticatedResourceSource>) => {
- const cacheKey = getAuthenticatedSvgCacheKey(source);
- const cached = authenticatedSvgCache.get(cacheKey);
- if (cached) {
- return cached;
- }
- if (authenticatedSvgCache.size >= AUTHENTICATED_SVG_CACHE_LIMIT) {
- const oldestKey = authenticatedSvgCache.keys().next().value;
- if (oldestKey) {
- authenticatedSvgCache.delete(oldestKey);
- }
- }
- const pending = fetch(source.uri, { headers: source.headers })
- .then(async (response) => {
- if (!response.ok) {
- throw new Error(`Resource request failed with ${response.status}`);
- }
- if (!response.headers.get("Content-Type")?.toLowerCase().includes("svg")) {
- return null;
- }
- const xml = await response.text();
- const viewBox = xml.match(/viewBox=["']\s*[\d.-]+\s+[\d.-]+\s+([\d.]+)\s+([\d.]+)\s*["']/i);
- const width = Number(viewBox?.[1]);
- const height = Number(viewBox?.[2]);
- return {
- aspectRatio: width > 0 && height > 0 ? width / height : null,
- xml,
- };
- })
- .catch(() => {
- authenticatedSvgCache.delete(cacheKey);
- return null;
- });
- authenticatedSvgCache.set(cacheKey, pending);
- return pending;
-};
-
-const AuthenticatedResourceImage = ({
- alt,
- fitAspect = false,
- resizeMode = "cover",
- source,
- style,
+const RichEditorModal = ({
+ baseUrl,
+ initialDraft,
+ imageCompressionEnabled,
+ memo,
+ notebooks,
+ onClose,
+ updateMutation,
}: {
- alt: string;
- fitAspect?: boolean;
- resizeMode?: "center" | "contain" | "cover" | "repeat" | "stretch";
- source: ReturnType<typeof getAuthenticatedResourceSource>;
- style: StyleProp<ImageStyle>;
-}) => {
- const [aspectRatio, setAspectRatio] = useState(16 / 9);
- const [svgXml, setSvgXml] = useState<string | null>(null);
- const svgRequestStartedRef = useRef(false);
- const svgSourceKeyRef = useRef("");
- const svgSourceKey = getAuthenticatedSvgCacheKey(source);
- const imageStyle = fitAspect ? [style, { aspectRatio, height: undefined, width: "100%" as const }] : style;
-
- useEffect(() => {
- setSvgXml(null);
- setAspectRatio(16 / 9);
- svgRequestStartedRef.current = false;
- svgSourceKeyRef.current = svgSourceKey;
- const cached = authenticatedSvgCache.get(svgSourceKey);
- if (cached) {
- svgRequestStartedRef.current = true;
- void cached.then((result) => {
- if (!result || svgSourceKeyRef.current !== svgSourceKey) {
- return;
- }
- if (result.aspectRatio) {
- setAspectRatio(result.aspectRatio);
- }
- setSvgXml(result.xml);
- });
- }
- return () => {
- if (svgSourceKeyRef.current === svgSourceKey) {
- svgSourceKeyRef.current = "";
- }
- };
- }, [svgSourceKey]);
-
- const loadSvgFallback = () => {
- if (svgRequestStartedRef.current) {
- return;
- }
- svgRequestStartedRef.current = true;
- void loadAuthenticatedSvg(source)
- .then((result) => {
- if (!result || svgSourceKeyRef.current !== svgSourceKey) {
- return;
- }
- if (result.aspectRatio) {
- setAspectRatio(result.aspectRatio);
- }
- setSvgXml(result.xml);
- });
- };
-
- if (svgXml) {
- return (
- <View accessibilityLabel={alt || undefined} accessible={Boolean(alt)} style={imageStyle}>
- <SvgXml height="100%" width="100%" xml={svgXml} />
- </View>
- );
- }
-
- return (
- <RNImage
- accessibilityLabel={alt || undefined}
- accessible={Boolean(alt)}
- fadeDuration={Platform.OS === "android" ? 0 : undefined}
- onLoad={(event) => {
- const { height, width } = event.nativeEvent.source;
- if (height > 0 && width > 0) {
- setAspectRatio(width / height);
- }
- }}
- onError={loadSvgFallback}
- resizeMethod={Platform.OS === "android" ? "resize" : "auto"}
- resizeMode={resizeMode}
- source={source}
- style={imageStyle}
- />
- );
-};
-
-const MemoDetailModal = ({
- isDeleting,
- isLoading,
- isRestoring,
- isSaving,
- memo,
- notebookName,
- onClose,
- onDelete,
- onRichEdit,
- onOpenRevisions,
- onResolveSyncConflict,
- onRestore,
- syncStatus,
- visible,
-}: {
- isDeleting: boolean;
- isLoading: boolean;
- isRestoring: boolean;
- isSaving: boolean;
- memo: MemoDetail | null;
- notebookName: string;
- onClose: () => void;
- onDelete: (memo: MemoDetail) => void;
- onRichEdit: (memo: MemoDetail) => void;
- onOpenRevisions: (memo: MemoDetail) => void;
- onResolveSyncConflict: (memo: MemoDetail) => void;
- onRestore: (memo: MemoDetail) => void;
- syncStatus: MobileSyncQueueItem["status"] | null;
- visible: boolean;
-}) => {
- const { session } = useSession();
- const { resolvedTheme } = useMobileTheme();
- const { resolvedLocale } = useMobileLocale();
- const { width: viewportWidth } = useWindowDimensions();
- const safeAreaInsets = useSafeAreaInsets();
- const [actionsOpen, setActionsOpen] = useState(false);
- const [searchOpen, setSearchOpen] = useState(false);
- const [searchQuery, setSearchQuery] = useState("");
- const [activeMatchIndex, setActiveMatchIndex] = useState(0);
- const localePreference = useMobileLocalePreference();
- const themedDetailMarkdownStyles = useMemo(
- () => resolveMobileThemeStyles(detailMarkdownStyles, resolvedTheme),
- [resolvedTheme]
- );
- const detailMarkdownRules = useMemo<RenderRules>(() => {
- const availableTableWidth = Math.max(0, viewportWidth - DETAIL_CONTENT_HORIZONTAL_PADDING * 2);
- const getTableColumnCount = (node: ASTNode, parents: ASTNode[]) => {
- const table = node.type === "table" ? node : parents.find((parent) => parent.type === "table");
- const tableSection = table?.children.find((child) => child.type === "thead" || child.type === "tbody");
- const firstRow = tableSection?.children.find((child) => child.type === "tr");
- return Math.max(1, firstRow?.children.filter((child) => child.type === "th" || child.type === "td").length ?? 1);
- };
- const renderTableCell = (node: ASTNode, children: ReactNode[], parents: ASTNode[], markdownStyles: Record<string, StyleProp<ViewStyle>>, isHeader: boolean) => {
- const columnCount = getTableColumnCount(node, parents);
- const row = parents.find((parent) => parent.type === "tr");
- const cellIndex = row?.children.findIndex((child) => child.key === node.key) ?? -1;
- const isLastCell = cellIndex === (row?.children.length ?? 0) - 1;
- const wideCellStyle = columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT
- ? { flex: 0, width: DETAIL_TABLE_MIN_COLUMN_WIDTH }
- : undefined;
-
- return (
- <View
- key={node.key}
- style={[
- markdownStyles[isHeader ? "_VIEW_SAFE_th" : "_VIEW_SAFE_td"],
- wideCellStyle,
- !isLastCell && markdownStyles._VIEW_SAFE_tableCellDivider,
- ]}
- >
- {children}
- </View>
- );
- };
-
- return {
- fence: (node, _children, _parents, markdownStyles, inheritedStyles = {}) => {
- const language = getMobileMarkdownFenceLanguage((node as ASTNode & { sourceInfo?: string }).sourceInfo);
- const content = trimMobileMarkdownFenceContent(node.content);
- if (language === "mermaid") {
- return (
- <MobileMermaidDiagram
- key={node.key}
- locale={resolvedLocale}
- source={content}
- theme={resolvedTheme}
- />
- );
- }
- return <RNText key={node.key} style={[inheritedStyles, markdownStyles.fence]}>{content}</RNText>;
- },
- image: (node, _children, _parents, markdownStyles) => (
- <AuthenticatedResourceImage
- alt={String(node.attributes.alt ?? "")}
- fitAspect
- key={node.key}
- resizeMode="contain"
- source={getAuthenticatedResourceSource(String(node.attributes.src ?? ""), session)}
- style={markdownStyles._VIEW_SAFE_image}
- />
- ),
- table: (node, children, parents, markdownStyles) => {
- const columnCount = getTableColumnCount(node, parents);
- const tableWidth = columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT
- ? columnCount * DETAIL_TABLE_MIN_COLUMN_WIDTH
- : availableTableWidth;
-
- return (
- <ScrollView
- contentContainerStyle={markdownStyles._VIEW_SAFE_tableScrollContent}
- horizontal
- key={node.key}
- nestedScrollEnabled
- showsHorizontalScrollIndicator={columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT}
- style={markdownStyles._VIEW_SAFE_tableScroll}
- >
- <View style={[markdownStyles._VIEW_SAFE_table, { width: tableWidth }]}>{children}</View>
- </ScrollView>
- );
- },
- td: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, false),
- th: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, true),
- };
- }, [resolvedLocale, resolvedTheme, session, viewportWidth]);
- 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 syncStatusLabel = isSaving || syncStatus === "syncing"
- ? "保存中"
- : syncStatus === "conflict"
- ? "同步冲突"
- : syncStatus === "error"
- ? "同步失败"
- : syncStatus === "pending"
- ? "待同步"
- : "已同步";
- const editFabBottom = Math.max(
- safeAreaInsets.bottom,
- Platform.OS === "android" ? ANDROID_SYSTEM_NAVIGATION_FALLBACK : 0
- ) + 16;
-
- useEffect(() => {
- setActiveMatchIndex(0);
- }, [detailText, searchQuery]);
-
- const moveSearchMatch = (direction: 1 | -1) => {
- if (searchMatches.length === 0) {
- return;
- }
-
- setActiveMatchIndex((current) => (current + direction + searchMatches.length) % searchMatches.length);
- };
-
- const closeActionsAndRun = (action: () => void) => {
- setActionsOpen(false);
- action();
- };
-
- return (
- <Modal animationType="slide" onRequestClose={onClose} presentationStyle="fullScreen" visible={visible}>
- <SafeAreaView style={styles.modalSafeArea}>
- <View style={styles.detailHeader}>
- <Pressable accessibilityLabel="返回列表" accessibilityRole="button" onPress={onClose} style={styles.detailHeaderButton}>
- <ChevronLeft color="#475569" size={21} />
- </Pressable>
- <View style={styles.detailHeaderActions}>
- <Pressable
- accessibilityHint={syncStatus === "conflict" ? "查看并处理同步冲突" : undefined}
- accessibilityLabel={syncStatusLabel}
- accessibilityRole={syncStatus === "conflict" ? "button" : "text"}
- disabled={syncStatus !== "conflict" || !memo}
- onPress={() => memo && onResolveSyncConflict(memo)}
- >
- <Text
- numberOfLines={1}
- style={[styles.detailSyncStatus, syncStatus === "conflict" && styles.detailSyncStatusConflict]}
- >
- {syncStatusLabel}
- </Text>
- </Pressable>
- {memo && !memo.isDeleted ? (
- <Pressable
- accessibilityLabel="版本历史"
- accessibilityRole="button"
- onPress={() => onOpenRevisions(memo)}
- style={styles.detailHeaderIconButton}
- >
- <History color="#475569" size={20} />
- </Pressable>
- ) : null}
- {memo?.isDeleted ? (
- <Pressable accessibilityLabel="笔记操作" accessibilityRole="button" onPress={() => setActionsOpen(true)} style={styles.detailHeaderIconButton}>
- <MoreHorizontal color="#475569" size={21} />
- </Pressable>
- ) : null}
- </View>
- </View>
-
- {isLoading ? (
- <View style={styles.centerState}>
- <ActivityIndicator color="#0f172a" />
- </View>
- ) : memo ? (
- <ScrollView contentContainerStyle={styles.detailContent}>
- <Text style={styles.detailTitle}>{memo.title?.trim() || DEFAULT_MEMO_TITLE}</Text>
- <View style={styles.detailMetaRow}>
- <View style={styles.detailNotebookButton}>
- <Text numberOfLines={1} style={styles.detailNotebookName}>{notebookName}</Text>
- <ChevronDown color="#94a3b8" size={14} />
- </View>
- <View style={styles.detailTagsGroup}>
- <Tag color="#64748b" size={16} />
- <Text
- numberOfLines={1}
- style={[styles.detailTagsInline, memo.tags.length === 0 && styles.detailTagsPlaceholder]}
- >
- {memo.tags.length ? memo.tags.join(", ") : "添加标签,用逗号分隔"}
- </Text>
- </View>
- </View>
- {searchOpen ? (
- <View style={styles.noteSearchPanel}>
- <View style={styles.searchBox}>
- <Search color="#64748b" size={18} />
- <TextInput
- accessibilityLabel="在当前笔记内搜索"
- autoCapitalize="none"
- autoCorrect={false}
- onChangeText={setSearchQuery}
- placeholder="在当前笔记内搜索"
- placeholderTextColor="#94a3b8"
- style={styles.searchInput}
- value={searchQuery}
- />
- <Text style={[styles.noteSearchCount, searchQuery.trim() && searchMatches.length === 0 && styles.noteSearchCountEmpty]}>{searchMatchLabel}</Text>
- </View>
- <View style={styles.richEditorSearchActions}>
- <ActionButton disabled={searchMatches.length === 0} label="上一个搜索结果" onPress={() => moveSearchMatch(-1)}>
- <ChevronLeft color={searchMatches.length === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
- </ActionButton>
- <ActionButton disabled={searchMatches.length === 0} label="下一个搜索结果" onPress={() => moveSearchMatch(1)}>
- <ChevronRight color={searchMatches.length === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
- </ActionButton>
- <ActionButton label="关闭搜索" onPress={() => {
- setSearchOpen(false);
- setSearchQuery("");
- }}>
- <X color="#0f172a" size={16} />
- </ActionButton>
- </View>
- </View>
- ) : null}
- <View style={styles.detailDivider} />
- {searchOpen && searchQuery.trim() ? (
- <HighlightedDetailText activeIndex={activeMatchIndex} matches={searchMatches} text={detailText} />
- ) : (
- <MobileMermaidProvider theme={resolvedTheme}>
- <Markdown rules={detailMarkdownRules} style={themedDetailMarkdownStyles}>{detailText}</Markdown>
- </MobileMermaidProvider>
- )}
- </ScrollView>
- ) : (
- <View style={styles.centerState}>
- <Text style={styles.errorText}>笔记加载失败</Text>
- </View>
- )}
- {memo && !memo.isDeleted ? (
- <Pressable
- accessibilityLabel="编辑笔记"
- accessibilityRole="button"
- onPress={() => {
- beginEditorStartup();
- onRichEdit(memo);
- }}
- style={[styles.detailEditFab, { bottom: editFabBottom }]}
- >
- <Pencil color="#ffffff" size={20} />
- </Pressable>
- ) : null}
- {memo?.isDeleted ? (
- <Modal animationType="fade" onRequestClose={() => setActionsOpen(false)} transparent visible={actionsOpen}>
- <Pressable onPress={() => setActionsOpen(false)} style={styles.actionSheetBackdrop}>
- <Pressable style={styles.actionSheet}>
- <View style={styles.actionSheetHandle} />
- <Text style={styles.actionSheetTitle}>笔记操作</Text>
- <ActionSheetItem icon={<Search color="#0f172a" size={18} />} label="搜索当前笔记" onPress={() => closeActionsAndRun(() => {
- setSearchOpen(true);
- })} />
- <ActionSheetItem icon={<History color="#0f172a" size={18} />} label="版本历史" onPress={() => closeActionsAndRun(() => onOpenRevisions(memo))} />
- <ActionSheetItem disabled={isRestoring} icon={<RotateCcw color="#0f172a" size={18} />} label={isRestoring ? "恢复中" : "恢复笔记"} onPress={() => closeActionsAndRun(() => onRestore(memo))} />
- <View style={styles.listActionDivider} />
- <ActionSheetItem danger disabled={isDeleting} icon={<Trash2 color="#b91c1c" size={18} />} label={isDeleting ? "删除中" : "彻底删除"} onPress={() => closeActionsAndRun(() => onDelete(memo))} />
- </Pressable>
- </Pressable>
- </Modal>
- ) : null}
- </SafeAreaView>
- </Modal>
- );
-};
-
-const HighlightedDetailText = ({
- activeIndex,
- matches,
- text,
-}: {
- activeIndex: number;
- matches: Array<{ end: number; start: number }>;
- text: string;
-}) => {
- if (matches.length === 0) {
- return <Text style={styles.detailMarkdown}>{text}</Text>;
- }
-
- const segments: ReactNode[] = [];
- let cursor = 0;
-
- matches.forEach((match, index) => {
- if (match.start > cursor) {
- segments.push(text.slice(cursor, match.start));
- }
-
- segments.push(
- <Text key={`${match.start}-${match.end}`} style={index === activeIndex ? styles.noteSearchHighlightActive : styles.noteSearchHighlight}>
- {text.slice(match.start, match.end)}
- </Text>
- );
- cursor = match.end;
- });
-
- if (cursor < text.length) {
- segments.push(text.slice(cursor));
- }
-
- return <Text style={styles.detailMarkdown}>{segments}</Text>;
-};
-
-const RichEditorModal = ({
- baseUrl,
- initialDraft,
- imageCompressionEnabled,
- memo,
- notebooks,
- onClose,
- updateMutation,
-}: {
- baseUrl: string;
- initialDraft: MobileMemoDraft | null;
- imageCompressionEnabled: boolean;
- memo: MemoDetail | null;
- notebooks: Notebook[];
- onClose: () => void;
- updateMutation: MobileMemoUpdateMutation;
+ baseUrl: string;
+ initialDraft: MobileMemoDraft | null;
+ imageCompressionEnabled: boolean;
+ memo: MemoDetail | null;
+ notebooks: Notebook[];
+ onClose: () => void;
+ updateMutation: MobileMemoUpdateMutation;
}) => {
const { client } = useSession();
const { resolvedLocale } = useMobileLocale();
@@ -3639,162 +2513,6 @@ const RichEditorModal = ({
);
};
-const MemoList = ({
- emptyAction,
- emptyDescription,
- emptyTitle,
- error,
- isError,
- initialSyncProgress,
- isLoading,
- isLoadingMore = false,
- isRefreshing,
- listDensity,
- memos,
- onMemoLongPress,
- onMemoPress,
- onLoadMore,
- onRefresh,
- onRetry,
- selectionMode = false,
- selectedMemoIds = new Set(),
-}: {
- emptyAction?: { label: string; onPress: () => void };
- emptyDescription: string;
- emptyTitle: string;
- error?: unknown;
- isError: boolean;
- initialSyncProgress: MobileBootstrapProgress | null;
- isLoading: boolean;
- isLoadingMore?: boolean;
- isRefreshing: boolean;
- listDensity: MobileMemoListDensity;
- memos: MemoSummary[];
- onMemoLongPress?: (memo: MemoSummary) => void;
- onMemoPress: (memoId: string) => void;
- onLoadMore?: () => void;
- onRefresh: () => void;
- onRetry?: () => void;
- selectionMode?: boolean;
- selectedMemoIds?: Set<string>;
-}) => {
- const localePreference = useMobileLocalePreference();
- const englishLocale = isEnglishMobileLocale(localePreference);
- const hasInitialSyncProgress = initialSyncProgress !== null;
- const loadedCount = initialSyncProgress?.loadedCount ?? 0;
- const totalCount = initialSyncProgress?.totalCount ?? 0;
- const progressPercent = totalCount > 0 ? Math.min(100, Math.round((loadedCount / totalCount) * 100)) : 0;
- const progressTitle = englishLocale ? "Syncing your notes" : "正在同步笔记";
- const progressDescription = totalCount > 0
- ? (englishLocale ? `${loadedCount} of ${totalCount} notes loaded` : `已加载 ${loadedCount} / ${totalCount} 条笔记`)
- : (englishLocale ? "Preparing your notes for the first sync…" : "正在准备首次同步…");
- const loadingTitle = hasInitialSyncProgress ? progressTitle : (englishLocale ? "Loading notes" : "正在加载笔记");
- const loadingDescription = hasInitialSyncProgress
- ? progressDescription
- : (englishLocale ? "Loading notebooks and notes…" : "正在加载笔记本和笔记…");
-
- if ((isLoading || hasInitialSyncProgress) && memos.length === 0) {
- return (
- <View accessibilityLabel={loadingTitle} accessibilityLiveRegion="polite" style={styles.memoListStateWrap}>
- <View style={styles.memoListLoadingCard}>
- <ActivityIndicator color="#059669" size="large" />
- <Text style={styles.memoListLoadingTitle}>{loadingTitle}</Text>
- <Text style={styles.memoListLoadingDescription}>{loadingDescription}</Text>
- {totalCount > 0 ? (
- <View style={styles.memoSyncProgressTrack}>
- <View style={[styles.memoSyncProgressFill, { width: `${progressPercent}%` }]} />
- </View>
- ) : null}
- </View>
- </View>
- );
- }
-
- if (isError && memos.length === 0) {
- return (
- <View style={styles.memoListStateWrap}>
- <View style={styles.memoListErrorCard}>
- <Text style={styles.memoListErrorTitle}>暂时没有拉到笔记</Text>
- <Text style={styles.memoListErrorDescription}>网络或 PWA 后台恢复可能短暂中断了同步。这里不会把它当作空笔记本。</Text>
- {onRetry ? (
- <Pressable accessibilityLabel="重试加载" accessibilityRole="button" onPress={onRetry} style={styles.memoListRetryButton}>
- <RotateCcw color="#92400e" size={17} />
- <Text style={styles.memoListRetryText}>重试</Text>
- </Pressable>
- ) : null}
- </View>
- </View>
- );
- }
-
- return (
- <FlatList
- contentContainerStyle={memos.length === 0 ? styles.emptyList : styles.list}
- data={memos}
- initialNumToRender={10}
- keyExtractor={(memo) => memo.id}
- maxToRenderPerBatch={8}
- onEndReached={onLoadMore}
- onEndReachedThreshold={0.35}
- removeClippedSubviews={Platform.OS === "android"}
- refreshControl={<RefreshControl onRefresh={onRefresh} refreshing={isRefreshing} tintColor="#0f172a" />}
- style={styles.memoList}
- renderItem={({ item }) => (
- <MemoCard
- memo={item}
- listDensity={listDensity}
- onLongPress={!selectionMode && onMemoLongPress ? () => onMemoLongPress(item) : undefined}
- onPress={() => onMemoPress(item.id)}
- selected={selectedMemoIds.has(item.id)}
- selectionMode={selectionMode}
- />
- )}
- ListEmptyComponent={
- <View style={styles.memoListEmptyCard}>
- <Text style={styles.emptyTitle}>{emptyTitle}</Text>
- <Text style={styles.mutedText}>{emptyDescription}</Text>
- {emptyAction ? (
- <Pressable accessibilityRole="button" onPress={emptyAction.onPress} style={styles.emptyActionButton}>
- <Plus color="#ffffff" size={18} />
- <Text style={styles.emptyActionButtonText}>{emptyAction.label}</Text>
- </Pressable>
- ) : null}
- </View>
- }
- ListHeaderComponent={hasInitialSyncProgress ? (
- <View accessibilityLiveRegion="polite" style={styles.memoSyncBanner}>
- <ActivityIndicator color="#059669" size="small" />
- <View style={styles.memoSyncBannerContent}>
- <Text style={styles.memoSyncBannerTitle}>{progressTitle}</Text>
- <Text style={styles.memoSyncBannerDescription}>{progressDescription}</Text>
- <View style={styles.memoSyncProgressTrack}>
- <View style={[styles.memoSyncProgressFill, { width: `${progressPercent}%` }]} />
- </View>
- </View>
- </View>
- ) : isError ? (
- <View accessibilityLiveRegion="polite" style={styles.memoSyncErrorBanner}>
- <View style={styles.memoSyncBannerContent}>
- <Text style={styles.memoSyncErrorBannerTitle}>{englishLocale ? "Sync paused" : "同步已暂停"}</Text>
- <Text style={styles.memoSyncErrorBannerDescription}>
- {englishLocale ? "Loaded notes remain available. Check your connection and retry." : "已加载的笔记仍可使用,请检查网络后重试。"}
- </Text>
- </View>
- {onRetry ? (
- <Pressable accessibilityRole="button" onPress={onRetry} style={styles.memoSyncErrorRetryButton}>
- <RotateCcw color="#92400e" size={15} />
- <Text style={styles.memoListRetryText}>{englishLocale ? "Retry" : "重试"}</Text>
- </Pressable>
- ) : null}
- </View>
- ) : null}
- ListFooterComponent={isLoadingMore ? <ActivityIndicator color="#0f172a" style={styles.listLoadingFooter} /> : null}
- updateCellsBatchingPeriod={32}
- windowSize={7}
- />
- );
-};
-
const MoveSelectionModal = ({
bottomOffset,
isMoving,
@@ -4144,110 +2862,6 @@ const OptionPill = ({ active, label, onPress }: { active: boolean; label: string
</Pressable>
);
-const MobileFilterButton = ({ active, icon, label, onPress }: { active: boolean; icon: ReactNode; label: string; onPress: () => void }) => (
- <Pressable
- accessibilityLabel={label}
- accessibilityRole="button"
- accessibilityState={{ selected: active }}
- onPress={onPress}
- style={[styles.mobileFilterButton, active && styles.mobileFilterButtonActive]}
- >
- {icon}
- </Pressable>
-);
-
-const MemoCard = memo(function MemoCard({
- listDensity,
- memo,
- onLongPress,
- onPress,
- selected = false,
- selectionMode = false,
-}: {
- listDensity: MobileMemoListDensity;
- memo: MemoSummary;
- onLongPress?: () => void;
- onPress: () => void;
- selected?: boolean;
- selectionMode?: boolean;
-}) {
- const localePreference = useMobileLocalePreference();
- const memoTitle = memo.title?.trim() || DEFAULT_MEMO_TITLE;
- const pressScale = useSharedValue(1);
- const pressAnimatedStyle = useAnimatedStyle(() => ({
- transform: [{ scale: pressScale.value }],
- }));
-
- return (
- <Animated.View
- entering={FadeInDown.duration(260).springify().damping(18)}
- exiting={FadeOutUp.duration(220)}
- layout={LinearTransition.duration(220)}
- style={[
- styles.memoCard,
- listDensity === "compact" && styles.memoCardCompact,
- selected && styles.memoCardSelected,
- pressAnimatedStyle,
- ]}
- >
- {selectionMode ? (
- <Pressable
- accessibilityLabel={`${selected ? "取消选择" : "选择"} ${memoTitle}`}
- accessibilityRole="button"
- accessibilityState={{ selected }}
- onPress={onPress}
- style={styles.memoSelectionButton}
- >
- <View style={[styles.selectionIndicator, selected && styles.selectionIndicatorActive]}>
- {selected ? <Check color="#ffffff" size={14} /> : null}
- </View>
- </Pressable>
- ) : null}
- <Pressable
- accessibilityLabel={memoTitle}
- accessibilityRole="button"
- delayLongPress={520}
- onLongPress={onLongPress}
- onPress={onPress}
- onPressIn={() => {
- pressScale.value = withTiming(0.985, { duration: 100 });
- }}
- onPressOut={() => {
- pressScale.value = withTiming(1, { duration: 160 });
- }}
- style={[styles.memoCardContent, listDensity === "compact" && styles.memoCardContentCompact, selectionMode && styles.memoCardContentWithSelection]}
- >
- <View style={styles.memoCardTop}>
- {memo.isPinned ? (
- <Text accessibilityElementsHidden importantForAccessibility="no-hide-descendants" style={styles.memoPinnedStar}>★</Text>
- ) : null}
- <Text numberOfLines={1} style={styles.memoTitle}>
- {memoTitle}
- </Text>
- </View>
- {listDensity === "preview" ? (
- <Text numberOfLines={2} style={styles.memoExcerpt}>
- {memo.excerpt || "空笔记"}
- </Text>
- ) : null}
- <View style={[styles.memoMeta, listDensity === "compact" && styles.memoMetaCompact]}>
- <Text style={styles.memoDate}>{formatMemoPreviewDate(memo.updatedAt, localePreference)}</Text>
- {memo.tags.slice(0, 3).map((tag) => (
- <Text key={tag} style={styles.tag}>
- #{tag}
- </Text>
- ))}
- </View>
- </Pressable>
- </Animated.View>
- );
-}, (previous, next) =>
- previous.memo === next.memo &&
- previous.listDensity === next.listDensity &&
- previous.selected === next.selected &&
- previous.selectionMode === next.selectionMode
-);
-
const PanelRow = ({ label, value }: { label: string; value: string }) => (
<View style={styles.panelRow}>
<Text style={styles.panelLabel}>{label}</Text>
@@ -4308,259 +2922,6 @@ const CreateMemoToolbarButton = ({
</Pressable>
);
-const parseTags = (value: string) =>
- Array.from(
- new Set(
- value
- .split(/[,,\n]/)
- .map((tag) => tag.trim())
- .filter(Boolean)
- )
- );
-
-const useDebouncedValue = <T,>(value: T, delay: number) => {
- const [debouncedValue, setDebouncedValue] = useState(value);
-
- useEffect(() => {
- const timeout = setTimeout(() => setDebouncedValue(value), delay);
- return () => clearTimeout(timeout);
- }, [delay, value]);
-
- return debouncedValue;
-};
-
-const flattenNotebooks = (notebooks: Notebook[]) => {
- const byParent = new Map<string | null, Notebook[]>();
- const byId = new Set(notebooks.map((notebook) => notebook.id));
- const result: NotebookOption[] = [];
-
- for (const notebook of notebooks) {
- const parentId = notebook.parentId && byId.has(notebook.parentId) ? notebook.parentId : null;
- const siblings = byParent.get(parentId) ?? [];
- siblings.push(notebook);
- byParent.set(parentId, siblings);
- }
-
- for (const siblings of byParent.values()) {
- siblings.sort(compareNotebooksManual);
- }
-
- const walk = (parentId: string | null, depth: number) => {
- for (const notebook of byParent.get(parentId) ?? []) {
- result.push({ notebook, depth });
- walk(notebook.id, depth + 1);
- }
- };
-
- walk(null, 0);
- return result;
-};
-
-const compareNotebooksManual = (left: Notebook, right: Notebook) =>
- left.sortOrder - right.sortOrder || left.name.localeCompare(right.name, "zh-CN") || left.id.localeCompare(right.id);
-
-const filterNotebookOptions = (options: NotebookOption[], searchText: string) => {
- const query = searchText.trim().toLowerCase();
-
- if (!query) {
- return options;
- }
-
- 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>();
-
- for (const notebook of notebooks) {
- if (notebook.parentId && notebookIds.has(notebook.parentId)) {
- parentIds.add(notebook.parentId);
- }
- }
-
- return parentIds;
-};
-
-const getNotebookAncestorIds = (notebooks: Notebook[], notebookId: string) => {
- const byId = new Map(notebooks.map((notebook) => [notebook.id, notebook]));
- const ancestorIds = new Set<string>();
- let current = byId.get(notebookId);
-
- while (current?.parentId) {
- if (ancestorIds.has(current.parentId)) {
- break;
- }
- ancestorIds.add(current.parentId);
- current = byId.get(current.parentId);
- }
-
- return ancestorIds;
-};
-
-const filterCollapsedNotebookOptions = (options: NotebookOption[], collapsedNotebookIds: Set<string>) => {
- if (collapsedNotebookIds.size === 0) {
- return options;
- }
-
- const visibleOptions: NotebookOption[] = [];
- let hiddenDepth: number | null = null;
-
- for (const option of options) {
- if (hiddenDepth !== null && option.depth > hiddenDepth) {
- continue;
- }
-
- hiddenDepth = null;
- visibleOptions.push(option);
-
- if (collapsedNotebookIds.has(option.notebook.id)) {
- hiddenDepth = option.depth;
- }
- }
-
- return visibleOptions;
-};
-
-const isNotebookDescendant = (notebooks: Notebook[], candidateNotebookId: string, ancestorNotebookId: string) => {
- let current = notebooks.find((notebook) => notebook.id === candidateNotebookId) ?? null;
-
- while (current?.parentId) {
- if (current.parentId === ancestorNotebookId) {
- return true;
- }
-
- current = notebooks.find((notebook) => notebook.id === current?.parentId) ?? null;
- }
-
- return false;
-};
-
-const getResolvedMobileLocale = (localePreference: MobileLocaleMode) =>
- localePreference === "system" ? Intl.DateTimeFormat().resolvedOptions().locale || "zh-CN" : localePreference;
-
-const isEnglishMobileLocale = (localePreference: MobileLocaleMode) => getResolvedMobileLocale(localePreference).startsWith("en");
-
-const getMobileSystemInfoText = (localePreference: MobileLocaleMode) =>
- isEnglishMobileLocale(localePreference)
- ? {
- appIdentifier: "App identifier",
- build: "Build",
- client: "Client",
- description: "View the current app version, build identifier, and runtime environment.",
- disconnected: "Disconnected",
- followSystem: "Follow system",
- installMode: "Mode",
- instanceUrl: "Instance URL",
- language: "Language",
- memoCount: "Notes",
- notSet: "Not set",
- notebookCount: "Notebooks",
- platform: "System",
- mobileApp: "Mobile app",
- platformVersion: "System version",
- timeZone: "Time zone",
- title: "System info",
- unknown: "Unknown",
- version: "Version",
- }
- : {
- appIdentifier: "应用标识",
- build: "构建",
- client: "客户端",
- description: "查看当前应用版本、构建标识和运行环境。",
- disconnected: "未连接",
- followSystem: "跟随系统",
- installMode: "安装形态",
- instanceUrl: "实例地址",
- language: "语言",
- memoCount: "笔记总数",
- notSet: "未设置",
- notebookCount: "笔记本数量",
- platform: "系统",
- mobileApp: "移动应用",
- platformVersion: "系统版本",
- timeZone: "时区",
- title: "系统信息",
- unknown: "未知",
- version: "版本",
- };
-
-const getMobileSystemInfoItems = (localePreference: MobileLocaleMode) => {
- const copy = getMobileSystemInfoText(localePreference);
- const resolvedLocale = getResolvedMobileLocale(localePreference);
- const platformName =
- Platform.OS === "android"
- ? "Android"
- : Platform.OS === "ios"
- ? "iOS"
- : Platform.OS === "macos"
- ? "macOS"
- : Platform.OS === "windows"
- ? "Windows"
- : Platform.OS;
-
- return [
- { label: copy.version, value: `v${MOBILE_APP_VERSION}` },
- { label: copy.build, value: __DEV__ ? "development" : "production" },
- { label: copy.client, value: copy.mobileApp },
- { label: copy.platform, value: platformName },
- { label: copy.platformVersion, value: String(Platform.Version) },
- { label: copy.language, value: localePreference === "system" ? `${resolvedLocale} (${copy.followSystem})` : resolvedLocale },
- { label: copy.timeZone, value: Intl.DateTimeFormat().resolvedOptions().timeZone || copy.unknown },
- { label: copy.installMode, value: formatExecutionEnvironment(Constants.executionEnvironment, localePreference) },
- ];
-};
-
-const buildMobileFeedbackUrl = (localePreference: MobileLocaleMode) => {
- const english = isEnglishMobileLocale(localePreference);
-
- return buildGitHubFeedbackUrl({
- contentHeading: english ? "Feedback" : "反馈内容",
- contentPrompt: english
- ? "Describe the problem, steps to reproduce it, or the feature you would like to see."
- : "请描述遇到的问题、复现步骤,或你希望增加的功能。",
- privacyNotice: english
- ? "GitHub Issues are public. Do not include passwords, tokens, instance URLs, or private note content."
- : "GitHub Issue 公开可见,请勿提交密码、Token、实例地址或私人笔记内容。",
- systemInfo: getMobileSystemInfoItems(localePreference),
- systemInfoHeading: english ? "System information" : "系统信息",
- systemInfoNotice: english
- ? "The following information was generated by EdgeEver to help diagnose the issue."
- : "以下信息由 EdgeEver 自动生成,可帮助定位问题。",
- titlePrefix: english ? "[Feedback] " : "[反馈] ",
- });
-};
-
-const formatDate = (value: string, localePreference: MobileLocaleMode = "system") =>
- new Intl.DateTimeFormat(getResolvedMobileLocale(localePreference), {
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- }).format(new Date(value));
-
-const formatMemoPreviewDate = (value: string, localePreference: MobileLocaleMode = "system") => {
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) {
- return "";
- }
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
- const memoDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
- const locale = getResolvedMobileLocale(localePreference);
- if (memoDay === today) {
- return new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }).format(date);
- }
- if (memoDay === today - 24 * 60 * 60 * 1000) {
- return isEnglishMobileLocale(localePreference) ? "Yesterday" : "昨天";
- }
- return new Intl.DateTimeFormat(locale, { year: "numeric", month: "numeric", day: "numeric" }).format(date);
-};
-
const blobToDataUrl = (blob: Blob) => new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(reader.error ?? new Error("资源读取失败"));
@@ -4597,2235 +2958,3 @@ const appendResourceMarkdown = (
return trimmed ? `${trimmed}\n\n${markdown}\n` : `${markdown}\n`;
};
-
-const createOptimisticMemo = (
- memo: MemoDetail,
- payload: MobileMemoUpdatePayload
-): MemoDetail => {
- const contentMarkdown = payload.contentMarkdown ?? memo.contentMarkdown;
- const contentText = markdownToLocalText(contentMarkdown);
-
- return {
- ...memo,
- ...(payload.title !== undefined ? { title: payload.title } : {}),
- ...(payload.isPinned !== undefined ? { isPinned: payload.isPinned } : {}),
- ...(payload.notebookId !== undefined ? { notebookId: payload.notebookId } : {}),
- ...(payload.tags !== undefined ? { tags: payload.tags } : {}),
- ...(payload.contentJson !== undefined ? { contentJson: payload.contentJson } : {}),
- ...(payload.contentMarkdown !== undefined
- ? {
- contentMarkdown,
- contentText,
- excerpt: contentText.slice(0, 180),
- }
- : {}),
- updatedAt: new Date().toISOString(),
- };
-};
-
-const applyOptimisticMemoToCache = (queryClient: QueryClient, previousMemo: MemoDetail, nextMemo: MemoDetail) => {
- const detailQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "memo"] });
-
- for (const query of detailQueries) {
- const data = query.state.data as { memo?: MemoDetail } | undefined;
- if (data?.memo?.id === nextMemo.id || data?.memo?.id === previousMemo.id) {
- queryClient.setQueryData(query.queryKey, { ...data, memo: nextMemo });
- }
- }
-
- const listQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "memos"] });
-
- for (const query of listQueries) {
- const data = query.state.data as InfiniteData<Awaited<ReturnType<typeof listLocalMemos>>, number> | undefined;
- if (!Array.isArray(data?.pages) || data.pages.length === 0) {
- continue;
- }
-
- const previouslyMatched = memoMatchesListQuery(previousMemo, query.queryKey);
- const nextMatches = memoMatchesListQuery(nextMemo, query.queryKey);
- const flattened = data.pages.flatMap((page) => page.memos);
- const withoutMemo = flattened.filter((memo) => memo.id !== nextMemo.id && memo.id !== previousMemo.id);
- const nextMemos = nextMatches ? sortMemoSummaries([nextMemo, ...withoutMemo], query.queryKey[5]) : withoutMemo;
- const totalCount = Math.max(0, data.pages[0].totalCount + (nextMatches ? 1 : 0) - (previouslyMatched ? 1 : 0));
- let cursor = 0;
- const pages = data.pages.map((page, index) => {
- const pageSize = index === data.pages.length - 1 ? Math.min(page.memos.length, Math.max(0, nextMemos.length - cursor)) : page.memos.length;
- const memos = nextMemos.slice(cursor, cursor + pageSize);
- cursor += pageSize;
- return { ...page, memos, totalCount };
- });
-
- queryClient.setQueryData(query.queryKey, { ...data, pages });
- }
-
- const searchQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "search"] });
- for (const query of searchQueries) {
- const data = query.state.data as InfiniteData<Awaited<ReturnType<typeof listLocalMemos>>, number> | undefined;
- if (Array.isArray(data?.pages) && data.pages.some((page) => page.memos.some((memo) => memo.id === nextMemo.id || memo.id === previousMemo.id))) {
- queryClient.setQueryData(query.queryKey, {
- ...data,
- pages: data.pages.map((page) => ({
- ...page,
- memos: page.memos.map((memo) => (memo.id === nextMemo.id || memo.id === previousMemo.id ? nextMemo : memo)),
- })),
- });
- }
- }
-
- if (previousMemo.notebookId !== nextMemo.notebookId) {
- queryClient.setQueriesData<{ notebooks: Notebook[] }>({ queryKey: ["mobile", "notebooks"] }, (data) => {
- if (!data) {
- return data;
- }
-
- return {
- ...data,
- notebooks: data.notebooks.map((notebook) => {
- if (notebook.id === previousMemo.notebookId) {
- return { ...notebook, memoCount: Math.max(0, notebook.memoCount - 1) };
- }
- if (notebook.id === nextMemo.notebookId) {
- return { ...notebook, memoCount: notebook.memoCount + 1, lastMemoUpdatedAt: nextMemo.updatedAt };
- }
- return notebook;
- }),
- };
- });
- }
-};
-
-const findCachedMemoDetail = (queryClient: QueryClient, memoId: string) => {
- const detailQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "memo"] });
-
- for (const query of detailQueries) {
- const data = query.state.data as { memo?: MemoDetail } | undefined;
- if (data?.memo?.id === memoId) {
- return data.memo;
- }
- }
-
- return null;
-};
-
-const memoMatchesListQuery = (memo: MemoSummary, queryKey: readonly unknown[]) => {
- const view = queryKey[2];
- const notebookId = queryKey[3];
- const filter = queryKey[4];
- const notebookIds = Array.isArray(queryKey[6]) ? queryKey[6] : [];
-
- if ((view === "trash") !== memo.isDeleted) {
- return false;
- }
- if (notebookId !== ALL_NOTES_ID && !notebookIds.includes(memo.notebookId)) {
- return false;
- }
- if (filter === "tagged" && memo.tags.length === 0) {
- return false;
- }
- if (filter === "untagged" && memo.tags.length > 0) {
- return false;
- }
- if (filter === "pinned" && !memo.isPinned) {
- return false;
- }
-
- return true;
-};
-
-const sortMemoSummaries = (memos: MemoSummary[], sortMode: unknown) =>
- [...memos].sort((left, right) => {
- if (sortMode === "title-asc") {
- return (left.title || DEFAULT_MEMO_TITLE).localeCompare(right.title || DEFAULT_MEMO_TITLE);
- }
- if (sortMode === "created-desc") {
- return right.createdAt.localeCompare(left.createdAt);
- }
- return right.updatedAt.localeCompare(left.updatedAt);
- });
-
-const markdownToLocalText = (markdown: string) =>
- markdown
- .replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
- .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
- .replace(/[`*_>#~-]/g, " ")
- .replace(/\s+/g, " ")
- .trim();
-
-const getTextSearchMatches = (text: string, query: string) => {
- const normalizedQuery = query.trim().toLowerCase();
-
- if (!normalizedQuery) {
- return [];
- }
-
- const normalizedText = text.toLowerCase();
- const matches: Array<{ end: number; start: number }> = [];
- let cursor = 0;
-
- while (cursor < normalizedText.length) {
- const start = normalizedText.indexOf(normalizedQuery, cursor);
-
- if (start === -1) {
- break;
- }
-
- const end = start + normalizedQuery.length;
- matches.push({ end, start });
- cursor = end;
- }
-
- return matches;
-};
-
-const formatRevisionActor = (actor: string) => {
- if (actor.startsWith("user:")) {
- return "user";
- }
-
- if (actor.startsWith("agent:")) {
- return "agent";
- }
-
- return actor || "system";
-};
-
-const detailMarkdownStyles = StyleSheet.create({
- body: {
- color: "#0f172a",
- fontSize: 17,
- lineHeight: 27,
- },
- blockquote: {
- backgroundColor: "#f8fafc",
- borderLeftColor: "#94a3b8",
- borderLeftWidth: 3,
- marginVertical: 10,
- paddingHorizontal: 14,
- paddingVertical: 8,
- },
- bullet_list: {
- marginVertical: 8,
- },
- code_inline: {
- backgroundColor: "#f1f5f9",
- borderRadius: 4,
- color: "#334155",
- fontSize: 15,
- },
- fence: {
- backgroundColor: "#0f172a",
- borderColor: "#0f172a",
- borderRadius: 8,
- color: "#e2e8f0",
- fontSize: 14,
- marginVertical: 10,
- padding: 12,
- },
- heading1: {
- color: "#0f172a",
- fontSize: 26,
- fontWeight: "800",
- lineHeight: 34,
- marginBottom: 10,
- marginTop: 14,
- },
- heading2: {
- color: "#0f172a",
- fontSize: 21,
- fontWeight: "800",
- lineHeight: 29,
- marginBottom: 8,
- marginTop: 18,
- },
- heading3: {
- color: "#0f172a",
- fontSize: 18,
- fontWeight: "800",
- lineHeight: 26,
- marginBottom: 6,
- marginTop: 14,
- },
- link: {
- color: "#059669",
- },
- list_item: {
- marginVertical: 3,
- },
- ordered_list: {
- marginVertical: 8,
- },
- paragraph: {
- marginBottom: 10,
- marginTop: 0,
- },
- strong: {
- fontWeight: "800",
- },
- table: {
- backgroundColor: "#ffffff",
- borderColor: "#d8d8d8",
- borderRadius: 2,
- borderWidth: 1,
- overflow: "hidden",
- },
- tableCellDivider: {
- borderRightColor: "#dedede",
- borderRightWidth: 1,
- },
- tableScroll: {
- marginBottom: 10,
- marginTop: 10,
- maxWidth: "100%",
- },
- tableScrollContent: {
- flexGrow: 1,
- },
- td: {
- flex: 1,
- minWidth: 0,
- paddingHorizontal: 10,
- paddingVertical: 7,
- },
- th: {
- backgroundColor: "#f2f2f2",
- flex: 1,
- minWidth: 0,
- paddingHorizontal: 10,
- paddingVertical: 7,
- },
- tr: {
- borderBottomColor: "#dedede",
- borderBottomWidth: 1,
- flexDirection: "row",
- },
-});
-
-const baseWorkspaceStyles = StyleSheet.create({
- editorRuntimePrewarm: {
- position: "absolute",
- left: -2,
- top: -2,
- width: 1,
- height: 1,
- opacity: 0.01,
- },
- safeArea: {
- backgroundColor: "#f8fafc",
- flex: 1,
- },
- viewBody: {
- flex: 1,
- paddingBottom: 0,
- },
- settingsScreen: {
- backgroundColor: "#f8fafc",
- flex: 1,
- },
- settingsHeader: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- flexDirection: "row",
- minHeight: 56,
- paddingHorizontal: 12,
- },
- settingsBackButton: {
- alignItems: "center",
- borderRadius: 8,
- height: 36,
- justifyContent: "center",
- width: 36,
- },
- settingsThemeButton: {
- alignItems: "center",
- borderRadius: 8,
- flexDirection: "row",
- gap: 8,
- height: 36,
- justifyContent: "center",
- paddingHorizontal: 8,
- },
- settingsThemeText: {
- color: "#475569",
- fontSize: 14,
- fontWeight: "700",
- },
- settingsHeaderTitle: {
- alignItems: "center",
- flex: 1,
- flexDirection: "row",
- gap: 8,
- justifyContent: "flex-start",
- },
- updateDot: {
- backgroundColor: "#10b981",
- borderColor: "#ffffff",
- borderRadius: 5,
- borderWidth: 1,
- height: 9,
- marginLeft: 1,
- width: 9,
- },
- settingsTitle: {
- color: "#0f172a",
- fontSize: 16,
- fontWeight: "800",
- },
- settingsScrollContent: {
- padding: 16,
- paddingBottom: 96,
- },
- settingsMenu: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 16,
- borderWidth: 1,
- overflow: "hidden",
- },
- settingsMenuRow: {
- alignItems: "center",
- flexDirection: "row",
- justifyContent: "space-between",
- minHeight: 64,
- paddingHorizontal: 16,
- },
- settingsMenuRowBorder: {
- borderTopColor: "#f1f5f9",
- borderTopWidth: 1,
- },
- settingsMenuLabel: {
- alignItems: "center",
- flex: 1,
- flexDirection: "row",
- gap: 12,
- minWidth: 0,
- },
- settingsMenuIcon: {
- alignItems: "center",
- backgroundColor: "#ecfdf5",
- borderRadius: 8,
- height: 32,
- justifyContent: "center",
- width: 32,
- },
- settingsMenuText: {
- color: "#1e293b",
- fontSize: 14,
- fontWeight: "700",
- },
- settingsFeedbackCopy: {
- flex: 1,
- gap: 1,
- minWidth: 0,
- },
- settingsFeedbackDescription: {
- color: "#64748b",
- fontSize: 12,
- lineHeight: 17,
- },
- settingsFeedbackIcon: {
- backgroundColor: "#f1f5f9",
- },
- settingsDetailList: {
- gap: 16,
- },
- accountSummaryCard: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 12,
- borderWidth: 1,
- flexDirection: "row",
- gap: 12,
- padding: 16,
- },
- accountSummaryIcon: {
- alignItems: "center",
- backgroundColor: "#ecfdf5",
- borderRadius: 999,
- height: 40,
- justifyContent: "center",
- width: 40,
- },
- accountSummaryContent: {
- flex: 1,
- minWidth: 0,
- },
- accountSummaryHelp: {
- color: "#64748b",
- fontSize: 12,
- lineHeight: 18,
- marginTop: 3,
- },
- accountSummaryTitle: {
- color: "#64748b",
- fontSize: 12,
- fontWeight: "700",
- },
- accountSummaryName: {
- color: "#0f172a",
- fontSize: 15,
- fontWeight: "800",
- marginTop: 2,
- },
- settingsGroup: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 12,
- borderWidth: 1,
- overflow: "hidden",
- },
- settingsAiEmbeddedCardFirst: {
- borderRadius: 0,
- borderWidth: 0,
- },
- settingsAiEmbeddedCard: {
- borderBottomWidth: 0,
- borderLeftWidth: 0,
- borderRadius: 0,
- borderRightWidth: 0,
- borderTopColor: "#f1f5f9",
- borderTopWidth: 1,
- },
- settingsGroupHeader: {
- alignItems: "center",
- flexDirection: "row",
- gap: 8,
- padding: 16,
- },
- settingsGroupTitle: {
- color: "#0f172a",
- fontSize: 14,
- fontWeight: "800",
- },
- settingsContentRow: {
- borderTopColor: "#f1f5f9",
- borderTopWidth: 1,
- gap: 10,
- minHeight: 64,
- padding: 16,
- },
- settingsSelect: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- justifyContent: "space-between",
- minHeight: 40,
- paddingHorizontal: 12,
- },
- settingsSelectText: {
- color: "#0f172a",
- flex: 1,
- fontSize: 14,
- },
- settingsSwitchStart: {
- alignItems: "flex-start",
- },
- settingsRowTitle: {
- color: "#0f172a",
- fontSize: 14,
- fontWeight: "700",
- },
- settingsRowDescription: {
- color: "#64748b",
- fontSize: 12,
- lineHeight: 17,
- },
- settingsLinkDescription: {
- color: "#64748b",
- fontSize: 12,
- lineHeight: 17,
- paddingHorizontal: 16,
- },
- settingsAccordionHeader: {
- alignItems: "center",
- flexDirection: "row",
- justifyContent: "space-between",
- paddingRight: 16,
- },
- settingsAccordionChevron: {
- transform: [{ rotate: "0deg" }],
- },
- settingsAccordionChevronExpanded: {
- transform: [{ rotate: "180deg" }],
- },
- settingsAccordionContent: {
- borderTopColor: "#f1f5f9",
- borderTopWidth: 1,
- gap: 10,
- padding: 16,
- },
- settingsDialogBackdrop: {
- alignItems: "center",
- backgroundColor: "rgba(15, 23, 42, 0.46)",
- flex: 1,
- justifyContent: "center",
- padding: 20,
- },
- localePickerBackdrop: {
- flex: 1,
- },
- localePickerMenu: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- elevation: 8,
- overflow: "hidden",
- padding: 4,
- position: "absolute",
- shadowColor: "#0f172a",
- shadowOffset: { height: 4, width: 0 },
- shadowOpacity: 0.14,
- shadowRadius: 10,
- },
- localePickerOption: {
- alignItems: "center",
- borderRadius: 6,
- flexDirection: "row",
- justifyContent: "space-between",
- minHeight: 38,
- paddingHorizontal: 10,
- },
- localePickerOptionActive: {
- backgroundColor: "#ecfdf5",
- },
- localePickerOptionText: {
- color: "#334155",
- flex: 1,
- fontSize: 14,
- },
- localePickerOptionTextActive: {
- color: "#047857",
- fontWeight: "700",
- },
- settingsLinkCopy: {
- flex: 1,
- paddingBottom: 16,
- },
- settingsLogoutButton: {
- alignItems: "center",
- alignSelf: "flex-start",
- backgroundColor: "#e11d48",
- borderRadius: 8,
- flexDirection: "row",
- gap: 8,
- minHeight: 40,
- paddingHorizontal: 14,
- },
- settingsLogoutCard: {
- backgroundColor: "#fff1f2",
- borderColor: "#fecaca",
- borderRadius: 8,
- borderWidth: 1,
- padding: 16,
- },
- settingsLogoutText: {
- color: "#ffffff",
- fontSize: 14,
- fontWeight: "800",
- },
- iconButton: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- height: 38,
- justifyContent: "center",
- width: 38,
- },
- iconButtonPlaceholder: {
- height: 38,
- width: 38,
- },
- mobileListHeader: {
- backgroundColor: "#f8fafc",
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- paddingBottom: 8,
- paddingHorizontal: 16,
- paddingTop: 8,
- },
- mobileSelectionHeader: {
- alignItems: "center",
- flexDirection: "row",
- minHeight: 44,
- },
- mobileSelectionTitle: {
- color: "#0f172a",
- flex: 1,
- fontSize: 17,
- fontWeight: "800",
- paddingHorizontal: 8,
- },
- mobileSelectionClose: {
- alignItems: "center",
- height: 38,
- justifyContent: "center",
- width: 38,
- },
- mobileListTitleRow: {
- alignItems: "center",
- flexDirection: "row",
- justifyContent: "space-between",
- marginBottom: 12,
- minHeight: MOBILE_UI_METRICS.compactControlHeight,
- },
- mobileNotebookTitleButton: {
- alignItems: "center",
- flexDirection: "row",
- flexShrink: 1,
- gap: 4,
- minHeight: MOBILE_UI_METRICS.compactControlHeight,
- paddingRight: 12,
- },
- mobileNotebookTitle: {
- color: "#0f172a",
- flexShrink: 1,
- fontSize: 17,
- fontWeight: "700",
- },
- mobileMoreButton: {
- alignItems: "center",
- borderRadius: MOBILE_UI_METRICS.compactControlHeight / 2,
- height: MOBILE_UI_METRICS.compactControlHeight,
- justifyContent: "center",
- width: MOBILE_UI_METRICS.compactControlHeight,
- },
- mobileSearchRow: {
- alignItems: "center",
- flexDirection: "row",
- gap: 8,
- },
- mobileSearchButton: {
- alignItems: "center",
- backgroundColor: "#f1f5f9",
- borderColor: "transparent",
- borderRadius: MOBILE_UI_METRICS.compactControlHeight / 2,
- borderWidth: 1,
- flex: 1,
- flexDirection: "row",
- gap: 8,
- height: MOBILE_UI_METRICS.compactControlHeight,
- paddingHorizontal: 12,
- },
- mobileSearchButtonActive: {
- backgroundColor: "#ecfdf5",
- borderColor: "#10b981",
- },
- mobileSearchButtonActiveDark: {
- backgroundColor: "rgb(255, 255, 255)",
- },
- mobileSearchInput: {
- color: "#0f172a",
- flex: 1,
- fontSize: 14,
- height: MOBILE_UI_METRICS.compactControlHeight,
- paddingVertical: 0,
- },
- mobileSearchInputActiveDark: {
- color: "rgb(15, 23, 42)",
- },
- mobileSearchClearButton: {
- alignItems: "center",
- height: 28,
- justifyContent: "center",
- width: 28,
- },
- mobileListConstraint: {
- alignItems: "center",
- backgroundColor: "rgb(236, 253, 245)",
- borderColor: "rgb(167, 243, 208)",
- borderLeftColor: "rgb(16, 185, 129)",
- borderLeftWidth: 3,
- borderRadius: 6,
- borderWidth: 1,
- flexDirection: "row",
- gap: 8,
- marginTop: 12,
- minHeight: 32,
- paddingHorizontal: 10,
- paddingVertical: 6,
- },
- mobileListConstraintFilter: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderLeftColor: "#e2e8f0",
- borderLeftWidth: 1,
- },
- mobileSearchStatusPill: {
- alignItems: "center",
- backgroundColor: "#059669",
- borderRadius: 999,
- flexDirection: "row",
- gap: 4,
- paddingHorizontal: 8,
- paddingVertical: 4,
- },
- mobileSearchStatusPillText: {
- color: "#ffffff",
- fontSize: 12,
- fontWeight: "700",
- },
- mobileListConstraintText: {
- color: "#065f46",
- flex: 1,
- fontSize: 12,
- fontWeight: "700",
- },
- mobileListConstraintTextFilter: {
- color: "#64748b",
- },
- mobileListConstraintAction: {
- color: "#065f46",
- fontSize: 12,
- fontWeight: "700",
- },
- mobileListConstraintActionFilter: {
- color: "#475569",
- },
- mobileFilterButton: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: MOBILE_UI_METRICS.compactControlHeight / 2,
- borderWidth: 1,
- height: MOBILE_UI_METRICS.compactControlHeight,
- justifyContent: "center",
- width: MOBILE_UI_METRICS.compactControlHeight,
- },
- mobileFilterButtonActive: {
- backgroundColor: "#334155",
- borderColor: "#334155",
- },
- searchBox: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- gap: 10,
- minHeight: 46,
- paddingHorizontal: 12,
- },
- searchInput: {
- color: "#0f172a",
- flex: 1,
- fontSize: 15,
- minHeight: 44,
- },
- layoutToggle: {
- alignSelf: "flex-start",
- backgroundColor: "#f8fafc",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- overflow: "hidden",
- },
- layoutToggleButton: {
- alignItems: "center",
- flexDirection: "row",
- height: 36,
- justifyContent: "center",
- width: 36,
- },
- layoutToggleButtonActive: {
- backgroundColor: "#ecfdf5",
- },
- secondaryIconButton: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- height: 40,
- justifyContent: "center",
- width: 40,
- },
- optionPill: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- justifyContent: "center",
- marginRight: 6,
- minHeight: 32,
- paddingHorizontal: 12,
- },
- optionPillActive: {
- backgroundColor: "#ecfdf5",
- borderColor: "#a7f3d0",
- },
- optionPillText: {
- color: "#475569",
- fontSize: 13,
- fontWeight: "700",
- },
- optionPillTextActive: {
- color: "#047857",
- },
- list: {
- paddingBottom: 18,
- paddingHorizontal: 12,
- paddingTop: 12,
- },
- memoList: {
- flex: 1,
- },
- listLoadingFooter: {
- marginVertical: 18,
- },
- emptyList: {
- flexGrow: 1,
- paddingBottom: 22,
- },
- memoListStateWrap: {
- paddingHorizontal: 12,
- paddingTop: 16,
- },
- 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: 13,
- lineHeight: 20,
- marginTop: 7,
- maxWidth: 300,
- textAlign: "center",
- },
- memoSyncBanner: {
- alignItems: "center",
- backgroundColor: "#ecfdf5",
- borderColor: "#a7f3d0",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- gap: 12,
- marginBottom: 10,
- paddingHorizontal: 14,
- paddingVertical: 12,
- },
- memoSyncBannerContent: {
- flex: 1,
- },
- memoSyncBannerTitle: {
- color: "#065f46",
- fontSize: 13,
- fontWeight: "800",
- },
- memoSyncBannerDescription: {
- color: "#047857",
- fontSize: 12,
- marginTop: 2,
- },
- memoSyncProgressTrack: {
- backgroundColor: "#d1fae5",
- borderRadius: 999,
- height: 4,
- marginTop: 10,
- overflow: "hidden",
- width: "100%",
- },
- memoSyncProgressFill: {
- backgroundColor: "#059669",
- borderRadius: 999,
- height: "100%",
- },
- memoSyncErrorBanner: {
- alignItems: "center",
- backgroundColor: "#fffbeb",
- borderColor: "#fcd34d",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- gap: 10,
- marginBottom: 10,
- paddingHorizontal: 14,
- paddingVertical: 12,
- },
- memoSyncErrorBannerTitle: {
- color: "#451a03",
- fontSize: 13,
- fontWeight: "800",
- },
- memoSyncErrorBannerDescription: {
- color: "#92400e",
- fontSize: 12,
- lineHeight: 18,
- marginTop: 2,
- },
- memoSyncErrorRetryButton: {
- alignItems: "center",
- flexDirection: "row",
- gap: 5,
- paddingHorizontal: 4,
- paddingVertical: 8,
- },
- memoListErrorCard: {
- alignItems: "center",
- backgroundColor: "#fffbeb",
- borderColor: "#fcd34d",
- borderRadius: 8,
- borderStyle: "dashed",
- borderWidth: 1,
- paddingHorizontal: 16,
- paddingVertical: 34,
- },
- memoListErrorTitle: {
- color: "#451a03",
- fontSize: 14,
- fontWeight: "800",
- },
- memoListErrorDescription: {
- color: "#92400e",
- fontSize: 12,
- lineHeight: 20,
- marginTop: 8,
- maxWidth: 300,
- textAlign: "center",
- },
- memoListRetryButton: {
- alignItems: "center",
- backgroundColor: "#fef3c7",
- borderRadius: 8,
- flexDirection: "row",
- gap: 7,
- marginTop: 16,
- minHeight: 36,
- paddingHorizontal: 12,
- },
- memoListRetryText: {
- color: "#92400e",
- fontSize: 13,
- fontWeight: "800",
- },
- memoListEmptyCard: {
- alignItems: "center",
- alignSelf: "stretch",
- backgroundColor: "#ffffff",
- borderColor: "#cbd5e1",
- borderRadius: 8,
- borderStyle: "dashed",
- borderWidth: 1,
- marginHorizontal: 12,
- marginTop: 12,
- paddingHorizontal: 16,
- paddingVertical: 34,
- },
- memoCard: {
- alignItems: "stretch",
- backgroundColor: "#ffffff",
- borderColor: "#f1f5f9",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- marginBottom: 12,
- minHeight: 132,
- overflow: "hidden",
- },
- memoCardCompact: {
- marginBottom: 10,
- minHeight: 84,
- },
- memoCardSelected: {
- backgroundColor: "#f8fafc",
- borderColor: "#e2e8f0",
- },
- memoCardContent: {
- flex: 1,
- minWidth: 0,
- padding: 16,
- },
- memoCardContentCompact: {
- padding: 13,
- },
- memoCardContentWithSelection: {
- paddingLeft: 12,
- },
- memoSelectionButton: {
- alignItems: "center",
- justifyContent: "center",
- marginLeft: 8,
- width: 44,
- },
- memoCardTop: {
- alignItems: "center",
- flexDirection: "row",
- gap: 6,
- },
- selectionIndicator: {
- alignItems: "center",
- borderColor: "#cbd5e1",
- borderRadius: 12,
- borderWidth: 1,
- height: 24,
- justifyContent: "center",
- width: 24,
- },
- selectionIndicatorActive: {
- backgroundColor: "#0f172a",
- borderColor: "#0f172a",
- },
- memoTitle: {
- color: "#0f172a",
- flex: 1,
- fontSize: 16,
- fontWeight: "700",
- },
- memoPinnedStar: {
- color: "#64748b",
- fontSize: 16,
- lineHeight: 16,
- width: 16,
- },
- memoExcerpt: {
- color: "#0f172a",
- fontSize: 14,
- lineHeight: 20,
- marginTop: 8,
- minHeight: 40,
- },
- memoMeta: {
- alignItems: "center",
- flexDirection: "row",
- flexWrap: "wrap",
- gap: 8,
- marginTop: 20,
- },
- memoMetaCompact: {
- marginTop: 8,
- },
- memoDate: {
- color: "#334155",
- fontSize: 12,
- fontWeight: "500",
- },
- tag: {
- backgroundColor: "#f1f5f9",
- borderRadius: 2,
- color: "#0f172a",
- fontSize: 12,
- fontWeight: "500",
- overflow: "hidden",
- paddingHorizontal: 6,
- paddingVertical: 2,
- },
- centerState: {
- alignItems: "center",
- flex: 1,
- gap: 8,
- justifyContent: "center",
- padding: 24,
- },
- errorText: {
- color: "#dc2626",
- fontSize: 14,
- fontWeight: "700",
- lineHeight: 20,
- },
- emptyTitle: {
- color: "#334155",
- fontSize: 16,
- fontWeight: "800",
- },
- mutedText: {
- color: "#64748b",
- fontSize: 13,
- textAlign: "center",
- },
- emptyActionButton: {
- alignItems: "center",
- backgroundColor: "#0f172a",
- borderRadius: 8,
- flexDirection: "row",
- gap: 8,
- marginTop: 8,
- minHeight: 38,
- paddingHorizontal: 14,
- },
- emptyActionButtonText: {
- color: "#ffffff",
- fontSize: 13,
- fontWeight: "800",
- },
- panelRow: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- gap: 6,
- padding: 14,
- },
- systemInfoRows: {
- borderTopColor: "#e2e8f0",
- borderTopWidth: 1,
- },
- systemInfoRow: {
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- flexDirection: "row",
- },
- systemInfoRowLast: {
- borderBottomWidth: 0,
- },
- systemInfoCell: {
- flex: 1,
- gap: 3,
- minWidth: 0,
- paddingHorizontal: 8,
- paddingVertical: 9,
- },
- systemInfoCellDivider: {
- borderRightColor: "#e2e8f0",
- borderRightWidth: 1,
- },
- systemInfoListValue: {
- color: "#0f172a",
- fontFamily: "monospace",
- fontSize: 12,
- fontWeight: "700",
- },
- panelLinkRow: {
- alignItems: "center",
- flexDirection: "row",
- justifyContent: "space-between",
- },
- panelLinkText: {
- flex: 1,
- gap: 6,
- minWidth: 0,
- },
- panelLabel: {
- color: "#64748b",
- fontSize: 12,
- fontWeight: "700",
- },
- panelValue: {
- color: "#0f172a",
- fontSize: 15,
- fontWeight: "700",
- },
- preferenceStack: {
- gap: 12,
- },
- preferenceText: {
- flex: 1,
- gap: 6,
- minWidth: 0,
- },
- buttonDisabled: {
- opacity: 0.5,
- },
- modalSafeArea: {
- backgroundColor: "#f8fafc",
- flex: 1,
- },
- createMemoSafeArea: {
- backgroundColor: "#ffffff",
- flex: 1,
- },
- createMemoHeader: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderBottomColor: "#f1f5f9",
- borderBottomWidth: 1,
- flexDirection: "row",
- gap: 8,
- justifyContent: "space-between",
- minHeight: 52,
- paddingBottom: 8,
- paddingHorizontal: 12,
- paddingTop: 8,
- },
- createMemoBackButton: {
- alignItems: "center",
- borderRadius: 999,
- height: 38,
- justifyContent: "center",
- width: 38,
- },
- createMemoHeaderActions: {
- alignItems: "center",
- flexDirection: "row",
- gap: 8,
- },
- createMemoStatus: {
- backgroundColor: "#f1f5f9",
- borderRadius: 999,
- color: "#64748b",
- fontSize: 12,
- fontWeight: "700",
- overflow: "hidden",
- paddingHorizontal: 10,
- paddingVertical: 6,
- },
- createMemoStatusActive: {
- backgroundColor: "#ecfdf5",
- color: "#047857",
- },
- createMemoDoneButton: {
- alignItems: "center",
- backgroundColor: "#020617",
- borderRadius: 999,
- justifyContent: "center",
- minHeight: 36,
- minWidth: 58,
- paddingHorizontal: 12,
- paddingVertical: 7,
- },
- createMemoDoneButtonDisabled: {
- backgroundColor: "#e2e8f0",
- },
- createMemoDoneText: {
- color: "#ffffff",
- fontSize: 14,
- fontWeight: "700",
- },
- createMemoDoneTextDisabled: {
- color: "#64748b",
- },
- createMemoMain: {
- flex: 1,
- paddingBottom: 8,
- paddingHorizontal: 12,
- paddingTop: 14,
- },
- createMemoTitleInput: {
- color: "#0f172a",
- fontSize: 28,
- fontWeight: "800",
- lineHeight: 34,
- minHeight: 42,
- padding: 0,
- },
- createMemoMetaRow: {
- alignItems: "center",
- flexDirection: "row",
- gap: 10,
- minHeight: 40,
- },
- createMemoNotebookButton: {
- alignItems: "center",
- flexDirection: "row",
- flexShrink: 1,
- gap: 3,
- maxWidth: "46%",
- minHeight: 30,
- paddingRight: 5,
- },
- createMemoNotebookText: {
- color: "#64748b",
- flexShrink: 1,
- fontSize: 15,
- fontWeight: "700",
- },
- createMemoTagsInput: {
- color: "#64748b",
- flex: 1,
- fontSize: 15,
- lineHeight: 23,
- minHeight: 36,
- minWidth: 0,
- padding: 0,
- },
- createMemoToolButton: {
- alignItems: "center",
- borderColor: "transparent",
- borderRadius: 999,
- borderWidth: 1,
- height: 32,
- justifyContent: "center",
- width: 36,
- },
- createMemoToolButtonPressed: {
- backgroundColor: "#ecfdf5",
- borderColor: "#bbf7d0",
- },
- createMemoEditorFrame: {
- borderColor: "#e2e8f0",
- borderRadius: 10,
- borderWidth: 1,
- flex: 1,
- marginHorizontal: -4,
- marginTop: 4,
- overflow: "hidden",
- },
- createMemoEditor: {
- backgroundColor: "#ffffff",
- flex: 1,
- },
- richEditorSafeArea: {
- backgroundColor: "#ffffff",
- flex: 1,
- },
- richEditorHeaderStatus: {
- maxWidth: 76,
- },
- richEditorContainer: {
- backgroundColor: "#ffffff",
- flex: 1,
- paddingHorizontal: 12,
- paddingTop: 14,
- },
- richEditorStatusError: {
- backgroundColor: "#fef2f2",
- color: "#b91c1c",
- },
- richEditorFrame: {
- flex: 1,
- marginHorizontal: -12,
- },
- richStandaloneMetaRow: {
- minHeight: 30,
- },
- richStandaloneTagsInput: {
- minHeight: 30,
- },
- richEditorSearchActions: {
- alignItems: "center",
- flexDirection: "row",
- flexWrap: "wrap",
- gap: 8,
- },
- richEditorLoading: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- bottom: 0,
- gap: 10,
- justifyContent: "center",
- left: 0,
- position: "absolute",
- right: 0,
- top: 0,
- zIndex: 2,
- },
- richEditorWebView: {
- backgroundColor: "#ffffff",
- flex: 1,
- },
- richEditorInlineError: {
- backgroundColor: "#fef2f2",
- color: "#b91c1c",
- fontSize: 12,
- paddingHorizontal: 14,
- paddingVertical: 8,
- },
- richEditorDraftNotice: {
- backgroundColor: "#fffbeb",
- color: "#92400e",
- fontSize: 12,
- paddingHorizontal: 14,
- paddingVertical: 7,
- },
- richEditorPerf: {
- backgroundColor: "#f8fafc",
- color: "#64748b",
- fontSize: 10,
- paddingHorizontal: 14,
- paddingVertical: 4,
- textAlign: "right",
- },
- managementHeader: {
- alignItems: "center",
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- flexDirection: "row",
- minHeight: 64,
- paddingHorizontal: 14,
- },
- managementBackButton: {
- alignItems: "center",
- borderRadius: 8,
- height: 36,
- justifyContent: "center",
- marginRight: 10,
- width: 36,
- },
- managementHeaderText: {
- flex: 1,
- minWidth: 0,
- },
- managementTitleRow: {
- alignItems: "center",
- flexDirection: "row",
- gap: 8,
- },
- managementTitle: {
- color: "#0f172a",
- fontSize: 16,
- fontWeight: "800",
- },
- managementSubtitle: {
- color: "#64748b",
- fontSize: 11,
- fontWeight: "600",
- marginTop: 2,
- },
- modalHeader: {
- alignItems: "center",
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- flexDirection: "row",
- justifyContent: "space-between",
- padding: 14,
- },
- modalTitle: {
- color: "#0f172a",
- flex: 1,
- fontSize: 16,
- fontWeight: "800",
- marginHorizontal: 12,
- textAlign: "center",
- },
- actionSheetBackdrop: {
- backgroundColor: "rgba(15, 23, 42, 0.34)",
- flex: 1,
- justifyContent: "flex-end",
- },
- actionSheet: {
- backgroundColor: "#ffffff",
- borderTopLeftRadius: 16,
- borderTopRightRadius: 16,
- gap: 8,
- paddingBottom: 28,
- paddingHorizontal: 16,
- paddingTop: 10,
- },
- listActionSheet: {
- backgroundColor: "#ffffff",
- borderRadius: MOBILE_UI_METRICS.floatingSheetCornerRadius,
- marginHorizontal: 12,
- maxHeight: "82%",
- overflow: "hidden",
- paddingBottom: 8,
- paddingTop: 8,
- },
- selectionMoreSheet: {
- backgroundColor: "#ffffff",
- borderRadius: 10,
- gap: 0,
- marginHorizontal: 8,
- overflow: "hidden",
- paddingBottom: 8,
- paddingTop: 8,
- },
- moveSelectionSheet: {
- maxHeight: "76%",
- },
- moveSelectionSearch: {
- borderBottomColor: "#f1f5f9",
- borderBottomWidth: 1,
- padding: 12,
- },
- moveSelectionList: {
- gap: 8,
- padding: 8,
- },
- listActionSheetHeader: {
- alignItems: "center",
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- flexDirection: "row",
- minHeight: 48,
- paddingHorizontal: 12,
- },
- listActionSheetHeaderText: {
- flex: 1,
- minWidth: 0,
- },
- sheetCloseButton: {
- alignItems: "center",
- borderRadius: 8,
- height: 38,
- justifyContent: "center",
- width: 38,
- },
- listActionSheetScroll: {
- flexShrink: 1,
- },
- listActionSheetContent: {
- padding: 8,
- },
- actionSheetSubtitle: {
- color: "#64748b",
- fontSize: 12,
- marginTop: 2,
- },
- listActionDivider: {
- backgroundColor: "#f1f5f9",
- height: 1,
- marginVertical: 8,
- },
- notebookPickerSheet: {
- maxHeight: "82%",
- paddingBottom: 8,
- paddingHorizontal: 0,
- },
- notebookPickerHeader: {
- alignItems: "center",
- borderBottomColor: "#e2e8f0",
- borderBottomWidth: 1,
- flexDirection: "row",
- justifyContent: "space-between",
- minHeight: 56,
- paddingHorizontal: 16,
- },
- notebookPickerHeaderText: {
- flex: 1,
- gap: 2,
- },
- notebookPickerCloseButton: {
- alignItems: "center",
- borderRadius: 6,
- height: 32,
- justifyContent: "center",
- width: 32,
- },
- notebookPickerSectionHeader: {
- alignItems: "center",
- flexDirection: "row",
- justifyContent: "space-between",
- minHeight: 32,
- paddingHorizontal: 12,
- },
- notebookPickerToggleAll: {
- borderRadius: 6,
- paddingHorizontal: 8,
- paddingVertical: 6,
- },
- notebookPickerToggleAllText: {
- color: "#64748b",
- fontSize: 12,
- fontWeight: "700",
- },
- notebookPickerScroll: {
- flexShrink: 1,
- },
- notebookPickerContent: {
- padding: 8,
- },
- notebookPickerSearchBox: {
- alignItems: "center",
- backgroundColor: "#f1f5f9",
- borderRadius: 6,
- flexDirection: "row",
- gap: 8,
- height: 36,
- marginBottom: 8,
- paddingHorizontal: 12,
- },
- notebookPickerSearchInput: {
- color: "#0f172a",
- flex: 1,
- fontSize: 14,
- height: 36,
- paddingVertical: 0,
- },
- notebookPickerRow: {
- alignItems: "center",
- backgroundColor: "transparent",
- borderRadius: 6,
- flexDirection: "row",
- gap: 8,
- minHeight: 48,
- paddingHorizontal: 12,
- },
- notebookPickerAllRow: {
- marginBottom: 4,
- },
- notebookPickerRowActive: {
- backgroundColor: "#f1f5f9",
- },
- actionSheetHandle: {
- alignSelf: "center",
- backgroundColor: "#cbd5e1",
- borderRadius: 999,
- height: 4,
- marginBottom: 8,
- width: 42,
- },
- actionSheetTitle: {
- color: "#0f172a",
- fontSize: 15,
- fontWeight: "800",
- paddingBottom: 4,
- },
- actionSheetSectionTitle: {
- color: "#64748b",
- fontSize: 12,
- fontWeight: "600",
- paddingHorizontal: 12,
- paddingVertical: 8,
- },
- actionSheetItem: {
- alignItems: "center",
- backgroundColor: "transparent",
- borderRadius: 7,
- flexDirection: "row",
- gap: 10,
- minHeight: 48,
- paddingHorizontal: 12,
- },
- actionSheetItemCompact: {
- minHeight: 44,
- },
- actionSheetItemText: {
- color: "#0f172a",
- fontSize: 14,
- fontWeight: "800",
- },
- actionSheetItemTextCompact: {
- fontWeight: "500",
- },
- actionSheetItemTextDanger: {
- color: "#b91c1c",
- },
- sheetOptionRow: {
- alignItems: "center",
- borderRadius: 7,
- flexDirection: "row",
- gap: 10,
- minHeight: 44,
- paddingHorizontal: 12,
- },
- sheetOptionRowActive: {
- backgroundColor: "rgb(236, 253, 245)",
- },
- sheetOptionIcon: {
- alignItems: "center",
- justifyContent: "center",
- width: 20,
- },
- sheetOptionLabel: {
- color: "#0f172a",
- flex: 1,
- fontSize: 14,
- fontWeight: "500",
- },
- sheetOptionLabelActive: {
- color: "rgb(4, 120, 87)",
- },
- sheetOptionCheck: {
- alignItems: "center",
- backgroundColor: "#10b981",
- borderRadius: 9,
- height: 18,
- justifyContent: "center",
- width: 18,
- },
- sheetOptionCheckHidden: {
- opacity: 0,
- },
- detailContent: {
- paddingBottom: 112,
- paddingHorizontal: DETAIL_CONTENT_HORIZONTAL_PADDING,
- paddingTop: 16,
- },
- detailTitle: {
- color: "#0f172a",
- fontSize: 24,
- fontWeight: "700",
- lineHeight: 30,
- },
- detailHeader: {
- alignItems: "center",
- borderBottomColor: "#f1f5f9",
- borderBottomWidth: 1,
- flexDirection: "row",
- justifyContent: "space-between",
- minHeight: 48,
- paddingHorizontal: 12,
- },
- detailHeaderButton: {
- alignItems: "center",
- borderRadius: 6,
- height: 32,
- justifyContent: "center",
- width: 32,
- },
- detailHeaderActions: {
- alignItems: "center",
- flexDirection: "row",
- gap: 2,
- },
- detailHeaderIconButton: {
- alignItems: "center",
- borderRadius: 6,
- height: 32,
- justifyContent: "center",
- width: 32,
- },
- detailSyncStatus: {
- backgroundColor: "#f1f5f9",
- borderRadius: 999,
- color: "#64748b",
- fontSize: 11,
- fontWeight: "500",
- maxWidth: 88,
- overflow: "hidden",
- paddingHorizontal: 8,
- paddingVertical: 4,
- },
- detailSyncStatusConflict: {
- backgroundColor: "#fff7ed",
- color: "#c2410c",
- fontWeight: "700",
- },
- detailMetaRow: {
- alignItems: "center",
- flexDirection: "row",
- gap: 8,
- marginTop: 12,
- },
- detailNotebookButton: {
- alignItems: "center",
- flexDirection: "row",
- gap: 4,
- height: 32,
- maxWidth: "46%",
- paddingHorizontal: 8,
- },
- detailNotebookName: {
- color: "#64748b",
- flexShrink: 1,
- fontSize: 14,
- },
- detailTagsGroup: {
- alignItems: "center",
- flex: 1,
- flexDirection: "row",
- gap: 8,
- height: 32,
- paddingHorizontal: 8,
- },
- detailTagsInline: {
- color: "#64748b",
- flex: 1,
- fontSize: 14,
- },
- detailTagsPlaceholder: {
- color: "#94a3b8",
- },
- detailDivider: {
- backgroundColor: "#e2e8f0",
- height: 1,
- marginHorizontal: -16,
- marginTop: 16,
- marginBottom: 18,
- },
- detailEditFab: {
- alignItems: "center",
- backgroundColor: "#10b981",
- borderRadius: 24,
- elevation: 6,
- height: 48,
- justifyContent: "center",
- position: "absolute",
- right: 16,
- shadowColor: "#0f172a",
- shadowOffset: { width: 0, height: 4 },
- shadowOpacity: 0.2,
- shadowRadius: 8,
- width: 48,
- },
- detailMarkdown: {
- color: "#1f2937",
- fontSize: 16,
- lineHeight: 25,
- marginTop: 20,
- },
- noteSearchPanel: {
- backgroundColor: "#f8fafc",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- gap: 10,
- marginTop: 14,
- padding: 10,
- },
- noteSearchCount: {
- color: "#64748b",
- fontSize: 12,
- fontWeight: "800",
- },
- noteSearchCountEmpty: {
- color: "#b91c1c",
- },
- noteSearchHighlight: {
- backgroundColor: "#fef3c7",
- color: "#78350f",
- },
- noteSearchHighlightActive: {
- backgroundColor: "#fde68a",
- color: "#0f172a",
- fontWeight: "800",
- },
- actionButton: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- gap: 6,
- minHeight: 38,
- paddingHorizontal: 12,
- },
- actionButtonDanger: {
- backgroundColor: "#fef2f2",
- borderColor: "#fecaca",
- },
- actionButtonText: {
- color: "#0f172a",
- fontSize: 13,
- fontWeight: "800",
- },
- actionButtonTextDanger: {
- color: "#b91c1c",
- },
- parentSelectList: {
- flexGrow: 0,
- },
- notebookPicker: {
- gap: 10,
- },
- centerInline: {
- alignItems: "center",
- padding: 18,
- },
- emptyInlinePanel: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderStyle: "dashed",
- borderWidth: 1,
- gap: 8,
- padding: 22,
- },
- guideHero: {
- backgroundColor: "#ecfdf5",
- borderColor: "#a7f3d0",
- borderRadius: 8,
- borderWidth: 1,
- gap: 8,
- padding: 14,
- },
- promptCard: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- gap: 10,
- padding: 14,
- },
- promptCardHeader: {
- alignItems: "center",
- flexDirection: "row",
- flexWrap: "wrap",
- gap: 10,
- justifyContent: "space-between",
- },
- moveNotebookRow: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- flexDirection: "row",
- gap: 12,
- minHeight: 58,
- padding: 12,
- },
- moveNotebookRowActive: {
- borderColor: "#0f172a",
- },
- moveNotebookRowCompact: {
- borderWidth: 0,
- minHeight: 44,
- paddingHorizontal: 12,
- paddingVertical: 5,
- },
- moveNotebookRowCompactActive: {
- backgroundColor: "#ecfdf5",
- },
- moveNotebookTextCompactActive: {
- color: "#047857",
- },
- moveNotebookText: {
- flex: 1,
- gap: 4,
- minWidth: 0,
- },
- moveNotebookSelectArea: {
- flex: 1,
- gap: 4,
- justifyContent: "center",
- minHeight: 34,
- minWidth: 0,
- },
- notebookTreeToggle: {
- alignItems: "center",
- borderRadius: 8,
- height: 32,
- justifyContent: "center",
- width: 32,
- },
- notebookTreeTogglePlaceholder: {
- alignItems: "center",
- height: 32,
- justifyContent: "center",
- width: 32,
- },
- notebookTreeRows: {
- gap: 10,
- },
- notebookTreeRowsCompact: {
- gap: 0,
- },
- editorForm: {
- gap: 12,
- padding: 18,
- paddingBottom: 48,
- },
- revisionHistoryContent: {
- gap: 12,
- padding: 16,
- paddingBottom: 48,
- },
- revisionSummaryRow: {
- alignItems: "center",
- flexDirection: "row",
- gap: 10,
- justifyContent: "space-between",
- },
- revisionSummaryText: {
- flex: 1,
- gap: 6,
- minWidth: 0,
- },
- revisionChangeBadge: {
- alignSelf: "flex-start",
- backgroundColor: "#fffbeb",
- borderColor: "#fde68a",
- borderRadius: 999,
- borderWidth: 1,
- color: "#92400e",
- fontSize: 11,
- fontWeight: "700",
- overflow: "hidden",
- paddingHorizontal: 8,
- paddingVertical: 3,
- },
- revisionTimelineLabel: {
- color: "#94a3b8",
- fontSize: 11,
- fontWeight: "700",
- letterSpacing: 0.6,
- textTransform: "uppercase",
- },
- revisionTimeline: {
- gap: 7,
- },
- revisionTimelineState: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderColor: "#cbd5e1",
- borderRadius: 8,
- borderStyle: "dashed",
- borderWidth: 1,
- gap: 12,
- paddingHorizontal: 16,
- paddingVertical: 32,
- },
- revisionTimelineError: {
- color: "#64748b",
- fontSize: 12,
- lineHeight: 18,
- textAlign: "center",
- },
- revisionPill: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- minHeight: 68,
- paddingHorizontal: 12,
- paddingVertical: 9,
- },
- revisionPillActive: {
- backgroundColor: "#ecfdf5",
- borderColor: "#a7f3d0",
- },
- revisionPillTitle: {
- color: "#0f172a",
- fontSize: 13,
- fontWeight: "800",
- },
- revisionPillTitleActive: {
- color: "#047857",
- },
- revisionPillMeta: {
- color: "#64748b",
- fontSize: 11,
- fontWeight: "700",
- marginTop: 4,
- },
- revisionPreviewCard: {
- backgroundColor: "#ffffff",
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- padding: 10,
- },
- revisionPreviewText: {
- color: "#334155",
- fontSize: 13,
- lineHeight: 20,
- },
- label: {
- color: "#334155",
- fontSize: 13,
- fontWeight: "800",
- },
- bottomNav: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderTopColor: "#e2e8f0",
- borderTopWidth: 1,
- flexDirection: "row",
- justifyContent: "space-between",
- paddingHorizontal: 36,
- },
- bottomCreateButton: {
- alignItems: "center",
- backgroundColor: "#10b981",
- borderColor: "#ffffff",
- borderRadius: MOBILE_UI_METRICS.floatingCreateButtonSize / 2,
- borderWidth: 4,
- height: MOBILE_UI_METRICS.floatingCreateButtonSize,
- justifyContent: "center",
- marginTop: -16,
- shadowColor: "#10b981",
- shadowOffset: { width: 0, height: 10 },
- shadowOpacity: 0.28,
- shadowRadius: 18,
- width: MOBILE_UI_METRICS.floatingCreateButtonSize,
- },
- bottomCreateButtonDisabled: {
- backgroundColor: "#cbd5e1",
- shadowOpacity: 0,
- },
- selectionBar: {
- backgroundColor: "#ffffff",
- borderTopColor: "#e2e8f0",
- borderTopWidth: 1,
- bottom: 0,
- left: 0,
- paddingHorizontal: 32,
- paddingTop: 4,
- position: "absolute",
- right: 0,
- },
- selectionActions: {
- flexDirection: "row",
- justifyContent: "space-between",
- },
- selectionAction: {
- alignItems: "center",
- flex: 1,
- gap: 4,
- justifyContent: "center",
- minHeight: 56,
- },
- selectionActionText: {
- color: "#0f172a",
- fontSize: 11,
- fontWeight: "800",
- },
- selectionActionTextDanger: {
- color: "#b91c1c",
- },
- bottomNavItem: {
- alignItems: "center",
- gap: 4,
- minHeight: MOBILE_UI_METRICS.minimumTouchTarget,
- minWidth: 58,
- },
- bottomNavText: {
- color: "#64748b",
- fontSize: 11,
- fontWeight: "700",
- },
- bottomNavTextActive: {
- color: "#0f172a",
- },
- previewBackdrop: {
- alignItems: "center",
- backgroundColor: "#000000",
- flex: 1,
- justifyContent: "center",
- },
- shareImportBackdrop: {
- alignItems: "center",
- backgroundColor: "rgba(15, 23, 42, 0.42)",
- flex: 1,
- justifyContent: "center",
- padding: 24,
- },
- shareImportCard: {
- alignItems: "center",
- backgroundColor: "#ffffff",
- borderRadius: 18,
- gap: 10,
- maxWidth: 340,
- paddingHorizontal: 28,
- paddingVertical: 26,
- width: "100%",
- },
- shareImportTitle: {
- color: "#0f172a",
- fontSize: 17,
- fontWeight: "800",
- marginTop: 4,
- },
- shareImportDescription: {
- color: "#64748b",
- fontSize: 13,
- lineHeight: 20,
- textAlign: "center",
- },
-});
-
-let styles = baseWorkspaceStyles;
-let workspaceStylesTheme: MobileResolvedTheme = "light";
-
-const refreshWorkspaceThemeStyles = (theme: MobileResolvedTheme) => {
- if (workspaceStylesTheme === theme) {
- return;
- }
- styles = resolveMobileThemeStyles(baseWorkspaceStyles, theme);
- workspaceStylesTheme = theme;
-};
diff --git a/apps/mobile/src/screens/WorkspaceSettingsView.tsx b/apps/mobile/src/screens/WorkspaceSettingsView.tsx
new file mode 100644
index 00000000..9dcf00d9
--- /dev/null
+++ b/apps/mobile/src/screens/WorkspaceSettingsView.tsx
@@ -0,0 +1,437 @@
+import { useEffect, useRef, useState, type ComponentRef, type ReactNode } from "react";
+import * as Clipboard from "expo-clipboard";
+import Constants from "expo-constants";
+import { buildGitHubFeedbackUrl, type AuthUser } from "@edgeever/shared";
+import { ActivityIndicator, BackHandler, Linking, Modal, Platform, ScrollView, Switch, View } from "react-native";
+import { Check, ChevronDown, ChevronLeft, ChevronRight, Copy, ExternalLink, Image as ImageIcon, Info, LogOut, MessageSquare, Moon, RefreshCw, ShieldCheck, SlidersHorizontal, Sun, UserRound } from "../components/icons";
+import { Pressable, Text } from "../components/LocalizedText";
+import { useMobileLocale } from "../lib/mobile-locale";
+import { useMobileTheme } from "../lib/mobile-theme";
+import { useMobileUpdate } from "../lib/mobile-update";
+import type { MobileLocalePreference } from "../lib/preferences";
+import { AccountSecurityPanel } from "./AccountSecurityModal";
+import { getResolvedMobileLocale, isEnglishMobileLocale } from "./workspace-utils";
+import { styles } from "./workspace-styles";
+
+const useMobileLocalePreference = () => useMobileLocale().preference;
+
+const MOBILE_APP_VERSION = Constants.expoConfig?.version ?? "0.1.2";
+
+const formatExecutionEnvironment = (environment: string | null | undefined, localePreference: MobileLocaleMode = "system") => {
+ const english = isEnglishMobileLocale(localePreference);
+
+ switch (environment) {
+ case "standalone":
+ return english ? "Standalone app" : "独立安装包";
+ case "storeClient":
+ return english ? "Expo Go / development client" : "Expo Go / 开发客户端";
+ case "bare":
+ return "Bare React Native";
+ default:
+ return environment || getMobileSystemInfoText(localePreference).unknown;
+ }
+};
+const MOBILE_LOCALE_OPTIONS: Array<{ label: string; value: MobileLocalePreference }> = [
+ { label: "跟随系统", value: "system" },
+ { label: "简体中文", value: "zh-CN" },
+ { label: "English", value: "en-US" },
+];
+type SettingsTab = "general" | "account" | "system";
+export type MobileLocaleMode = MobileLocalePreference;
+
+export const SettingsView = ({
+ currentUser,
+ imageCompressionEnabled,
+ localePreference,
+ onClose,
+ onImageCompressionChange,
+ onLocalePreferenceChange,
+ onSignOut,
+}: {
+ currentUser: AuthUser | null;
+ imageCompressionEnabled: boolean;
+ localePreference: MobileLocaleMode;
+ onClose: () => void;
+ onImageCompressionChange: (enabled: boolean) => void;
+ onLocalePreferenceChange: (locale: MobileLocaleMode) => void;
+ onSignOut: () => void;
+}) => {
+ const { resolvedTheme, toggleTheme } = useMobileTheme();
+ const { translate } = useMobileLocale();
+ const [activeTab, setActiveTab] = useState<SettingsTab | null>(null);
+ const [localePickerOpen, setLocalePickerOpen] = useState(false);
+ const [localePickerAnchor, setLocalePickerAnchor] = useState<{ left: number; top: number; width: number } | null>(null);
+ const localeSelectRef = useRef<ComponentRef<typeof Pressable>>(null);
+ const tabs: Array<{ key: SettingsTab; label: string; icon: ReactNode }> = [
+ { key: "general", label: "常规设置", icon: <SlidersHorizontal color="#059669" size={17} /> },
+ { key: "account", label: "登录设置", icon: <ShieldCheck color="#059669" size={17} /> },
+ ];
+ const systemInfoCopy = getMobileSystemInfoText(localePreference);
+ const activeTabItem = activeTab === "system"
+ ? { label: systemInfoCopy.title, icon: <Info color="#059669" size={17} /> }
+ : tabs.find((tab) => tab.key === activeTab);
+ const title = activeTabItem?.label ?? "我的";
+ const activeLocaleLabel = MOBILE_LOCALE_OPTIONS.find((option) => option.value === localePreference)?.label ?? "跟随系统";
+ const openLocalePicker = () => {
+ localeSelectRef.current?.measureInWindow((left, top, width, height) => {
+ setLocalePickerAnchor({ left, top: top + height + 4, width });
+ setLocalePickerOpen(true);
+ });
+ };
+ const openFeedback = () => {
+ void Linking.openURL(buildMobileFeedbackUrl(localePreference));
+ };
+
+ useEffect(() => {
+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
+ if (activeTab) {
+ setActiveTab(null);
+ } else {
+ onClose();
+ }
+ return true;
+ });
+
+ return () => subscription.remove();
+ }, [activeTab, onClose]);
+
+ const renderContent = () => {
+ if (activeTab === "system") {
+ return (
+ <View style={styles.settingsDetailList}>
+ <SystemInfoCard defaultExpanded />
+ </View>
+ );
+ }
+ if (activeTab === "general") {
+ return (
+ <View style={styles.settingsDetailList}>
+ <SettingsGroup title="偏好设置" icon={<ImageIcon color="#047857" size={16} />}>
+ <View style={styles.settingsContentRow}>
+ <View style={styles.preferenceStack}>
+ <View style={styles.preferenceText}>
+ <Text style={styles.settingsRowTitle}>界面语言</Text>
+ <Text style={styles.settingsRowDescription}>切换产品界面的显示语言。</Text>
+ </View>
+ <Pressable accessibilityLabel="界面语言" accessibilityRole="button" onPress={openLocalePicker} ref={localeSelectRef} style={styles.settingsSelect}>
+ <Text style={styles.settingsSelectText}>{activeLocaleLabel}</Text>
+ <ChevronDown color="#64748b" size={18} />
+ </Pressable>
+ </View>
+ </View>
+ <View style={styles.settingsContentRow}>
+ <View style={styles.preferenceStack}>
+ <View style={styles.preferenceText}>
+ <Text style={styles.settingsRowTitle}>压缩笔记内图片</Text>
+ <Text style={styles.settingsRowDescription}>上传大图时在本地压缩,节省资源占用。</Text>
+ </View>
+ <View style={styles.settingsSwitchStart}>
+ <Switch accessibilityLabel={translate("是否压缩笔记内图片")} onValueChange={onImageCompressionChange} value={imageCompressionEnabled} />
+ </View>
+ </View>
+ </View>
+ </SettingsGroup>
+ </View>
+ );
+ }
+ return (
+ <View style={styles.settingsDetailList}>
+ <View style={styles.accountSummaryCard}>
+ <View style={styles.accountSummaryIcon}>
+ <UserRound color="#047857" size={19} />
+ </View>
+ <View style={styles.accountSummaryContent}>
+ <Text style={styles.accountSummaryTitle}>{translate("当前账户")}</Text>
+ <Text style={styles.accountSummaryName}>{currentUser?.displayName || currentUser?.username || "—"}</Text>
+ <Text style={styles.accountSummaryHelp}>
+ @{currentUser?.username ?? "—"} · {currentUser?.role === "owner" ? translate("实例管理员") : translate("成员")}
+ </Text>
+ </View>
+ </View>
+ <View style={styles.settingsGroup}>
+ <AccountSecurityPanel active />
+ </View>
+ <View style={styles.settingsLogoutCard}>
+ <Pressable onPress={onSignOut} style={styles.settingsLogoutButton}>
+ <LogOut color="#ffffff" size={17} />
+ <Text style={styles.settingsLogoutText}>退出登录</Text>
+ </Pressable>
+ </View>
+ </View>
+ );
+ };
+
+ return (
+ <View style={styles.settingsScreen}>
+ <View style={styles.settingsHeader}>
+ <Pressable accessibilityLabel="返回" onPress={() => activeTab ? setActiveTab(null) : onClose()} style={styles.settingsBackButton}>
+ <ChevronLeft color="#64748b" size={21} />
+ </Pressable>
+ <View style={styles.settingsHeaderTitle}>
+ {activeTab ? activeTabItem?.icon : <UserRound color="#047857" size={17} />}
+ <Text numberOfLines={1} style={styles.settingsTitle}>{title}</Text>
+ </View>
+ <Pressable
+ accessibilityLabel={resolvedTheme === "dark" ? "切换到浅色模式" : "切换到深色模式"}
+ accessibilityRole="button"
+ onPress={toggleTheme}
+ style={styles.settingsThemeButton}
+ >
+ {resolvedTheme === "dark" ? <Sun color="#64748b" size={19} /> : <Moon color="#64748b" size={19} />}
+ <Text numberOfLines={1} style={styles.settingsThemeText}>{resolvedTheme === "dark" ? "切换到浅色模式" : "切换到深色模式"}</Text>
+ </Pressable>
+ </View>
+ <ScrollView contentContainerStyle={styles.settingsScrollContent} style={styles.viewBody}>
+ {activeTab === null ? (
+ <View style={styles.settingsDetailList}>
+ <View style={styles.settingsMenu}>
+ {tabs.map((tab, index) => (
+ <Pressable key={tab.key} onPress={() => setActiveTab(tab.key)} style={[styles.settingsMenuRow, index > 0 && styles.settingsMenuRowBorder]}>
+ <View style={styles.settingsMenuLabel}>
+ <View style={styles.settingsMenuIcon}>{tab.icon}</View>
+ <Text style={styles.settingsMenuText}>{tab.label}</Text>
+ </View>
+ <ChevronRight color="#94a3b8" size={17} />
+ </Pressable>
+ ))}
+ </View>
+ <View style={styles.settingsMenu}>
+ <Pressable accessibilityRole="button" onPress={() => setActiveTab("system")} style={styles.settingsMenuRow}>
+ <View style={styles.settingsMenuLabel}>
+ <View style={styles.settingsMenuIcon}><Info color="#059669" size={17} /></View>
+ <View style={styles.settingsFeedbackCopy}>
+ <Text style={styles.settingsMenuText}>{systemInfoCopy.title}</Text>
+ <Text style={styles.settingsFeedbackDescription}>{systemInfoCopy.description}</Text>
+ </View>
+ </View>
+ <ChevronRight color="#94a3b8" size={17} />
+ </Pressable>
+ <Pressable accessibilityRole="link" onPress={openFeedback} style={[styles.settingsMenuRow, styles.settingsMenuRowBorder]}>
+ <View style={styles.settingsMenuLabel}>
+ <View style={[styles.settingsMenuIcon, styles.settingsFeedbackIcon]}><MessageSquare color="#64748b" size={17} /></View>
+ <View style={styles.settingsFeedbackCopy}>
+ <Text style={styles.settingsMenuText}>意见反馈</Text>
+ <Text style={styles.settingsFeedbackDescription}>报告问题或提出功能建议</Text>
+ </View>
+ </View>
+ <ExternalLink color="#94a3b8" size={17} />
+ </Pressable>
+ </View>
+ </View>
+ ) : renderContent()}
+ </ScrollView>
+ <Modal animationType="fade" onRequestClose={() => setLocalePickerOpen(false)} statusBarTranslucent transparent visible={localePickerOpen && Boolean(localePickerAnchor)}>
+ <Pressable onPress={() => setLocalePickerOpen(false)} style={styles.localePickerBackdrop}>
+ {localePickerAnchor ? (
+ <View style={[styles.localePickerMenu, localePickerAnchor]}>
+ {MOBILE_LOCALE_OPTIONS.map((option) => {
+ const active = localePreference === option.value;
+ return (
+ <Pressable
+ accessibilityRole="radio"
+ accessibilityState={{ checked: active }}
+ key={option.value}
+ onPress={() => {
+ onLocalePreferenceChange(option.value);
+ setLocalePickerOpen(false);
+ }}
+ style={[styles.localePickerOption, active && styles.localePickerOptionActive]}
+ >
+ <Text style={[styles.localePickerOptionText, active && styles.localePickerOptionTextActive]}>{option.label}</Text>
+ {active ? <Check color="#047857" size={16} /> : null}
+ </Pressable>
+ );
+ })}
+ </View>
+ ) : null}
+ </Pressable>
+ </Modal>
+ </View>
+ );
+};
+
+const SettingsGroup = ({ children, icon, title }: { children: ReactNode; icon?: ReactNode; title?: string }) => (
+ <View style={styles.settingsGroup}>
+ {title ? <View style={styles.settingsGroupHeader}>{icon}<Text style={styles.settingsGroupTitle}>{title}</Text></View> : null}
+ {children}
+ </View>
+);
+
+
+const SettingsActionButton = ({
+ children,
+ disabled = false,
+ label,
+ onPress,
+}: {
+ children: ReactNode;
+ disabled?: boolean;
+ label: string;
+ onPress: () => void;
+}) => (
+ <Pressable accessibilityRole="button" disabled={disabled} onPress={onPress} style={[styles.actionButton, disabled && styles.buttonDisabled]}>
+ {children}
+ <Text style={styles.actionButtonText}>{label}</Text>
+ </Pressable>
+);
+
+const SystemInfoCard = ({ defaultExpanded = false }: { defaultExpanded?: boolean }) => {
+ const [copied, setCopied] = useState(false);
+ const [expanded, setExpanded] = useState(defaultExpanded);
+ const { checkForUpdate, hasUpdate, status } = useMobileUpdate();
+ const localePreference = useMobileLocalePreference();
+ const copy = getMobileSystemInfoText(localePreference);
+ const infoItems = getMobileSystemInfoItems(localePreference);
+
+ const copySystemInfo = async () => {
+ await Clipboard.setStringAsync(infoItems.map((item) => `${item.label}: ${item.value}`).join("\n"));
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1600);
+ };
+
+ return (
+ <View style={styles.settingsGroup}>
+ <Pressable accessibilityState={{ expanded }} onPress={() => setExpanded((value) => !value)} style={styles.settingsAccordionHeader}>
+ <View style={styles.settingsLinkCopy}>
+ <View style={styles.settingsGroupHeader}>
+ <Info color="#047857" size={16} />
+ <Text style={styles.settingsGroupTitle}>{copy.title}</Text>
+ {hasUpdate ? <View accessibilityLabel="有新版本" style={styles.updateDot} /> : null}
+ </View>
+ <Text style={styles.settingsLinkDescription}>{copy.description}</Text>
+ </View>
+ {expanded ? <ChevronDown color="#94a3b8" size={17} /> : <ChevronRight color="#94a3b8" size={17} />}
+ </Pressable>
+ {expanded ? (
+ <View style={styles.settingsAccordionContent}>
+ <SettingsActionButton label={copied ? "已复制" : "复制信息"} onPress={copySystemInfo}>
+ {copied ? <ShieldCheck color="#047857" size={16} /> : <Copy color="#0f172a" size={16} />}
+ </SettingsActionButton>
+ <SettingsActionButton
+ disabled={status === "checking"}
+ label={status === "checking" ? "正在检查…" : hasUpdate ? "发现新版本" : "检查更新"}
+ onPress={() => void checkForUpdate()}
+ >
+ {status === "checking" ? <ActivityIndicator color="#047857" size="small" /> : <RefreshCw color="#047857" size={16} />}
+ </SettingsActionButton>
+ <View style={styles.systemInfoRows}>
+ {Array.from({ length: Math.ceil(infoItems.length / 3) }, (_, rowIndex) => {
+ const rowItems = infoItems.slice(rowIndex * 3, rowIndex * 3 + 3);
+
+ return (
+ <View
+ key={`system-info-row-${rowIndex}`}
+ style={[styles.systemInfoRow, rowIndex === Math.ceil(infoItems.length / 3) - 1 && styles.systemInfoRowLast]}
+ >
+ {rowItems.map((item, itemIndex) => (
+ <View
+ key={item.label}
+ style={[styles.systemInfoCell, itemIndex < rowItems.length - 1 && styles.systemInfoCellDivider]}
+ >
+ <Text numberOfLines={1} style={styles.panelLabel}>{item.label}</Text>
+ <Text numberOfLines={1} selectable style={styles.systemInfoListValue}>
+ {item.value}
+ </Text>
+ </View>
+ ))}
+ </View>
+ );
+ })}
+ </View>
+ </View>
+ ) : null}
+ </View>
+ );
+};
+
+
+const getMobileSystemInfoText = (localePreference: MobileLocaleMode) =>
+ isEnglishMobileLocale(localePreference)
+ ? {
+ appIdentifier: "App identifier",
+ build: "Build",
+ client: "Client",
+ description: "View the current app version, build identifier, and runtime environment.",
+ disconnected: "Disconnected",
+ followSystem: "Follow system",
+ installMode: "Mode",
+ instanceUrl: "Instance URL",
+ language: "Language",
+ memoCount: "Notes",
+ notSet: "Not set",
+ notebookCount: "Notebooks",
+ platform: "System",
+ mobileApp: "Mobile app",
+ platformVersion: "System version",
+ timeZone: "Time zone",
+ title: "System info",
+ unknown: "Unknown",
+ version: "Version",
+ }
+ : {
+ appIdentifier: "应用标识",
+ build: "构建",
+ client: "客户端",
+ description: "查看当前应用版本、构建标识和运行环境。",
+ disconnected: "未连接",
+ followSystem: "跟随系统",
+ installMode: "安装形态",
+ instanceUrl: "实例地址",
+ language: "语言",
+ memoCount: "笔记总数",
+ notSet: "未设置",
+ notebookCount: "笔记本数量",
+ platform: "系统",
+ mobileApp: "移动应用",
+ platformVersion: "系统版本",
+ timeZone: "时区",
+ title: "系统信息",
+ unknown: "未知",
+ version: "版本",
+ };
+
+const getMobileSystemInfoItems = (localePreference: MobileLocaleMode) => {
+ const copy = getMobileSystemInfoText(localePreference);
+ const resolvedLocale = getResolvedMobileLocale(localePreference);
+ const platformName =
+ Platform.OS === "android"
+ ? "Android"
+ : Platform.OS === "ios"
+ ? "iOS"
+ : Platform.OS === "macos"
+ ? "macOS"
+ : Platform.OS === "windows"
+ ? "Windows"
+ : Platform.OS;
+
+ return [
+ { label: copy.version, value: `v${MOBILE_APP_VERSION}` },
+ { label: copy.build, value: __DEV__ ? "development" : "production" },
+ { label: copy.client, value: copy.mobileApp },
+ { label: copy.platform, value: platformName },
+ { label: copy.platformVersion, value: String(Platform.Version) },
+ { label: copy.language, value: localePreference === "system" ? `${resolvedLocale} (${copy.followSystem})` : resolvedLocale },
+ { label: copy.timeZone, value: Intl.DateTimeFormat().resolvedOptions().timeZone || copy.unknown },
+ { label: copy.installMode, value: formatExecutionEnvironment(Constants.executionEnvironment, localePreference) },
+ ];
+};
+
+const buildMobileFeedbackUrl = (localePreference: MobileLocaleMode) => {
+ const english = isEnglishMobileLocale(localePreference);
+
+ return buildGitHubFeedbackUrl({
+ contentHeading: english ? "Feedback" : "反馈内容",
+ contentPrompt: english
+ ? "Describe the problem, steps to reproduce it, or the feature you would like to see."
+ : "请描述遇到的问题、复现步骤,或你希望增加的功能。",
+ privacyNotice: english
+ ? "GitHub Issues are public. Do not include passwords, tokens, instance URLs, or private note content."
+ : "GitHub Issue 公开可见,请勿提交密码、Token、实例地址或私人笔记内容。",
+ systemInfo: getMobileSystemInfoItems(localePreference),
+ systemInfoHeading: english ? "System information" : "系统信息",
+ systemInfoNotice: english
+ ? "The following information was generated by EdgeEver to help diagnose the issue."
+ : "以下信息由 EdgeEver 自动生成,可帮助定位问题。",
+ titlePrefix: english ? "[Feedback] " : "[反馈] ",
+ });
+};
diff --git a/apps/mobile/src/screens/workspace-memo-cache.test.ts b/apps/mobile/src/screens/workspace-memo-cache.test.ts
new file mode 100644
index 00000000..369ad4c8
--- /dev/null
+++ b/apps/mobile/src/screens/workspace-memo-cache.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test } from "bun:test";
+import type { MemoDetail } from "@edgeever/shared";
+import { createOptimisticMemo, memoMatchesListQuery } from "./workspace-memo-cache";
+
+const memo: MemoDetail = {
+ id: "memo_1",
+ notebookId: "notebook_1",
+ title: "Original",
+ excerpt: "Original body",
+ contentJson: { type: "doc", content: [] },
+ contentMarkdown: "Original body",
+ contentText: "Original body",
+ tags: [],
+ isPinned: false,
+ isArchived: false,
+ isDeleted: false,
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ deletedAt: null,
+ revision: 1,
+ sourceMemoIds: [],
+ mergeSourceCount: 0,
+ mergedIntoMemoId: null,
+ contentHash: "hash_1",
+};
+
+describe("mobile workspace memo cache", () => {
+ test("builds a complete optimistic memo without mutating the source", () => {
+ const optimistic = createOptimisticMemo(memo, {
+ contentMarkdown: "# Updated\n\nBody",
+ isPinned: true,
+ tags: ["updated"],
+ title: "Updated",
+ });
+
+ expect(optimistic).toMatchObject({
+ title: "Updated",
+ contentText: "Updated Body",
+ excerpt: "Updated Body",
+ isPinned: true,
+ tags: ["updated"],
+ });
+ expect(memo.title).toBe("Original");
+ });
+
+ test("matches the active list view, notebook, and filter contract", () => {
+ expect(memoMatchesListQuery(memo, ["mobile", "memos", "notebook", "all", "all", "updated-desc", []])).toBe(true);
+ expect(memoMatchesListQuery(memo, ["mobile", "memos", "trash", "all", "all", "updated-desc", []])).toBe(false);
+ expect(memoMatchesListQuery(memo, ["mobile", "memos", "notebook", "notebook_2", "all", "updated-desc", ["notebook_2"]])).toBe(false);
+ expect(memoMatchesListQuery(memo, ["mobile", "memos", "notebook", "all", "tagged", "updated-desc", []])).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/screens/workspace-memo-cache.ts b/apps/mobile/src/screens/workspace-memo-cache.ts
new file mode 100644
index 00000000..71a53ed0
--- /dev/null
+++ b/apps/mobile/src/screens/workspace-memo-cache.ts
@@ -0,0 +1,149 @@
+import { type InfiniteData, type QueryClient } from "@tanstack/react-query";
+import type { MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";
+import { listLocalMemos } from "../lib/local-mirror";
+import { markdownToLocalText, sortMemoSummaries } from "./workspace-utils";
+
+const ALL_NOTES_ID = "all";
+
+export type MobileMemoUpdatePayload = {
+ title?: string;
+ contentJson?: TiptapDoc;
+ contentMarkdown?: string;
+ isPinned?: boolean;
+ notebookId?: string;
+ tags?: string[];
+};
+
+export const createOptimisticMemo = (
+ memo: MemoDetail,
+ payload: MobileMemoUpdatePayload
+): MemoDetail => {
+ const contentMarkdown = payload.contentMarkdown ?? memo.contentMarkdown;
+ const contentText = markdownToLocalText(contentMarkdown);
+
+ return {
+ ...memo,
+ ...(payload.title !== undefined ? { title: payload.title } : {}),
+ ...(payload.isPinned !== undefined ? { isPinned: payload.isPinned } : {}),
+ ...(payload.notebookId !== undefined ? { notebookId: payload.notebookId } : {}),
+ ...(payload.tags !== undefined ? { tags: payload.tags } : {}),
+ ...(payload.contentJson !== undefined ? { contentJson: payload.contentJson } : {}),
+ ...(payload.contentMarkdown !== undefined
+ ? {
+ contentMarkdown,
+ contentText,
+ excerpt: contentText.slice(0, 180),
+ }
+ : {}),
+ updatedAt: new Date().toISOString(),
+ };
+};
+
+export const memoMatchesListQuery = (memo: MemoSummary, queryKey: readonly unknown[]) => {
+ const view = queryKey[2];
+ const notebookId = queryKey[3];
+ const filter = queryKey[4];
+ const notebookIds = Array.isArray(queryKey[6]) ? queryKey[6] : [];
+
+ if ((view === "trash") !== memo.isDeleted) {
+ return false;
+ }
+ if (notebookId !== ALL_NOTES_ID && !notebookIds.includes(memo.notebookId)) {
+ return false;
+ }
+ if (filter === "tagged" && memo.tags.length === 0) {
+ return false;
+ }
+ if (filter === "untagged" && memo.tags.length > 0) {
+ return false;
+ }
+ if (filter === "pinned" && !memo.isPinned) {
+ return false;
+ }
+
+ return true;
+};
+
+export const applyOptimisticMemoToCache = (queryClient: QueryClient, previousMemo: MemoDetail, nextMemo: MemoDetail) => {
+ const detailQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "memo"] });
+
+ for (const query of detailQueries) {
+ const data = query.state.data as { memo?: MemoDetail } | undefined;
+ if (data?.memo?.id === nextMemo.id || data?.memo?.id === previousMemo.id) {
+ queryClient.setQueryData(query.queryKey, { ...data, memo: nextMemo });
+ }
+ }
+
+ const listQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "memos"] });
+
+ for (const query of listQueries) {
+ const data = query.state.data as InfiniteData<Awaited<ReturnType<typeof listLocalMemos>>, number> | undefined;
+ if (!Array.isArray(data?.pages) || data.pages.length === 0) {
+ continue;
+ }
+
+ const previouslyMatched = memoMatchesListQuery(previousMemo, query.queryKey);
+ const nextMatches = memoMatchesListQuery(nextMemo, query.queryKey);
+ const flattened = data.pages.flatMap((page) => page.memos);
+ const withoutMemo = flattened.filter((memo) => memo.id !== nextMemo.id && memo.id !== previousMemo.id);
+ const nextMemos = nextMatches ? sortMemoSummaries([nextMemo, ...withoutMemo], query.queryKey[5]) : withoutMemo;
+ const totalCount = Math.max(0, data.pages[0].totalCount + (nextMatches ? 1 : 0) - (previouslyMatched ? 1 : 0));
+ let cursor = 0;
+ const pages = data.pages.map((page, index) => {
+ const pageSize = index === data.pages.length - 1 ? Math.min(page.memos.length, Math.max(0, nextMemos.length - cursor)) : page.memos.length;
+ const memos = nextMemos.slice(cursor, cursor + pageSize);
+ cursor += pageSize;
+ return { ...page, memos, totalCount };
+ });
+
+ queryClient.setQueryData(query.queryKey, { ...data, pages });
+ }
+
+ const searchQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "search"] });
+ for (const query of searchQueries) {
+ const data = query.state.data as InfiniteData<Awaited<ReturnType<typeof listLocalMemos>>, number> | undefined;
+ if (Array.isArray(data?.pages) && data.pages.some((page) => page.memos.some((memo) => memo.id === nextMemo.id || memo.id === previousMemo.id))) {
+ queryClient.setQueryData(query.queryKey, {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ memos: page.memos.map((memo) => (memo.id === nextMemo.id || memo.id === previousMemo.id ? nextMemo : memo)),
+ })),
+ });
+ }
+ }
+
+ if (previousMemo.notebookId !== nextMemo.notebookId) {
+ queryClient.setQueriesData<{ notebooks: Notebook[] }>({ queryKey: ["mobile", "notebooks"] }, (data) => {
+ if (!data) {
+ return data;
+ }
+
+ return {
+ ...data,
+ notebooks: data.notebooks.map((notebook) => {
+ if (notebook.id === previousMemo.notebookId) {
+ return { ...notebook, memoCount: Math.max(0, notebook.memoCount - 1) };
+ }
+ if (notebook.id === nextMemo.notebookId) {
+ return { ...notebook, memoCount: notebook.memoCount + 1, lastMemoUpdatedAt: nextMemo.updatedAt };
+ }
+ return notebook;
+ }),
+ };
+ });
+ }
+};
+
+export const findCachedMemoDetail = (queryClient: QueryClient, memoId: string) => {
+ const detailQueries = queryClient.getQueryCache().findAll({ queryKey: ["mobile", "memo"] });
+
+ for (const query of detailQueries) {
+ const data = query.state.data as { memo?: MemoDetail } | undefined;
+ if (data?.memo?.id === memoId) {
+ return data.memo;
+ }
+ }
+
+ return null;
+};
diff --git a/apps/mobile/src/screens/workspace-styles.ts b/apps/mobile/src/screens/workspace-styles.ts
new file mode 100644
index 00000000..ddcadaa1
--- /dev/null
+++ b/apps/mobile/src/screens/workspace-styles.ts
@@ -0,0 +1,1935 @@
+import { StyleSheet } from "react-native";
+import { MOBILE_UI_METRICS } from "@edgeever/shared/mobile-ui";
+import { resolveMobileThemeStyles, type MobileResolvedTheme } from "../lib/mobile-theme";
+
+const DETAIL_CONTENT_HORIZONTAL_PADDING = 16;
+
+const baseWorkspaceStyles = StyleSheet.create({
+ editorRuntimePrewarm: {
+ position: "absolute",
+ left: -2,
+ top: -2,
+ width: 1,
+ height: 1,
+ opacity: 0.01,
+ },
+ safeArea: {
+ backgroundColor: "#f8fafc",
+ flex: 1,
+ },
+ viewBody: {
+ flex: 1,
+ paddingBottom: 0,
+ },
+ settingsScreen: {
+ backgroundColor: "#f8fafc",
+ flex: 1,
+ },
+ settingsHeader: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ minHeight: 56,
+ paddingHorizontal: 12,
+ },
+ settingsBackButton: {
+ alignItems: "center",
+ borderRadius: 8,
+ height: 36,
+ justifyContent: "center",
+ width: 36,
+ },
+ settingsThemeButton: {
+ alignItems: "center",
+ borderRadius: 8,
+ flexDirection: "row",
+ gap: 8,
+ height: 36,
+ justifyContent: "center",
+ paddingHorizontal: 8,
+ },
+ settingsThemeText: {
+ color: "#475569",
+ fontSize: 14,
+ fontWeight: "700",
+ },
+ settingsHeaderTitle: {
+ alignItems: "center",
+ flex: 1,
+ flexDirection: "row",
+ gap: 8,
+ justifyContent: "flex-start",
+ },
+ updateDot: {
+ backgroundColor: "#10b981",
+ borderColor: "#ffffff",
+ borderRadius: 5,
+ borderWidth: 1,
+ height: 9,
+ marginLeft: 1,
+ width: 9,
+ },
+ settingsTitle: {
+ color: "#0f172a",
+ fontSize: 16,
+ fontWeight: "800",
+ },
+ settingsScrollContent: {
+ padding: 16,
+ paddingBottom: 96,
+ },
+ settingsMenu: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 16,
+ borderWidth: 1,
+ overflow: "hidden",
+ },
+ settingsMenuRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ justifyContent: "space-between",
+ minHeight: 64,
+ paddingHorizontal: 16,
+ },
+ settingsMenuRowBorder: {
+ borderTopColor: "#f1f5f9",
+ borderTopWidth: 1,
+ },
+ settingsMenuLabel: {
+ alignItems: "center",
+ flex: 1,
+ flexDirection: "row",
+ gap: 12,
+ minWidth: 0,
+ },
+ settingsMenuIcon: {
+ alignItems: "center",
+ backgroundColor: "#ecfdf5",
+ borderRadius: 8,
+ height: 32,
+ justifyContent: "center",
+ width: 32,
+ },
+ settingsMenuText: {
+ color: "#1e293b",
+ fontSize: 14,
+ fontWeight: "700",
+ },
+ settingsFeedbackCopy: {
+ flex: 1,
+ gap: 1,
+ minWidth: 0,
+ },
+ settingsFeedbackDescription: {
+ color: "#64748b",
+ fontSize: 12,
+ lineHeight: 17,
+ },
+ settingsFeedbackIcon: {
+ backgroundColor: "#f1f5f9",
+ },
+ settingsDetailList: {
+ gap: 16,
+ },
+ accountSummaryCard: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 12,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 12,
+ padding: 16,
+ },
+ accountSummaryIcon: {
+ alignItems: "center",
+ backgroundColor: "#ecfdf5",
+ borderRadius: 999,
+ height: 40,
+ justifyContent: "center",
+ width: 40,
+ },
+ accountSummaryContent: {
+ flex: 1,
+ minWidth: 0,
+ },
+ accountSummaryHelp: {
+ color: "#64748b",
+ fontSize: 12,
+ lineHeight: 18,
+ marginTop: 3,
+ },
+ accountSummaryTitle: {
+ color: "#64748b",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ accountSummaryName: {
+ color: "#0f172a",
+ fontSize: 15,
+ fontWeight: "800",
+ marginTop: 2,
+ },
+ settingsGroup: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 12,
+ borderWidth: 1,
+ overflow: "hidden",
+ },
+ settingsAiEmbeddedCardFirst: {
+ borderRadius: 0,
+ borderWidth: 0,
+ },
+ settingsAiEmbeddedCard: {
+ borderBottomWidth: 0,
+ borderLeftWidth: 0,
+ borderRadius: 0,
+ borderRightWidth: 0,
+ borderTopColor: "#f1f5f9",
+ borderTopWidth: 1,
+ },
+ settingsGroupHeader: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 8,
+ padding: 16,
+ },
+ settingsGroupTitle: {
+ color: "#0f172a",
+ fontSize: 14,
+ fontWeight: "800",
+ },
+ settingsContentRow: {
+ borderTopColor: "#f1f5f9",
+ borderTopWidth: 1,
+ gap: 10,
+ minHeight: 64,
+ padding: 16,
+ },
+ settingsSelect: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ justifyContent: "space-between",
+ minHeight: 40,
+ paddingHorizontal: 12,
+ },
+ settingsSelectText: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 14,
+ },
+ settingsSwitchStart: {
+ alignItems: "flex-start",
+ },
+ settingsRowTitle: {
+ color: "#0f172a",
+ fontSize: 14,
+ fontWeight: "700",
+ },
+ settingsRowDescription: {
+ color: "#64748b",
+ fontSize: 12,
+ lineHeight: 17,
+ },
+ settingsLinkDescription: {
+ color: "#64748b",
+ fontSize: 12,
+ lineHeight: 17,
+ paddingHorizontal: 16,
+ },
+ settingsAccordionHeader: {
+ alignItems: "center",
+ flexDirection: "row",
+ justifyContent: "space-between",
+ paddingRight: 16,
+ },
+ settingsAccordionChevron: {
+ transform: [{ rotate: "0deg" }],
+ },
+ settingsAccordionChevronExpanded: {
+ transform: [{ rotate: "180deg" }],
+ },
+ settingsAccordionContent: {
+ borderTopColor: "#f1f5f9",
+ borderTopWidth: 1,
+ gap: 10,
+ padding: 16,
+ },
+ settingsDialogBackdrop: {
+ alignItems: "center",
+ backgroundColor: "rgba(15, 23, 42, 0.46)",
+ flex: 1,
+ justifyContent: "center",
+ padding: 20,
+ },
+ localePickerBackdrop: {
+ flex: 1,
+ },
+ localePickerMenu: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ elevation: 8,
+ overflow: "hidden",
+ padding: 4,
+ position: "absolute",
+ shadowColor: "#0f172a",
+ shadowOffset: { height: 4, width: 0 },
+ shadowOpacity: 0.14,
+ shadowRadius: 10,
+ },
+ localePickerOption: {
+ alignItems: "center",
+ borderRadius: 6,
+ flexDirection: "row",
+ justifyContent: "space-between",
+ minHeight: 38,
+ paddingHorizontal: 10,
+ },
+ localePickerOptionActive: {
+ backgroundColor: "#ecfdf5",
+ },
+ localePickerOptionText: {
+ color: "#334155",
+ flex: 1,
+ fontSize: 14,
+ },
+ localePickerOptionTextActive: {
+ color: "#047857",
+ fontWeight: "700",
+ },
+ settingsLinkCopy: {
+ flex: 1,
+ paddingBottom: 16,
+ },
+ settingsLogoutButton: {
+ alignItems: "center",
+ alignSelf: "flex-start",
+ backgroundColor: "#e11d48",
+ borderRadius: 8,
+ flexDirection: "row",
+ gap: 8,
+ minHeight: 40,
+ paddingHorizontal: 14,
+ },
+ settingsLogoutCard: {
+ backgroundColor: "#fff1f2",
+ borderColor: "#fecaca",
+ borderRadius: 8,
+ borderWidth: 1,
+ padding: 16,
+ },
+ settingsLogoutText: {
+ color: "#ffffff",
+ fontSize: 14,
+ fontWeight: "800",
+ },
+ iconButton: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ height: 38,
+ justifyContent: "center",
+ width: 38,
+ },
+ iconButtonPlaceholder: {
+ height: 38,
+ width: 38,
+ },
+ mobileListHeader: {
+ backgroundColor: "#f8fafc",
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ paddingBottom: 8,
+ paddingHorizontal: 16,
+ paddingTop: 8,
+ },
+ mobileSelectionHeader: {
+ alignItems: "center",
+ flexDirection: "row",
+ minHeight: 44,
+ },
+ mobileSelectionTitle: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 17,
+ fontWeight: "800",
+ paddingHorizontal: 8,
+ },
+ mobileSelectionClose: {
+ alignItems: "center",
+ height: 38,
+ justifyContent: "center",
+ width: 38,
+ },
+ mobileListTitleRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ justifyContent: "space-between",
+ marginBottom: 12,
+ minHeight: MOBILE_UI_METRICS.compactControlHeight,
+ },
+ mobileNotebookTitleButton: {
+ alignItems: "center",
+ flexDirection: "row",
+ flexShrink: 1,
+ gap: 4,
+ minHeight: MOBILE_UI_METRICS.compactControlHeight,
+ paddingRight: 12,
+ },
+ mobileNotebookTitle: {
+ color: "#0f172a",
+ flexShrink: 1,
+ fontSize: 17,
+ fontWeight: "700",
+ },
+ mobileMoreButton: {
+ alignItems: "center",
+ borderRadius: MOBILE_UI_METRICS.compactControlHeight / 2,
+ height: MOBILE_UI_METRICS.compactControlHeight,
+ justifyContent: "center",
+ width: MOBILE_UI_METRICS.compactControlHeight,
+ },
+ mobileSearchRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 8,
+ },
+ mobileSearchButton: {
+ alignItems: "center",
+ backgroundColor: "#f1f5f9",
+ borderColor: "transparent",
+ borderRadius: MOBILE_UI_METRICS.compactControlHeight / 2,
+ borderWidth: 1,
+ flex: 1,
+ flexDirection: "row",
+ gap: 8,
+ height: MOBILE_UI_METRICS.compactControlHeight,
+ paddingHorizontal: 12,
+ },
+ mobileSearchButtonActive: {
+ backgroundColor: "#ecfdf5",
+ borderColor: "#10b981",
+ },
+ mobileSearchButtonActiveDark: {
+ backgroundColor: "rgb(255, 255, 255)",
+ },
+ mobileSearchInput: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 14,
+ height: MOBILE_UI_METRICS.compactControlHeight,
+ paddingVertical: 0,
+ },
+ mobileSearchInputActiveDark: {
+ color: "rgb(15, 23, 42)",
+ },
+ mobileSearchClearButton: {
+ alignItems: "center",
+ height: 28,
+ justifyContent: "center",
+ width: 28,
+ },
+ mobileListConstraint: {
+ alignItems: "center",
+ backgroundColor: "rgb(236, 253, 245)",
+ borderColor: "rgb(167, 243, 208)",
+ borderLeftColor: "rgb(16, 185, 129)",
+ borderLeftWidth: 3,
+ borderRadius: 6,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 8,
+ marginTop: 12,
+ minHeight: 32,
+ paddingHorizontal: 10,
+ paddingVertical: 6,
+ },
+ mobileListConstraintFilter: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderLeftColor: "#e2e8f0",
+ borderLeftWidth: 1,
+ },
+ mobileSearchStatusPill: {
+ alignItems: "center",
+ backgroundColor: "#059669",
+ borderRadius: 999,
+ flexDirection: "row",
+ gap: 4,
+ paddingHorizontal: 8,
+ paddingVertical: 4,
+ },
+ mobileSearchStatusPillText: {
+ color: "#ffffff",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ mobileListConstraintText: {
+ color: "#065f46",
+ flex: 1,
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ mobileListConstraintTextFilter: {
+ color: "#64748b",
+ },
+ mobileListConstraintAction: {
+ color: "#065f46",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ mobileListConstraintActionFilter: {
+ color: "#475569",
+ },
+ mobileFilterButton: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: MOBILE_UI_METRICS.compactControlHeight / 2,
+ borderWidth: 1,
+ height: MOBILE_UI_METRICS.compactControlHeight,
+ justifyContent: "center",
+ width: MOBILE_UI_METRICS.compactControlHeight,
+ },
+ mobileFilterButtonActive: {
+ backgroundColor: "#334155",
+ borderColor: "#334155",
+ },
+ searchBox: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 10,
+ minHeight: 46,
+ paddingHorizontal: 12,
+ },
+ searchInput: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 15,
+ minHeight: 44,
+ },
+ layoutToggle: {
+ alignSelf: "flex-start",
+ backgroundColor: "#f8fafc",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ overflow: "hidden",
+ },
+ layoutToggleButton: {
+ alignItems: "center",
+ flexDirection: "row",
+ height: 36,
+ justifyContent: "center",
+ width: 36,
+ },
+ layoutToggleButtonActive: {
+ backgroundColor: "#ecfdf5",
+ },
+ secondaryIconButton: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ height: 40,
+ justifyContent: "center",
+ width: 40,
+ },
+ optionPill: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ justifyContent: "center",
+ marginRight: 6,
+ minHeight: 32,
+ paddingHorizontal: 12,
+ },
+ optionPillActive: {
+ backgroundColor: "#ecfdf5",
+ borderColor: "#a7f3d0",
+ },
+ optionPillText: {
+ color: "#475569",
+ fontSize: 13,
+ fontWeight: "700",
+ },
+ optionPillTextActive: {
+ color: "#047857",
+ },
+ list: {
+ paddingBottom: 18,
+ paddingHorizontal: 12,
+ paddingTop: 12,
+ },
+ memoList: {
+ flex: 1,
+ },
+ listLoadingFooter: {
+ marginVertical: 18,
+ },
+ emptyList: {
+ flexGrow: 1,
+ paddingBottom: 22,
+ },
+ memoListStateWrap: {
+ paddingHorizontal: 12,
+ paddingTop: 16,
+ },
+ 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: 13,
+ lineHeight: 20,
+ marginTop: 7,
+ maxWidth: 300,
+ textAlign: "center",
+ },
+ memoSyncBanner: {
+ alignItems: "center",
+ backgroundColor: "#ecfdf5",
+ borderColor: "#a7f3d0",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 12,
+ marginBottom: 10,
+ paddingHorizontal: 14,
+ paddingVertical: 12,
+ },
+ memoSyncBannerContent: {
+ flex: 1,
+ },
+ memoSyncBannerTitle: {
+ color: "#065f46",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ memoSyncBannerDescription: {
+ color: "#047857",
+ fontSize: 12,
+ marginTop: 2,
+ },
+ memoSyncProgressTrack: {
+ backgroundColor: "#d1fae5",
+ borderRadius: 999,
+ height: 4,
+ marginTop: 10,
+ overflow: "hidden",
+ width: "100%",
+ },
+ memoSyncProgressFill: {
+ backgroundColor: "#059669",
+ borderRadius: 999,
+ height: "100%",
+ },
+ memoSyncErrorBanner: {
+ alignItems: "center",
+ backgroundColor: "#fffbeb",
+ borderColor: "#fcd34d",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 10,
+ marginBottom: 10,
+ paddingHorizontal: 14,
+ paddingVertical: 12,
+ },
+ memoSyncErrorBannerTitle: {
+ color: "#451a03",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ memoSyncErrorBannerDescription: {
+ color: "#92400e",
+ fontSize: 12,
+ lineHeight: 18,
+ marginTop: 2,
+ },
+ memoSyncErrorRetryButton: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 5,
+ paddingHorizontal: 4,
+ paddingVertical: 8,
+ },
+ memoListErrorCard: {
+ alignItems: "center",
+ backgroundColor: "#fffbeb",
+ borderColor: "#fcd34d",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ paddingHorizontal: 16,
+ paddingVertical: 34,
+ },
+ memoListErrorTitle: {
+ color: "#451a03",
+ fontSize: 14,
+ fontWeight: "800",
+ },
+ memoListErrorDescription: {
+ color: "#92400e",
+ fontSize: 12,
+ lineHeight: 20,
+ marginTop: 8,
+ maxWidth: 300,
+ textAlign: "center",
+ },
+ memoListRetryButton: {
+ alignItems: "center",
+ backgroundColor: "#fef3c7",
+ borderRadius: 8,
+ flexDirection: "row",
+ gap: 7,
+ marginTop: 16,
+ minHeight: 36,
+ paddingHorizontal: 12,
+ },
+ memoListRetryText: {
+ color: "#92400e",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ memoListEmptyCard: {
+ alignItems: "center",
+ alignSelf: "stretch",
+ backgroundColor: "#ffffff",
+ borderColor: "#cbd5e1",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ marginHorizontal: 12,
+ marginTop: 12,
+ paddingHorizontal: 16,
+ paddingVertical: 34,
+ },
+ memoCard: {
+ alignItems: "stretch",
+ backgroundColor: "#ffffff",
+ borderColor: "#f1f5f9",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ marginBottom: 12,
+ minHeight: 132,
+ overflow: "hidden",
+ },
+ memoCardCompact: {
+ marginBottom: 10,
+ minHeight: 84,
+ },
+ memoCardSelected: {
+ backgroundColor: "#f8fafc",
+ borderColor: "#e2e8f0",
+ },
+ memoCardContent: {
+ flex: 1,
+ minWidth: 0,
+ padding: 16,
+ },
+ memoCardContentCompact: {
+ padding: 13,
+ },
+ memoCardContentWithSelection: {
+ paddingLeft: 12,
+ },
+ memoSelectionButton: {
+ alignItems: "center",
+ justifyContent: "center",
+ marginLeft: 8,
+ width: 44,
+ },
+ memoCardTop: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 6,
+ },
+ selectionIndicator: {
+ alignItems: "center",
+ borderColor: "#cbd5e1",
+ borderRadius: 12,
+ borderWidth: 1,
+ height: 24,
+ justifyContent: "center",
+ width: 24,
+ },
+ selectionIndicatorActive: {
+ backgroundColor: "#0f172a",
+ borderColor: "#0f172a",
+ },
+ memoTitle: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 16,
+ fontWeight: "700",
+ },
+ memoPinnedStar: {
+ color: "#64748b",
+ fontSize: 16,
+ lineHeight: 16,
+ width: 16,
+ },
+ memoExcerpt: {
+ color: "#0f172a",
+ fontSize: 14,
+ lineHeight: 20,
+ marginTop: 8,
+ minHeight: 40,
+ },
+ memoMeta: {
+ alignItems: "center",
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 8,
+ marginTop: 20,
+ },
+ memoMetaCompact: {
+ marginTop: 8,
+ },
+ memoDate: {
+ color: "#334155",
+ fontSize: 12,
+ fontWeight: "500",
+ },
+ tag: {
+ backgroundColor: "#f1f5f9",
+ borderRadius: 2,
+ color: "#0f172a",
+ fontSize: 12,
+ fontWeight: "500",
+ overflow: "hidden",
+ paddingHorizontal: 6,
+ paddingVertical: 2,
+ },
+ centerState: {
+ alignItems: "center",
+ flex: 1,
+ gap: 8,
+ justifyContent: "center",
+ padding: 24,
+ },
+ errorText: {
+ color: "#dc2626",
+ fontSize: 14,
+ fontWeight: "700",
+ lineHeight: 20,
+ },
+ emptyTitle: {
+ color: "#334155",
+ fontSize: 16,
+ fontWeight: "800",
+ },
+ mutedText: {
+ color: "#64748b",
+ fontSize: 13,
+ textAlign: "center",
+ },
+ emptyActionButton: {
+ alignItems: "center",
+ backgroundColor: "#0f172a",
+ borderRadius: 8,
+ flexDirection: "row",
+ gap: 8,
+ marginTop: 8,
+ minHeight: 38,
+ paddingHorizontal: 14,
+ },
+ emptyActionButtonText: {
+ color: "#ffffff",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ panelRow: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ gap: 6,
+ padding: 14,
+ },
+ systemInfoRows: {
+ borderTopColor: "#e2e8f0",
+ borderTopWidth: 1,
+ },
+ systemInfoRow: {
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ },
+ systemInfoRowLast: {
+ borderBottomWidth: 0,
+ },
+ systemInfoCell: {
+ flex: 1,
+ gap: 3,
+ minWidth: 0,
+ paddingHorizontal: 8,
+ paddingVertical: 9,
+ },
+ systemInfoCellDivider: {
+ borderRightColor: "#e2e8f0",
+ borderRightWidth: 1,
+ },
+ systemInfoListValue: {
+ color: "#0f172a",
+ fontFamily: "monospace",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ panelLinkRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ justifyContent: "space-between",
+ },
+ panelLinkText: {
+ flex: 1,
+ gap: 6,
+ minWidth: 0,
+ },
+ panelLabel: {
+ color: "#64748b",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ panelValue: {
+ color: "#0f172a",
+ fontSize: 15,
+ fontWeight: "700",
+ },
+ preferenceStack: {
+ gap: 12,
+ },
+ preferenceText: {
+ flex: 1,
+ gap: 6,
+ minWidth: 0,
+ },
+ buttonDisabled: {
+ opacity: 0.5,
+ },
+ modalSafeArea: {
+ backgroundColor: "#f8fafc",
+ flex: 1,
+ },
+ createMemoSafeArea: {
+ backgroundColor: "#ffffff",
+ flex: 1,
+ },
+ createMemoHeader: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderBottomColor: "#f1f5f9",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ gap: 8,
+ justifyContent: "space-between",
+ minHeight: 52,
+ paddingBottom: 8,
+ paddingHorizontal: 12,
+ paddingTop: 8,
+ },
+ createMemoBackButton: {
+ alignItems: "center",
+ borderRadius: 999,
+ height: 38,
+ justifyContent: "center",
+ width: 38,
+ },
+ createMemoHeaderActions: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 8,
+ },
+ createMemoStatus: {
+ backgroundColor: "#f1f5f9",
+ borderRadius: 999,
+ color: "#64748b",
+ fontSize: 12,
+ fontWeight: "700",
+ overflow: "hidden",
+ paddingHorizontal: 10,
+ paddingVertical: 6,
+ },
+ createMemoStatusActive: {
+ backgroundColor: "#ecfdf5",
+ color: "#047857",
+ },
+ createMemoDoneButton: {
+ alignItems: "center",
+ backgroundColor: "#020617",
+ borderRadius: 999,
+ justifyContent: "center",
+ minHeight: 36,
+ minWidth: 58,
+ paddingHorizontal: 12,
+ paddingVertical: 7,
+ },
+ createMemoDoneButtonDisabled: {
+ backgroundColor: "#e2e8f0",
+ },
+ createMemoDoneText: {
+ color: "#ffffff",
+ fontSize: 14,
+ fontWeight: "700",
+ },
+ createMemoDoneTextDisabled: {
+ color: "#64748b",
+ },
+ createMemoMain: {
+ flex: 1,
+ paddingBottom: 8,
+ paddingHorizontal: 12,
+ paddingTop: 14,
+ },
+ createMemoTitleInput: {
+ color: "#0f172a",
+ fontSize: 28,
+ fontWeight: "800",
+ lineHeight: 34,
+ minHeight: 42,
+ padding: 0,
+ },
+ createMemoMetaRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 10,
+ minHeight: 40,
+ },
+ createMemoNotebookButton: {
+ alignItems: "center",
+ flexDirection: "row",
+ flexShrink: 1,
+ gap: 3,
+ maxWidth: "46%",
+ minHeight: 30,
+ paddingRight: 5,
+ },
+ createMemoNotebookText: {
+ color: "#64748b",
+ flexShrink: 1,
+ fontSize: 15,
+ fontWeight: "700",
+ },
+ createMemoTagsInput: {
+ color: "#64748b",
+ flex: 1,
+ fontSize: 15,
+ lineHeight: 23,
+ minHeight: 36,
+ minWidth: 0,
+ padding: 0,
+ },
+ createMemoToolButton: {
+ alignItems: "center",
+ borderColor: "transparent",
+ borderRadius: 999,
+ borderWidth: 1,
+ height: 32,
+ justifyContent: "center",
+ width: 36,
+ },
+ createMemoToolButtonPressed: {
+ backgroundColor: "#ecfdf5",
+ borderColor: "#bbf7d0",
+ },
+ createMemoEditorFrame: {
+ borderColor: "#e2e8f0",
+ borderRadius: 10,
+ borderWidth: 1,
+ flex: 1,
+ marginHorizontal: -4,
+ marginTop: 4,
+ overflow: "hidden",
+ },
+ createMemoEditor: {
+ backgroundColor: "#ffffff",
+ flex: 1,
+ },
+ richEditorSafeArea: {
+ backgroundColor: "#ffffff",
+ flex: 1,
+ },
+ richEditorHeaderStatus: {
+ maxWidth: 76,
+ },
+ richEditorContainer: {
+ backgroundColor: "#ffffff",
+ flex: 1,
+ paddingHorizontal: 12,
+ paddingTop: 14,
+ },
+ richEditorStatusError: {
+ backgroundColor: "#fef2f2",
+ color: "#b91c1c",
+ },
+ richEditorFrame: {
+ flex: 1,
+ marginHorizontal: -12,
+ },
+ richStandaloneMetaRow: {
+ minHeight: 30,
+ },
+ richStandaloneTagsInput: {
+ minHeight: 30,
+ },
+ richEditorSearchActions: {
+ alignItems: "center",
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 8,
+ },
+ richEditorLoading: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ bottom: 0,
+ gap: 10,
+ justifyContent: "center",
+ left: 0,
+ position: "absolute",
+ right: 0,
+ top: 0,
+ zIndex: 2,
+ },
+ richEditorWebView: {
+ backgroundColor: "#ffffff",
+ flex: 1,
+ },
+ richEditorInlineError: {
+ backgroundColor: "#fef2f2",
+ color: "#b91c1c",
+ fontSize: 12,
+ paddingHorizontal: 14,
+ paddingVertical: 8,
+ },
+ richEditorDraftNotice: {
+ backgroundColor: "#fffbeb",
+ color: "#92400e",
+ fontSize: 12,
+ paddingHorizontal: 14,
+ paddingVertical: 7,
+ },
+ richEditorPerf: {
+ backgroundColor: "#f8fafc",
+ color: "#64748b",
+ fontSize: 10,
+ paddingHorizontal: 14,
+ paddingVertical: 4,
+ textAlign: "right",
+ },
+ managementHeader: {
+ alignItems: "center",
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ minHeight: 64,
+ paddingHorizontal: 14,
+ },
+ managementBackButton: {
+ alignItems: "center",
+ borderRadius: 8,
+ height: 36,
+ justifyContent: "center",
+ marginRight: 10,
+ width: 36,
+ },
+ managementHeaderText: {
+ flex: 1,
+ minWidth: 0,
+ },
+ managementTitleRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 8,
+ },
+ managementTitle: {
+ color: "#0f172a",
+ fontSize: 16,
+ fontWeight: "800",
+ },
+ managementSubtitle: {
+ color: "#64748b",
+ fontSize: 11,
+ fontWeight: "600",
+ marginTop: 2,
+ },
+ modalHeader: {
+ alignItems: "center",
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ justifyContent: "space-between",
+ padding: 14,
+ },
+ modalTitle: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 16,
+ fontWeight: "800",
+ marginHorizontal: 12,
+ textAlign: "center",
+ },
+ actionSheetBackdrop: {
+ backgroundColor: "rgba(15, 23, 42, 0.34)",
+ flex: 1,
+ justifyContent: "flex-end",
+ },
+ actionSheet: {
+ backgroundColor: "#ffffff",
+ borderTopLeftRadius: 16,
+ borderTopRightRadius: 16,
+ gap: 8,
+ paddingBottom: 28,
+ paddingHorizontal: 16,
+ paddingTop: 10,
+ },
+ listActionSheet: {
+ backgroundColor: "#ffffff",
+ borderRadius: MOBILE_UI_METRICS.floatingSheetCornerRadius,
+ marginHorizontal: 12,
+ maxHeight: "82%",
+ overflow: "hidden",
+ paddingBottom: 8,
+ paddingTop: 8,
+ },
+ selectionMoreSheet: {
+ backgroundColor: "#ffffff",
+ borderRadius: 10,
+ gap: 0,
+ marginHorizontal: 8,
+ overflow: "hidden",
+ paddingBottom: 8,
+ paddingTop: 8,
+ },
+ moveSelectionSheet: {
+ maxHeight: "76%",
+ },
+ moveSelectionSearch: {
+ borderBottomColor: "#f1f5f9",
+ borderBottomWidth: 1,
+ padding: 12,
+ },
+ moveSelectionList: {
+ gap: 8,
+ padding: 8,
+ },
+ listActionSheetHeader: {
+ alignItems: "center",
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ minHeight: 48,
+ paddingHorizontal: 12,
+ },
+ listActionSheetHeaderText: {
+ flex: 1,
+ minWidth: 0,
+ },
+ sheetCloseButton: {
+ alignItems: "center",
+ borderRadius: 8,
+ height: 38,
+ justifyContent: "center",
+ width: 38,
+ },
+ listActionSheetScroll: {
+ flexShrink: 1,
+ },
+ listActionSheetContent: {
+ padding: 8,
+ },
+ actionSheetSubtitle: {
+ color: "#64748b",
+ fontSize: 12,
+ marginTop: 2,
+ },
+ listActionDivider: {
+ backgroundColor: "#f1f5f9",
+ height: 1,
+ marginVertical: 8,
+ },
+ notebookPickerSheet: {
+ maxHeight: "82%",
+ paddingBottom: 8,
+ paddingHorizontal: 0,
+ },
+ notebookPickerHeader: {
+ alignItems: "center",
+ borderBottomColor: "#e2e8f0",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ justifyContent: "space-between",
+ minHeight: 56,
+ paddingHorizontal: 16,
+ },
+ notebookPickerHeaderText: {
+ flex: 1,
+ gap: 2,
+ },
+ notebookPickerCloseButton: {
+ alignItems: "center",
+ borderRadius: 6,
+ height: 32,
+ justifyContent: "center",
+ width: 32,
+ },
+ notebookPickerSectionHeader: {
+ alignItems: "center",
+ flexDirection: "row",
+ justifyContent: "space-between",
+ minHeight: 32,
+ paddingHorizontal: 12,
+ },
+ notebookPickerToggleAll: {
+ borderRadius: 6,
+ paddingHorizontal: 8,
+ paddingVertical: 6,
+ },
+ notebookPickerToggleAllText: {
+ color: "#64748b",
+ fontSize: 12,
+ fontWeight: "700",
+ },
+ notebookPickerScroll: {
+ flexShrink: 1,
+ },
+ notebookPickerContent: {
+ padding: 8,
+ },
+ notebookPickerSearchBox: {
+ alignItems: "center",
+ backgroundColor: "#f1f5f9",
+ borderRadius: 6,
+ flexDirection: "row",
+ gap: 8,
+ height: 36,
+ marginBottom: 8,
+ paddingHorizontal: 12,
+ },
+ notebookPickerSearchInput: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 14,
+ height: 36,
+ paddingVertical: 0,
+ },
+ notebookPickerRow: {
+ alignItems: "center",
+ backgroundColor: "transparent",
+ borderRadius: 6,
+ flexDirection: "row",
+ gap: 8,
+ minHeight: 48,
+ paddingHorizontal: 12,
+ },
+ notebookPickerAllRow: {
+ marginBottom: 4,
+ },
+ notebookPickerRowActive: {
+ backgroundColor: "#f1f5f9",
+ },
+ actionSheetHandle: {
+ alignSelf: "center",
+ backgroundColor: "#cbd5e1",
+ borderRadius: 999,
+ height: 4,
+ marginBottom: 8,
+ width: 42,
+ },
+ actionSheetTitle: {
+ color: "#0f172a",
+ fontSize: 15,
+ fontWeight: "800",
+ paddingBottom: 4,
+ },
+ actionSheetSectionTitle: {
+ color: "#64748b",
+ fontSize: 12,
+ fontWeight: "600",
+ paddingHorizontal: 12,
+ paddingVertical: 8,
+ },
+ actionSheetItem: {
+ alignItems: "center",
+ backgroundColor: "transparent",
+ borderRadius: 7,
+ flexDirection: "row",
+ gap: 10,
+ minHeight: 48,
+ paddingHorizontal: 12,
+ },
+ actionSheetItemCompact: {
+ minHeight: 44,
+ },
+ actionSheetItemText: {
+ color: "#0f172a",
+ fontSize: 14,
+ fontWeight: "800",
+ },
+ actionSheetItemTextCompact: {
+ fontWeight: "500",
+ },
+ actionSheetItemTextDanger: {
+ color: "#b91c1c",
+ },
+ sheetOptionRow: {
+ alignItems: "center",
+ borderRadius: 7,
+ flexDirection: "row",
+ gap: 10,
+ minHeight: 44,
+ paddingHorizontal: 12,
+ },
+ sheetOptionRowActive: {
+ backgroundColor: "rgb(236, 253, 245)",
+ },
+ sheetOptionIcon: {
+ alignItems: "center",
+ justifyContent: "center",
+ width: 20,
+ },
+ sheetOptionLabel: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 14,
+ fontWeight: "500",
+ },
+ sheetOptionLabelActive: {
+ color: "rgb(4, 120, 87)",
+ },
+ sheetOptionCheck: {
+ alignItems: "center",
+ backgroundColor: "#10b981",
+ borderRadius: 9,
+ height: 18,
+ justifyContent: "center",
+ width: 18,
+ },
+ sheetOptionCheckHidden: {
+ opacity: 0,
+ },
+ detailContent: {
+ paddingBottom: 112,
+ paddingHorizontal: DETAIL_CONTENT_HORIZONTAL_PADDING,
+ paddingTop: 16,
+ },
+ detailTitle: {
+ color: "#0f172a",
+ fontSize: 24,
+ fontWeight: "700",
+ lineHeight: 30,
+ },
+ detailHeader: {
+ alignItems: "center",
+ borderBottomColor: "#f1f5f9",
+ borderBottomWidth: 1,
+ flexDirection: "row",
+ justifyContent: "space-between",
+ minHeight: 48,
+ paddingHorizontal: 12,
+ },
+ detailHeaderButton: {
+ alignItems: "center",
+ borderRadius: 6,
+ height: 32,
+ justifyContent: "center",
+ width: 32,
+ },
+ detailHeaderActions: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 2,
+ },
+ detailHeaderIconButton: {
+ alignItems: "center",
+ borderRadius: 6,
+ height: 32,
+ justifyContent: "center",
+ width: 32,
+ },
+ detailSyncStatus: {
+ backgroundColor: "#f1f5f9",
+ borderRadius: 999,
+ color: "#64748b",
+ fontSize: 11,
+ fontWeight: "500",
+ maxWidth: 88,
+ overflow: "hidden",
+ paddingHorizontal: 8,
+ paddingVertical: 4,
+ },
+ detailSyncStatusConflict: {
+ backgroundColor: "#fff7ed",
+ color: "#c2410c",
+ fontWeight: "700",
+ },
+ detailMetaRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 8,
+ marginTop: 12,
+ },
+ detailNotebookButton: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 4,
+ height: 32,
+ maxWidth: "46%",
+ paddingHorizontal: 8,
+ },
+ detailNotebookName: {
+ color: "#64748b",
+ flexShrink: 1,
+ fontSize: 14,
+ },
+ detailTagsGroup: {
+ alignItems: "center",
+ flex: 1,
+ flexDirection: "row",
+ gap: 8,
+ height: 32,
+ paddingHorizontal: 8,
+ },
+ detailTagsInline: {
+ color: "#64748b",
+ flex: 1,
+ fontSize: 14,
+ },
+ detailTagsPlaceholder: {
+ color: "#94a3b8",
+ },
+ detailDivider: {
+ backgroundColor: "#e2e8f0",
+ height: 1,
+ marginHorizontal: -16,
+ marginTop: 16,
+ marginBottom: 18,
+ },
+ detailEditFab: {
+ alignItems: "center",
+ backgroundColor: "#10b981",
+ borderRadius: 24,
+ elevation: 6,
+ height: 48,
+ justifyContent: "center",
+ position: "absolute",
+ right: 16,
+ shadowColor: "#0f172a",
+ shadowOffset: { width: 0, height: 4 },
+ shadowOpacity: 0.2,
+ shadowRadius: 8,
+ width: 48,
+ },
+ detailMarkdown: {
+ color: "#1f2937",
+ fontSize: 16,
+ lineHeight: 25,
+ marginTop: 20,
+ },
+ noteSearchPanel: {
+ backgroundColor: "#f8fafc",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ gap: 10,
+ marginTop: 14,
+ padding: 10,
+ },
+ noteSearchCount: {
+ color: "#64748b",
+ fontSize: 12,
+ fontWeight: "800",
+ },
+ noteSearchCountEmpty: {
+ color: "#b91c1c",
+ },
+ noteSearchHighlight: {
+ backgroundColor: "#fef3c7",
+ color: "#78350f",
+ },
+ noteSearchHighlightActive: {
+ backgroundColor: "#fde68a",
+ color: "#0f172a",
+ fontWeight: "800",
+ },
+ actionButton: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 6,
+ minHeight: 38,
+ paddingHorizontal: 12,
+ },
+ actionButtonDanger: {
+ backgroundColor: "#fef2f2",
+ borderColor: "#fecaca",
+ },
+ actionButtonText: {
+ color: "#0f172a",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ actionButtonTextDanger: {
+ color: "#b91c1c",
+ },
+ parentSelectList: {
+ flexGrow: 0,
+ },
+ notebookPicker: {
+ gap: 10,
+ },
+ centerInline: {
+ alignItems: "center",
+ padding: 18,
+ },
+ emptyInlinePanel: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ gap: 8,
+ padding: 22,
+ },
+ guideHero: {
+ backgroundColor: "#ecfdf5",
+ borderColor: "#a7f3d0",
+ borderRadius: 8,
+ borderWidth: 1,
+ gap: 8,
+ padding: 14,
+ },
+ promptCard: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ gap: 10,
+ padding: 14,
+ },
+ promptCardHeader: {
+ alignItems: "center",
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 10,
+ justifyContent: "space-between",
+ },
+ moveNotebookRow: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ flexDirection: "row",
+ gap: 12,
+ minHeight: 58,
+ padding: 12,
+ },
+ moveNotebookRowActive: {
+ borderColor: "#0f172a",
+ },
+ moveNotebookRowCompact: {
+ borderWidth: 0,
+ minHeight: 44,
+ paddingHorizontal: 12,
+ paddingVertical: 5,
+ },
+ moveNotebookRowCompactActive: {
+ backgroundColor: "#ecfdf5",
+ },
+ moveNotebookTextCompactActive: {
+ color: "#047857",
+ },
+ moveNotebookText: {
+ flex: 1,
+ gap: 4,
+ minWidth: 0,
+ },
+ moveNotebookSelectArea: {
+ flex: 1,
+ gap: 4,
+ justifyContent: "center",
+ minHeight: 34,
+ minWidth: 0,
+ },
+ notebookTreeToggle: {
+ alignItems: "center",
+ borderRadius: 8,
+ height: 32,
+ justifyContent: "center",
+ width: 32,
+ },
+ notebookTreeTogglePlaceholder: {
+ alignItems: "center",
+ height: 32,
+ justifyContent: "center",
+ width: 32,
+ },
+ notebookTreeRows: {
+ gap: 10,
+ },
+ notebookTreeRowsCompact: {
+ gap: 0,
+ },
+ editorForm: {
+ gap: 12,
+ padding: 18,
+ paddingBottom: 48,
+ },
+ revisionHistoryContent: {
+ gap: 12,
+ padding: 16,
+ paddingBottom: 48,
+ },
+ revisionSummaryRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 10,
+ justifyContent: "space-between",
+ },
+ revisionSummaryText: {
+ flex: 1,
+ gap: 6,
+ minWidth: 0,
+ },
+ revisionChangeBadge: {
+ alignSelf: "flex-start",
+ backgroundColor: "#fffbeb",
+ borderColor: "#fde68a",
+ borderRadius: 999,
+ borderWidth: 1,
+ color: "#92400e",
+ fontSize: 11,
+ fontWeight: "700",
+ overflow: "hidden",
+ paddingHorizontal: 8,
+ paddingVertical: 3,
+ },
+ revisionTimelineLabel: {
+ color: "#94a3b8",
+ fontSize: 11,
+ fontWeight: "700",
+ letterSpacing: 0.6,
+ textTransform: "uppercase",
+ },
+ revisionTimeline: {
+ gap: 7,
+ },
+ revisionTimelineState: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#cbd5e1",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ gap: 12,
+ paddingHorizontal: 16,
+ paddingVertical: 32,
+ },
+ revisionTimelineError: {
+ color: "#64748b",
+ fontSize: 12,
+ lineHeight: 18,
+ textAlign: "center",
+ },
+ revisionPill: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ minHeight: 68,
+ paddingHorizontal: 12,
+ paddingVertical: 9,
+ },
+ revisionPillActive: {
+ backgroundColor: "#ecfdf5",
+ borderColor: "#a7f3d0",
+ },
+ revisionPillTitle: {
+ color: "#0f172a",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ revisionPillTitleActive: {
+ color: "#047857",
+ },
+ revisionPillMeta: {
+ color: "#64748b",
+ fontSize: 11,
+ fontWeight: "700",
+ marginTop: 4,
+ },
+ revisionPreviewCard: {
+ backgroundColor: "#ffffff",
+ borderColor: "#e2e8f0",
+ borderRadius: 8,
+ borderWidth: 1,
+ padding: 10,
+ },
+ revisionPreviewText: {
+ color: "#334155",
+ fontSize: 13,
+ lineHeight: 20,
+ },
+ label: {
+ color: "#334155",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ bottomNav: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderTopColor: "#e2e8f0",
+ borderTopWidth: 1,
+ flexDirection: "row",
+ justifyContent: "space-between",
+ paddingHorizontal: 36,
+ },
+ bottomCreateButton: {
+ alignItems: "center",
+ backgroundColor: "#10b981",
+ borderColor: "#ffffff",
+ borderRadius: MOBILE_UI_METRICS.floatingCreateButtonSize / 2,
+ borderWidth: 4,
+ height: MOBILE_UI_METRICS.floatingCreateButtonSize,
+ justifyContent: "center",
+ marginTop: -16,
+ shadowColor: "#10b981",
+ shadowOffset: { width: 0, height: 10 },
+ shadowOpacity: 0.28,
+ shadowRadius: 18,
+ width: MOBILE_UI_METRICS.floatingCreateButtonSize,
+ },
+ bottomCreateButtonDisabled: {
+ backgroundColor: "#cbd5e1",
+ shadowOpacity: 0,
+ },
+ selectionBar: {
+ backgroundColor: "#ffffff",
+ borderTopColor: "#e2e8f0",
+ borderTopWidth: 1,
+ bottom: 0,
+ left: 0,
+ paddingHorizontal: 32,
+ paddingTop: 4,
+ position: "absolute",
+ right: 0,
+ },
+ selectionActions: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ },
+ selectionAction: {
+ alignItems: "center",
+ flex: 1,
+ gap: 4,
+ justifyContent: "center",
+ minHeight: 56,
+ },
+ selectionActionText: {
+ color: "#0f172a",
+ fontSize: 11,
+ fontWeight: "800",
+ },
+ selectionActionTextDanger: {
+ color: "#b91c1c",
+ },
+ bottomNavItem: {
+ alignItems: "center",
+ gap: 4,
+ minHeight: MOBILE_UI_METRICS.minimumTouchTarget,
+ minWidth: 58,
+ },
+ bottomNavText: {
+ color: "#64748b",
+ fontSize: 11,
+ fontWeight: "700",
+ },
+ bottomNavTextActive: {
+ color: "#0f172a",
+ },
+ previewBackdrop: {
+ alignItems: "center",
+ backgroundColor: "#000000",
+ flex: 1,
+ justifyContent: "center",
+ },
+ shareImportBackdrop: {
+ alignItems: "center",
+ backgroundColor: "rgba(15, 23, 42, 0.42)",
+ flex: 1,
+ justifyContent: "center",
+ padding: 24,
+ },
+ shareImportCard: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderRadius: 18,
+ gap: 10,
+ maxWidth: 340,
+ paddingHorizontal: 28,
+ paddingVertical: 26,
+ width: "100%",
+ },
+ shareImportTitle: {
+ color: "#0f172a",
+ fontSize: 17,
+ fontWeight: "800",
+ marginTop: 4,
+ },
+ shareImportDescription: {
+ color: "#64748b",
+ fontSize: 13,
+ lineHeight: 20,
+ textAlign: "center",
+ },
+});
+
+export let styles = baseWorkspaceStyles;
+let workspaceStylesTheme: MobileResolvedTheme = "light";
+
+export const refreshWorkspaceThemeStyles = (theme: MobileResolvedTheme) => {
+ if (workspaceStylesTheme === theme) {
+ return;
+ }
+ styles = resolveMobileThemeStyles(baseWorkspaceStyles, theme);
+ workspaceStylesTheme = theme;
+};
diff --git a/apps/mobile/src/screens/workspace-utils.test.ts b/apps/mobile/src/screens/workspace-utils.test.ts
new file mode 100644
index 00000000..5fd4a37d
--- /dev/null
+++ b/apps/mobile/src/screens/workspace-utils.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from "bun:test";
+import type { Notebook } from "@edgeever/shared";
+import {
+ filterCollapsedNotebookOptions,
+ flattenNotebooks,
+ getNotebookAncestorIds,
+ getNotebookParentIdSet,
+ getTextSearchMatches,
+ markdownToLocalText,
+ parseTags,
+} from "./workspace-utils";
+
+const notebook = (id: string, parentId: string | null, sortOrder: number): Notebook => ({
+ id,
+ parentId,
+ name: id,
+ slug: id,
+ icon: null,
+ color: null,
+ sortOrder,
+ memoCount: 0,
+ lastMemoUpdatedAt: null,
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+});
+
+describe("mobile workspace utilities", () => {
+ test("flattens, sorts, and collapses notebook trees", () => {
+ const notebooks = [notebook("child", "root", 20), notebook("root", null, 10), notebook("sibling", null, 30)];
+ const options = flattenNotebooks(notebooks);
+
+ expect(options.map(({ notebook: item, depth }) => [item.id, depth])).toEqual([
+ ["root", 0],
+ ["child", 1],
+ ["sibling", 0],
+ ]);
+ expect(filterCollapsedNotebookOptions(options, new Set(["root"])).map(({ notebook: item }) => item.id)).toEqual([
+ "root",
+ "sibling",
+ ]);
+ expect(getNotebookParentIdSet(notebooks)).toEqual(new Set(["root"]));
+ expect(getNotebookAncestorIds(notebooks, "child")).toEqual(new Set(["root"]));
+ });
+
+ test("normalizes tags, markdown preview text, and search matches", () => {
+ expect(parseTags(" one,two, one\nthree ")).toEqual(["one", "two", "three"]);
+ expect(markdownToLocalText("## Hello [EdgeEver](https://edgeever.org) ![logo](logo.png)")).toBe("Hello EdgeEver");
+ expect(getTextSearchMatches("One one none", "one")).toEqual([
+ { start: 0, end: 3 },
+ { start: 4, end: 7 },
+ { start: 9, end: 12 },
+ ]);
+ });
+});
diff --git a/apps/mobile/src/screens/workspace-utils.ts b/apps/mobile/src/screens/workspace-utils.ts
new file mode 100644
index 00000000..38dc455c
--- /dev/null
+++ b/apps/mobile/src/screens/workspace-utils.ts
@@ -0,0 +1,202 @@
+import type { MemoSummary, Notebook } from "@edgeever/shared";
+import type { MobileLocalePreference } from "../lib/preferences";
+
+export type NotebookOption = {
+ notebook: Notebook;
+ depth: number;
+};
+
+export const parseTags = (value: string) =>
+ Array.from(
+ new Set(
+ value
+ .split(/[,,\n]/)
+ .map((tag) => tag.trim())
+ .filter(Boolean)
+ )
+ );
+
+const compareNotebooksManual = (left: Notebook, right: Notebook) =>
+ left.sortOrder - right.sortOrder || left.name.localeCompare(right.name, "zh-CN") || left.id.localeCompare(right.id);
+
+export const flattenNotebooks = (notebooks: Notebook[]) => {
+ const byParent = new Map<string | null, Notebook[]>();
+ const byId = new Set(notebooks.map((notebook) => notebook.id));
+ const result: NotebookOption[] = [];
+
+ for (const notebook of notebooks) {
+ const parentId = notebook.parentId && byId.has(notebook.parentId) ? notebook.parentId : null;
+ const siblings = byParent.get(parentId) ?? [];
+ siblings.push(notebook);
+ byParent.set(parentId, siblings);
+ }
+
+ for (const siblings of byParent.values()) {
+ siblings.sort(compareNotebooksManual);
+ }
+
+ const walk = (parentId: string | null, depth: number) => {
+ for (const notebook of byParent.get(parentId) ?? []) {
+ result.push({ notebook, depth });
+ walk(notebook.id, depth + 1);
+ }
+ };
+
+ walk(null, 0);
+ return result;
+};
+
+export const filterNotebookOptions = (options: NotebookOption[], searchText: string) => {
+ const query = searchText.trim().toLowerCase();
+
+ if (!query) {
+ return options;
+ }
+
+ return options.filter(({ notebook }) => notebook.name.toLowerCase().includes(query) || (notebook.slug || "").toLowerCase().includes(query));
+};
+
+export const filterNotebookOptionsById = (options: NotebookOption[], visibleIds: ReadonlySet<string>) =>
+ options.filter(({ notebook }) => visibleIds.has(notebook.id));
+
+export const getNotebookParentIdSet = (notebooks: Notebook[]) => {
+ const notebookIds = new Set(notebooks.map((notebook) => notebook.id));
+ const parentIds = new Set<string>();
+
+ for (const notebook of notebooks) {
+ if (notebook.parentId && notebookIds.has(notebook.parentId)) {
+ parentIds.add(notebook.parentId);
+ }
+ }
+
+ return parentIds;
+};
+
+export const getNotebookAncestorIds = (notebooks: Notebook[], notebookId: string) => {
+ const byId = new Map(notebooks.map((notebook) => [notebook.id, notebook]));
+ const ancestorIds = new Set<string>();
+ let current = byId.get(notebookId);
+
+ while (current?.parentId) {
+ if (ancestorIds.has(current.parentId)) {
+ break;
+ }
+ ancestorIds.add(current.parentId);
+ current = byId.get(current.parentId);
+ }
+
+ return ancestorIds;
+};
+
+export const filterCollapsedNotebookOptions = (options: NotebookOption[], collapsedNotebookIds: Set<string>) => {
+ if (collapsedNotebookIds.size === 0) {
+ return options;
+ }
+
+ const visibleOptions: NotebookOption[] = [];
+ let hiddenDepth: number | null = null;
+
+ for (const option of options) {
+ if (hiddenDepth !== null && option.depth > hiddenDepth) {
+ continue;
+ }
+
+ hiddenDepth = null;
+ visibleOptions.push(option);
+
+ if (collapsedNotebookIds.has(option.notebook.id)) {
+ hiddenDepth = option.depth;
+ }
+ }
+
+ return visibleOptions;
+};
+
+export const getResolvedMobileLocale = (localePreference: MobileLocalePreference) =>
+ localePreference === "system" ? Intl.DateTimeFormat().resolvedOptions().locale || "zh-CN" : localePreference;
+
+export const isEnglishMobileLocale = (localePreference: MobileLocalePreference) =>
+ getResolvedMobileLocale(localePreference).startsWith("en");
+
+export const formatDate = (value: string, localePreference: MobileLocalePreference = "system") =>
+ new Intl.DateTimeFormat(getResolvedMobileLocale(localePreference), {
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(value));
+
+export const formatMemoPreviewDate = (value: string, localePreference: MobileLocalePreference = "system") => {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) {
+ return "";
+ }
+ const now = new Date();
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
+ const memoDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
+ const locale = getResolvedMobileLocale(localePreference);
+ if (memoDay === today) {
+ return new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }).format(date);
+ }
+ if (memoDay === today - 24 * 60 * 60 * 1000) {
+ return isEnglishMobileLocale(localePreference) ? "Yesterday" : "昨天";
+ }
+ return new Intl.DateTimeFormat(locale, { year: "numeric", month: "numeric", day: "numeric" }).format(date);
+};
+
+export const sortMemoSummaries = (memos: MemoSummary[], sortMode: unknown) =>
+ [...memos].sort((left, right) => {
+ if (sortMode === "title-asc") {
+ return (left.title || "无标题笔记").localeCompare(right.title || "无标题笔记");
+ }
+ if (sortMode === "created-desc") {
+ return right.createdAt.localeCompare(left.createdAt);
+ }
+ return right.updatedAt.localeCompare(left.updatedAt);
+ });
+
+export const markdownToLocalText = (markdown: string) =>
+ markdown
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
+ .replace(/[`*_>#~-]/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+
+export const getTextSearchMatches = (text: string, query: string) => {
+ const normalizedQuery = query.trim().toLowerCase();
+
+ if (!normalizedQuery) {
+ return [];
+ }
+
+ const normalizedText = text.toLowerCase();
+ const matches: Array<{ end: number; start: number }> = [];
+ let cursor = 0;
+
+ while (cursor < normalizedText.length) {
+ const start = normalizedText.indexOf(normalizedQuery, cursor);
+
+ if (start === -1) {
+ break;
+ }
+
+ const end = start + normalizedQuery.length;
+ matches.push({ end, start });
+ cursor = end;
+ }
+
+ return matches;
+};
+
+export const formatRevisionActor = (actor: string) => {
+ if (actor.startsWith("user:")) {
+ return "user";
+ }
+
+ if (actor.startsWith("agent:")) {
+ return "agent";
+ }
+
+ return actor || "system";
+};
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index c4a5d865..aa739611 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -70,7 +70,6 @@ import { sanitizeAndScopeCss } from "@/lib/css-sandbox";
import { RevisionHistoryDialog } from "./dialogs/RevisionHistoryDialog";
import { api } from "@/lib/api";
import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceUrl } from "@/lib/desktop-resources";
-import { consumeStandaloneMobileEditorReturn, openStandaloneMobileEditor } from "@/lib/mobile-editor";
import { cn, formatDateTime, parseTagsText } from "@/lib/utils";
import { EDITOR_CONTENT_MAX_WIDTH, EDITOR_CONTENT_MAX_WIDTH_COLLAPSED } from "@/lib/workspace-ui";
import {
@@ -114,6 +113,7 @@ import { isBrowserOffline } from "@/lib/network-status";
import { shouldOpenEditorLink } from "@/lib/editor-link-click";
import { processFilesSequentially } from "@/lib/file-batch";
import { MEMO_ID_REMAPPED_EVENT } from "@/lib/sync-events";
+import { useStandaloneMobileEditor } from "@/hooks/useStandaloneMobileEditor";
const SUPPORTED_PASTE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
const MOBILE_EDITOR_QUERY = "(max-width: 639px)";
@@ -551,563 +551,18 @@ type RichEditorPaneProps = EditorPaneProps & {
onRequestMobileNativeEdit?: () => void;
};
-const MobileNativeEditorPane = ({
- memo,
- repository,
- notebooks,
- isTrashView,
- onBackToList,
- onSaved,
- onMobileDefaultEditConsumed,
- onExitMobileNativeEdit,
-}: EditorPaneProps & { onExitMobileNativeEdit: () => void }) => {
- const { t } = useTranslation();
- const titleRef = useRef<HTMLInputElement | null>(null);
- const tagsRef = useRef<HTMLInputElement | null>(null);
- const bodyRef = useRef<HTMLTextAreaElement | null>(null);
- const draftTimerRef = useRef<number | null>(null);
- const saveTimerRef = useRef<number | null>(null);
- const memoRef = useRef<MemoDetail | null>(memo);
- const editSessionRef = useRef<MemoEditSession | null>(null);
- const editingMemoIdRef = useRef<string | null>(memo?.id ?? null);
- const hasUnsavedChangesRef = useRef(false);
- const hydratingRef = useRef(false);
- const savingRef = useRef(false);
- const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "queued" | "error" | "conflict">("idle");
- const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
- const [notebookUpdatePending, setNotebookUpdatePending] = useState(false);
- const [mobileNotebookSheetOpen, setMobileNotebookSheetOpen] = useState(false);
- const notebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
- const readOnly = isTrashView || Boolean(memo?.isDeleted);
- const currentNotebookLabel = notebookOptions.find((notebook) => notebook.id === memo?.notebookId)?.name ?? t("editor.notebookFallback");
-
- const getTitleValue = useCallback(() => titleRef.current?.value ?? "", []);
- const getTagsValue = useCallback(() => tagsRef.current?.value ?? "", []);
- const getBodyValue = useCallback(() => bodyRef.current?.value ?? "", []);
-
- const clearTimers = useCallback(() => {
- if (draftTimerRef.current !== null) {
- window.clearTimeout(draftTimerRef.current);
- draftTimerRef.current = null;
- }
-
- if (saveTimerRef.current !== null) {
- window.clearTimeout(saveTimerRef.current);
- saveTimerRef.current = null;
- }
- }, []);
-
- const persistDraft = useCallback(() => {
- const currentMemo = memoRef.current;
- if (!currentMemo || currentMemo.isDeleted || editingMemoIdRef.current !== currentMemo.id) {
- return;
- }
-
- void localDb.drafts.put({
- memoId: currentMemo.id,
- title: getTitleValue(),
- tagsText: getTagsValue(),
- contentJson: markdownToDoc(getBodyValue()),
- updatedAt: new Date().toISOString(),
- });
- }, [getBodyValue, getTagsValue, getTitleValue]);
-
- const currentSnapshot = useCallback(() => {
- const currentMemo = memoRef.current;
- if (!currentMemo) {
- return null;
- }
-
- return JSON.stringify({
- memoId: currentMemo.id,
- title: getTitleValue(),
- tagsText: getTagsValue(),
- body: getBodyValue(),
- });
- }, [getBodyValue, getTagsValue, getTitleValue]);
-
- const saveCurrent = useCallback(async () => {
- const currentMemo = memoRef.current;
- const snapshot = currentSnapshot();
-
- const editSession = editSessionRef.current;
- if (
- !currentMemo ||
- currentMemo.isDeleted ||
- editingMemoIdRef.current !== currentMemo.id ||
- !snapshot ||
- savingRef.current ||
- !editSession
- ) {
- return false;
- }
-
- clearTimers();
- savingRef.current = true;
- setSaveState("saving");
-
- const contentJson = markdownToDoc(getBodyValue());
- const payload: MemoUpdateSyncPayload = {
- memoId: currentMemo.id,
- expectedRevision: currentMemo.revision,
- expectedContentHash: currentMemo.contentHash,
- editSessionId: editSession.id,
- title: getTitleValue(),
- contentJson,
- tags: parseTagsText(getTagsValue()),
- };
-
- try {
- const { memo: localMemo } = await repository.updateMemo(currentMemo, payload);
-
- memoRef.current = localMemo;
- await onSaved(localMemo);
-
- if (currentSnapshot() === snapshot) {
- hasUnsavedChangesRef.current = false;
- setHasUnsavedChanges(false);
- await localDb.drafts.delete(localMemo.id);
- setSaveState("queued");
- } else {
- persistDraft();
- hasUnsavedChangesRef.current = true;
- setHasUnsavedChanges(true);
- setSaveState("idle");
- }
-
- return true;
- } catch (error) {
- const code = error && typeof error === "object" && "code" in error ? String(error.code) : null;
-
- if (code === "revision_conflict") {
- setSaveState("conflict");
- return false;
- }
-
- if (shouldQueueMemoSaveError(error)) {
- await queueMemoUpdate(payload);
- await localDb.drafts.put({
- memoId: payload.memoId,
- title: payload.title,
- tagsText: getTagsValue(),
- contentJson: payload.contentJson,
- updatedAt: new Date().toISOString(),
- });
- hasUnsavedChangesRef.current = false;
- setHasUnsavedChanges(false);
- setSaveState("queued");
- return true;
- }
-
- setSaveState("error");
- return false;
- } finally {
- savingRef.current = false;
- }
- }, [clearTimers, currentSnapshot, getBodyValue, getTagsValue, getTitleValue, onSaved, persistDraft, repository]);
-
- const markDirty = useCallback(() => {
- const currentMemo = memoRef.current;
- if (hydratingRef.current || currentMemo?.isDeleted || !currentMemo || editingMemoIdRef.current !== currentMemo.id) {
- return;
- }
-
- if (!hasUnsavedChangesRef.current) {
- hasUnsavedChangesRef.current = true;
- setHasUnsavedChanges(true);
- }
- setSaveState((current) => (current === "conflict" ? current : "idle"));
-
- if (draftTimerRef.current !== null) {
- window.clearTimeout(draftTimerRef.current);
- }
- draftTimerRef.current = window.setTimeout(() => {
- draftTimerRef.current = null;
- persistDraft();
- }, MOBILE_DRAFT_PERSIST_DELAY_MS);
-
- if (saveTimerRef.current !== null) {
- window.clearTimeout(saveTimerRef.current);
- saveTimerRef.current = null;
- }
- saveTimerRef.current = window.setTimeout(() => {
- saveTimerRef.current = null;
- if (hasUnsavedChangesRef.current) {
- void saveCurrent();
- }
- }, EDITOR_LOCAL_SAVE_DELAY_MS);
- }, [persistDraft, saveCurrent]);
-
- useEffect(() => {
- document.documentElement.classList.add("edgeever-mobile-native-editing");
- document.body.classList.add("edgeever-mobile-native-editing");
-
- return () => {
- document.documentElement.classList.remove("edgeever-mobile-native-editing");
- document.body.classList.remove("edgeever-mobile-native-editing");
- };
- }, []);
-
- useEffect(() => () => clearTimers(), [clearTimers]);
-
- useEffect(() => {
- const element = bodyRef.current;
- if (!element) {
- return;
- }
-
- element.addEventListener("input", markDirty);
- return () => element.removeEventListener("input", markDirty);
- }, [markDirty]);
-
- useEffect(() => {
- if (!memo) {
- memoRef.current = null;
- editSessionRef.current = null;
- return;
- }
-
- let cancelled = false;
- const sameMemo = editingMemoIdRef.current === memo.id;
- memoRef.current = memo;
-
- if (sameMemo && hasUnsavedChangesRef.current && !memo.isDeleted) {
- return;
- }
-
- void (async () => {
- let [draft, queuedUpdate, editSessionResponse] = memo.isDeleted
- ? [null, null, null]
- : await Promise.all([
- localDb.drafts.get(memo.id),
- localDb.syncQueue.get(getMemoUpdateQueueId(memo.id)),
- requiresLocalEditSession(memo) ? Promise.resolve(null) : api.createMemoEditSession(memo.id),
- ]);
-
- if (cancelled) {
- return;
- }
-
- if (queuedUpdate && isMemoUpdateAlreadyApplied(memo, queuedUpdate)) {
- await Promise.all([
- localDb.syncQueue.delete(queuedUpdate.id),
- localDb.drafts.delete(memo.id),
- ]);
- draft = null;
- queuedUpdate = undefined;
- }
-
- const draftUpdatedAt = draft ? Date.parse(draft.updatedAt) : 0;
- const remoteUpdatedAt = Date.parse(memo.updatedAt);
- const useDraft = Boolean(draft && (queuedUpdate || draftUpdatedAt >= remoteUpdatedAt));
- const nextTitle = useDraft && draft ? draft.title : getEditableMemoTitle(memo.title);
- const nextTagsText = useDraft && draft ? draft.tagsText : memo.tags.join(", ");
- const nextContent = useDraft && draft
- ? draft.contentJson
- : resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown);
- editSessionRef.current = editSessionResponse?.editSession ?? (requiresLocalEditSession(memo) ? createLocalEditSession(memo) : null);
-
- hydratingRef.current = true;
- editingMemoIdRef.current = memo.id;
- if (titleRef.current) {
- titleRef.current.value = nextTitle;
- }
- if (tagsRef.current) {
- tagsRef.current.value = nextTagsText;
- }
- if (bodyRef.current) {
- bodyRef.current.value = docToMarkdown(nextContent);
- }
- hasUnsavedChangesRef.current = Boolean(useDraft && !queuedUpdate);
- setHasUnsavedChanges(hasUnsavedChangesRef.current);
- setSaveState(queuedUpdate ? syncStatusToSaveState(queuedUpdate.status) : "idle");
- window.setTimeout(() => {
- hydratingRef.current = false;
- bodyRef.current?.focus({ preventScroll: true });
- }, 0);
- })();
-
- return () => {
- cancelled = true;
- };
- }, [memo]);
-
- useEffect(() => {
- const persistBeforeSuspend = () => {
- if (hasUnsavedChangesRef.current) {
- persistDraft();
- }
- };
- const persistWhenHidden = () => {
- if (document.visibilityState === "hidden") {
- persistBeforeSuspend();
- }
- };
-
- window.addEventListener("pagehide", persistBeforeSuspend);
- document.addEventListener("visibilitychange", persistWhenHidden);
-
- return () => {
- window.removeEventListener("pagehide", persistBeforeSuspend);
- document.removeEventListener("visibilitychange", persistWhenHidden);
- };
- }, [persistDraft]);
-
- const finishEditing = async (goBack: boolean) => {
- if (!readOnly && hasUnsavedChangesRef.current) {
- const saved = await saveCurrent();
- if (!saved && saveState !== "queued") {
- return;
- }
- }
-
- onMobileDefaultEditConsumed();
- onExitMobileNativeEdit();
- if (goBack) {
- onBackToList();
- }
- };
-
- const updateMemoNotebook = (notebookId: string, sourceMemo: MemoDetail = memoRef.current ?? memo!) => {
- if (readOnly || !sourceMemo || notebookId === sourceMemo.notebookId || notebookUpdatePending) {
- setMobileNotebookSheetOpen(false);
- return;
- }
-
- setNotebookUpdatePending(true);
- setSaveState("saving");
-
- void api
- .updateMemo(sourceMemo.id, {
- expectedRevision: sourceMemo.revision,
- notebookId,
- })
- .then(async (data) => {
- memoRef.current = data.memo;
- await onSaved(data.memo);
- setSaveState("saved");
- window.setTimeout(() => setSaveState("idle"), 1200);
- })
- .catch(() => setSaveState("error"))
- .finally(() => {
- setNotebookUpdatePending(false);
- setMobileNotebookSheetOpen(false);
- });
- };
-
- const handleNotebookChange = (notebookId: string) => {
- if (!hasUnsavedChangesRef.current) {
- updateMemoNotebook(notebookId);
- return;
- }
-
- void saveCurrent().then((saved) => {
- if (saved) {
- updateMemoNotebook(notebookId);
- }
- });
- };
-
- const saveLabel =
- saveState === "saving"
- ? t("editor.saveState.saving")
- : saveState === "saved"
- ? t("editor.saveState.saved")
- : saveState === "queued"
- ? t("editor.saveState.queued")
- : saveState === "conflict"
- ? t("editor.saveState.conflict")
- : saveState === "error"
- ? t("editor.saveState.error")
- : hasUnsavedChanges
- ? t("editor.saveState.unsaved")
- : t("editor.saveState.saved");
-
- const saveStateClassName =
- saveState === "error" || saveState === "conflict"
- ? "bg-rose-50 text-rose-700"
- : saveState === "queued"
- ? "bg-amber-50/60 text-amber-600/80"
- : saveState === "saving" || hasUnsavedChanges
- ? "bg-emerald-50 text-emerald-700"
- : "bg-slate-100 text-slate-500";
-
- if (!memo) {
- return (
- <div className="fixed inset-0 z-[90] flex items-center justify-center bg-white text-sm text-slate-500 sm:hidden">
- {t("editor.loading")}
- </div>
- );
- }
-
- return (
- <div className="fixed inset-0 z-[90] overflow-y-auto bg-white text-slate-950 sm:hidden" data-edgeever-mobile-native-editor>
- <header className="flex min-h-12 items-center justify-between gap-2 border-b border-slate-100 bg-white px-3 py-2">
- <Button
- size="icon"
- variant="ghost"
- title={hasUnsavedChanges && !readOnly ? t("editor.saveAndBack") : t("editor.backToList")}
- aria-label={hasUnsavedChanges && !readOnly ? t("editor.saveAndBack") : t("editor.backToList")}
- disabled={savingRef.current || notebookUpdatePending}
- onClick={() => void finishEditing(true)}
- >
- <ChevronLeft className="h-4 w-4" />
- </Button>
- <div className="flex min-w-0 flex-1 justify-end gap-2">
- <span className={cn("inline-flex max-w-[5.5rem] truncate rounded-full px-2 py-1 text-[11px] font-medium", saveStateClassName)}>
- {saveLabel}
- </span>
- <button
- className="inline-flex h-8 items-center justify-center rounded-full bg-slate-950 px-3 text-xs font-semibold text-white disabled:bg-slate-200 disabled:text-slate-500"
- type="button"
- disabled={savingRef.current || notebookUpdatePending}
- onClick={() => void finishEditing(false)}
- >
- {saveState === "saving" ? t("editor.saveState.saving") : t("editor.done")}
- </button>
- </div>
- </header>
-
- <main className="bg-white">
- <div className="space-y-3 px-4 pb-4 pt-4">
- <input
- ref={titleRef}
- defaultValue={getEditableMemoTitle(memo.title)}
- readOnly={readOnly}
- onInput={markDirty}
- className="block w-full border-0 bg-transparent text-2xl font-bold leading-tight text-slate-950 outline-none placeholder:text-slate-300"
- placeholder={t("common.untitledMemo")}
- />
- <div className="flex flex-wrap items-center gap-2">
- <button
- className="flex h-8 min-w-0 max-w-full items-center gap-1 rounded-md border border-transparent bg-transparent px-2 text-sm font-medium text-slate-600 outline-none disabled:opacity-50"
- type="button"
- disabled={readOnly || notebookUpdatePending}
- title={t("editor.currentNotebook")}
- aria-label={t("editor.currentNotebookAria", { name: currentNotebookLabel })}
- onClick={() => setMobileNotebookSheetOpen(true)}
- >
- <span className="min-w-0 truncate">{currentNotebookLabel}</span>
- <ChevronDown className="h-3.5 w-3.5 shrink-0 text-slate-400" />
- </button>
- <label className="flex h-8 min-w-[12rem] flex-1 items-center gap-2 rounded-md border border-transparent px-2 text-sm text-slate-500">
- <Tags className="h-4 w-4" />
- <input
- ref={tagsRef}
- defaultValue={memo.tags.join(", ")}
- readOnly={readOnly}
- onInput={markDirty}
- className="min-w-0 flex-1 bg-transparent outline-none placeholder:text-slate-400"
- placeholder={t("editor.tagPlaceholder")}
- />
- </label>
- </div>
- </div>
-
- <textarea
- ref={bodyRef}
- defaultValue={docToMarkdown(resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown))}
- autoCapitalize="sentences"
- autoComplete="on"
- autoCorrect="on"
- enterKeyHint="enter"
- inputMode="text"
- name="memo-body-native"
- spellCheck
- readOnly={readOnly}
- aria-label={t("editor.noteBodyAria")}
- placeholder={t("editor.placeholder")}
- className="block min-h-[70dvh] w-full resize-none border-0 bg-white px-4 py-4 text-base leading-7 text-slate-900 outline-none placeholder:text-slate-400"
- style={{ WebkitUserSelect: "text", userSelect: "text", caretColor: "auto" }}
- />
- </main>
-
- {mobileNotebookSheetOpen && (
- <MobileNotebookSelectSheet
- isUpdating={notebookUpdatePending || saveState === "saving"}
- options={notebookOptions}
- selectedNotebookId={memo.notebookId}
- onClose={() => setMobileNotebookSheetOpen(false)}
- onSelect={handleNotebookChange}
- />
- )}
- </div>
- );
-};
-
export const EditorPane = (props: EditorPaneProps) => {
- const [isMobileViewport, setIsMobileViewport] = useState(() =>
- typeof window === "undefined" ? false : window.matchMedia(MOBILE_EDITOR_QUERY).matches
- );
- const [mobileNativeEditMemoId, setMobileNativeEditMemoId] = useState<string | null>(null);
- const standaloneOpenMemoIdRef = useRef<string | null>(null);
const { t } = useTranslation();
const readOnly = props.isTrashView || Boolean(props.memo?.isDeleted);
- const mobileDefaultEditRequested = Boolean(
- props.memo?.id && props.memo.id === props.mobileDefaultEditMemoId && !readOnly
- );
- const mobileNativeEditingActive = Boolean(
- isMobileViewport &&
- props.memo &&
- !readOnly &&
- (mobileDefaultEditRequested || mobileNativeEditMemoId === props.memo.id)
- );
-
- useEffect(() => {
- if (isMobileViewport && mobileDefaultEditRequested && props.memo?.id) {
- if (consumeStandaloneMobileEditorReturn(props.memo.id)) {
- props.onMobileDefaultEditConsumed();
- setMobileNativeEditMemoId(null);
- props.onBackToList();
- return;
- }
-
- if (standaloneOpenMemoIdRef.current === props.memo.id) {
- return;
- }
-
- standaloneOpenMemoIdRef.current = props.memo.id;
- props.onMobileDefaultEditConsumed();
- openStandaloneMobileEditor(props.memo.id);
- }
- }, [isMobileViewport, mobileDefaultEditRequested, props.memo?.id, props.onBackToList, props.onMobileDefaultEditConsumed]);
-
- useEffect(() => {
- const clearReturnedStandaloneEditor = () => {
- if (!consumeStandaloneMobileEditorReturn(props.memo?.id ?? null)) {
- return;
- }
-
- props.onMobileDefaultEditConsumed();
- setMobileNativeEditMemoId(null);
- props.onBackToList();
- };
-
- clearReturnedStandaloneEditor();
- window.addEventListener("pageshow", clearReturnedStandaloneEditor);
- document.addEventListener("visibilitychange", clearReturnedStandaloneEditor);
-
- return () => {
- window.removeEventListener("pageshow", clearReturnedStandaloneEditor);
- document.removeEventListener("visibilitychange", clearReturnedStandaloneEditor);
- };
- }, [props.memo?.id, props.onBackToList, props.onMobileDefaultEditConsumed]);
-
- useEffect(() => {
- const mediaQuery = window.matchMedia(MOBILE_EDITOR_QUERY);
- const updateMobileViewport = () => setIsMobileViewport(mediaQuery.matches);
-
- updateMobileViewport();
- mediaQuery.addEventListener("change", updateMobileViewport);
-
- return () => mediaQuery.removeEventListener("change", updateMobileViewport);
- }, []);
-
- useEffect(() => {
- setMobileNativeEditMemoId(null);
- }, [props.memo?.id]);
+ const { editingActive, requestEdit } = useStandaloneMobileEditor({
+ memoId: props.memo?.id ?? null,
+ mobileDefaultEditMemoId: props.mobileDefaultEditMemoId,
+ onBackToList: props.onBackToList,
+ onDefaultEditConsumed: props.onMobileDefaultEditConsumed,
+ readOnly,
+ });
- if (mobileNativeEditingActive) {
+ if (editingActive) {
return (
<div className="flex h-full min-h-0 items-center justify-center bg-white text-sm font-medium text-slate-400">
{t("editor.openEditor")}
@@ -1118,20 +573,11 @@ export const EditorPane = (props: EditorPaneProps) => {
return (
<RichEditorPane
{...props}
- // On desktop this is also the create-note autofocus request. On mobile
- // the native editor branch above consumes it before RichEditorPane is
- // rendered.
mobileDefaultEditMemoId={props.mobileDefaultEditMemoId}
- onRequestMobileNativeEdit={() => {
- if (props.memo?.id && !readOnly) {
- setMobileNativeEditMemoId(props.memo.id);
- openStandaloneMobileEditor(props.memo.id);
- }
- }}
+ onRequestMobileNativeEdit={requestEdit}
/>
);
};
-
const RichEditorPane = ({
memo,
repository,
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 69804106..61db1185 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -38,7 +38,7 @@ import {
type MobileEditorReturnPreview,
} from "@/lib/mobile-editor";
import { cn } from "@/lib/utils";
-import { isBrowserOffline, isBrowserOnline, verifyBrowserConnectivity } from "@/lib/network-status";
+import { isBrowserOffline, isBrowserOnline } from "@/lib/network-status";
import { createExcerpt, docToText, getNotebookDescendantIds, resolveMemoContentDoc, type Notebook, type AuthUser, type MemoSummary, type MemoDetail, type Resource, type MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";
import { toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";
import type {
@@ -83,8 +83,8 @@ import {
} from "@/lib/app-helpers";
import { useBrowserBackLayer } from "@/lib/app-hooks";
import { updateMemoSummaryInLists, type MemoListQueryData } from "@/lib/memo-list-cache";
-import type { SyncQueueSummary } from "@/lib/sync-queue";
-import { notifyMemoIdRemapped, SYNC_QUEUE_DEFERRED_EVENT } from "@/lib/sync-events";
+import { emptySyncQueueSummary, type SyncQueueSummary } from "@/lib/sync-queue";
+import { notifyMemoIdRemapped } from "@/lib/sync-events";
import {
createLocalDataScope,
putLocalMemo,
@@ -93,12 +93,12 @@ import {
} from "@/lib/local-mirror";
import { createRepository } from "@/lib/repository";
import {
- BACKGROUND_WORKSPACE_REFRESH_INTERVAL_MS,
refreshWorkspaceData,
resolveSyncedMemoId,
shouldNavigateHomeWhenOpeningMemo,
type WorkspaceRefreshMode,
} from "@/lib/workspace-refresh";
+import { useWorkspaceSyncLifecycle } from "@/hooks/useWorkspaceSyncLifecycle";
const isDesktopViewport = () => window.matchMedia("(min-width: 1024px)").matches;
const PULL_TO_REFRESH_TRIGGER_PX = 72;
@@ -140,14 +140,6 @@ const SETTINGS_PATH = "/settings";
const TEMPLATES_PATH = "/templates";
const TRASH_VIEW_SEARCH = "?view=trash";
const getMobileEditorReturnMemoId = (search: string) => new URLSearchParams(search).get(MOBILE_EDITOR_RETURN_PARAM);
-const emptySyncQueueSummary = (): SyncQueueSummary => ({
- total: 0,
- pending: 0,
- syncing: 0,
- conflict: 0,
- error: 0,
-});
-
const PaneLoadingFallback = ({ label = "Loading" }: { label?: string }) => (
<div className="flex h-full min-h-0 items-center justify-center bg-white text-sm font-medium text-slate-400" role="status">
{label}
@@ -748,9 +740,6 @@ export const WorkspaceApp = ({
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const isPullRefreshingRef = useRef(false);
const skipNextHomeRouteSyncRef = useRef(false);
- const deferredSyncTimerRef = useRef<number | null>(null);
- const deferredSyncPendingRef = useRef(false);
- const runQueuedSyncRef = useRef<() => Promise<void>>(async () => undefined);
const [mobileListActionsOpen, setMobileListActionsOpen] = useState(false);
const [mobileMoveOpen, setMobileMoveOpen] = useState(false);
@@ -982,57 +971,6 @@ export const WorkspaceApp = ({
enabled: rightView === "templates",
});
- useEffect(() => {
- let cancelled = false;
- let timeoutId: number | null = null;
- let idleId: number | null = null;
-
- const refreshLocalMirror = async () => {
- try {
- if (!cancelled) await refreshWorkspaceFromServer("background");
- } catch {
- // The existing remote queries remain the safe fallback when local
- // mirror sync is unavailable (for example before login or offline).
- }
- };
-
- const scheduleRefresh = (delay: number) => {
- if (timeoutId !== null) {
- window.clearTimeout(timeoutId);
- }
- timeoutId = window.setTimeout(() => {
- timeoutId = null;
- const idleWindow = window as Window & {
- requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
- cancelIdleCallback?: (id: number) => void;
- };
- if (idleWindow.requestIdleCallback) {
- idleId = idleWindow.requestIdleCallback(() => void refreshLocalMirror(), { timeout: 2500 });
- } else {
- void refreshLocalMirror();
- }
- }, delay);
- };
-
- // Do not compete with the first remote queries for bandwidth. The initial
- // screen can render from the remote fallback; the full local snapshot is
- // hydrated once the browser is idle.
- scheduleRefresh(1200);
- const handleOnline = () => scheduleRefresh(300);
- window.addEventListener("online", handleOnline);
- return () => {
- cancelled = true;
- if (timeoutId !== null) {
- window.clearTimeout(timeoutId);
- }
- const idleWindow = window as Window & { cancelIdleCallback?: (id: number) => void };
- if (idleId !== null) {
- idleWindow.cancelIdleCallback?.(idleId);
- }
- window.removeEventListener("online", handleOnline);
- };
- }, [refreshWorkspaceFromServer]);
-
const savedTemplates = templatesQuery.data?.templates ?? [];
const notebooks = notebooksQuery.data?.notebooks ?? [];
@@ -1408,111 +1346,13 @@ export const WorkspaceApp = ({
};
}, [mobilePullToRefreshActive, refreshLatestMemos]);
- useEffect(() => {
- let active = true;
- const updateOnlineState = async () => {
- const online = await verifyBrowserConnectivity();
- if (!active) return;
- setIsOnline(online);
- if (online) {
- void refreshWorkspaceFromServer("manual").catch(() => {
- // Keep the current local mirror available when reconnect sync fails.
- });
- }
- };
-
- window.addEventListener("online", updateOnlineState);
- window.addEventListener("offline", updateOnlineState);
- void updateOnlineState();
-
- return () => {
- active = false;
- window.removeEventListener("online", updateOnlineState);
- window.removeEventListener("offline", updateOnlineState);
- };
- }, [refreshWorkspaceFromServer]);
-
- useEffect(() => {
- runQueuedSyncRef.current = runQueuedSync;
- }, [runQueuedSync]);
-
- useEffect(() => {
- const handleQueueChanged = () => {
- deferredSyncPendingRef.current = false;
- if (deferredSyncTimerRef.current !== null) {
- window.clearTimeout(deferredSyncTimerRef.current);
- deferredSyncTimerRef.current = null;
- }
- void runQueuedSync();
- };
- window.addEventListener("edgeever:sync-queue-changed", handleQueueChanged);
- return () => window.removeEventListener("edgeever:sync-queue-changed", handleQueueChanged);
- }, [runQueuedSync]);
-
- useEffect(() => {
- const scheduleDeferredSync = () => {
- deferredSyncPendingRef.current = true;
- if (deferredSyncTimerRef.current !== null) {
- window.clearTimeout(deferredSyncTimerRef.current);
- deferredSyncTimerRef.current = null;
- }
- if (syncIntervalMs === null) {
- return;
- }
- deferredSyncTimerRef.current = window.setTimeout(() => {
- deferredSyncTimerRef.current = null;
- deferredSyncPendingRef.current = false;
- void runQueuedSyncRef.current();
- }, syncIntervalMs);
- };
-
- window.addEventListener(SYNC_QUEUE_DEFERRED_EVENT, scheduleDeferredSync);
- if (deferredSyncPendingRef.current) {
- scheduleDeferredSync();
- }
- return () => {
- window.removeEventListener(SYNC_QUEUE_DEFERRED_EVENT, scheduleDeferredSync);
- if (deferredSyncTimerRef.current !== null) {
- window.clearTimeout(deferredSyncTimerRef.current);
- deferredSyncTimerRef.current = null;
- }
- };
- }, [syncIntervalMs]);
-
- useEffect(() => {
- const refreshVisibleWorkspace = () => {
- if (document.visibilityState === "hidden" || isBrowserOffline()) {
- return;
- }
-
- void refreshWorkspaceFromServer("background").catch(() => {
- // A later focus, visibility, or interval refresh will retry.
- });
- };
-
- const intervalId = window.setInterval(refreshVisibleWorkspace, BACKGROUND_WORKSPACE_REFRESH_INTERVAL_MS);
- window.addEventListener("focus", refreshVisibleWorkspace);
- window.addEventListener("pageshow", refreshVisibleWorkspace);
- document.addEventListener("visibilitychange", refreshVisibleWorkspace);
-
- return () => {
- window.clearInterval(intervalId);
- window.removeEventListener("focus", refreshVisibleWorkspace);
- window.removeEventListener("pageshow", refreshVisibleWorkspace);
- document.removeEventListener("visibilitychange", refreshVisibleWorkspace);
- };
- }, [refreshWorkspaceFromServer]);
-
- useEffect(() => {
- if (syncSummary.total === 0) {
- return;
- }
- const timer = window.setInterval(() => {
- void runQueuedSync();
- }, 15_000);
-
- return () => window.clearInterval(timer);
- }, [runQueuedSync, syncSummary.total]);
+ useWorkspaceSyncLifecycle({
+ pendingSyncCount: syncSummary.total,
+ refreshWorkspace: refreshWorkspaceFromServer,
+ runQueuedSync,
+ setOnline: setIsOnline,
+ syncIntervalMs,
+ });
const selectedNotebookDescendantIds = useMemo(
() => (selectedNotebookId ? getNotebookDescendantIds(notebooks, selectedNotebookId) : []),
diff --git a/apps/web/src/hooks/useStandaloneMobileEditor.ts b/apps/web/src/hooks/useStandaloneMobileEditor.ts
new file mode 100644
index 00000000..55c3eb77
--- /dev/null
+++ b/apps/web/src/hooks/useStandaloneMobileEditor.ts
@@ -0,0 +1,80 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { consumeStandaloneMobileEditorReturn, openStandaloneMobileEditor } from "@/lib/mobile-editor";
+
+const MOBILE_EDITOR_QUERY = "(max-width: 639px)";
+
+export const useStandaloneMobileEditor = ({
+ memoId,
+ mobileDefaultEditMemoId,
+ onBackToList,
+ onDefaultEditConsumed,
+ readOnly,
+}: {
+ memoId: string | null;
+ mobileDefaultEditMemoId: string | null;
+ onBackToList: () => void;
+ onDefaultEditConsumed: () => void;
+ readOnly: boolean;
+}) => {
+ const [isMobileViewport, setIsMobileViewport] = useState(() =>
+ typeof window === "undefined" ? false : window.matchMedia(MOBILE_EDITOR_QUERY).matches
+ );
+ const [requestedMemoId, setRequestedMemoId] = useState<string | null>(null);
+ const standaloneOpenMemoIdRef = useRef<string | null>(null);
+ const defaultEditRequested = Boolean(memoId && memoId === mobileDefaultEditMemoId && !readOnly);
+ const editingActive = Boolean(
+ isMobileViewport && memoId && !readOnly && (defaultEditRequested || requestedMemoId === memoId)
+ );
+
+ useEffect(() => {
+ if (!isMobileViewport || !defaultEditRequested || !memoId) return;
+ if (consumeStandaloneMobileEditorReturn(memoId)) {
+ onDefaultEditConsumed();
+ setRequestedMemoId(null);
+ onBackToList();
+ return;
+ }
+ if (standaloneOpenMemoIdRef.current === memoId) return;
+
+ standaloneOpenMemoIdRef.current = memoId;
+ onDefaultEditConsumed();
+ openStandaloneMobileEditor(memoId);
+ }, [defaultEditRequested, isMobileViewport, memoId, onBackToList, onDefaultEditConsumed]);
+
+ useEffect(() => {
+ const clearReturnedEditor = () => {
+ if (!consumeStandaloneMobileEditorReturn(memoId)) return;
+ onDefaultEditConsumed();
+ setRequestedMemoId(null);
+ onBackToList();
+ };
+
+ clearReturnedEditor();
+ window.addEventListener("pageshow", clearReturnedEditor);
+ document.addEventListener("visibilitychange", clearReturnedEditor);
+ return () => {
+ window.removeEventListener("pageshow", clearReturnedEditor);
+ document.removeEventListener("visibilitychange", clearReturnedEditor);
+ };
+ }, [memoId, onBackToList, onDefaultEditConsumed]);
+
+ useEffect(() => {
+ const mediaQuery = window.matchMedia(MOBILE_EDITOR_QUERY);
+ const updateViewport = () => setIsMobileViewport(mediaQuery.matches);
+ updateViewport();
+ mediaQuery.addEventListener("change", updateViewport);
+ return () => mediaQuery.removeEventListener("change", updateViewport);
+ }, []);
+
+ useEffect(() => {
+ setRequestedMemoId(null);
+ }, [memoId]);
+
+ const requestEdit = useCallback(() => {
+ if (!memoId || readOnly) return;
+ setRequestedMemoId(memoId);
+ openStandaloneMobileEditor(memoId);
+ }, [memoId, readOnly]);
+
+ return { editingActive, requestEdit };
+};
diff --git a/apps/web/src/hooks/useWorkspaceSyncLifecycle.ts b/apps/web/src/hooks/useWorkspaceSyncLifecycle.ts
new file mode 100644
index 00000000..138e8afc
--- /dev/null
+++ b/apps/web/src/hooks/useWorkspaceSyncLifecycle.ts
@@ -0,0 +1,158 @@
+import { useEffect, useRef } from "react";
+import { isBrowserOffline, verifyBrowserConnectivity } from "@/lib/network-status";
+import { SYNC_QUEUE_DEFERRED_EVENT } from "@/lib/sync-events";
+import { BACKGROUND_WORKSPACE_REFRESH_INTERVAL_MS, type WorkspaceRefreshMode } from "@/lib/workspace-refresh";
+
+type RefreshWorkspace = (mode: WorkspaceRefreshMode) => Promise<unknown>;
+
+export const useWorkspaceSyncLifecycle = ({
+ pendingSyncCount,
+ refreshWorkspace,
+ runQueuedSync,
+ setOnline,
+ syncIntervalMs,
+}: {
+ pendingSyncCount: number;
+ refreshWorkspace: RefreshWorkspace;
+ runQueuedSync: () => Promise<void>;
+ setOnline: (online: boolean) => void;
+ syncIntervalMs: number | null;
+}) => {
+ const deferredSyncTimerRef = useRef<number | null>(null);
+ const deferredSyncPendingRef = useRef(false);
+ const runQueuedSyncRef = useRef(runQueuedSync);
+
+ useEffect(() => {
+ runQueuedSyncRef.current = runQueuedSync;
+ }, [runQueuedSync]);
+
+ useEffect(() => {
+ let cancelled = false;
+ let timeoutId: number | null = null;
+ let idleId: number | null = null;
+
+ const refreshLocalMirror = async () => {
+ try {
+ if (!cancelled) await refreshWorkspace("background");
+ } catch {
+ // Remote queries remain available if local mirror hydration fails.
+ }
+ };
+
+ const scheduleRefresh = (delay: number) => {
+ if (timeoutId !== null) window.clearTimeout(timeoutId);
+ timeoutId = window.setTimeout(() => {
+ timeoutId = null;
+ const idleWindow = window as Window & {
+ requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
+ cancelIdleCallback?: (id: number) => void;
+ };
+ if (idleWindow.requestIdleCallback) {
+ idleId = idleWindow.requestIdleCallback(() => void refreshLocalMirror(), { timeout: 2500 });
+ } else {
+ void refreshLocalMirror();
+ }
+ }, delay);
+ };
+
+ scheduleRefresh(1200);
+ const handleOnline = () => scheduleRefresh(300);
+ window.addEventListener("online", handleOnline);
+ return () => {
+ cancelled = true;
+ if (timeoutId !== null) window.clearTimeout(timeoutId);
+ if (idleId !== null) {
+ (window as Window & { cancelIdleCallback?: (id: number) => void }).cancelIdleCallback?.(idleId);
+ }
+ window.removeEventListener("online", handleOnline);
+ };
+ }, [refreshWorkspace]);
+
+ useEffect(() => {
+ let active = true;
+ const updateOnlineState = async () => {
+ const online = await verifyBrowserConnectivity();
+ if (!active) return;
+ setOnline(online);
+ if (online) {
+ void refreshWorkspace("manual").catch(() => {
+ // Keep the local mirror available when reconnect sync fails.
+ });
+ }
+ };
+
+ window.addEventListener("online", updateOnlineState);
+ window.addEventListener("offline", updateOnlineState);
+ void updateOnlineState();
+ return () => {
+ active = false;
+ window.removeEventListener("online", updateOnlineState);
+ window.removeEventListener("offline", updateOnlineState);
+ };
+ }, [refreshWorkspace, setOnline]);
+
+ useEffect(() => {
+ const handleQueueChanged = () => {
+ deferredSyncPendingRef.current = false;
+ if (deferredSyncTimerRef.current !== null) {
+ window.clearTimeout(deferredSyncTimerRef.current);
+ deferredSyncTimerRef.current = null;
+ }
+ void runQueuedSync();
+ };
+ window.addEventListener("edgeever:sync-queue-changed", handleQueueChanged);
+ return () => window.removeEventListener("edgeever:sync-queue-changed", handleQueueChanged);
+ }, [runQueuedSync]);
+
+ useEffect(() => {
+ const scheduleDeferredSync = () => {
+ deferredSyncPendingRef.current = true;
+ if (deferredSyncTimerRef.current !== null) {
+ window.clearTimeout(deferredSyncTimerRef.current);
+ deferredSyncTimerRef.current = null;
+ }
+ if (syncIntervalMs === null) return;
+ deferredSyncTimerRef.current = window.setTimeout(() => {
+ deferredSyncTimerRef.current = null;
+ deferredSyncPendingRef.current = false;
+ void runQueuedSyncRef.current();
+ }, syncIntervalMs);
+ };
+
+ window.addEventListener(SYNC_QUEUE_DEFERRED_EVENT, scheduleDeferredSync);
+ if (deferredSyncPendingRef.current) scheduleDeferredSync();
+ return () => {
+ window.removeEventListener(SYNC_QUEUE_DEFERRED_EVENT, scheduleDeferredSync);
+ if (deferredSyncTimerRef.current !== null) {
+ window.clearTimeout(deferredSyncTimerRef.current);
+ deferredSyncTimerRef.current = null;
+ }
+ };
+ }, [syncIntervalMs]);
+
+ useEffect(() => {
+ const refreshVisibleWorkspace = () => {
+ if (document.visibilityState === "hidden" || isBrowserOffline()) return;
+ void refreshWorkspace("background").catch(() => {
+ // A later focus, visibility, or interval refresh will retry.
+ });
+ };
+
+ const intervalId = window.setInterval(refreshVisibleWorkspace, BACKGROUND_WORKSPACE_REFRESH_INTERVAL_MS);
+ window.addEventListener("focus", refreshVisibleWorkspace);
+ window.addEventListener("pageshow", refreshVisibleWorkspace);
+ document.addEventListener("visibilitychange", refreshVisibleWorkspace);
+ return () => {
+ window.clearInterval(intervalId);
+ window.removeEventListener("focus", refreshVisibleWorkspace);
+ window.removeEventListener("pageshow", refreshVisibleWorkspace);
+ document.removeEventListener("visibilitychange", refreshVisibleWorkspace);
+ };
+ }, [refreshWorkspace]);
+
+ useEffect(() => {
+ if (pendingSyncCount === 0) return;
+ const timer = window.setInterval(() => void runQueuedSync(), 15_000);
+ return () => window.clearInterval(timer);
+ }, [pendingSyncCount, runQueuedSync]);
+};
diff --git a/apps/web/src/lib/sync-queue.ts b/apps/web/src/lib/sync-queue.ts
index 627f44eb..39a798fa 100644
--- a/apps/web/src/lib/sync-queue.ts
+++ b/apps/web/src/lib/sync-queue.ts
@@ -1,4 +1,16 @@
-import type { MemoDetail, MemoTemplate, Notebook, Resource, TiptapDoc } from "@edgeever/shared";
+import {
+ createEmptySyncQueueSummary,
+ createEmptySyncRunResult,
+ getSyncRetryAt,
+ summarizeSyncQueue,
+ type MemoDetail,
+ type MemoTemplate,
+ type Notebook,
+ type Resource,
+ type SyncQueueSummary,
+ type SyncRunResult,
+ type TiptapDoc,
+} from "@edgeever/shared";
import { liveQuery } from "dexie";
import { ApiRequestError, api } from "@/lib/api";
import {
@@ -14,29 +26,10 @@ import {
import { getCachedLocalResourceBytes, removeCachedLocalResourceBytes } from "@/lib/local-resource-cache";
import { isBrowserOffline } from "@/lib/network-status";
-export type SyncQueueSummary = {
- total: number;
- pending: number;
- syncing: number;
- conflict: number;
- error: number;
-};
-
-export type SyncRunResult = {
- attempted: number;
- synced: number;
- failed: number;
- conflicted: number;
-};
+export type { SyncQueueSummary, SyncRunResult } from "@edgeever/shared";
export type SyncQueueResult = MemoDetail | Notebook | MemoTemplate | Resource | null;
-export const emptySyncQueueSummary = (): SyncQueueSummary => ({
- total: 0,
- pending: 0,
- syncing: 0,
- conflict: 0,
- error: 0,
-});
+export const emptySyncQueueSummary = createEmptySyncQueueSummary;
export const getMemoUpdateQueueId = (memoId: string) => `memo.update:${memoId}`;
export const getMemoCreateQueueId = (temporaryId: string) => `memo.create:${temporaryId}`;
@@ -247,12 +240,7 @@ const runQueuedChanges = async (options: {
onSynced?: (memo: MemoDetail, item: SyncQueueItem) => void | Promise<void>;
onActionSynced?: (result: SyncQueueResult, item: SyncQueueItem) => void | Promise<void>;
}): Promise<SyncRunResult> => {
- const result: SyncRunResult = {
- attempted: 0,
- synced: 0,
- failed: 0,
- conflicted: 0,
- };
+ const result = createEmptySyncRunResult();
if (isBrowserOffline()) {
return result;
@@ -313,7 +301,7 @@ const runQueuedChanges = async (options: {
status,
attemptCount,
lastError: getErrorMessage(error),
- nextAttemptAt: status === "error" ? nextRetryAt(attemptCount) : null,
+ nextAttemptAt: status === "error" ? getSyncRetryAt(attemptCount) : null,
claimId: null,
updatedAt: new Date().toISOString(),
});
@@ -595,16 +583,6 @@ const syncQueueItem = async (item: SyncQueueItem): Promise<SyncQueueResult> => {
return data.memo;
};
-const summarizeSyncQueue = (items: SyncQueueItem[]): SyncQueueSummary =>
- items.reduce(
- (summary, item) => {
- summary.total += 1;
- summary[item.status] += 1;
- return summary;
- },
- emptySyncQueueSummary()
- );
-
const isRevisionConflict = (error: unknown) =>
error instanceof ApiRequestError && error.code === "revision_conflict";
@@ -615,8 +593,3 @@ const getErrorMessage = (error: unknown) => {
return "Sync failed";
};
-
-const nextRetryAt = (attemptCount: number) => {
- const delayMs = Math.min(5 * 60_000, 2 ** Math.min(attemptCount, 6) * 1000);
- return new Date(Date.now() + delayMs).toISOString();
-};
diff --git a/crates/desktop-sidecar/src/database.rs b/crates/desktop-sidecar/src/database.rs
new file mode 100644
index 00000000..2fffefcd
--- /dev/null
+++ b/crates/desktop-sidecar/src/database.rs
@@ -0,0 +1,306 @@
+use rusqlite::{backup::Backup, Connection, DatabaseName};
+use serde_json::{json, Value};
+use std::env;
+use std::fs;
+use std::io;
+use std::path::{Path, PathBuf};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+#[cfg(unix)]
+use std::os::unix::fs::PermissionsExt;
+
+fn string_param(params: &Value, key: &str) -> Result<String, String> {
+ params
+ .get(key)
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ .ok_or_else(|| format!("Missing string parameter: {key}"))
+}
+
+pub(crate) fn data_dir() -> PathBuf {
+ let args: Vec<String> = env::args().collect();
+ args.windows(2)
+ .find(|pair| pair[0] == "--data-dir")
+ .map(|pair| PathBuf::from(&pair[1]))
+ .unwrap_or_else(|| PathBuf::from(".edgeever-desktop"))
+}
+
+pub(crate) fn migrations_dir() -> PathBuf {
+ let args: Vec<String> = env::args().collect();
+ args.windows(2)
+ .find(|pair| pair[0] == "--migrations-dir")
+ .map(|pair| PathBuf::from(&pair[1]))
+ .unwrap_or_else(|| PathBuf::from("migrations"))
+}
+
+fn restrict_directory(path: &Path) -> io::Result<()> {
+ #[cfg(unix)]
+ {
+ let mut permissions = fs::metadata(path)?.permissions();
+ permissions.set_mode(0o700);
+ fs::set_permissions(path, permissions)?;
+ }
+ Ok(())
+}
+
+fn restrict_file(path: &Path) -> io::Result<()> {
+ #[cfg(unix)]
+ {
+ if path.exists() {
+ let mut permissions = fs::metadata(path)?.permissions();
+ permissions.set_mode(0o600);
+ fs::set_permissions(path, permissions)?;
+ }
+ }
+ Ok(())
+}
+
+fn apply_migrations(connection: &Connection, migrations: &Path) -> rusqlite::Result<()> {
+ connection.execute_batch(
+ "CREATE TABLE IF NOT EXISTS _edgeever_migrations (
+ name TEXT PRIMARY KEY,
+ applied_at TEXT NOT NULL
+ );",
+ )?;
+
+ let mut files: Vec<PathBuf> = fs::read_dir(migrations)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
+ .filter_map(|entry| entry.ok().map(|item| item.path()))
+ .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("sql"))
+ .collect();
+ files.sort();
+
+ for path in files {
+ let name = path
+ .file_name()
+ .and_then(|value| value.to_str())
+ .unwrap_or_default();
+ let already_applied: bool = connection.query_row(
+ "SELECT EXISTS(SELECT 1 FROM _edgeever_migrations WHERE name = ?1)",
+ [name],
+ |row| row.get(0),
+ )?;
+ if already_applied {
+ continue;
+ }
+
+ let sql = fs::read_to_string(&path)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let transaction = connection.unchecked_transaction()?;
+ transaction.execute_batch(&sql)?;
+ transaction.execute(
+ "INSERT INTO _edgeever_migrations (name, applied_at) VALUES (?1, datetime('now'))",
+ [name],
+ )?;
+ transaction.commit()?;
+ }
+ Ok(())
+}
+
+fn copy_directory(source: &Path, destination: &Path) -> io::Result<()> {
+ if !source.exists() {
+ return Ok(());
+ }
+ fs::create_dir_all(destination)?;
+ for entry in fs::read_dir(source)? {
+ let entry = entry?;
+ let source_path = entry.path();
+ let destination_path = destination.join(entry.file_name());
+ if source_path.is_dir() {
+ copy_directory(&source_path, &destination_path)?;
+ } else {
+ fs::copy(source_path, destination_path)?;
+ }
+ }
+ Ok(())
+}
+
+pub(crate) fn backup_database(connection: &Connection, root: &Path) -> rusqlite::Result<PathBuf> {
+ let backup_dir = root.join("backups");
+ fs::create_dir_all(&backup_dir)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ restrict_directory(&backup_dir)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let backup_path = backup_dir.join(format!(
+ "edgeever-{}.sqlite",
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ ));
+ let backup_path_text = backup_path.to_string_lossy().to_string();
+ connection.execute("VACUUM INTO ?1", [&backup_path_text])?;
+ restrict_file(&backup_path)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let resource_backup = backup_path.with_extension("resources");
+ fs::remove_dir_all(&resource_backup).ok();
+ copy_directory(&root.join("resource-outbox"), &resource_backup)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let mut backups: Vec<PathBuf> = fs::read_dir(&backup_dir)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
+ .filter_map(|entry| entry.ok().map(|item| item.path()))
+ .filter(|path| {
+ path.file_name()
+ .and_then(|name| name.to_str())
+ .map(|name| name.starts_with("edgeever-") && name.ends_with(".sqlite"))
+ .unwrap_or(false)
+ })
+ .collect();
+ backups.sort();
+ while backups.len() > 5 {
+ if let Some(oldest) = backups.first() {
+ fs::remove_file(oldest)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ fs::remove_dir_all(oldest.with_extension("resources")).ok();
+ }
+ backups.remove(0);
+ }
+ Ok(backup_path)
+}
+
+pub(crate) fn list_backups(root: &Path) -> rusqlite::Result<Value> {
+ let backup_dir = root.join("backups");
+ fs::create_dir_all(&backup_dir)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let mut backups = Vec::new();
+ for entry in fs::read_dir(&backup_dir)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
+ {
+ let path = entry
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
+ .path();
+ let name = path
+ .file_name()
+ .and_then(|value| value.to_str())
+ .unwrap_or_default()
+ .to_owned();
+ if !name.starts_with("edgeever-") || !name.ends_with(".sqlite") {
+ continue;
+ }
+ let metadata = fs::metadata(&path)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let modified_at = metadata
+ .modified()
+ .ok()
+ .and_then(|value| value.duration_since(UNIX_EPOCH).ok())
+ .map(|value| value.as_secs().to_string())
+ .unwrap_or_default();
+ backups.push(json!({ "path": path.to_string_lossy(), "name": name, "size": metadata.len(), "modifiedAt": modified_at }));
+ }
+ backups.sort_by(|left, right| {
+ right
+ .get("name")
+ .and_then(Value::as_str)
+ .cmp(&left.get("name").and_then(Value::as_str))
+ });
+ Ok(json!({ "backups": backups }))
+}
+
+pub(crate) fn restore_database(
+ database: &mut Connection,
+ root: &Path,
+ migrations: &Path,
+ params: &Value,
+) -> Result<Value, String> {
+ let requested = string_param(params, "path")?;
+ let backup_dir = root
+ .join("backups")
+ .canonicalize()
+ .map_err(|error| error.to_string())?;
+ let backup_path = PathBuf::from(requested)
+ .canonicalize()
+ .map_err(|error| error.to_string())?;
+ if backup_path.parent() != Some(backup_dir.as_path())
+ || backup_path.extension().and_then(|value| value.to_str()) != Some("sqlite")
+ {
+ return Err("Backup path must point to a managed EdgeEver backup".to_owned());
+ }
+
+ // Windows refuses to rotate/delete a backup while a read connection still
+ // holds the managed file open. Restore from a temporary copy so retention
+ // can safely remove the selected snapshot when it is the oldest one.
+ let source_copy = root.join(".edgeever-restore-source.sqlite");
+ fs::remove_file(&source_copy).ok();
+ fs::copy(&backup_path, &source_copy).map_err(|error| error.to_string())?;
+ let source = Connection::open(&source_copy).map_err(|error| error.to_string())?;
+ // A protective backup rotates the five-file retention window. Preserve the
+ // selected snapshot's resource companion before that rotation can remove
+ // it when the user restores the oldest retained backup.
+ let resource_backup = backup_path.with_extension("resources");
+ let resource_restore_source = root.join("resource-outbox.restore-source");
+ fs::remove_dir_all(&resource_restore_source).ok();
+ if resource_backup.is_dir() {
+ copy_directory(&resource_backup, &resource_restore_source)
+ .map_err(|error| error.to_string())?;
+ }
+ // Open the selected snapshot before rotation: if it is the oldest of the
+ // five retained files, the protective backup may remove its directory
+ // entry while this read-only connection keeps the snapshot available.
+ let protective_backup = backup_database(&*database, root).map_err(|error| error.to_string())?;
+ let backup = Backup::new_with_names(&source, DatabaseName::Main, database, DatabaseName::Main)
+ .map_err(|error| error.to_string())?;
+ backup
+ .run_to_completion(100, Duration::from_millis(5), None)
+ .map_err(|error| error.to_string())?;
+ drop(backup);
+ drop(source);
+ fs::remove_file(&source_copy).map_err(|error| error.to_string())?;
+ apply_migrations(database, migrations).map_err(|error| error.to_string())?;
+ let resource_source = if resource_restore_source.is_dir() {
+ resource_restore_source.as_path()
+ } else {
+ resource_backup.as_path()
+ };
+ if resource_source.is_dir() {
+ let restored_resources = root.join("resource-outbox.restore");
+ fs::remove_dir_all(&restored_resources).ok();
+ copy_directory(resource_source, &restored_resources).map_err(|error| error.to_string())?;
+ fs::remove_dir_all(root.join("resource-outbox")).ok();
+ fs::rename(restored_resources, root.join("resource-outbox"))
+ .map_err(|error| error.to_string())?;
+ }
+ fs::remove_dir_all(&resource_restore_source).ok();
+ Ok(json!({ "ok": true, "path": protective_backup }))
+}
+
+pub(crate) fn open_database(root: &Path, migrations: &Path) -> rusqlite::Result<Connection> {
+ fs::create_dir_all(root)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ restrict_directory(root)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ let existed = root.join("edgeever.sqlite").exists();
+ let connection = Connection::open(root.join("edgeever.sqlite"))?;
+ connection.pragma_update(None, "journal_mode", "WAL")?;
+ connection.execute_batch(
+ "CREATE TABLE IF NOT EXISTS _edgeever_sidecar_meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS _edgeever_sidecar_outbox (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kind TEXT NOT NULL,
+ entity_id TEXT NOT NULL,
+ payload_json TEXT NOT NULL CHECK (json_valid(payload_json)),
+ status TEXT NOT NULL DEFAULT 'pending',
+ attempt_count INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
+ );
+ CREATE INDEX IF NOT EXISTS idx_sidecar_outbox_status ON _edgeever_sidecar_outbox(status, id);",
+ )?;
+ if existed {
+ backup_database(&connection, root)?;
+ }
+ apply_migrations(&connection, migrations)?;
+ for path in [
+ root.join("edgeever.sqlite"),
+ root.join("edgeever.sqlite-wal"),
+ root.join("edgeever.sqlite-shm"),
+ ] {
+ restrict_file(&path)
+ .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
+ }
+ Ok(connection)
+}
diff --git a/crates/desktop-sidecar/src/main.rs b/crates/desktop-sidecar/src/main.rs
index 6d0accf4..24c1f81f 100644
--- a/crates/desktop-sidecar/src/main.rs
+++ b/crates/desktop-sidecar/src/main.rs
@@ -1,15 +1,16 @@
-use rusqlite::{backup::Backup, Connection, DatabaseName, OptionalExtension};
+mod database;
+
+use database::{
+ backup_database, data_dir, list_backups, migrations_dir, open_database, restore_database,
+};
+use rusqlite::{Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::env;
-use std::fs;
use std::io::{self, BufRead, Write};
-use std::path::{Path, PathBuf};
-use std::time::{Duration, SystemTime, UNIX_EPOCH};
-
-#[cfg(unix)]
-use std::os::unix::fs::PermissionsExt;
+use std::path::Path;
+use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Deserialize)]
struct RpcRequest {
@@ -25,294 +26,6 @@ struct RpcError<'a> {
message: String,
}
-fn data_dir() -> PathBuf {
- let args: Vec<String> = env::args().collect();
- args.windows(2)
- .find(|pair| pair[0] == "--data-dir")
- .map(|pair| PathBuf::from(&pair[1]))
- .unwrap_or_else(|| PathBuf::from(".edgeever-desktop"))
-}
-
-fn migrations_dir() -> PathBuf {
- let args: Vec<String> = env::args().collect();
- args.windows(2)
- .find(|pair| pair[0] == "--migrations-dir")
- .map(|pair| PathBuf::from(&pair[1]))
- .unwrap_or_else(|| PathBuf::from("migrations"))
-}
-
-fn restrict_directory(path: &Path) -> io::Result<()> {
- #[cfg(unix)]
- {
- let mut permissions = fs::metadata(path)?.permissions();
- permissions.set_mode(0o700);
- fs::set_permissions(path, permissions)?;
- }
- Ok(())
-}
-
-fn restrict_file(path: &Path) -> io::Result<()> {
- #[cfg(unix)]
- {
- if path.exists() {
- let mut permissions = fs::metadata(path)?.permissions();
- permissions.set_mode(0o600);
- fs::set_permissions(path, permissions)?;
- }
- }
- Ok(())
-}
-
-fn apply_migrations(connection: &Connection, migrations: &Path) -> rusqlite::Result<()> {
- connection.execute_batch(
- "CREATE TABLE IF NOT EXISTS _edgeever_migrations (
- name TEXT PRIMARY KEY,
- applied_at TEXT NOT NULL
- );",
- )?;
-
- let mut files: Vec<PathBuf> = fs::read_dir(migrations)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
- .filter_map(|entry| entry.ok().map(|item| item.path()))
- .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("sql"))
- .collect();
- files.sort();
-
- for path in files {
- let name = path
- .file_name()
- .and_then(|value| value.to_str())
- .unwrap_or_default();
- let already_applied: bool = connection.query_row(
- "SELECT EXISTS(SELECT 1 FROM _edgeever_migrations WHERE name = ?1)",
- [name],
- |row| row.get(0),
- )?;
- if already_applied {
- continue;
- }
-
- let sql = fs::read_to_string(&path)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let transaction = connection.unchecked_transaction()?;
- transaction.execute_batch(&sql)?;
- transaction.execute(
- "INSERT INTO _edgeever_migrations (name, applied_at) VALUES (?1, datetime('now'))",
- [name],
- )?;
- transaction.commit()?;
- }
- Ok(())
-}
-
-fn copy_directory(source: &Path, destination: &Path) -> io::Result<()> {
- if !source.exists() {
- return Ok(());
- }
- fs::create_dir_all(destination)?;
- for entry in fs::read_dir(source)? {
- let entry = entry?;
- let source_path = entry.path();
- let destination_path = destination.join(entry.file_name());
- if source_path.is_dir() {
- copy_directory(&source_path, &destination_path)?;
- } else {
- fs::copy(source_path, destination_path)?;
- }
- }
- Ok(())
-}
-
-fn backup_database(connection: &Connection, root: &Path) -> rusqlite::Result<PathBuf> {
- let backup_dir = root.join("backups");
- fs::create_dir_all(&backup_dir)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- restrict_directory(&backup_dir)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let backup_path = backup_dir.join(format!(
- "edgeever-{}.sqlite",
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_millis()
- ));
- let backup_path_text = backup_path.to_string_lossy().to_string();
- connection.execute("VACUUM INTO ?1", [&backup_path_text])?;
- restrict_file(&backup_path)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let resource_backup = backup_path.with_extension("resources");
- fs::remove_dir_all(&resource_backup).ok();
- copy_directory(&root.join("resource-outbox"), &resource_backup)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let mut backups: Vec<PathBuf> = fs::read_dir(&backup_dir)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
- .filter_map(|entry| entry.ok().map(|item| item.path()))
- .filter(|path| {
- path.file_name()
- .and_then(|name| name.to_str())
- .map(|name| name.starts_with("edgeever-") && name.ends_with(".sqlite"))
- .unwrap_or(false)
- })
- .collect();
- backups.sort();
- while backups.len() > 5 {
- if let Some(oldest) = backups.first() {
- fs::remove_file(oldest)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- fs::remove_dir_all(oldest.with_extension("resources")).ok();
- }
- backups.remove(0);
- }
- Ok(backup_path)
-}
-
-fn list_backups(root: &Path) -> rusqlite::Result<Value> {
- let backup_dir = root.join("backups");
- fs::create_dir_all(&backup_dir)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let mut backups = Vec::new();
- for entry in fs::read_dir(&backup_dir)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
- {
- let path = entry
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
- .path();
- let name = path
- .file_name()
- .and_then(|value| value.to_str())
- .unwrap_or_default()
- .to_owned();
- if !name.starts_with("edgeever-") || !name.ends_with(".sqlite") {
- continue;
- }
- let metadata = fs::metadata(&path)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let modified_at = metadata
- .modified()
- .ok()
- .and_then(|value| value.duration_since(UNIX_EPOCH).ok())
- .map(|value| value.as_secs().to_string())
- .unwrap_or_default();
- backups.push(json!({ "path": path.to_string_lossy(), "name": name, "size": metadata.len(), "modifiedAt": modified_at }));
- }
- backups.sort_by(|left, right| {
- right
- .get("name")
- .and_then(Value::as_str)
- .cmp(&left.get("name").and_then(Value::as_str))
- });
- Ok(json!({ "backups": backups }))
-}
-
-fn restore_database(
- database: &mut Connection,
- root: &Path,
- migrations: &Path,
- params: &Value,
-) -> Result<Value, String> {
- let requested = string_param(params, "path")?;
- let backup_dir = root
- .join("backups")
- .canonicalize()
- .map_err(|error| error.to_string())?;
- let backup_path = PathBuf::from(requested)
- .canonicalize()
- .map_err(|error| error.to_string())?;
- if backup_path.parent() != Some(backup_dir.as_path())
- || backup_path.extension().and_then(|value| value.to_str()) != Some("sqlite")
- {
- return Err("Backup path must point to a managed EdgeEver backup".to_owned());
- }
-
- // Windows refuses to rotate/delete a backup while a read connection still
- // holds the managed file open. Restore from a temporary copy so retention
- // can safely remove the selected snapshot when it is the oldest one.
- let source_copy = root.join(".edgeever-restore-source.sqlite");
- fs::remove_file(&source_copy).ok();
- fs::copy(&backup_path, &source_copy).map_err(|error| error.to_string())?;
- let source = Connection::open(&source_copy).map_err(|error| error.to_string())?;
- // A protective backup rotates the five-file retention window. Preserve the
- // selected snapshot's resource companion before that rotation can remove
- // it when the user restores the oldest retained backup.
- let resource_backup = backup_path.with_extension("resources");
- let resource_restore_source = root.join("resource-outbox.restore-source");
- fs::remove_dir_all(&resource_restore_source).ok();
- if resource_backup.is_dir() {
- copy_directory(&resource_backup, &resource_restore_source)
- .map_err(|error| error.to_string())?;
- }
- // Open the selected snapshot before rotation: if it is the oldest of the
- // five retained files, the protective backup may remove its directory
- // entry while this read-only connection keeps the snapshot available.
- let protective_backup = backup_database(&*database, root).map_err(|error| error.to_string())?;
- let backup = Backup::new_with_names(&source, DatabaseName::Main, database, DatabaseName::Main)
- .map_err(|error| error.to_string())?;
- backup
- .run_to_completion(100, Duration::from_millis(5), None)
- .map_err(|error| error.to_string())?;
- drop(backup);
- drop(source);
- fs::remove_file(&source_copy).map_err(|error| error.to_string())?;
- apply_migrations(database, migrations).map_err(|error| error.to_string())?;
- let resource_source = if resource_restore_source.is_dir() {
- resource_restore_source.as_path()
- } else {
- resource_backup.as_path()
- };
- if resource_source.is_dir() {
- let restored_resources = root.join("resource-outbox.restore");
- fs::remove_dir_all(&restored_resources).ok();
- copy_directory(resource_source, &restored_resources).map_err(|error| error.to_string())?;
- fs::remove_dir_all(root.join("resource-outbox")).ok();
- fs::rename(restored_resources, root.join("resource-outbox"))
- .map_err(|error| error.to_string())?;
- }
- fs::remove_dir_all(&resource_restore_source).ok();
- Ok(json!({ "ok": true, "path": protective_backup }))
-}
-
-fn open_database(root: &Path, migrations: &Path) -> rusqlite::Result<Connection> {
- fs::create_dir_all(root)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- restrict_directory(root)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- let existed = root.join("edgeever.sqlite").exists();
- let connection = Connection::open(root.join("edgeever.sqlite"))?;
- connection.pragma_update(None, "journal_mode", "WAL")?;
- connection.execute_batch(
- "CREATE TABLE IF NOT EXISTS _edgeever_sidecar_meta (
- key TEXT PRIMARY KEY,
- value TEXT NOT NULL,
- updated_at TEXT NOT NULL
- );
- CREATE TABLE IF NOT EXISTS _edgeever_sidecar_outbox (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- kind TEXT NOT NULL,
- entity_id TEXT NOT NULL,
- payload_json TEXT NOT NULL CHECK (json_valid(payload_json)),
- status TEXT NOT NULL DEFAULT 'pending',
- attempt_count INTEGER NOT NULL DEFAULT 0,
- last_error TEXT,
- created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
- updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
- );
- CREATE INDEX IF NOT EXISTS idx_sidecar_outbox_status ON _edgeever_sidecar_outbox(status, id);",
- )?;
- if existed {
- backup_database(&connection, root)?;
- }
- apply_migrations(&connection, migrations)?;
- for path in [
- root.join("edgeever.sqlite"),
- root.join("edgeever.sqlite-wal"),
- root.join("edgeever.sqlite-shm"),
- ] {
- restrict_file(&path)
- .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
- }
- Ok(connection)
-}
-
fn enqueue_change(
database: &Connection,
kind: &str,
diff --git a/packages/shared/src/sync.test.mjs b/packages/shared/src/sync.test.mjs
new file mode 100644
index 00000000..fc28f9cb
--- /dev/null
+++ b/packages/shared/src/sync.test.mjs
@@ -0,0 +1,68 @@
+import { describe, expect, test } from "bun:test";
+import {
+ createEmptySyncQueueSummary,
+ createEmptySyncRunResult,
+ getNextSyncQueueRetryDelay,
+ getSyncRetryAt,
+ getSyncRetryDelayMs,
+ summarizeSyncQueue,
+} from "./sync.ts";
+
+describe("shared sync queue contract", () => {
+ test("creates independent empty summaries and run results", () => {
+ const firstSummary = createEmptySyncQueueSummary();
+ const secondSummary = createEmptySyncQueueSummary();
+ firstSummary.pending = 1;
+
+ expect(secondSummary).toEqual({
+ total: 0,
+ pending: 0,
+ syncing: 0,
+ conflict: 0,
+ error: 0,
+ });
+ expect(createEmptySyncRunResult()).toEqual({
+ attempted: 0,
+ synced: 0,
+ failed: 0,
+ conflicted: 0,
+ });
+ });
+
+ test("summarizes every queue status", () => {
+ expect(summarizeSyncQueue([
+ { status: "pending" },
+ { status: "pending" },
+ { status: "syncing" },
+ { status: "conflict" },
+ { status: "error" },
+ ])).toEqual({
+ total: 5,
+ pending: 2,
+ syncing: 1,
+ conflict: 1,
+ error: 1,
+ });
+ });
+
+ test("shares capped exponential retry timing", () => {
+ const now = Date.parse("2026-08-01T00:00:00.000Z");
+
+ expect(getSyncRetryDelayMs(1)).toBe(2_000);
+ expect(getSyncRetryDelayMs(20)).toBe(64_000);
+ expect(getSyncRetryAt(2, now)).toBe("2026-08-01T00:00:04.000Z");
+ });
+
+ test("finds the earliest retry while ignoring conflicts", () => {
+ const now = Date.parse("2026-08-01T00:00:00.000Z");
+ const items = [
+ { status: "pending", nextAttemptAt: null },
+ { status: "error", nextAttemptAt: "2026-08-01T00:00:05.000Z" },
+ { status: "conflict", nextAttemptAt: "2026-08-01T00:00:01.000Z" },
+ ];
+
+ expect(getNextSyncQueueRetryDelay(items, now)).toBe(250);
+ expect(getNextSyncQueueRetryDelay(items.slice(1), now)).toBe(5_000);
+ expect(getNextSyncQueueRetryDelay(items.slice(2), now)).toBeNull();
+ });
+});
diff --git a/packages/shared/src/sync.ts b/packages/shared/src/sync.ts
index 16424dc6..979ae16d 100644
--- a/packages/shared/src/sync.ts
+++ b/packages/shared/src/sync.ts
@@ -42,3 +42,74 @@ export type SyncOutboxOperation =
| "notebook.create"
| "notebook.update"
| "notebook.delete";
+
+export type SyncQueueStatus = "pending" | "syncing" | "conflict" | "error";
+
+export type SyncQueueSummary = {
+ total: number;
+ pending: number;
+ syncing: number;
+ conflict: number;
+ error: number;
+};
+
+export type SyncRunResult = {
+ attempted: number;
+ synced: number;
+ failed: number;
+ conflicted: number;
+};
+
+export type SyncQueueStatusItem = {
+ status: SyncQueueStatus;
+};
+
+export type RetryableSyncQueueItem = SyncQueueStatusItem & {
+ nextAttemptAt: string | null;
+};
+
+export const createEmptySyncQueueSummary = (): SyncQueueSummary => ({
+ total: 0,
+ pending: 0,
+ syncing: 0,
+ conflict: 0,
+ error: 0,
+});
+
+export const createEmptySyncRunResult = (): SyncRunResult => ({
+ attempted: 0,
+ synced: 0,
+ failed: 0,
+ conflicted: 0,
+});
+
+export const summarizeSyncQueue = (
+ items: ReadonlyArray<SyncQueueStatusItem>
+): SyncQueueSummary => items.reduce((summary, item) => {
+ summary.total += 1;
+ summary[item.status] += 1;
+ return summary;
+}, createEmptySyncQueueSummary());
+
+export const getSyncRetryDelayMs = (attemptCount: number) =>
+ Math.min(5 * 60_000, 2 ** Math.min(Math.max(0, attemptCount), 6) * 1000);
+
+export const getSyncRetryAt = (attemptCount: number, now = Date.now()) =>
+ new Date(now + getSyncRetryDelayMs(attemptCount)).toISOString();
+
+export const getNextSyncQueueRetryDelay = (
+ items: ReadonlyArray<RetryableSyncQueueItem>,
+ now = Date.now(),
+ minimumDelayMs = 250
+): number | null => {
+ const retryTimes = items
+ .filter((item) => item.status === "pending" || item.status === "error" || item.status === "syncing")
+ .map((item) => (item.nextAttemptAt ? Date.parse(item.nextAttemptAt) : now))
+ .filter(Number.isFinite);
+
+ if (retryTimes.length === 0) {
+ return null;
+ }
+
+ return Math.max(minimumDelayMs, Math.min(...retryTimes) - now);
+};
diff --git a/scripts/wrangler-runner.mjs b/scripts/wrangler-runner.mjs
index a681c6a1..d537084b 100644
--- a/scripts/wrangler-runner.mjs
+++ b/scripts/wrangler-runner.mjs
@@ -1,5 +1,5 @@
import { spawnSync } from "node:child_process";
-import { existsSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
export const resolveWranglerCliPath = (cwd = resolve(".")) =>
@@ -91,5 +91,19 @@ export const runWranglerSync = (args, options = {}) => {
);
}
+ // Wrangler can successfully handle --version without writing to the child
+ // pipe when it is launched by Bun's test runner. Preserve the runner's
+ // stdout contract using the version from the exact local package we ran.
+ if (result.status === 0 && args.length === 1 && args[0] === "--version" && !String(result.stdout ?? "").trim()) {
+ try {
+ const metadata = JSON.parse(readFileSync(resolve(cwd, "node_modules", "wrangler", "package.json"), "utf8"));
+ if (typeof metadata.version === "string") {
+ result.stdout = options.encoding ? `${metadata.version}\n` : Buffer.from(`${metadata.version}\n`);
+ }
+ } catch {
+ // Leave the original successful result intact if package metadata is unavailable.
+ }
+ }
+
return result;
};
diff --git a/tests/mobile-app-scope.test.ts b/tests/mobile-app-scope.test.ts
index f28b04db..8928a62f 100644
--- a/tests/mobile-app-scope.test.ts
+++ b/tests/mobile-app-scope.test.ts
@@ -5,6 +5,10 @@ const workspaceSource = readFileSync(
new URL("../apps/mobile/src/screens/WorkspaceScreen.tsx", import.meta.url),
"utf8"
);
+const memoDetailSource = readFileSync(
+ new URL("../apps/mobile/src/screens/WorkspaceMemoDetail.tsx", import.meta.url),
+ "utf8"
+);
const accountSecuritySource = readFileSync(
new URL("../apps/mobile/src/screens/AccountSecurityModal.tsx", import.meta.url),
"utf8"
@@ -31,10 +35,10 @@ describe("mobile app scope", () => {
});
test("keeps version history reachable from an active note", () => {
- expect(workspaceSource).toMatch(
+ expect(memoDetailSource).toMatch(
/\{memo && !memo\.isDeleted \? \(\s*<Pressable\s+accessibilityLabel="版本历史"/
);
- expect(workspaceSource).toContain('syncStatus === "conflict"');
- expect(workspaceSource).toContain("onResolveSyncConflict");
+ expect(memoDetailSource).toContain('syncStatus === "conflict"');
+ expect(memoDetailSource).toContain("onResolveSyncConflict");
});
});