Skip to content

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

fix(mobile): improve protected image load UX and diagnostics

tianma-iff4868b313652
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsx
index 6f9a9b74..bff378a1 100644
--- a/apps/mobile/src/components/LocalTiptapEditor.tsx
+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx
@@ -34,6 +34,7 @@ import {
isMobileImageUploadPlaceholderSource,
stripMobileImageUploadPlaceholders,
} from "../lib/mobile-image-upload-placeholder";
+import { toProtectedResourceLoadPath } from "../lib/mobile-protected-resources";
type EditorDoc = TiptapDoc;
@@ -887,11 +888,10 @@ const normalizeImageSources = (doc: EditorDoc, baseUrl: string) => {
const getPersistableEditorDoc = (doc: EditorDoc, baseUrl: string) =>
normalizeImageSources(stripMobileImageUploadPlaceholders(doc), baseUrl);
-const normalizeProtectedResourceSource = (source: string, baseUrl: string) => {
- const normalizedBaseUrl = baseUrl.replace(/\/+$/, "");
- const relativeSource = source.startsWith(`${normalizedBaseUrl}/`) ? source.slice(normalizedBaseUrl.length) : source;
- return relativeSource.startsWith("/api/v1/resources/") ? relativeSource : null;
-};
+const normalizeProtectedResourceSource = (source: string, baseUrl: string) =>
+ // Shared normalizer adds `/blob` so editor loads hit the API blob route even when
+ // note content stores the bare `/api/v1/resources/:id` form.
+ toProtectedResourceLoadPath(source, baseUrl);
const resolveUrl = (source: string, baseUrl: string) => {
if (!source.startsWith("/")) {
@@ -1312,6 +1312,14 @@ const createProtectedImageExtension = (
placeholder.removeAttribute("role");
placeholder.removeAttribute("aria-live");
};
+ // Keep the upload preview until decode succeeds — never swap to a
+ // 401-prone bare resource URL that flashes a broken icon.
+ preload.onerror = () => {
+ if (activeRequestId !== requestId) {
+ return;
+ }
+ overlay.textContent = locale === "en-US" ? "Image failed to load" : "图片加载失败";
+ };
preload.src = displaySource;
};
@@ -1328,13 +1336,18 @@ const createProtectedImageExtension = (
void loadResource(protectedSource)
.then((dataUrl) => {
- if (activeRequestId === requestId) {
- revealLoadedImage(dataUrl ?? resolveUrl(source, baseUrl), attributes, activeRequestId);
+ if (activeRequestId !== requestId) {
+ return;
+ }
+ if (dataUrl) {
+ revealLoadedImage(dataUrl, attributes, activeRequestId);
+ return;
}
+ overlay.textContent = locale === "en-US" ? "Image failed to load" : "图片加载失败";
})
.catch(() => {
if (activeRequestId === requestId) {
- revealLoadedImage(resolveUrl(source, baseUrl), attributes, activeRequestId);
+ overlay.textContent = locale === "en-US" ? "Image failed to load" : "图片加载失败";
}
});
};
@@ -1376,13 +1389,28 @@ const createProtectedImageExtension = (
}
const wrapper = document.createElement("figure");
- wrapper.className = "edgeever-image-node";
+ wrapper.className = "edgeever-image-node is-loading";
wrapper.contentEditable = "false";
+ wrapper.setAttribute("role", "img");
+ wrapper.setAttribute("aria-busy", "true");
+
+ const loading = document.createElement("div");
+ loading.className = "edgeever-image-loading";
+ loading.setAttribute("aria-hidden", "true");
+ const spinner = document.createElement("span");
+ spinner.className = "edgeever-image-upload-spinner";
+ loading.append(spinner);
+
const image = document.createElement("img");
+ // Never leave <img> without a successful src — empty/401 src paints the
+ // browser broken-image glyph before the authenticated data URL arrives.
+ image.hidden = true;
+
const actionButton = document.createElement("button");
actionButton.type = "button";
actionButton.className = "edgeever-image-actions";
actionButton.contentEditable = "false";
+ actionButton.hidden = true;
actionButton.setAttribute("aria-label", locale === "en-US" ? "Image actions" : "图片操作");
actionButton.textContent = "⋯";
bindImageActionButton(wrapper, actionButton);
@@ -1398,23 +1426,47 @@ const createProtectedImageExtension = (
emitImagePreview(wrapper);
});
}
- wrapper.append(image, actionButton, sizeControls.dom);
+ wrapper.append(loading, image, actionButton, sizeControls.dom);
const imageType = node.type;
let requestId = 0;
+ let renderedSource = "";
+ let displayReady = false;
const clearRequest = () => {
requestId += 1;
};
- const renderNode = (attributes: Record<string, unknown>) => {
- clearRequest();
- sizeControls.setActiveWidth(applyImageWidth(wrapper, attributes));
- const source = String(attributes.src ?? "");
+ const setImagePhase = (phase: "loading" | "ready" | "failed") => {
+ wrapper.classList.toggle("is-loading", phase === "loading");
+ wrapper.classList.toggle("is-failed", phase === "failed");
+ wrapper.setAttribute("aria-busy", phase === "loading" ? "true" : "false");
+ loading.hidden = phase === "ready";
+ image.hidden = phase !== "ready";
+ actionButton.hidden = phase !== "ready";
+ if (phase === "failed") {
+ loading.replaceChildren();
+ const label = document.createElement("span");
+ label.className = "edgeever-image-loading-label";
+ label.textContent = locale === "en-US" ? "Image failed to load" : "图片加载失败";
+ loading.append(label);
+ loading.hidden = false;
+ } else if (phase === "loading") {
+ loading.replaceChildren(spinner);
+ }
+ };
+
+ const applyImageMeta = (attributes: Record<string, unknown>) => {
const alt = String(attributes.alt ?? "");
const title = String(attributes.title ?? "");
+ const source = String(attributes.src ?? "");
wrapper.dataset.resourceHref = source;
wrapper.dataset.resourceFilename = alt || title;
image.alt = alt;
+ if (alt) {
+ wrapper.setAttribute("aria-label", alt);
+ } else {
+ wrapper.removeAttribute("aria-label");
+ }
const referrerPolicy = getImageReferrerPolicy(source);
if (referrerPolicy) {
image.referrerPolicy = referrerPolicy;
@@ -1426,24 +1478,73 @@ const createProtectedImageExtension = (
} else {
image.removeAttribute("title");
}
+ };
- const protectedSource = normalizeProtectedResourceSource(source, baseUrl);
- if (!protectedSource) {
- image.src = resolveUrl(source, baseUrl);
+ /** Decode off-DOM first so the visible <img> never paints a broken glyph. */
+ const revealDisplaySource = (displaySource: string, activeRequestId: number) => {
+ const preload = document.createElement("img");
+ const preloadReferrerPolicy = getImageReferrerPolicy(displaySource);
+ if (preloadReferrerPolicy) {
+ preload.referrerPolicy = preloadReferrerPolicy;
+ }
+ preload.onload = () => {
+ if (activeRequestId !== requestId) {
+ return;
+ }
+ image.src = displaySource;
+ displayReady = true;
+ setImagePhase("ready");
+ };
+ preload.onerror = () => {
+ if (activeRequestId !== requestId) {
+ return;
+ }
+ displayReady = false;
+ image.removeAttribute("src");
+ setImagePhase("failed");
+ };
+ preload.src = displaySource;
+ };
+
+ const renderNode = (attributes: Record<string, unknown>) => {
+ sizeControls.setActiveWidth(applyImageWidth(wrapper, attributes));
+ applyImageMeta(attributes);
+ const source = String(attributes.src ?? "");
+
+ // Width / alt-only updates must not tear down a successfully loaded image.
+ if (source === renderedSource && displayReady && image.getAttribute("src")) {
return;
}
+ clearRequest();
+ renderedSource = source;
+ displayReady = false;
image.removeAttribute("src");
+ setImagePhase("loading");
+
const activeRequestId = requestId;
+ const protectedSource = normalizeProtectedResourceSource(source, baseUrl);
+ if (!protectedSource) {
+ revealDisplaySource(resolveUrl(source, baseUrl), activeRequestId);
+ return;
+ }
+
void loadResource(protectedSource)
.then((dataUrl) => {
- if (activeRequestId === requestId) {
- image.src = dataUrl ?? resolveUrl(source, baseUrl);
+ if (activeRequestId !== requestId) {
+ return;
+ }
+ // Do not fall back to an unauthenticated absolute URL — that 401s and
+ // briefly shows the broken-image icon before any error UI.
+ if (!dataUrl) {
+ setImagePhase("failed");
+ return;
}
+ revealDisplaySource(dataUrl, activeRequestId);
})
.catch(() => {
if (activeRequestId === requestId) {
- image.src = resolveUrl(source, baseUrl);
+ setImagePhase("failed");
}
});
};
@@ -1461,7 +1562,7 @@ const createProtectedImageExtension = (
},
selectNode: () => {
wrapper.classList.add("is-selected");
- sizeControls.setVisible(!readOnly);
+ sizeControls.setVisible(!readOnly && displayReady);
},
deselectNode: () => {
wrapper.classList.remove("is-selected");
@@ -1799,9 +1900,15 @@ const getEditorStyles = (theme: "light" | "dark", options?: { viewer?: boolean }
.edgeever-image-upload-preview { display: block; width: 100%; max-height: 360px; margin: 0 !important; object-fit: contain; border-radius: 10px; }
.edgeever-image-upload-overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 10px; border-radius: 10px; background: rgba(15, 23, 42, 0.38); color: #fff; font-size: 14px; font-weight: 600; text-shadow: 0 1px 2px rgba(15, 23, 42, 0.45); }
.edgeever-image-node, .edgeever-image-upload-result { position: relative; display: block; max-width: 100%; margin: 14px auto; line-height: 0; }
- .edgeever-image-node > img, .edgeever-image-upload-result > img { width: 100%; margin: 0; }
+ .edgeever-image-node.is-loading, .edgeever-image-node.is-failed { min-height: 120px; overflow: hidden; border-radius: 10px; background: ${theme === "dark" ? "#1e293b" : "#f1f5f9"}; }
+ .edgeever-image-loading { display: flex; min-height: 120px; align-items: center; justify-content: center; gap: 10px; padding: 16px; color: ${theme === "dark" ? "#94a3b8" : "#64748b"}; font-size: 13px; font-weight: 600; line-height: 1.3; }
+ .edgeever-image-loading[hidden] { display: none; }
+ .edgeever-image-loading-label { text-align: center; }
+ .edgeever-image-node > img, .edgeever-image-upload-result > img { display: block; width: 100%; margin: 0; border-radius: 10px; }
+ .edgeever-image-node > img[hidden] { display: none; }
.edgeever-image-node.is-selected > img, .edgeever-image-upload-result.is-selected > img { outline: 2px solid #0f766e; outline-offset: 3px; }
.edgeever-image-actions { position: absolute; right: 8px; bottom: 8px; z-index: 3; display: inline-flex; width: 42px; height: 42px; appearance: none; align-items: center; justify-content: center; border: 1px solid ${theme === "dark" ? "#475569" : "#cbd5e1"}; border-radius: 999px; background: ${theme === "dark" ? "rgba(15, 23, 42, 0.9)" : "rgba(255, 255, 255, 0.92)"}; color: ${theme === "dark" ? "#e2e8f0" : "#334155"}; font-size: 24px; font-weight: 700; line-height: 1; box-shadow: 0 3px 12px rgba(15, 23, 42, 0.2); }
+ .edgeever-image-actions[hidden] { display: none; }
.edgeever-image-size-controls { position: absolute; top: 8px; left: 50%; z-index: 2; display: flex; width: max-content; max-width: calc(100vw - 40px); align-items: center; gap: 3px; transform: translateX(-50%); border: 1px solid ${theme === "dark" ? "#475569" : "#bbf7d0"}; border-radius: 9px; padding: 4px; background: ${theme === "dark" ? "rgba(15, 23, 42, 0.96)" : "rgba(255, 255, 255, 0.96)"}; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.2); line-height: 1.15; }
.edgeever-image-size-controls[hidden] { display: none; }
.edgeever-image-size-button { display: inline-flex; min-width: 52px; min-height: 38px; appearance: none; align-items: center; justify-content: center; border: 0; border-radius: 7px; padding: 4px 7px; background: transparent; color: ${theme === "dark" ? "#cbd5e1" : "#475569"}; font: inherit; font-size: 12px; font-weight: 700; }
diff --git a/apps/mobile/src/lib/mobile-protected-resources.test.mjs b/apps/mobile/src/lib/mobile-protected-resources.test.mjs
new file mode 100644
index 00000000..5f01a525
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-protected-resources.test.mjs
@@ -0,0 +1,174 @@
+import { describe, expect, test } from "bun:test";
+import {
+ createOnceProtectedResourceFailureNotifier,
+ isProtectedResourceSource,
+ loadProtectedResourceDataUrl,
+ normalizeProtectedResourcePath,
+ toProtectedResourceLoadFailure,
+ toProtectedResourceLoadPath,
+} from "./mobile-protected-resources.ts";
+
+describe("normalizeProtectedResourcePath", () => {
+ test("adds /blob when missing", () => {
+ expect(normalizeProtectedResourcePath("/api/v1/resources/res_1")).toBe(
+ "/api/v1/resources/res_1/blob"
+ );
+ });
+
+ test("keeps existing /blob and strips query", () => {
+ expect(normalizeProtectedResourcePath("/api/v1/resources/res_1/blob?x=1")).toBe(
+ "/api/v1/resources/res_1/blob"
+ );
+ });
+
+ test("strips instance base URL", () => {
+ expect(
+ normalizeProtectedResourcePath(
+ "https://demo.example.com/api/v1/resources/res_9",
+ "https://demo.example.com"
+ )
+ ).toBe("/api/v1/resources/res_9/blob");
+ });
+
+ test("leaves external URLs alone", () => {
+ expect(normalizeProtectedResourcePath("https://cdn.example.com/cat.png")).toBe(
+ "https://cdn.example.com/cat.png"
+ );
+ });
+});
+
+describe("toProtectedResourceLoadPath", () => {
+ test("returns null for non-resource sources", () => {
+ expect(toProtectedResourceLoadPath("https://mmbiz.qpic.cn/x.jpg")).toBeNull();
+ expect(toProtectedResourceLoadPath("data:image/png;base64,aa")).toBeNull();
+ });
+
+ test("normalizes protected sources", () => {
+ expect(
+ toProtectedResourceLoadPath(
+ "https://app.example/api/v1/resources/res_a",
+ "https://app.example"
+ )
+ ).toBe("/api/v1/resources/res_a/blob");
+ });
+});
+
+describe("isProtectedResourceSource", () => {
+ test("matches relative and absolute resource URLs", () => {
+ expect(isProtectedResourceSource("/api/v1/resources/res_1/blob")).toBe(true);
+ expect(
+ isProtectedResourceSource("https://x.test/api/v1/resources/res_1/blob", {
+ baseUrl: "https://x.test",
+ })
+ ).toBe(true);
+ expect(isProtectedResourceSource("https://other.test/img.png", { baseUrl: "https://x.test" })).toBe(
+ false
+ );
+ });
+});
+
+const withFakeFileReader = async (run) => {
+ const OriginalFileReader = globalThis.FileReader;
+ class FakeFileReader {
+ result = null;
+ onerror = null;
+ onloadend = null;
+ readAsDataURL(blob) {
+ void blob;
+ this.result = "data:image/png;base64,AQID";
+ queueMicrotask(() => this.onloadend?.());
+ }
+ }
+ globalThis.FileReader = FakeFileReader;
+ try {
+ return await run();
+ } finally {
+ globalThis.FileReader = OriginalFileReader;
+ }
+};
+
+describe("loadProtectedResourceDataUrl", () => {
+ test("fetches the blob path and returns a data URL", async () => {
+ await withFakeFileReader(async () => {
+ const calls = [];
+ const blob = new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" });
+ const dataUrl = await loadProtectedResourceDataUrl("/api/v1/resources/res_z", {
+ getResourceBlob: async (path) => {
+ calls.push(path);
+ return blob;
+ },
+ });
+ expect(calls).toEqual(["/api/v1/resources/res_z/blob"]);
+ expect(dataUrl?.startsWith("data:")).toBe(true);
+ });
+ });
+
+ test("reports failures and returns null without throwing", async () => {
+ const failures = [];
+ const dataUrl = await loadProtectedResourceDataUrl("/api/v1/resources/res_z/blob", {
+ getResourceBlob: async () => {
+ const error = new Error("Resource download failed");
+ error.status = 401;
+ throw error;
+ },
+ onFailure: (failure) => failures.push(failure),
+ });
+ expect(dataUrl).toBeNull();
+ expect(failures).toEqual([
+ {
+ message: "Resource download failed",
+ path: "/api/v1/resources/res_z/blob",
+ status: 401,
+ },
+ ]);
+ });
+
+ test("reuses cache entries and drops failed ones", async () => {
+ await withFakeFileReader(async () => {
+ let hits = 0;
+ const cache = new Map();
+ const blob = new Blob([new Uint8Array([9])], { type: "image/png" });
+ const options = {
+ cache,
+ getResourceBlob: async () => {
+ hits += 1;
+ return blob;
+ },
+ token: "tok",
+ };
+ const first = loadProtectedResourceDataUrl("/api/v1/resources/res_c/blob", options);
+ const second = loadProtectedResourceDataUrl("/api/v1/resources/res_c/blob", options);
+ expect(await first).toBe(await second);
+ expect(hits).toBe(1);
+ });
+
+ const failCache = new Map();
+ await loadProtectedResourceDataUrl("/api/v1/resources/res_bad/blob", {
+ cache: failCache,
+ getResourceBlob: async () => {
+ throw new Error("gone");
+ },
+ });
+ expect(failCache.size).toBe(0);
+ });
+});
+
+describe("failure helpers", () => {
+ test("extracts status from Api-like errors", () => {
+ expect(
+ toProtectedResourceLoadFailure("/api/v1/resources/x/blob", Object.assign(new Error("nope"), { status: 404 }))
+ ).toEqual({
+ message: "nope",
+ path: "/api/v1/resources/x/blob",
+ status: 404,
+ });
+ });
+
+ test("notifies only once", () => {
+ const seen = [];
+ const notify = createOnceProtectedResourceFailureNotifier((f) => seen.push(f.path));
+ notify({ message: "a", path: "/a" });
+ notify({ message: "b", path: "/b" });
+ expect(seen).toEqual(["/a"]);
+ });
+});
diff --git a/apps/mobile/src/lib/mobile-protected-resources.ts b/apps/mobile/src/lib/mobile-protected-resources.ts
new file mode 100644
index 00000000..e5cd613f
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-protected-resources.ts
@@ -0,0 +1,170 @@
+/**
+ * Shared helpers for authenticated note image / resource loading on mobile.
+ *
+ * Protected resources live at `/api/v1/resources/:id/blob` and require a Bearer
+ * token. WebView `<img>` cannot attach headers, so native code fetches the blob
+ * and injects a data URL. Failures used to be swallowed silently — always log
+ * and optionally surface a one-shot user notice.
+ */
+
+export type ProtectedResourceSession = {
+ baseUrl?: string | null;
+ token?: string | null;
+} | null | undefined;
+
+export type ProtectedResourceLoadFailure = {
+ message: string;
+ path: string;
+ status?: number;
+};
+
+export const isProtectedResourceSource = (
+ source: string,
+ session?: ProtectedResourceSession
+) => {
+ const baseUrl = session?.baseUrl?.replace(/\/+$/, "") ?? "";
+ return (
+ source.startsWith("/api/v1/resources/")
+ || Boolean(
+ baseUrl
+ && (source.startsWith(`${baseUrl}/api/v1/resources/`)
+ || source.startsWith("/api/v1/resources/"))
+ )
+ );
+};
+
+/**
+ * Strip instance base URL and ensure protected paths hit the blob route.
+ * Non-resource URLs are returned unchanged (relative form when base was stripped).
+ */
+export const normalizeProtectedResourcePath = (source: string, baseUrl = "") => {
+ const normalizedBase = baseUrl.replace(/\/+$/, "");
+ let path = source;
+ if (normalizedBase && path.startsWith(`${normalizedBase}/`)) {
+ path = path.slice(normalizedBase.length);
+ }
+ if (!path.startsWith("/api/v1/resources/")) {
+ return path;
+ }
+ if (/\/blob(?:$|[?#])/.test(path)) {
+ return path.replace(/[?#].*$/, "");
+ }
+ const match = path.match(/^(\/api\/v1\/resources\/[^/?#]+)/);
+ return match ? `${match[1]}/blob` : path;
+};
+
+/**
+ * Relative protected load path (`/api/v1/resources/:id/blob`) or null when the
+ * source is not a protected EdgeEver resource.
+ */
+export const toProtectedResourceLoadPath = (source: string, baseUrl = ""): string | null => {
+ const path = normalizeProtectedResourcePath(source, baseUrl);
+ return path.startsWith("/api/v1/resources/") ? path : null;
+};
+
+export const blobToDataUrl = (blob: Blob) =>
+ new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () => reject(reader.error ?? new Error("资源读取失败"));
+ reader.onloadend = () => {
+ if (typeof reader.result === "string") {
+ resolve(reader.result);
+ return;
+ }
+ reject(new Error("资源读取失败"));
+ };
+ reader.readAsDataURL(blob);
+ });
+
+export const toProtectedResourceLoadFailure = (
+ path: string,
+ error: unknown
+): ProtectedResourceLoadFailure => {
+ const status =
+ error
+ && typeof error === "object"
+ && "status" in error
+ && typeof (error as { status: unknown }).status === "number"
+ ? (error as { status: number }).status
+ : undefined;
+ const message =
+ error instanceof Error
+ ? error.message
+ : typeof error === "string"
+ ? error
+ : "Resource download failed";
+ return { message, path, status };
+};
+
+/** Always-on diagnostics for production feedback (#188). */
+export const reportProtectedResourceLoadFailure = (failure: ProtectedResourceLoadFailure) => {
+ const statusPart = failure.status != null ? ` status=${failure.status}` : "";
+ console.warn(
+ `[EdgeEver] protected image load failed path=${failure.path}${statusPart} message=${failure.message}`
+ );
+};
+
+/** First failure only — avoids spamming multi-image notes. */
+export const createOnceProtectedResourceFailureNotifier = (
+ notify: (failure: ProtectedResourceLoadFailure) => void
+) => {
+ let notified = false;
+ return (failure: ProtectedResourceLoadFailure) => {
+ if (notified) return;
+ notified = true;
+ notify(failure);
+ };
+};
+
+export type LoadProtectedResourceDataUrlOptions = {
+ baseUrl?: string;
+ /** Optional shared cache; failures are removed so a later retry can succeed. */
+ cache?: Map<string, Promise<string | null>>;
+ cacheLimit?: number;
+ getResourceBlob: (resourceUrl: string) => Promise<Blob>;
+ onFailure?: (failure: ProtectedResourceLoadFailure) => void;
+ /** Included in cache keys so token rotation does not reuse stale entries. */
+ token?: string | null;
+};
+
+const DEFAULT_CACHE_LIMIT = 32;
+
+export const loadProtectedResourceDataUrl = (
+ source: string,
+ options: LoadProtectedResourceDataUrlOptions
+): Promise<string | null> => {
+ const path = toProtectedResourceLoadPath(source, options.baseUrl ?? "");
+ if (!path || !options.getResourceBlob) {
+ return Promise.resolve(null);
+ }
+
+ const cache = options.cache;
+ const cacheKey = `${options.token ?? ""}\n${path}`;
+ if (cache) {
+ const cached = cache.get(cacheKey);
+ if (cached) {
+ return cached;
+ }
+ const limit = options.cacheLimit ?? DEFAULT_CACHE_LIMIT;
+ if (cache.size >= limit) {
+ const oldestKey = cache.keys().next().value;
+ if (oldestKey) {
+ cache.delete(oldestKey);
+ }
+ }
+ }
+
+ const pending = options
+ .getResourceBlob(path)
+ .then(blobToDataUrl)
+ .catch((error: unknown) => {
+ cache?.delete(cacheKey);
+ const failure = toProtectedResourceLoadFailure(path, error);
+ reportProtectedResourceLoadFailure(failure);
+ options.onFailure?.(failure);
+ return null;
+ });
+
+ cache?.set(cacheKey, pending);
+ return pending;
+};
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index def5b59f..03082d5c 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -16,6 +16,12 @@ import {
type MobileResourceTarget,
} from "../lib/mobile-attachments";
import { useMobileLocale } from "../lib/mobile-locale";
+import {
+ createOnceProtectedResourceFailureNotifier,
+ isProtectedResourceSource,
+ loadProtectedResourceDataUrl,
+ type ProtectedResourceLoadFailure,
+} from "../lib/mobile-protected-resources";
import { useMobileTheme } from "../lib/mobile-theme";
import { useSession } from "../lib/session";
import { beginEditorStartup } from "../lib/startup-performance";
@@ -32,29 +38,6 @@ type AuthenticatedImageSource = {
uri: string;
};
-const isProtectedResourceSource = (source: string, session: SessionLike) => {
- const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
- return source.startsWith("/api/v1/resources/")
- || Boolean(baseUrl && (source.startsWith(`${baseUrl}/api/v1/resources/`) || source.startsWith("/api/v1/resources/")));
-};
-
-/** Ensure protected resource URLs hit the blob route the API serves. */
-const normalizeProtectedResourcePath = (source: string, session: SessionLike) => {
- const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
- let path = source;
- if (baseUrl && path.startsWith(`${baseUrl}/`)) {
- path = path.slice(baseUrl.length);
- }
- if (!path.startsWith("/api/v1/resources/")) {
- return path;
- }
- if (/\/blob(?:$|[?#])/.test(path)) {
- return path;
- }
- const match = path.match(/^(\/api\/v1\/resources\/[^/?#]+)/);
- return match ? `${match[1]}/blob` : path;
-};
-
const getAuthenticatedResourceSource = (
source: string,
session: SessionLike
@@ -70,48 +53,37 @@ const getAuthenticatedResourceSource = (
};
};
-const blobToDataUrl = (blob: Blob) => new Promise<string>((resolve, reject) => {
- const reader = new FileReader();
- reader.onerror = () => reject(reader.error ?? new Error("资源读取失败"));
- reader.onloadend = () => {
- if (typeof reader.result === "string") {
- resolve(reader.result);
- return;
- }
- reject(new Error("资源读取失败"));
- };
- reader.readAsDataURL(blob);
-});
-
const resourceDataUrlCache = new Map<string, Promise<string | null>>();
-const loadProtectedResourceDataUrl = (
+const loadAuthenticatedImageDataUrl = (
source: string,
session: SessionLike,
- getResourceBlob: ((resourceUrl: string) => Promise<Blob>) | null | undefined
+ getResourceBlob: ((resourceUrl: string) => Promise<Blob>) | null | undefined,
+ onFailure?: (failure: ProtectedResourceLoadFailure) => void
) => {
if (!getResourceBlob || !isProtectedResourceSource(source, session)) {
return Promise.resolve(null);
}
- const path = normalizeProtectedResourcePath(source, session);
- const cacheKey = `${session?.token ?? ""}\n${path}`;
- const cached = resourceDataUrlCache.get(cacheKey);
- if (cached) {
- return cached;
- }
- if (resourceDataUrlCache.size >= RESOURCE_DATA_URL_CACHE_LIMIT) {
- const oldestKey = resourceDataUrlCache.keys().next().value;
- if (oldestKey) {
- resourceDataUrlCache.delete(oldestKey);
- }
- }
- const pending = getResourceBlob(path)
- .then(blobToDataUrl)
- .catch(() => {
- resourceDataUrlCache.delete(cacheKey);
- return null;
- });
- resourceDataUrlCache.set(cacheKey, pending);
- return pending;
+ return loadProtectedResourceDataUrl(source, {
+ baseUrl: session?.baseUrl ?? "",
+ cache: resourceDataUrlCache,
+ cacheLimit: RESOURCE_DATA_URL_CACHE_LIMIT,
+ getResourceBlob,
+ onFailure,
+ token: session?.token,
+ });
+};
+
+const alertProtectedImageLoadFailure = (
+ locale: "zh-CN" | "en-US",
+ failure: ProtectedResourceLoadFailure
+) => {
+ const statusLabel = failure.status != null ? String(failure.status) : locale === "en-US" ? "network error" : "网络错误";
+ Alert.alert(
+ locale === "en-US" ? "Image failed to load" : "图片加载失败",
+ locale === "en-US"
+ ? `Could not load a note image (${statusLabel}). Check the network and try again.`
+ : `笔记中的图片未能加载(${statusLabel})。请检查网络后重试。`
+ );
};
type CachedSvgResource = {
@@ -165,6 +137,7 @@ const AuthenticatedResourceImage = ({
fitAspect = false,
href,
loadResourceBlob,
+ onLoadFailure,
resizeMode = "cover",
session,
style,
@@ -173,28 +146,45 @@ const AuthenticatedResourceImage = ({
fitAspect?: boolean;
href: string;
loadResourceBlob?: ((resourceUrl: string) => Promise<Blob>) | null;
+ onLoadFailure?: (failure: ProtectedResourceLoadFailure) => void;
resizeMode?: "center" | "contain" | "cover" | "repeat" | "stretch";
session: SessionLike;
style: StyleProp<ImageStyle>;
}) => {
const headerSource = useMemo(() => getAuthenticatedResourceSource(href, session), [href, session]);
- const [displaySource, setDisplaySource] = useState<AuthenticatedImageSource>(headerSource);
+ const isProtected = isProtectedResourceSource(href, session);
+ // Protected images: wait for the data URL so we never paint a failed first frame.
+ const [displaySource, setDisplaySource] = useState<AuthenticatedImageSource | null>(
+ isProtected ? null : headerSource
+ );
const [aspectRatio, setAspectRatio] = useState(16 / 9);
const [svgXml, setSvgXml] = useState<string | null>(null);
+ const [loadFailed, setLoadFailed] = useState(false);
const svgRequestStartedRef = useRef(false);
const svgSourceKeyRef = useRef("");
- const svgSourceKey = getAuthenticatedSvgCacheKey(displaySource);
+ const svgSourceKey = displaySource ? getAuthenticatedSvgCacheKey(displaySource) : "";
const imageStyle = fitAspect ? [style, { aspectRatio, height: undefined, width: "100%" as const }] : style;
useEffect(() => {
let cancelled = false;
setSvgXml(null);
setAspectRatio(16 / 9);
+ setLoadFailed(false);
svgRequestStartedRef.current = false;
- setDisplaySource(headerSource);
+ setDisplaySource(isProtectedResourceSource(href, session) ? null : headerSource);
- void loadProtectedResourceDataUrl(href, session, loadResourceBlob).then((dataUrl) => {
- if (cancelled || !dataUrl) {
+ if (!isProtectedResourceSource(href, session)) {
+ return () => {
+ cancelled = true;
+ };
+ }
+
+ void loadAuthenticatedImageDataUrl(href, session, loadResourceBlob, onLoadFailure).then((dataUrl) => {
+ if (cancelled) {
+ return;
+ }
+ if (!dataUrl) {
+ setLoadFailed(true);
return;
}
setDisplaySource({ uri: dataUrl });
@@ -203,7 +193,7 @@ const AuthenticatedResourceImage = ({
return () => {
cancelled = true;
};
- }, [headerSource, href, loadResourceBlob, session]);
+ }, [headerSource, href, loadResourceBlob, onLoadFailure, session]);
useEffect(() => {
svgSourceKeyRef.current = svgSourceKey;
@@ -228,7 +218,7 @@ const AuthenticatedResourceImage = ({
}, [svgSourceKey]);
const loadSvgFallback = () => {
- if (svgRequestStartedRef.current) {
+ if (svgRequestStartedRef.current || !displaySource) {
return;
}
svgRequestStartedRef.current = true;
@@ -252,6 +242,18 @@ const AuthenticatedResourceImage = ({
);
}
+ if (!displaySource || loadFailed) {
+ return (
+ <View
+ accessibilityLabel={alt || undefined}
+ accessible={Boolean(alt)}
+ style={[imageStyle, resourceImageStyles.previewPlaceholder]}
+ >
+ {loadFailed ? null : <ActivityIndicator color="#94a3b8" />}
+ </View>
+ );
+ }
+
return (
<RNImage
accessibilityLabel={alt || undefined}
@@ -348,6 +350,14 @@ export const MemoDetailModal = ({
const [viewerReady, setViewerReady] = useState(false);
const viewerRef = useRef<LocalTiptapEditorRef>(null);
const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());
+ // One user-visible notice per opened memo (multi-image notes should not spam alerts).
+ const imageLoadFailureNotifier = useMemo(
+ () =>
+ createOnceProtectedResourceFailureNotifier((failure) => {
+ alertProtectedImageLoadFailure(resolvedLocale, failure);
+ }),
+ [memo?.id, resolvedLocale]
+ );
const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
const viewerContent = useMemo<TiptapDoc>(
@@ -382,15 +392,15 @@ export const MemoDetailModal = ({
if (!client) {
return Promise.resolve(null);
}
- const path = normalizeProtectedResourcePath(source, session);
- const cached = resourceDataUrlCacheRef.current.get(path);
- if (cached) {
- return cached;
- }
- const pending = client.getResourceBlob(path).then(blobToDataUrl).catch(() => null);
- resourceDataUrlCacheRef.current.set(path, pending);
- return pending;
- }, [client, session]);
+ return loadProtectedResourceDataUrl(source, {
+ baseUrl: session?.baseUrl ?? "",
+ cache: resourceDataUrlCacheRef.current,
+ cacheLimit: RESOURCE_DATA_URL_CACHE_LIMIT,
+ getResourceBlob: client.getResourceBlob,
+ onFailure: imageLoadFailureNotifier,
+ token: session?.token,
+ });
+ }, [client, imageLoadFailureNotifier, session?.baseUrl, session?.token]);
const onResourcePress = useCallback(async (targetJson: string) => {
const target = parseMobileResourceTargetJson(targetJson);
@@ -765,6 +775,7 @@ export const MemoDetailModal = ({
alt={imagePreview.alt}
href={imagePreview.source}
loadResourceBlob={client?.getResourceBlob}
+ onLoadFailure={imageLoadFailureNotifier}
resizeMode="contain"
session={session}
style={resourceImageStyles.previewImage}
@@ -850,4 +861,8 @@ const resourceImageStyles = StyleSheet.create({
height: "100%",
width: "100%",
},
+ previewPlaceholder: {
+ alignItems: "center",
+ justifyContent: "center",
+ },
});
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 64d34108..ea4abfc5 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -167,6 +167,11 @@ import {
saveMobileResourceAs,
type MobileResourceTarget,
} from "../lib/mobile-attachments";
+import {
+ createOnceProtectedResourceFailureNotifier,
+ loadProtectedResourceDataUrl,
+ type ProtectedResourceLoadFailure,
+} from "../lib/mobile-protected-resources";
const ALL_NOTES_ID = "all";
const DEFAULT_MEMO_TITLE = "无标题笔记";
@@ -178,6 +183,24 @@ const resolveEditableMemoTitle = (title?: string | null) => {
const trimmedTitle = title?.trim() ?? "";
return trimmedTitle === DEFAULT_MEMO_TITLE ? "" : trimmedTitle;
};
+
+const alertProtectedImageLoadFailure = (
+ locale: "zh-CN" | "en-US",
+ failure: ProtectedResourceLoadFailure
+) => {
+ const statusLabel = failure.status != null
+ ? String(failure.status)
+ : locale === "en-US"
+ ? "network error"
+ : "网络错误";
+ Alert.alert(
+ locale === "en-US" ? "Image failed to load" : "图片加载失败",
+ locale === "en-US"
+ ? `Could not load a note image (${statusLabel}). Check the network and try again.`
+ : `笔记中的图片未能加载(${statusLabel})。请检查网络后重试。`
+ );
+};
+
const useMobileLocalePreference = () => useMobileLocale().preference;
type MobileView = "notes" | "settings";
type MemoView = "notebook" | "trash";
@@ -1684,13 +1707,20 @@ const CreateMemoModal = ({
syncQueueScope: string;
visible: boolean;
}) => {
- const { client } = useSession();
+ const { client, session } = useSession();
const queryClient = useQueryClient();
const { resolvedLocale } = useMobileLocale();
const { resolvedTheme } = useMobileTheme();
const fallbackNotebookId = defaultNotebookId;
const editorRef = useRef<LocalTiptapEditorRef>(null);
const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());
+ const imageLoadFailureNotifier = useMemo(
+ () =>
+ createOnceProtectedResourceFailureNotifier((failure) => {
+ alertProtectedImageLoadFailure(resolvedLocale, failure);
+ }),
+ [resolvedLocale]
+ );
const contentJsonRef = useRef<TiptapDoc>(markdownToDoc(""));
const contentMarkdownRef = useRef("");
const draftVersionRef = useRef(0);
@@ -1989,14 +2019,14 @@ const CreateMemoModal = ({
if (!client) {
return Promise.resolve(null);
}
- const cached = resourceDataUrlCacheRef.current.get(source);
- if (cached) {
- return cached;
- }
- const pending = client.getResourceBlob(source).then(blobToDataUrl).catch(() => null);
- resourceDataUrlCacheRef.current.set(source, pending);
- return pending;
- }, [client]);
+ return loadProtectedResourceDataUrl(source, {
+ baseUrl: session?.baseUrl ?? baseUrl,
+ cache: resourceDataUrlCacheRef.current,
+ getResourceBlob: client.getResourceBlob,
+ onFailure: imageLoadFailureNotifier,
+ token: session?.token,
+ });
+ }, [baseUrl, client, imageLoadFailureNotifier, session?.baseUrl, session?.token]);
const downloadResource = useCallback(async (target: MobileResourceTarget) => {
if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");
@@ -2334,7 +2364,7 @@ const RichEditorModal = ({
onClose: () => void;
updateMutation: MobileMemoUpdateMutation;
}) => {
- const { client } = useSession();
+ const { client, session } = useSession();
const { resolvedLocale } = useMobileLocale();
const { resolvedTheme } = useMobileTheme();
const restoredDraft = initialDraft?.expectedRevision === memo?.revision ? initialDraft : null;
@@ -2343,6 +2373,13 @@ const RichEditorModal = ({
: resolveMemoContentDoc(memo?.contentJson, memo?.contentMarkdown);
const editorRef = useRef<LocalTiptapEditorRef>(null);
const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());
+ const imageLoadFailureNotifier = useMemo(
+ () =>
+ createOnceProtectedResourceFailureNotifier((failure) => {
+ alertProtectedImageLoadFailure(resolvedLocale, failure);
+ }),
+ [memo?.id, resolvedLocale]
+ );
const initialFocusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const contentJsonRef = useRef<TiptapDoc>(initialContentJson);
const contentMarkdownRef = useRef(restoredDraft?.contentMarkdown ?? memo?.contentMarkdown ?? "");
@@ -2555,14 +2592,14 @@ const RichEditorModal = ({
if (!client) {
return Promise.resolve(null);
}
- const cached = resourceDataUrlCacheRef.current.get(source);
- if (cached) {
- return cached;
- }
- const pending = client.getResourceBlob(source).then(blobToDataUrl).catch(() => null);
- resourceDataUrlCacheRef.current.set(source, pending);
- return pending;
- }, [client]);
+ return loadProtectedResourceDataUrl(source, {
+ baseUrl: session?.baseUrl ?? baseUrl,
+ cache: resourceDataUrlCacheRef.current,
+ getResourceBlob: client.getResourceBlob,
+ onFailure: imageLoadFailureNotifier,
+ token: session?.token,
+ });
+ }, [baseUrl, client, imageLoadFailureNotifier, session?.baseUrl, session?.token]);
const downloadResource = useCallback(async (target: MobileResourceTarget) => {
if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");
@@ -3170,19 +3207,6 @@ const CreateMemoToolbarButton = ({
</Pressable>
);
-const blobToDataUrl = (blob: Blob) => new Promise<string>((resolve, reject) => {
- const reader = new FileReader();
- reader.onerror = () => reject(reader.error ?? new Error("资源读取失败"));
- reader.onloadend = () => {
- if (typeof reader.result === "string") {
- resolve(reader.result);
- return;
- }
- reject(new Error("资源读取失败"));
- };
- reader.readAsDataURL(blob);
-});
-
const createMobileImageUploadId = () =>
`${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;