Skip to content

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

feat: 增强公开笔记本站点体验与发布控制 (#634)

LuoQianhong9ae88e3381a0
diff --git a/apps/api/src/api-context.ts b/apps/api/src/api-context.ts
index 7b47e15b..f10dccac 100644
--- a/apps/api/src/api-context.ts
+++ b/apps/api/src/api-context.ts
@@ -39,6 +39,7 @@ export type Bindings = {
};
export type WorkerBindings = Omit<Bindings, "storage" | "publicNetworkFetch" | "deploymentVersionCreatedAt"> & CloudflareStorageBindings & {
+ ASSETS: Fetcher;
CF_VERSION_METADATA?: { timestamp?: string };
};
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 41072f69..74c1c62f 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -120,6 +120,7 @@ import {
} from "./user-routes";
import { registerNotebookRoutes } from "./notebook-routes";
import { registerNotebookShareRoutes, registerPublicNotebookShareRoutes } from "./notebook-share-routes";
+import { isNotebookSitePagePath, renderNotebookSitePage } from "./notebook-site-page";
import { registerMemoShareRoutes, registerPublicShareRoutes } from "./share-routes";
import { registerPublicTableFormRoutes, registerTableFormRoutes } from "./table-form-routes";
import {
@@ -454,6 +455,10 @@ export const fetchEdgeEverApp = async (
const worker = {
async fetch(request: Request, env: WorkerBindings, ctx: ExecutionContext) {
+ if (isNotebookSitePagePath(new URL(request.url).pathname)) {
+ return (await renderNotebookSitePage(request, createCloudflareStorageAdapter(env).db,
+ () => env.ASSETS.fetch(new Request(new URL("/", request.url), { method: "GET" }))))!;
+ }
return fetchEdgeEverApp(request, {
...env,
storage: createCloudflareStorageAdapter(env),
diff --git a/apps/api/src/notebook-share-routes.test.mjs b/apps/api/src/notebook-share-routes.test.mjs
index a3efbbef..66b880e1 100644
--- a/apps/api/src/notebook-share-routes.test.mjs
+++ b/apps/api/src/notebook-share-routes.test.mjs
@@ -9,6 +9,8 @@ import {
} from "./notebook-share-routes";
import { hashPassword } from "./auth-crypto";
import { registerPublicShareRoutes } from "./share-routes";
+import { renderNotebookSitePage } from "./notebook-site-page";
+import { PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
const databases = [];
afterEach(() => databases.splice(0).forEach((db) => db.close()));
@@ -78,6 +80,8 @@ const fixture = (legacyHash) => {
db.exec(readFileSync("migrations/0068_notebook_share_passwords.sql", "utf8"));
if (legacyHash) db.run("UPDATE notebook_shares SET password_hash = ?", [legacyHash]);
db.exec(readFileSync("migrations/0069_share_password_encryption.sql", "utf8"));
+ for (const file of migrations.filter((file) => file > "migrations/0069_share_password_encryption.sql"))
+ db.exec(readFileSync(file, "utf8"));
const environment = {
EDGE_EVER_CREDENTIALS_ENCRYPTION_KEY: "test-share-master-key",
storage: createSelfHostedStorageAdapter(
@@ -120,6 +124,244 @@ const fixture = (legacyHash) => {
return { db, app, environment, request, addMemo, blobReads: () => blobReads };
};
+const manage = (f, path, body, init = {}) => f.app.request(`/api/v1/notebooks/root/share${path}`, {
+ method: body === undefined ? "GET" : "PATCH",
+ ...(body === undefined ? {} : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),
+ ...init,
+}, f.environment);
+
+describe("public notebook site controls", () => {
+ test("old share upgrade preserves scope, token, and password while settings patch is independent", async () => {
+ const f = fixture(await hashPassword("old-password"));
+ const before = f.db.query("SELECT token, password_hash FROM notebook_shares").get();
+ const saved = await manage(f, "/site", { siteSlug: "My-Docs", settings: { footerText: "Example", sortMode: "title" } });
+ expect(saved.status).toBe(200);
+ expect((await saved.json()).share.siteSlug).toBe("my-docs");
+ await manage(f, "/site", { settings: { logoUrl: "https://example.org/logo.png" } });
+ const { share } = await (await manage(f, "")).json();
+ expect(share.siteSettings.footerText).toBe("Example");
+ expect(share.siteSettings.allowIndexing).toBe(false);
+ expect(f.db.query("SELECT token, password_hash FROM notebook_shares").get()).toEqual(before);
+ expect((await f.request()).status).toBe(403);
+ const unlocked = await f.request("/unlock", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password: "old-password" }) });
+ const cookie = unlocked.headers.get("set-cookie").split(";")[0];
+ const directory = await (await f.request("", { headers: { cookie } })).json();
+ expect(directory.share.memos).toHaveLength(3);
+ });
+
+ test("exclusion gates every read path, keeps independent shares, and restores idempotently", async () => {
+ const f = fixture();
+ const child = await f.app.request("/api/v1/notebooks/child/share", { method: "POST" }, f.environment);
+ const childToken = (await child.json()).share.token;
+ expect((await manage(f, "/memos/memo_child", { excluded: true })).status).toBe(200);
+ expect((await manage(f, "/memos/memo_child", { excluded: true })).status).toBe(200);
+ const directory = await (await f.request()).json();
+ expect(directory.share.memos.map((m) => m.id)).not.toContain("memo_child");
+ for (const path of ["/memos/memo_child", "/memos/memo_child/preview", "/resources/res_memo_child/blob"])
+ expect((await f.request(path)).status).toBe(404);
+ expect(f.blobReads()).toBe(0);
+ const search = await (await f.request("/search?q=memo&limit=1")).json();
+ expect(search.memos).toHaveLength(1);
+ expect(search.memos[0].id).not.toBe("memo_child");
+ expect((await f.app.request(`/api/public/notebook-shares/${childToken}/memos/memo_child`, {}, f.environment)).status).toBe(200);
+ const excluded = await (await manage(f, "/excluded-memos")).json();
+ expect(excluded.memos.map((m) => m.id)).toEqual(["memo_child"]);
+ f.db.run("UPDATE memos SET tags_json = '[\"draft\"]' WHERE id = 'memo_child'");
+ f.db.run("UPDATE memos SET notebook_id = 'private' WHERE id = 'memo_child'");
+ f.db.run("UPDATE memos SET notebook_id = 'child' WHERE id = 'memo_child'");
+ expect((await f.request("/memos/memo_child")).status).toBe(404);
+ await manage(f, "/memos/memo_child", { excluded: false });
+ await manage(f, "/memos/memo_child", { excluded: false });
+ expect((await f.request("/memos/memo_child")).status).toBe(200);
+ expect((await f.request("/memos/memo_child/preview")).status).toBe(200);
+ });
+
+ test("original-note controls list live ancestor sites with independent exclusions and no new shares", async () => {
+ const f = fixture();
+ await f.app.request("/api/v1/notebooks/child/share", { method: "POST" }, f.environment);
+ const sites = (id = "memo_child", init = {}) => f.app.request(`/api/v1/memos/${id}/notebook-sites`, init, f.environment);
+ const response = await sites();
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
+ expect((await response.json()).sites).toEqual([
+ { notebookId: "child", notebookName: "child", excluded: false },
+ { notebookId: "root", notebookName: "root", excluded: false },
+ ]);
+ await manage(f, "/memos/memo_child", { excluded: true });
+ expect((await (await sites()).json()).sites).toEqual([
+ { notebookId: "child", notebookName: "child", excluded: false },
+ { notebookId: "root", notebookName: "root", excluded: true },
+ ]);
+ expect((await f.request("/memos/memo_child")).status).toBe(404);
+ const childToken = f.db.query("SELECT token FROM notebook_shares WHERE notebook_id = 'child'").get().token;
+ expect((await f.app.request(`/api/public/notebook-shares/${childToken}/memos/memo_child`, {}, f.environment)).status).toBe(200);
+ expect((await (await sites("memo_grand")).json()).sites).toHaveLength(2);
+ expect(f.db.query("SELECT COUNT(*) AS count FROM memo_shares").get().count).toBe(1);
+ expect((await (await sites("memo_private")).json()).sites).toEqual([]);
+ f.db.run("UPDATE memos SET notebook_id = 'private' WHERE id = 'memo_child'");
+ f.db.run("UPDATE notebooks SET parent_id = 'foreign' WHERE id = 'private'");
+ expect((await (await sites()).json()).sites).toEqual([]);
+ f.db.run("UPDATE notebooks SET is_deleted = 1 WHERE id = 'child'");
+ expect((await (await sites("memo_grand")).json()).sites).toEqual([]);
+ for (const kind of ["none", "agent"])
+ expect((await sites("memo_grand", { headers: { "test-auth": kind } })).status).toBe(403);
+ for (const id of ["missing", "memo_other"])
+ expect((await sites(id)).status).toBe(404);
+ f.db.run("UPDATE memos SET is_deleted = 1 WHERE id = 'memo_grand'");
+ expect((await sites("memo_grand")).status).toBe(404);
+ });
+
+ test("owner content management filters before paging and reports exclusions beyond the first page", async () => {
+ const f = fixture();
+ for (let i = 0; i < 105; i++) f.addMemo(`bulk_${String(i).padStart(3, "0")}`, "child");
+ await manage(f, "/memos/bulk_075", { excluded: true });
+ await manage(f, "/memos/memo_child", { excluded: true });
+ const firstResponse = await manage(f, "/memos?limit=20");
+ expect(firstResponse.status).toBe(200);
+ const first = await firstResponse.json();
+ expect(first.memos).toHaveLength(20);
+ expect(first.nextCursor).toBe("bulk_019");
+ expect(first.memos.every((memo) => typeof memo.excluded === "boolean")).toBe(true);
+ expect(first.memos[0].contentJson).toBeUndefined();
+ const later = await (await manage(f, "/memos?limit=20&cursor=bulk_074")).json();
+ expect(later.memos[0]).toMatchObject({ id: "bulk_075", notebookId: "child", notebookName: "child", excluded: true });
+ const excluded = await (await manage(f, "/memos?visibility=excluded&limit=1")).json();
+ expect(excluded.memos.map((memo) => memo.id)).toEqual(["bulk_075"]);
+ const nextExcluded = await (await manage(f, `/memos?visibility=excluded&limit=1&cursor=${excluded.nextCursor}`)).json();
+ expect(nextExcluded.memos.map((memo) => memo.id)).toEqual(["memo_child"]);
+ expect(nextExcluded.nextCursor).toBeNull();
+ f.db.run("UPDATE memo_contents SET content_text = 'OwnerBodyNeedle 中文正文检索' WHERE memo_id = 'bulk_075'");
+ for (const q of ["OwnerBodyNeedle", "正文检索"]) {
+ const found = await (await manage(f, `/memos?q=${encodeURIComponent(q)}`)).json();
+ expect(found.memos.map((memo) => memo.id)).toEqual(["bulk_075"]);
+ const picker = await (await manage(f, `/memos?visibility=public&q=${encodeURIComponent(q)}`)).json();
+ expect(picker.memos).toHaveLength(0);
+ }
+ expect((await manage(f, "/memos?visibility=invalid")).status).toBe(400);
+ for (const kind of ["none", "agent"])
+ expect((await manage(f, "/memos", undefined, { headers: { "test-auth": kind } })).status).toBe(403);
+ expect((await f.app.request("/api/v1/notebooks/foreign/share/memos", {}, f.environment)).status).toBe(404);
+ f.db.run("UPDATE notebooks SET is_deleted = 1 WHERE id = 'root'");
+ expect((await manage(f, "/memos")).status).toBe(404);
+ });
+
+ test("body and Chinese search filter before paging and combine with exact tags", async () => {
+ const f = fixture();
+ for (const id of ["memo_root", "memo_child", "memo_grand"]) {
+ f.db.run("UPDATE memo_contents SET content_text = 'OnlyBodyWord 中文检索内容' WHERE memo_id = ?", [id]);
+ f.db.run("INSERT OR REPLACE INTO memo_search_documents (memo_id, title, content_text, tags) VALUES (?, ?, 'OnlyBodyWord 中文检索内容', '')", [id, id]);
+ }
+ f.db.run(`UPDATE memos SET tags_json = '["guide"]' WHERE id = 'memo_root'`);
+ await manage(f, "/memos/memo_child", { excluded: true });
+ for (const q of ["OnlyBodyWord", "检索"]) {
+ const result = await (await f.request(`/search?q=${encodeURIComponent(q)}&limit=1`)).json();
+ expect(result.memos).toHaveLength(1);
+ expect(result.memos[0].excerpt).toContain(q);
+ expect(result.nextCursor).not.toBeNull();
+ const page2 = await (await f.request(`/search?q=${encodeURIComponent(q)}&limit=1&cursor=${result.nextCursor}`)).json();
+ expect(page2.memos).toHaveLength(1);
+ expect(page2.memos[0].id).not.toBe(result.memos[0].id);
+ expect(page2.nextCursor).toBeNull();
+ }
+ const tagged = await (await f.request("/search?q=OnlyBodyWord&tag=guide")).json();
+ expect(tagged.memos.map((m) => m.id)).toEqual(["memo_root"]);
+ const longBody = "prefix ".repeat(90) + "Alpha different words Omega";
+ f.db.run("UPDATE memo_contents SET content_text = ? WHERE memo_id = 'memo_root'", [longBody]);
+ f.db.run("UPDATE memo_search_documents SET content_text = ? WHERE memo_id = 'memo_root'", [longBody]);
+ const multiword = await (await f.request("/search?q=Alpha%20Omega")).json();
+ expect(multiword.memos[0].excerpt).toContain("Alpha");
+ expect(multiword.memos[0].excerpt).toContain("Omega");
+ });
+
+ test("rejects invalid targets, unknown settings, non-HTTPS URLs and oversized merged settings", async () => {
+ const f = fixture();
+ for (const id of ["memo_private", "memo_other", "missing"])
+ expect((await manage(f, `/memos/${id}`, { excluded: true })).status).toBe(404);
+ for (const settings of [{ homeMemoId: "memo_private" }, { excludedTags: ["draft"] }, { logoUrl: "javascript:alert(1)" }, { logoUrl: "broken" }, { headerLinks: [{ label: "x", url: "broken" }] }, { headerLinks: [{ label: "x", url: "http://example.org" }] }, { footerText: "x".repeat(17_000) }])
+ expect((await manage(f, "/site", { settings })).status).toBe(400);
+ expect((await manage(f, "/site", { settings: { footerText: "ok" } }, { headers: { "content-type": "application/json", "test-auth": "agent" } })).status).toBe(403);
+ expect((await manage(f, "/site", { settings: { footerText: "ok" } }, { headers: { "content-type": "application/json", "test-auth": "none" } })).status).toBe(403);
+ });
+
+ test("homepages fall back on exclusion and aliases disclose identity only", async () => {
+ const f = fixture();
+ await manage(f, "/site", { siteSlug: "My-Docs", settings: { homeMemoId: "memo_child" } });
+ expect((await (await f.request()).json()).share.settings.homeMemoId).toBe("memo_child");
+ await manage(f, "/memos/memo_child", { excluded: true });
+ expect((await (await f.request()).json()).share.settings.homeMemoId).toBeNull();
+ expect((await manage(f, "/site", { settings: { homeMemoId: "memo_child" } })).status).toBe(400);
+ const alias = await f.app.request("/api/public/notebook-sites/my-docs/resolve", {}, f.environment);
+ expect(await alias.json()).toEqual({ token });
+ const child = await f.app.request("/api/v1/notebooks/child/share", { method: "POST" }, f.environment);
+ expect(child.status).toBe(200);
+ const collision = await f.app.request("/api/v1/notebooks/child/share/site", { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ siteSlug: "MY-DOCS" }) }, f.environment);
+ expect(collision.status).toBe(409);
+ await f.app.request("/api/v1/notebooks/root/share", { method: "DELETE" }, f.environment);
+ expect((await f.app.request("/api/public/notebook-sites/my-docs/resolve", {}, f.environment)).status).toBe(404);
+ expect(f.db.query("SELECT count(*) AS count FROM notebook_share_excluded_memos").get().count).toBe(0);
+ });
+
+ test("enabling or rotating passwords disables indexing and clearing does not re-enable it", async () => {
+ const f = fixture();
+ await manage(f, "/site", { settings: { allowIndexing: true } });
+ expect((await (await f.request()).json()).share.settings.allowIndexing).toBe(true);
+ await manage(f, "", { passwordProtected: true });
+ expect((await manage(f, "/site", { settings: { allowIndexing: true } })).status).toBe(400);
+ await manage(f, "", { passwordProtected: false });
+ expect((await (await f.request()).json()).share.settings.allowIndexing).toBe(false);
+ });
+
+ test("server HTML escapes metadata, preserves protected privacy, and denies excluded aliases", async () => {
+ const f = fixture();
+ f.db.run("UPDATE memos SET title = ?, excerpt = ? WHERE id = 'memo_child'", ["<script>secret()</script> $& $' $$", 'A & B "quote"']);
+ await manage(f, "/site", { siteSlug: "docs", settings: { allowIndexing: true, homeMemoId: "memo_child" } });
+ const render = (path) => renderNotebookSitePage(new Request(`https://example.org${path}`), f.environment.storage.db,
+ async () => new Response('<html><head><title>Old</title><meta name="description" content="old"></head><body><div id="root"></div></body></html>', { headers: { "content-type": "text/html" } }));
+ const visible = await render("/s/docs/memo_child");
+ expect(visible.status).toBe(200);
+ expect(visible.headers.get("X-Robots-Tag")).toBe("index, follow");
+ const html = await visible.text();
+ expect(html).toContain("&lt;script&gt;secret()&lt;/script&gt;");
+ expect(html).toContain("&lt;script&gt;secret()&lt;/script&gt; $&amp; $&#39; $$");
+ expect(html).not.toContain("<script>secret()");
+ expect(html).toContain('rel="canonical" href="https://example.org/s/docs/memo_child"');
+ expect(html).toContain('property="og:description" content="A &amp; B &quot;quote&quot;"');
+ for (const suffix of ["", "/memo_child"]) {
+ const tokenPage = await render(`/share/notebook/${token}${suffix}`);
+ expect(tokenPage.status).toBe(200);
+ expect(tokenPage.headers.get("X-Robots-Tag")).toBe(PUBLIC_PAGE_ROBOTS);
+ const tokenHtml = await tokenPage.text();
+ expect(tokenHtml).toContain(`<meta name="robots" content="${PUBLIC_PAGE_ROBOTS}">`);
+ expect(tokenHtml).toContain(`rel="canonical" href="https://example.org/s/docs${suffix}"`);
+ }
+ await manage(f, "/memos/memo_child", { excluded: true });
+ const hidden = await render("/s/docs/memo_child");
+ expect(hidden.status).toBe(404);
+ expect(hidden.headers.get("X-Robots-Tag")).toBe(PUBLIC_PAGE_ROBOTS);
+ expect(await hidden.text()).not.toContain("secret()");
+ await manage(f, "", { passwordProtected: true });
+ const protectedPage = await render("/s/docs");
+ expect(protectedPage.headers.get("X-Robots-Tag")).toBe(PUBLIC_PAGE_ROBOTS);
+ expect(await protectedPage.text()).not.toContain("secret()");
+ expect(await render("/share/individual-token")).toBeNull();
+ });
+
+ test("Token pages without an alias remain noindex after opting in", async () => {
+ const f = fixture();
+ await manage(f, "/site", { settings: { allowIndexing: true } });
+ for (const suffix of ["", "/memo_child"]) {
+ const url = `https://example.org/share/notebook/${token}${suffix}`;
+ const response = await renderNotebookSitePage(new Request(url), f.environment.storage.db,
+ async () => new Response("<html><head></head><body></body></html>"));
+ expect(response.status).toBe(200);
+ expect(response.headers.get("X-Robots-Tag")).toBe(PUBLIC_PAGE_ROBOTS);
+ const html = await response.text();
+ expect(html).toContain(`<meta name="robots" content="${PUBLIC_PAGE_ROBOTS}">`);
+ expect(html).toContain(`rel="canonical" href="${url}"`);
+ }
+ });
+});
+
describe("live recursive notebook sharing", () => {
test("upgrades existing data without creating individual shares; exposes only the live workspace subtree", async () => {
const { db, request } = fixture();
diff --git a/apps/api/src/notebook-share-routes.ts b/apps/api/src/notebook-share-routes.ts
index 83f28807..c6e1feb8 100644
--- a/apps/api/src/notebook-share-routes.ts
+++ b/apps/api/src/notebook-share-routes.ts
@@ -1,5 +1,13 @@
import {
NotebookShareUpdateSchema,
+ NotebookSiteUpdateSchema,
+ NotebookSiteExclusionSchema,
+ readNotebookSiteSettings,
+ compareNotebookSiteTitles,
+ type NotebookSiteMemoPreview,
+ type NotebookSiteSearchResult,
+ type NotebookSiteContents,
+ type MemoNotebookSite,
PublicShareUnlockSchema,
collectMemoLinkIds,
accountNoteProseFromRow,
@@ -26,19 +34,13 @@ import { allowPasswordProtectedShare, setShareAccessCookie } from "./share-http-
import { isShareUnlockBlocked, nextShareUnlockFailure, type ShareUnlockState } from "./share-access";
import { encryptSharePassword, readSharePassword } from "./share-password-encryption";
import { generateSharePassword } from "./share-password";
-
-// Every public query starts at the live share, and constrains every level to
-// its workspace. Deleted ancestors stop traversal; UNION also tolerates cycles.
-const publicTreeSql = `WITH RECURSIVE tree(id, workspace_id) AS (
- SELECT n.id, n.workspace_id FROM notebook_shares ns
- JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
- WHERE ns.token = ? AND n.is_deleted = 0
- UNION
- SELECT n.id, n.workspace_id FROM notebooks n JOIN tree t ON n.parent_id = t.id
- WHERE n.workspace_id = t.workspace_id AND n.is_deleted = 0
-)`;
+import { publicTreeSql, getNotebookSite, resolveNotebookSiteToken } from "./notebook-site-service";
+import { toFtsQuery, escapeLike } from "./memo-list-service";
type ShareRow = {
+ id: string;
+ site_slug: string | null;
+ site_settings_json: string;
password_hash: string | null;
password_encrypted: string | null;
notebook_id: string;
@@ -48,6 +50,8 @@ type ShareRow = {
updated_at: string;
};
const mapShare = (row: ShareRow, password?: string): NotebookShare => ({
+ siteSlug: row.site_slug,
+ siteSettings: readNotebookSiteSettings(row.site_settings_json),
passwordProtected: Boolean(row.password_hash),
...(password ? { password } : {}),
notebookId: row.notebook_id,
@@ -56,12 +60,144 @@ const mapShare = (row: ShareRow, password?: string): NotebookShare => ({
createdAt: row.created_at,
updatedAt: row.updated_at,
});
-const selectShareSql = `SELECT ns.notebook_id, n.name AS notebook_name, ns.password_encrypted, ns.password_hash, ns.token, ns.created_at, ns.updated_at
+const selectShareSql = `SELECT ns.id, ns.site_slug, ns.site_settings_json, ns.notebook_id, n.name AS notebook_name, ns.password_encrypted, ns.password_hash, ns.token, ns.created_at, ns.updated_at
FROM notebook_shares ns JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
WHERE ns.workspace_id = ? AND n.is_deleted = 0`;
const validToken = (token: string) => /^[A-Za-z0-9_-]{43}$/.test(token);
+const pageSize = (value?: string) => Math.max(1, Math.min(100, Math.floor(Number(value) || 50)));
export const registerNotebookShareRoutes = (app: Hono<AppEnv>) => {
+ app.get("/api/v1/memos/:id/notebook-sites", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const db = c.env.storage.db;
+ const memoId = c.req.param("id");
+ const workspaceId = getWorkspaceId(c);
+ const memo = await db.prepare("SELECT notebook_id FROM memos WHERE id = ? AND workspace_id = ? AND is_deleted = 0")
+ .bind(memoId, workspaceId).first<{ notebook_id: string | null }>();
+ if (!memo) return notFound(c, "Memo not found");
+ const rows = await db.prepare(`WITH RECURSIVE ancestors(id, parent_id, workspace_id, name) AS (
+ SELECT id, parent_id, workspace_id, name FROM notebooks WHERE id = ? AND workspace_id = ? AND is_deleted = 0
+ UNION
+ SELECT n.id, n.parent_id, n.workspace_id, n.name FROM notebooks n JOIN ancestors a
+ ON n.id = a.parent_id AND n.workspace_id = a.workspace_id WHERE n.is_deleted = 0
+ )
+ SELECT n.id AS notebookId, n.name AS notebookName,
+ EXISTS (SELECT 1 FROM notebook_share_excluded_memos e WHERE e.share_id = ns.id AND e.memo_id = ?) AS excluded
+ FROM ancestors n JOIN notebook_shares ns ON ns.notebook_id = n.id AND ns.workspace_id = n.workspace_id
+ ORDER BY n.id`).bind(memo.notebook_id, workspaceId, memoId)
+ .all<Omit<MemoNotebookSite, "excluded"> & { excluded: number }>();
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ sites: rows.results.map((site) => ({ ...site, excluded: Boolean(site.excluded) })) });
+ });
+ app.get("/api/v1/notebooks/:id/share/memos", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const db = c.env.storage.db;
+ const share = await db.prepare(`${selectShareSql} AND ns.notebook_id = ?`)
+ .bind(getWorkspaceId(c), c.req.param("id")).first<ShareRow>();
+ if (!share) return notFound(c, "Active share not found");
+ const visibility = c.req.query("visibility") ?? "all";
+ if (!["all", "public", "excluded"].includes(visibility))
+ return apiError(c, "invalid_site_visibility", "Unknown content visibility filter", 400);
+ const limit = pageSize(c.req.query("limit"));
+ const query = c.req.query("q")?.trim() ?? "";
+ const excludedSql = "EXISTS (SELECT 1 FROM notebook_share_excluded_memos e WHERE e.share_id = t.share_id AND e.memo_id = m.id)";
+ const conditions = ["m.is_deleted = 0", "m.id > ?"];
+ const binds: unknown[] = [share.token, c.req.query("cursor") ?? ""];
+ if (visibility !== "all") conditions.push(`${visibility === "public" ? "NOT " : ""}${excludedSql}`);
+ if (query) {
+ const fts = toFtsQuery(query);
+ const like = `%${escapeLike(query)}%`;
+ conditions.push(`(m.title LIKE ? ESCAPE '\\' OR mc.content_text LIKE ? ESCAPE '\\' OR mc.content_markdown LIKE ? ESCAPE '\\'${fts ? " OR m.id IN (SELECT memo_id FROM memos_fts WHERE memos_fts MATCH ?)" : ""})`);
+ binds.push(like, like, like, ...(fts ? [fts] : []));
+ }
+ const rows = await db.prepare(`${publicTreeSql}
+ SELECT m.id, m.title, m.notebook_id AS notebookId, n.name AS notebookName, ${excludedSql} AS excluded
+ FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ JOIN notebooks n ON n.id = m.notebook_id
+ ${query ? "LEFT JOIN memo_contents mc ON mc.memo_id = m.id" : ""}
+ WHERE ${conditions.join(" AND ")} ORDER BY m.id LIMIT ?`)
+ .bind(...binds, limit + 1).all<Omit<NotebookSiteContents["memos"][number], "excluded"> & { excluded: number }>();
+ const memos = rows.results.slice(0, limit).map((memo) => ({ ...memo, excluded: Boolean(memo.excluded) }));
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ memos, nextCursor: rows.results.length > limit ? memos.at(-1)!.id : null } satisfies NotebookSiteContents);
+ });
+ app.patch("/api/v1/notebooks/:id/share/site", zValidator("json", NotebookSiteUpdateSchema), async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const db = c.env.storage.db;
+ const existing = await db.prepare(`${selectShareSql} AND ns.notebook_id = ?`)
+ .bind(getWorkspaceId(c), c.req.param("id")).first<ShareRow>();
+ if (!existing) return notFound(c, "Active share not found");
+ const input = c.req.valid("json");
+ const settings = { ...readNotebookSiteSettings(existing.site_settings_json), ...input.settings };
+ if (new TextEncoder().encode(JSON.stringify(settings)).length > 16 * 1024)
+ return apiError(c, "invalid_site_settings", "Site settings exceed 16 KiB", 400);
+ if (input.settings?.allowIndexing && existing.password_hash)
+ return apiError(c, "invalid_site_settings", "Password-protected sites cannot enable indexing", 400);
+ if (input.settings?.homeMemoId && !await db.prepare(`${publicTreeSql} SELECT id FROM visible_memos WHERE id = ?`)
+ .bind(existing.token, input.settings.homeMemoId).first())
+ return apiError(c, "invalid_site_homepage", "Homepage must be a visible note in this site", 400);
+ const patch = JSON.stringify(input.settings ?? {});
+ try {
+ const updated = await db.prepare(`UPDATE notebook_shares SET
+ site_slug = CASE WHEN ? THEN ? ELSE site_slug END,
+ site_settings_json = json_patch(site_settings_json, ?), updated_at = ?
+ WHERE id = ? AND workspace_id = ?
+ AND length(CAST(json_patch(site_settings_json, ?) AS BLOB)) <= 16384
+ AND (? = 0 OR password_hash IS NULL) RETURNING id`)
+ .bind(input.siteSlug !== undefined ? 1 : 0, input.siteSlug || null, patch, isoNow(), existing.id,
+ getWorkspaceId(c), patch, input.settings?.allowIndexing ? 1 : 0).first();
+ if (!updated) return apiError(c, "invalid_site_settings", "Settings could not be saved; refresh and try again", 400);
+ } catch (error) {
+ if (String(error).includes("UNIQUE constraint failed"))
+ return apiError(c, "site_slug_conflict", "This site alias is already in use", 409);
+ throw error;
+ }
+ const row = await db.prepare(`${selectShareSql} AND ns.notebook_id = ?`)
+ .bind(getWorkspaceId(c), c.req.param("id")).first<ShareRow>();
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ share: row ? mapShare(row, row.password_hash ? await readSharePassword(row.password_encrypted, row.token, c.env, row.password_hash) : undefined) : null });
+ });
+ app.get("/api/v1/notebooks/:id/share/excluded-memos", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const limit = pageSize(c.req.query("limit"));
+ const rows = await c.env.storage.db.prepare(`SELECT m.id, m.title FROM notebook_share_excluded_memos e
+ JOIN notebook_shares ns ON ns.id = e.share_id
+ JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ JOIN memos m ON m.id = e.memo_id AND m.workspace_id = ns.workspace_id
+ WHERE ns.workspace_id = ? AND ns.notebook_id = ? AND n.is_deleted = 0 AND m.is_deleted = 0
+ AND m.id > ? ORDER BY m.id LIMIT ?`)
+ .bind(getWorkspaceId(c), c.req.param("id"), c.req.query("cursor") ?? "", limit + 1)
+ .all<{ id: string; title: string | null }>();
+ const memos = rows.results.slice(0, limit);
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ memos, nextCursor: rows.results.length > limit ? memos.at(-1)!.id : null });
+ });
+ app.patch("/api/v1/notebooks/:id/share/memos/:memoId", zValidator("json", NotebookSiteExclusionSchema), async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const db = c.env.storage.db;
+ const share = await db.prepare(`${selectShareSql} AND ns.notebook_id = ?`)
+ .bind(getWorkspaceId(c), c.req.param("id")).first<ShareRow>();
+ if (!share) return notFound(c, "Active share not found");
+ const memoId = c.req.param("memoId");
+ const { excluded } = c.req.valid("json");
+ if (excluded) {
+ // The tree query deliberately ignores exclusions when selecting a target.
+ const target = await db.prepare(`${publicTreeSql} SELECT m.id FROM memos m JOIN tree t
+ ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id WHERE m.id = ? AND m.is_deleted = 0`)
+ .bind(share.token, memoId).first();
+ if (!target) return notFound(c, "Note not found in this notebook share");
+ await db.prepare("INSERT OR IGNORE INTO notebook_share_excluded_memos (share_id, memo_id) VALUES (?, ?)").bind(share.id, memoId).run();
+ } else {
+ await db.prepare("DELETE FROM notebook_share_excluded_memos WHERE share_id = ? AND memo_id = ?").bind(share.id, memoId).run();
+ }
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ memoId, excluded });
+ });
app.get("/api/v1/notebook-shares", async (c) => {
const denied = requireUser(c);
if (denied) return denied;
@@ -142,14 +278,15 @@ export const registerNotebookShareRoutes = (app: Hono<AppEnv>) => {
const encrypted = password ? await encryptSharePassword(password, existing.token, c.env) : null;
const now = isoNow();
await c.env.storage.db.prepare(`UPDATE notebook_shares SET password_hash = ?, password_encrypted = ?, unlock_failed_count = 0,
- unlock_window_started_at = NULL, unlock_blocked_until = NULL, updated_at = ?
- WHERE notebook_id = ? AND workspace_id = ?`).bind(passwordHash, encrypted, now, notebookId, workspaceId).run();
+ unlock_window_started_at = NULL, unlock_blocked_until = NULL,
+ site_settings_json = CASE WHEN ? IS NOT NULL THEN json_set(site_settings_json, '$.allowIndexing', json('false')) ELSE site_settings_json END, updated_at = ?
+ WHERE notebook_id = ? AND workspace_id = ?`).bind(passwordHash, encrypted, passwordHash, now, notebookId, workspaceId).run();
const actor = getAuditActor(c);
await audit(c.env.storage.db, actor.actorType, actor.actorId,
password ? (existing.password_hash ? "notebook.share_password_rotate" : "notebook.share_password_set") : "notebook.share_password_clear",
"notebook", notebookId, {});
c.header("Cache-Control", "private, no-store");
- return c.json({ share: mapShare({ ...existing, password_hash: passwordHash, updated_at: now }, password) });
+ return c.json({ share: mapShare({ ...existing, password_hash: passwordHash, site_settings_json: passwordHash ? JSON.stringify({ ...readNotebookSiteSettings(existing.site_settings_json), allowIndexing: false }) : existing.site_settings_json, updated_at: now }, password) });
});
app.delete("/api/v1/notebooks/:id/share", async (c) => {
const denied = requireUser(c);
@@ -175,6 +312,12 @@ export const registerNotebookShareRoutes = (app: Hono<AppEnv>) => {
};
export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
+ app.get("/api/public/notebook-sites/:slug/resolve", async (c) => {
+ c.header("Cache-Control", "private, no-store");
+ c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
+ const identity = await resolveNotebookSiteToken(c.env.storage.db, c.req.param("slug"));
+ return identity ? c.json(identity) : notFound(c, "Shared notebook not found");
+ });
app.use("/api/public/notebook-shares/*", async (c, next) => {
c.header("Cache-Control", "private, no-store");
c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
@@ -211,17 +354,49 @@ export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
await setShareAccessCookie(c, token, gate.password_hash, `/api/public/notebook-shares/${token}`);
return c.json({ ok: true });
});
+ app.get("/api/public/notebook-shares/:token/search", async (c) => {
+ const token = c.req.param("token");
+ const query = c.req.query("q")?.trim() ?? "";
+ const tag = c.req.query("tag")?.trim() ?? "";
+ const limit = pageSize(c.req.query("limit"));
+ const cursor = c.req.query("cursor") ?? "0";
+ const offset = /^\d+$/.test(cursor) && Number.isSafeInteger(Number(cursor)) ? Number(cursor) : 0;
+ const fts = toFtsQuery(query);
+ const like = `%${escapeLike(query)}%`;
+ const terms = query ? [...new Set([query, ...(query.match(/[\p{L}\p{N}_]+/gu) ?? []).slice(0, 8)])] : [];
+ const bodySql = "COALESCE(NULLIF(mc.content_text, ''), mc.content_markdown, '')";
+ const positions = terms.map(() => `coalesce(nullif(instr(lower(${bodySql}), lower(?)), 0), 2147483647)`);
+ const position = positions.length > 1 ? `min(${positions.join(",")})` : positions[0] ?? "1";
+ const conditions: string[] = [];
+ const binds: unknown[] = [token];
+ if (query) {
+ conditions.push(`(m.title LIKE ? ESCAPE '\\' OR mc.content_text LIKE ? ESCAPE '\\' OR mc.content_markdown LIKE ? ESCAPE '\\'${fts ? " OR m.id IN (SELECT memo_id FROM memos_fts WHERE memos_fts MATCH ?)" : ""})`);
+ binds.push(like, like, like, ...(fts ? [fts] : []));
+ }
+ if (tag) {
+ conditions.push("EXISTS (SELECT 1 FROM memo_tags mt WHERE mt.memo_id = m.id AND mt.workspace_id = m.workspace_id AND mt.normalized_name = lower(?))");
+ binds.push(tag);
+ }
+ const rows = await c.env.storage.db.prepare(`${publicTreeSql}
+ SELECT m.id, m.notebook_id AS notebookId, m.title, m.excerpt,
+ substr(${bodySql}, max(1, ${position} - 60), 240) AS snippet
+ FROM visible_memos m LEFT JOIN memo_contents mc ON mc.memo_id = m.id
+ ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""}
+ ORDER BY m.updated_at DESC, m.id LIMIT ? OFFSET ?`)
+ .bind(token, ...terms, ...binds.slice(1), limit + 1, offset)
+ .all<NotebookSiteSearchResult["memos"][number] & { snippet: string }>();
+ const memos = rows.results.slice(0, limit).map(({ snippet, ...row }) => ({ ...row, excerpt: snippet || row.excerpt || "", highlights: query ? [query, ...(query.match(/[\p{L}\p{N}_]+/gu) ?? [])] : [] }));
+ return c.json({ memos, nextCursor: rows.results.length > limit ? String(offset + limit) : null } satisfies NotebookSiteSearchResult);
+ });
+ app.get("/api/public/notebook-shares/:token/memos/:memoId/preview", async (c) => {
+ const row = await c.env.storage.db.prepare(`${publicTreeSql} SELECT id, title, excerpt FROM visible_memos WHERE id = ?`)
+ .bind(c.req.param("token"), c.req.param("memoId")).first<NotebookSiteMemoPreview>();
+ return row ? c.json({ memo: row }) : notFound(c, "Shared note not found");
+ });
app.get("/api/public/notebook-shares/:token", async (c) => {
const token = c.req.param("token");
if (!validToken(token)) return notFound(c, "Shared notebook not found");
- const root = await c.env.storage.db
- .prepare(
- `SELECT n.id, n.name FROM notebook_shares ns
- JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
- WHERE ns.token = ? AND n.is_deleted = 0`,
- )
- .bind(token)
- .first<{ id: string; name: string }>();
+ const root = await getNotebookSite(c.env.storage.db, token);
if (!root) return notFound(c, "Shared notebook not found");
const notebooks = await c.env.storage.db
.prepare(
@@ -236,17 +411,23 @@ export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
const memos = await c.env.storage.db
.prepare(
`${publicTreeSql}
- SELECT m.id, m.notebook_id AS notebookId, m.title FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ SELECT m.id, m.notebook_id AS notebookId, m.title FROM visible_memos m
WHERE m.is_deleted = 0 ORDER BY m.is_pinned DESC, m.updated_at DESC, m.id`,
)
.bind(token)
.all<PublicNotebookShare["memos"][number]>();
+ if (root.settings.sortMode === "title") {
+ notebooks.results.sort(compareNotebookSiteTitles);
+ memos.results.sort(compareNotebookSiteTitles);
+ }
const share: PublicNotebookShare = {
- notebookId: root.id,
+ notebookId: root.notebook_id,
+ siteSlug: root.site_slug,
+ settings: root.settings,
name: root.name,
notebooks: notebooks.results.map((n) => ({
...n,
- parentId: n.id === root.id ? null : n.parentId,
+ parentId: n.id === root.notebook_id ? null : n.parentId,
})),
memos: memos.results,
};
@@ -260,7 +441,7 @@ export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
`${publicTreeSql}
SELECT m.title, mc.content_json, mc.content_markdown, m.tags_json, m.updated_at, u.note_body_font,
u.note_prose_font_size, u.note_prose_line_height, u.note_prose_palette, u.note_prose_custom_css, u.note_prose_custom_colors
- FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ FROM visible_memos m
JOIN memo_contents mc ON mc.memo_id = m.id
JOIN notebook_shares ns ON ns.token = ?
LEFT JOIN users u ON u.id = ns.created_by
@@ -288,7 +469,7 @@ export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
const linked = await c.env.storage.db
.prepare(
`${publicTreeSql}
- SELECT m.id FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ SELECT m.id FROM visible_memos m
WHERE m.is_deleted = 0 AND m.id IN (${batch.map(() => "?").join(",")})`,
)
.bind(token, ...batch)
@@ -327,7 +508,7 @@ export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
SELECT r.object_key, r.storage_config_id, r.kind, r.mime_type, r.filename, r.byte_size,
m.workspace_id, NULL AS password_hash
FROM resources r JOIN memos m ON r.memo_id = m.id
- JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ JOIN visible_memos visible ON visible.id = m.id
WHERE r.id = ? AND r.is_deleted = 0 AND m.is_deleted = 0`,
)
.bind(token, c.req.param("resourceId"))
diff --git a/apps/api/src/notebook-site-page.ts b/apps/api/src/notebook-site-page.ts
new file mode 100644
index 00000000..8458a1ba
--- /dev/null
+++ b/apps/api/src/notebook-site-page.ts
@@ -0,0 +1,74 @@
+import { PUBLIC_PAGE_HEADERS, PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
+import type { DatabaseAdapter } from "./storage-contract";
+import { getNotebookSite, publicTreeSql, resolveNotebookSiteToken } from "./notebook-site-service";
+
+export const isNotebookSitePagePath = (path: string) => /^\/(?:share\/notebook|s)\/[^/]+(?:\/[^/]+)?\/?$/.test(path);
+const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]!);
+
+/** Shared business logic; runtime adapters supply only their app-shell loader. */
+export const renderNotebookSitePage = async (
+ request: Request,
+ db: DatabaseAdapter,
+ loadTemplate: () => Promise<Response>,
+): Promise<Response | null> => {
+ const url = new URL(request.url);
+ if (!isNotebookSitePagePath(url.pathname)) return null;
+ const alias = url.pathname.startsWith("/s/");
+ const parts = url.pathname.split("/");
+ const identity = parts[alias ? 2 : 3];
+ const memoId = parts[alias ? 3 : 4];
+ const resolved = alias ? await resolveNotebookSiteToken(db, identity) : { token: identity };
+ const site = resolved ? await getNotebookSite(db, resolved.token) : null;
+ let status = site ? 200 : 404;
+ let title = "Shared notebook · EdgeEver";
+ let description = "Read a shared notebook on EdgeEver.";
+ let indexable = false;
+ let canonical = `${url.origin}${url.pathname}`;
+ let image = new URL("/apple-touch-icon.png", url).href;
+ if (site && !site.password_hash) {
+ const selected = memoId || site.settings.homeMemoId;
+ const note = selected ? await db.prepare(`${publicTreeSql} SELECT title, excerpt FROM visible_memos WHERE id = ?`)
+ .bind(site.token, selected).first<{ title: string | null; excerpt: string }>() : null;
+ if (memoId && !note) status = 404;
+ if (status === 200) {
+ title = `${note?.title?.trim() || site.name} · EdgeEver`;
+ description = note?.excerpt || site.name;
+ indexable = alias && site.settings.allowIndexing;
+ const base = site.site_slug ? `/s/${encodeURIComponent(site.site_slug)}` : `/share/notebook/${encodeURIComponent(site.token)}`;
+ canonical = `${url.origin}${base}${memoId ? `/${encodeURIComponent(memoId)}` : ""}`;
+ image = site.settings.logoUrl || image;
+ }
+ }
+ const robots = indexable ? "index, follow" : PUBLIC_PAGE_ROBOTS;
+ const metadata = `<title>${escapeHtml(title)}</title>
+<meta name="description" content="${escapeHtml(description)}">
+<meta name="robots" content="${robots}">
+<link rel="canonical" href="${escapeHtml(canonical)}">
+<meta property="og:type" content="${memoId ? "article" : "website"}">
+<meta property="og:title" content="${escapeHtml(title)}">
+<meta property="og:description" content="${escapeHtml(description)}">
+<meta property="og:url" content="${escapeHtml(canonical)}">
+<meta property="og:image" content="${escapeHtml(image)}">
+<meta name="twitter:card" content="summary">
+<meta name="twitter:title" content="${escapeHtml(title)}">
+<meta name="twitter:description" content="${escapeHtml(description)}">
+<meta name="twitter:image" content="${escapeHtml(image)}">`;
+ const template = await loadTemplate();
+ if (!template.ok) return template;
+ const html = (await template.text())
+ .replace(/<title\b[^>]*>[\s\S]*?<\/title>/gi, "")
+ .replace(/<meta\b[^>]*(?:name|property)=["'](?:description|robots|og:[^"']+|twitter:[^"']+)["'][^>]*>/gi, "")
+ .replace(/<link\b[^>]*rel=["']canonical["'][^>]*>/gi, "")
+ .replace(/<\/head>/i, () => `${metadata}</head>`);
+ const headers = new Headers(template.headers);
+ headers.delete("Content-Length");
+ headers.delete("ETag");
+ headers.delete("Content-Encoding");
+ headers.delete("Last-Modified");
+ headers.delete("Age");
+ headers.delete("CF-Cache-Status");
+ for (const [key, value] of Object.entries(PUBLIC_PAGE_HEADERS)) headers.set(key, value);
+ headers.set("Content-Type", "text/html; charset=utf-8");
+ headers.set("X-Robots-Tag", robots);
+ return new Response(request.method === "HEAD" ? null : html, { status, headers });
+};
diff --git a/apps/api/src/notebook-site-service.ts b/apps/api/src/notebook-site-service.ts
new file mode 100644
index 00000000..458d16d1
--- /dev/null
+++ b/apps/api/src/notebook-site-service.ts
@@ -0,0 +1,39 @@
+import { readNotebookSiteSettings, type NotebookSiteSettings } from "@edgeever/shared";
+import type { DatabaseAdapter } from "./storage-contract";
+
+// Every consumer starts at the live share. Deleted ancestors and inconsistent
+// workspace references stop recursion; exclusions are scoped to that share.
+export const publicTreeSql = `WITH RECURSIVE tree(id, workspace_id, share_id) AS (
+ SELECT n.id, n.workspace_id, ns.id FROM notebook_shares ns
+ JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ WHERE ns.token = ? AND n.is_deleted = 0
+ UNION
+ SELECT n.id, n.workspace_id, t.share_id FROM notebooks n JOIN tree t ON n.parent_id = t.id
+ WHERE n.workspace_id = t.workspace_id AND n.is_deleted = 0
+), visible_memos AS (
+ SELECT m.* FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ WHERE m.is_deleted = 0 AND NOT EXISTS (
+ SELECT 1 FROM notebook_share_excluded_memos e WHERE e.share_id = t.share_id AND e.memo_id = m.id
+ )
+)`;
+
+export const getNotebookSite = async (db: DatabaseAdapter, token: string) => {
+ const row = await db.prepare(`SELECT ns.id, ns.token, ns.site_slug, ns.site_settings_json, ns.password_hash,
+ n.id AS notebook_id, n.name FROM notebook_shares ns
+ JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ WHERE ns.token = ? AND n.is_deleted = 0`).bind(token).first<{
+ id: string; token: string; site_slug: string | null; site_settings_json: string;
+ password_hash: string | null; notebook_id: string; name: string;
+ }>();
+ if (!row) return null;
+ const settings: NotebookSiteSettings = readNotebookSiteSettings(row.site_settings_json);
+ settings.allowIndexing = settings.allowIndexing && !row.password_hash;
+ if (settings.homeMemoId && !await db.prepare(`${publicTreeSql} SELECT id FROM visible_memos WHERE id = ?`)
+ .bind(token, settings.homeMemoId).first()) settings.homeMemoId = null;
+ return { ...row, settings };
+};
+
+export const resolveNotebookSiteToken = async (db: DatabaseAdapter, slug: string) =>
+ db.prepare(`SELECT ns.token FROM notebook_shares ns JOIN notebooks n
+ ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ WHERE lower(ns.site_slug) = lower(?) AND n.is_deleted = 0`).bind(slug).first<{ token: string }>();
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 43a63380..aa0b4686 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -29,6 +29,7 @@ const WorkspaceApp = lazy(() => import("@/components/WorkspaceApp").then((module
const PublicNotebookSharePage = lazy(() => import("@/components/PublicNotebookSharePage").then(module => ({ default: module.PublicNotebookSharePage })));
const PublicSharePage = lazy(() => import("@/components/PublicSharePage").then((module) => ({ default: module.PublicSharePage })));
const PublicTableFormPage = lazy(() => import("@/components/PublicTableFormPage").then((module) => ({ default: module.PublicTableFormPage })));
+const NotebookSiteManagementPage = lazy(() => import("@/components/NotebookSiteManagementPage").then((module) => ({ default: module.NotebookSiteManagementPage })));
const AuthLoadingScreen = ({ title = "EdgeEver", detail }: { title?: string; detail?: string }) => (
<div className="flex h-[100dvh] items-center justify-center bg-slate-50 px-6 text-center text-slate-700">
@@ -58,7 +59,7 @@ const EvernoteMigrationRoute = () => {
);
};
-const AuthenticatedWorkspace = () => {
+const AuthenticatedWorkspace = ({ siteManagement = false }: { siteManagement?: boolean }) => {
const queryClient = useQueryClient();
const { t, i18n } = useTranslation();
const desktopBridge = window.edgeeverDesktop;
@@ -211,13 +212,13 @@ const AuthenticatedWorkspace = () => {
return (
<Suspense fallback={<AuthLoadingScreen />}>
- <WorkspaceApp
+ {siteManagement ? <NotebookSiteManagementPage /> : <WorkspaceApp
authRequired={session.authRequired}
demoMode={session.demoMode}
isLoggingOut={logoutMutation.isPending}
user={session.user}
onLogout={() => logoutMutation.mutate()}
- />
+ />}
</Suspense>
);
};
@@ -234,11 +235,13 @@ export const App = () => {
<PwaInstallProvider>
<Routes>
<Route path="/share/notebook/:token/:memoId?" element={<Suspense fallback={<AuthLoadingScreen />}><PublicNotebookSharePage /></Suspense>} />
+ <Route path="/s/:slug/:memoId?" element={<Suspense fallback={<AuthLoadingScreen />}><PublicNotebookSharePage /></Suspense>} />
<Route path="/share/:token" element={<Suspense fallback={<AuthLoadingScreen />}><PublicSharePage /></Suspense>} />
<Route path="/form/:token" element={<Suspense fallback={<AuthLoadingScreen />}><PublicTableFormPage /></Suspense>} />
<Route path={EVERNOTE_MIGRATION_PATH} element={<EvernoteMigrationRoute />} />
<Route path="/" element={<AuthenticatedWorkspace />} />
<Route path="/settings" element={<AuthenticatedWorkspace />} />
+ <Route path="/notebooks/:notebookId/site" element={<AuthenticatedWorkspace siteManagement />} />
<Route path="/plugins" element={<AuthenticatedWorkspace />} />
<Route path="/plugins/:pluginId" element={<AuthenticatedWorkspace />} />
<Route path="/templates" element={<AuthenticatedWorkspace />} />
diff --git a/apps/web/src/components/MemoListPane.tsx b/apps/web/src/components/MemoListPane.tsx
index 8cec5578..9211fed3 100644
--- a/apps/web/src/components/MemoListPane.tsx
+++ b/apps/web/src/components/MemoListPane.tsx
@@ -63,6 +63,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { MemoCard } from "./MemoCard";
+import { MemoNotebookSites } from "./MemoNotebookSites";
import { ClipboardCopyNotice } from "./ClipboardCopyNotice";
import { WeChatCopyProgress } from "./WeChatCopyProgress";
import { cn } from "@/lib/utils";
@@ -1656,6 +1657,7 @@ export const MemoListPane = ({
{contextShareQuery.data?.share ? <Globe className="h-4 w-4 text-slate-950" /> : <Share2 className="h-4 w-4 text-slate-500" />}
{t(isLocalMemoId(memoContextMenu.memo.id) ? "sharing.afterSync" : contextShareQuery.data?.share ? "sharing.manage" : "sharing.action")}
</DropdownMenuItem>
+ {!isLocalMemoId(memoContextMenu.memo.id) && <MemoNotebookSites key={memoContextMenu.memo.id} memoId={memoContextMenu.memo.id} presentation="menu" />}
{!memoContextMenu.memo.diagramKind && !memoContextMenu.memo.structuredTable && !memoContextMenu.memo.infographic && !memoContextMenu.memo.poster && (
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
diff --git a/apps/web/src/components/MemoNotebookSites.tsx b/apps/web/src/components/MemoNotebookSites.tsx
new file mode 100644
index 00000000..9b5d906a
--- /dev/null
+++ b/apps/web/src/components/MemoNotebookSites.tsx
@@ -0,0 +1,71 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Globe } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import { Button } from "./ui/button";
+import { Switch } from "./ui/switch";
+import {
+ DropdownMenuCheckboxItem, DropdownMenuItem, DropdownMenuLabel,
+ DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger,
+} from "./ui/dropdown-menu";
+
+export const memoNotebookSitesQueryKey = (memoId: string) => ["memo-notebook-sites", getConfiguredDesktopApiBaseUrl(), memoId] as const;
+
+export const MemoNotebookSites = ({ memoId, presentation = "dialog" }: {
+ memoId: string;
+ presentation?: "dialog" | "menu";
+}) => {
+ const { t } = useTranslation();
+ const client = useQueryClient();
+ const baseUrl = getConfiguredDesktopApiBaseUrl();
+ const queryKey = memoNotebookSitesQueryKey(memoId);
+ const query = useQuery({
+ queryKey,
+ queryFn: () => api.getMemoNotebookSites(memoId),
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ });
+ const change = useMutation({
+ mutationFn: ({ notebookId, excluded }: { notebookId: string; excluded: boolean }) => api.setNotebookSiteExclusion(notebookId, memoId, excluded),
+ onSuccess: async (_, { notebookId }) => {
+ await Promise.all([
+ client.invalidateQueries({ queryKey }),
+ client.invalidateQueries({ queryKey: ["notebook-site-memos"] }),
+ client.invalidateQueries({ queryKey: ["notebook-share", baseUrl, notebookId] }),
+ ]);
+ },
+ });
+ const sites = query.data?.sites ?? [];
+ if (query.isSuccess && sites.length === 0) return null;
+ const busy = change.isPending || query.isFetching;
+ if (presentation === "menu") return <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2 px-3"><Globe className="size-4 shrink-0" />{t("notebookSite.noteSites")}</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-[min(20rem,var(--radix-dropdown-menu-content-available-height))] w-64 max-w-[calc(100vw-1.5rem)] overflow-y-auto" collisionPadding={12}>
+ {query.isPending ? <DropdownMenuItem disabled>{t("sharing.publicLoading")}</DropdownMenuItem>
+ : query.isError ? <>
+ <DropdownMenuLabel className="font-normal text-destructive">{t("sharing.error")}</DropdownMenuLabel>
+ <DropdownMenuItem onSelect={(event) => { event.preventDefault(); void query.refetch(); }}>{t("sharing.retry")}</DropdownMenuItem>
+ </> : sites.map((site) => <DropdownMenuCheckboxItem key={site.notebookId} checked={!site.excluded} disabled={busy}
+ aria-label={t("notebookSite.showInSite", { name: site.notebookName })}
+ className="break-words whitespace-normal"
+ onSelect={(event) => event.preventDefault()}
+ onCheckedChange={(checked) => change.mutate({ notebookId: site.notebookId, excluded: !checked })}>
+ {site.notebookName}
+ </DropdownMenuCheckboxItem>)}
+ {change.isError && <DropdownMenuLabel role="alert" className="break-words font-normal text-destructive">{change.error.message}</DropdownMenuLabel>}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>;
+ return <section className="space-y-3 rounded-lg border p-3" aria-label={t("notebookSite.noteSites")}>
+ <h2 className="text-sm font-semibold">{t("notebookSite.noteSites")}</h2>
+ <p className="text-xs text-muted-foreground">{t("notebookSite.noteSitesHint")}</p>
+ {query.isPending ? <p role="status" className="text-sm text-muted-foreground">{t("sharing.publicLoading")}</p>
+ : query.isError ? <div className="space-y-2"><p role="alert" className="text-xs text-destructive">{t("sharing.error")}</p><Button type="button" size="sm" variant="outline" onClick={() => void query.refetch()}>{t("sharing.retry")}</Button></div>
+ : sites.map((site) => <label key={site.notebookId} className="flex items-center justify-between gap-3 text-sm">
+ <span className="min-w-0 break-words">{t("notebookSite.showInSite", { name: site.notebookName })}</span>
+ <Switch aria-label={t("notebookSite.showInSite", { name: site.notebookName })} checked={!site.excluded} disabled={busy} onCheckedChange={(checked) => change.mutate({ notebookId: site.notebookId, excluded: !checked })} />
+ </label>)}
+ {change.isSuccess && <p role="status" className="text-xs text-muted-foreground">{t("notebookSite.contentSaved")}</p>}
+ {change.isError && <p role="alert" className="break-words text-xs text-destructive">{change.error.message}</p>}
+ </section>;
+};
diff --git a/apps/web/src/components/NotebookSiteArticleTools.tsx b/apps/web/src/components/NotebookSiteArticleTools.tsx
new file mode 100644
index 00000000..21e8d702
--- /dev/null
+++ b/apps/web/src/components/NotebookSiteArticleTools.tsx
@@ -0,0 +1,128 @@
+import { useQuery } from "@tanstack/react-query";
+import { useEffect, useState, type RefObject } from "react";
+import { useTranslation } from "react-i18next";
+import { Link } from "react-router";
+import { api } from "@/lib/api";
+import { Button } from "@/components/ui/button";
+import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger } from "@/components/ui/drawer";
+import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
+
+type Heading = { id: string; text: string; level: number };
+type Preview = { id: string; href: string; left: number; top: number };
+
+export const NotebookSiteArticleTools = ({ containerRef, token, memoUrls }: {
+ containerRef: RefObject<HTMLDivElement | null>; token: string; memoUrls: Readonly<Record<string, string>>;
+}) => {
+ const { t } = useTranslation();
+ const [headings, setHeadings] = useState<Heading[]>([]);
+ const [active, setActive] = useState("");
+ const [outlineOpen, setOutlineOpen] = useState(false);
+ const [preview, setPreview] = useState<Preview | null>(null);
+ const [cardHovered, setCardHovered] = useState(false);
+ useEffect(() => { if (preview && !memoUrls[preview.id]) setPreview(null); }, [memoUrls, preview]);
+ const query = useQuery({
+ queryKey: ["notebook-site-preview", token, preview?.id],
+ queryFn: () => api.previewPublicNotebookMemo(token, preview!.id),
+ enabled: Boolean(preview), retry: false, staleTime: 0,
+ });
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ const update = () => {
+ const counts = new Map<string, number>();
+ const result = [...container.querySelectorAll<HTMLElement>(".tiptap h1, .tiptap h2, .tiptap h3, .tiptap h4")].map((node) => {
+ const text = node.textContent?.trim() ?? "";
+ const slug = text.toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "") || "section";
+ const count = (counts.get(slug) ?? 0) + 1;
+ counts.set(slug, count);
+ node.id = `article-${slug}-${count}`;
+ node.style.scrollMarginTop = "6rem";
+ return { id: node.id, text, level: Number(node.tagName.slice(1)) };
+ });
+ setHeadings((previous) => JSON.stringify(previous) === JSON.stringify(result) ? previous : result);
+ };
+ update();
+ const observer = new MutationObserver(update);
+ observer.observe(container, { childList: true, subtree: true, characterData: true });
+ return () => observer.disconnect();
+ }, [containerRef]);
+ useEffect(() => {
+ if (!headings.length) return;
+ const update = () => {
+ let id = headings[0].id;
+ for (const heading of headings) {
+ if ((document.getElementById(heading.id)?.getBoundingClientRect().top ?? Infinity) <= 130) id = heading.id;
+ }
+ if (window.scrollY > 0 && window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 4)
+ id = headings.at(-1)!.id;
+ setActive(id);
+ };
+ let frame = 0;
+ const onScroll = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(update); };
+ window.addEventListener("scroll", onScroll, { passive: true });
+ let restoring = true;
+ let target: HTMLElement | null = null;
+ try { target = document.getElementById(decodeURIComponent(window.location.hash.slice(1))); } catch { /* Ignore malformed fragments. */ }
+ const stopRestoring = () => { restoring = false; };
+ const relayout = () => {
+ // Fonts and images may change height after TipTap has created headings.
+ // Stop restoring the initial fragment as soon as the reader interacts.
+ if (restoring && target && containerRef.current?.contains(target)) target.scrollIntoView({ block: "start", behavior: "instant" });
+ onScroll();
+ };
+ const observer = new ResizeObserver(relayout);
+ if (containerRef.current) observer.observe(containerRef.current);
+ for (const event of ["wheel", "touchstart", "pointerdown", "keydown"]) window.addEventListener(event, stopRestoring, { passive: true });
+ relayout();
+ return () => {
+ window.removeEventListener("scroll", onScroll); cancelAnimationFrame(frame); observer.disconnect();
+ for (const event of ["wheel", "touchstart", "pointerdown", "keydown"]) window.removeEventListener(event, stopRestoring);
+ };
+ }, [headings]);
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const show = (event: Event) => {
+ const link = event.target instanceof Element ? event.target.closest("a") : null;
+ if (!link) return;
+ const id = Object.keys(memoUrls).find((key) => new URL(memoUrls[key], location.origin).href === link.href);
+ if (!id) return;
+ clearTimeout(timer);
+ const rect = link.getBoundingClientRect();
+ setPreview({ id, href: memoUrls[id], left: rect.left, top: rect.bottom });
+ };
+ const hide = () => { timer = setTimeout(() => setPreview(null), 180); };
+ container.addEventListener("mouseover", show);
+ container.addEventListener("focusin", show);
+ if (!cardHovered) {
+ container.addEventListener("mouseout", hide);
+ container.addEventListener("focusout", hide);
+ }
+ return () => {
+ clearTimeout(timer);
+ container.removeEventListener("mouseover", show); container.removeEventListener("focusin", show);
+ container.removeEventListener("mouseout", hide); container.removeEventListener("focusout", hide);
+ };
+ }, [containerRef, memoUrls, cardHovered]);
+ const outline = <nav aria-label={t("notebookSite.outline")} className="max-h-[70dvh] space-y-1 overflow-y-auto text-xs">
+ {headings.map((heading) => <a href={`#${heading.id}`} key={heading.id} aria-current={active === heading.id ? "location" : undefined} className={`block rounded py-1.5 pr-2 ${active === heading.id ? "bg-muted font-semibold" : "text-muted-foreground"}`} style={{ paddingLeft: (heading.level - 1) * 12 + 8 }} onClick={(event) => {
+ event.preventDefault();
+ history.replaceState(history.state, "", `#${heading.id}`);
+ setOutlineOpen(false);
+ document.getElementById(heading.id)?.scrollIntoView({ block: "start", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "instant" : "smooth" });
+ }}>{heading.text}</a>)}
+ </nav>;
+ return <>
+ {headings.length > 0 && <>
+ <aside className="absolute bottom-0 right-3 top-8 hidden w-48 xl:block"><div className="sticky top-24"><h2 className="mb-3 text-xs font-semibold">{t("notebookSite.outline")}</h2>{outline}</div></aside>
+ <Drawer open={outlineOpen} onOpenChange={setOutlineOpen} shouldScaleBackground={false}><DrawerTrigger asChild><Button variant="outline" className="fixed bottom-5 right-5 z-20 shadow-md xl:hidden">{t("notebookSite.outline")}</Button></DrawerTrigger><DrawerContent><DrawerHeader><DrawerTitle>{t("notebookSite.outline")}</DrawerTitle><DrawerDescription>{t("sharing.readOnly")}</DrawerDescription></DrawerHeader><div className="px-6 pb-8">{outline}</div></DrawerContent></Drawer>
+ </>}
+ <HoverCard open={Boolean(preview)} onOpenChange={(open) => { if (!open) setPreview(null); }}>
+ <HoverCardTrigger asChild><span aria-hidden="true" className="pointer-events-none fixed" style={{ left: preview?.left ?? 0, top: preview?.top ?? 0 }} /></HoverCardTrigger>
+ {preview && <HoverCardContent data-notebook-preview="true" side="bottom" align="start" onMouseEnter={() => setCardHovered(true)} onMouseLeave={() => { setCardHovered(false); setPreview(null); }} onEscapeKeyDown={() => setPreview(null)}>
+ {query.isError ? <p>{t("notebookSite.previewUnavailable")}</p> : query.isPending ? <p>{t("sharing.publicLoading")}</p> : <Link to={preview.href} onClick={() => setPreview(null)}><strong className="block">{query.data.memo.title || t("common.untitledMemo")}</strong><span className="mt-2 line-clamp-4 block text-sm text-muted-foreground">{query.data.memo.excerpt}</span></Link>}
+ </HoverCardContent>}
+ </HoverCard>
+ </>;
+};
diff --git a/apps/web/src/components/NotebookSiteCodeBlock.tsx b/apps/web/src/components/NotebookSiteCodeBlock.tsx
new file mode 100644
index 00000000..1a367a02
--- /dev/null
+++ b/apps/web/src/components/NotebookSiteCodeBlock.tsx
@@ -0,0 +1,27 @@
+import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
+import { FRONT_MATTER_LANGUAGE } from "@edgeever/shared";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { copyTextToClipboard } from "@/lib/clipboard";
+import { Button } from "./ui/button";
+import { ButtonTooltip } from "./ui/button-tooltip";
+import { MermaidCodeBlock } from "./MermaidCodeBlock";
+import { NoteProperties } from "./editor/NoteProperties";
+
+export const NotebookSiteCodeBlock = (props: NodeViewProps) => {
+ const { t } = useTranslation();
+ const [collapsed, setCollapsed] = useState(false);
+ const [copied, setCopied] = useState<"idle" | "ok" | "error">("idle");
+ const language = String(props.node.attrs.language || "plaintext");
+ if (language === FRONT_MATTER_LANGUAGE) return <NoteProperties {...props} />;
+ if (language === "mermaid") return <MermaidCodeBlock {...props} />;
+ const copyLabel = t(copied === "ok" ? "editorToolbar.codeCopied" : copied === "error" ? "editorToolbar.codeCopyFailed" : "editorToolbar.copyCode");
+ const collapseLabel = t(collapsed ? "notebookSite.expand" : "notebookSite.collapse");
+ return <NodeViewWrapper className="edgeever-notebook-code not-prose my-5 overflow-hidden rounded-lg border">
+ <div contentEditable={false} className="flex items-center justify-between gap-3 border-b bg-muted px-3 py-1.5 text-xs">
+ <span aria-label={t("notebookSite.language")}>{language}</span>
+ <div className="flex gap-2"><ButtonTooltip title={copyLabel}><Button variant="ghost" size="sm" onClick={() => { void copyTextToClipboard(props.node.textContent).then((ok) => setCopied(ok ? "ok" : "error")); }}>{copyLabel}</Button></ButtonTooltip><ButtonTooltip title={collapseLabel}><Button variant="ghost" size="sm" aria-expanded={!collapsed} onClick={() => setCollapsed((value) => !value)}>{collapseLabel}</Button></ButtonTooltip></div>
+ </div>
+ <pre style={{ display: collapsed ? "none" : undefined }}><code><NodeViewContent /></code></pre>
+ </NodeViewWrapper>;
+};
diff --git a/apps/web/src/components/NotebookSiteManagementPage.tsx b/apps/web/src/components/NotebookSiteManagementPage.tsx
new file mode 100644
index 00000000..e7dada0d
--- /dev/null
+++ b/apps/web/src/components/NotebookSiteManagementPage.tsx
@@ -0,0 +1,42 @@
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { ArrowLeft, Share2 } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Link, useParams } from "react-router";
+import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import { Button } from "./ui/button";
+import { NotebookSiteSettings } from "./NotebookSiteSettings";
+import { ShareNotebookDialog } from "./dialogs/ShareNotebookDialog";
+
+export const NotebookSiteManagementPage = () => {
+ const { notebookId = "" } = useParams();
+ const { t } = useTranslation();
+ const client = useQueryClient();
+ const [sharing, setSharing] = useState(false);
+ const queryKey = ["notebook-share", getConfiguredDesktopApiBaseUrl(), notebookId];
+ const query = useQuery({
+ queryKey,
+ queryFn: () => api.getNotebookShare(notebookId),
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ });
+ const share = query.isError ? null : query.data?.share;
+ return <div className="flex h-[100dvh] flex-col bg-background text-foreground">
+ <header className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b bg-card px-4 py-3 sm:px-6">
+ <div className="flex min-w-0 items-center gap-3">
+ <Button asChild size="sm" variant="ghost"><Link to="/"><ArrowLeft className="size-4" />{t("notebookSite.backToNotes")}</Link></Button>
+ <div className="min-w-0"><h1 className="text-base font-semibold">{t("notebookSite.manage")}</h1><p className="max-w-[45vw] truncate text-xs text-muted-foreground">{share?.notebookName}</p></div>
+ </div>
+ {share && <Button size="sm" variant="outline" onClick={() => setSharing(true)}><Share2 className="size-4" />{t("sharing.notebookTitle")}</Button>}
+ </header>
+ <main className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto w-full max-w-5xl px-4 py-6 sm:px-6 sm:py-8">
+ {query.isPending ? <p role="status" className="py-12 text-center">{t("sharing.publicLoading")}</p>
+ : !share ? <section className="space-y-4 py-12 text-center"><p>{t(query.isError ? "sharing.error" : "notebookSite.noActiveShare")}</p>{query.isError && <Button variant="outline" onClick={() => void query.refetch()}>{t("sharing.retry")}</Button>}</section>
+ : <NotebookSiteSettings key={`${share.token}-${share.passwordProtected}`} notebookId={notebookId} share={share} onSaved={(data) => { client.setQueryData(queryKey, data); void client.invalidateQueries({ queryKey: ["notebook-shares"] }); }} />}
+ </div>
+ </main>
+ {share && <ShareNotebookDialog notebookId={notebookId} notebookName={share.notebookName} open={sharing} onOpenChange={setSharing} />}
+ </div>;
+};
diff --git a/apps/web/src/components/NotebookSiteMemoBrowser.tsx b/apps/web/src/components/NotebookSiteMemoBrowser.tsx
new file mode 100644
index 00000000..cd115b0e
--- /dev/null
+++ b/apps/web/src/components/NotebookSiteMemoBrowser.tsx
@@ -0,0 +1,58 @@
+import { useQuery } from "@tanstack/react-query";
+import { getMemoDisplayTitle, type NotebookSiteMemo } from "@edgeever/shared";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import { Button } from "./ui/button";
+import { Input } from "./ui/input";
+import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
+
+export const NotebookSiteMemoBrowser = ({ notebookId, token, selectedId, onSelect }: {
+ notebookId: string;
+ token: string;
+ selectedId?: string | null;
+ onSelect: (memo: NotebookSiteMemo) => void;
+}) => {
+ const { t } = useTranslation();
+ const [input, setInput] = useState("");
+ const [search, setSearch] = useState("");
+ const [cursors, setCursors] = useState<Array<string | null>>([null]);
+ const prefix = ["notebook-site-memos", getConfiguredDesktopApiBaseUrl(), token];
+ useEffect(() => {
+ const timer = window.setTimeout(() => { setSearch(input.trim()); setCursors([null]); }, 200);
+ return () => window.clearTimeout(timer);
+ }, [input]);
+ const cursor = cursors.at(-1)!;
+ const query = useQuery({
+ queryKey: [...prefix, notebookId, search, "public", cursor],
+ queryFn: () => api.listNotebookSiteMemos(notebookId, { q: search, visibility: "public", cursor, limit: 20 }),
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ });
+ const pagination = <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-xs text-muted-foreground" aria-live="polite">{t("notebookSite.page", { page: cursors.length })}</span>
+ <div className="flex gap-2">
+ <Button type="button" size="sm" variant="outline" disabled={cursors.length === 1 || query.isFetching} onClick={() => setCursors((previous) => previous.slice(0, -1))}>{t("notebookSite.previousPage")}</Button>
+ <Button type="button" size="sm" variant="outline" disabled={!query.data?.nextCursor || query.isFetching} onClick={() => { if (query.data?.nextCursor) setCursors((previous) => [...previous, query.data!.nextCursor]); }}>{t("notebookSite.nextPage")}</Button>
+ </div>
+ </div>;
+ return <section className="space-y-4" aria-label={t("notebookSite.chooseHomepage")}>
+ <Input type="search" value={input} onChange={(event) => setInput(event.target.value)} placeholder={t("notebookSite.findNotes")} aria-label={t("notebookSite.findNotes")} />
+ {pagination}
+ {query.isError ? <div role="alert" className="space-y-2 text-sm"><p>{t("sharing.error")}</p><Button type="button" variant="outline" onClick={() => void query.refetch()}>{t("sharing.retry")}</Button></div>
+ : query.isPending ? <p role="status" className="py-8 text-center text-sm text-muted-foreground">{t("sharing.publicLoading")}</p>
+ : !query.data?.memos.length ? <p className="py-8 text-center text-sm text-muted-foreground">{t("notebookSite.noNotes")}</p>
+ : <ul className="divide-y rounded-lg border bg-card">{query.data.memos.map((memo) => {
+ const title = getMemoDisplayTitle(memo.title, t("common.untitledMemo"));
+ return <li key={memo.id} className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 p-4">
+ <div className="min-w-0">
+ <Tooltip><TooltipTrigger asChild><span tabIndex={0} className="line-clamp-2 break-words rounded text-sm font-medium focus-visible:outline-none focus-visible:ring-2">{title}</span></TooltipTrigger><TooltipContent className="max-w-[80vw] break-words sm:max-w-lg">{title}</TooltipContent></Tooltip>
+ <p className="mt-1 truncate text-xs text-muted-foreground">{memo.notebookName}</p>
+ </div>
+ <Button type="button" size="sm" variant="outline" onClick={() => onSelect(memo)}>{t(selectedId === memo.id ? "notebookSite.homepageSelected" : "notebookSite.selectNote")}</Button>
+ </li>;
+ })}</ul>}
+ {query.data && query.data.memos.length > 0 && pagination}
+ </section>;
+};
diff --git a/apps/web/src/components/NotebookSiteSearch.tsx b/apps/web/src/components/NotebookSiteSearch.tsx
new file mode 100644
index 00000000..6ec9daab
--- /dev/null
+++ b/apps/web/src/components/NotebookSiteSearch.tsx
@@ -0,0 +1,60 @@
+import { useInfiniteQuery } from "@tanstack/react-query";
+import { getMemoDisplayTitle, type PublicNotebookShare } from "@edgeever/shared";
+import { createContext, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Link } from "react-router";
+import { api } from "@/lib/api";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+
+export const NotebookSiteSearchContext = createContext<(tag?: string) => void>(() => {});
+
+const Highlight = ({ text, terms }: { text: string; terms: string[] }) => {
+ const words = [...new Set(terms.filter(Boolean))].sort((a, b) => b.length - a.length);
+ if (!words.length) return <>{text}</>;
+ const pattern = new RegExp(`(${words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "giu");
+ return <>{text.split(pattern).map((part, index) => index % 2 ? <mark key={index}>{part}</mark> : part)}</>;
+};
+
+export const NotebookSiteSearch = ({ token, share, root, open, setOpen, tag, setTag }: {
+ token: string; share: PublicNotebookShare; root: string; open: boolean; setOpen: (value: boolean) => void;
+ tag: string; setTag: (value: string) => void;
+}) => {
+ const { t } = useTranslation();
+ const [query, setQuery] = useState("");
+ const [debounced, setDebounced] = useState("");
+ const returnFocus = useRef<HTMLElement | null>(null);
+ useEffect(() => {
+ const timer = window.setTimeout(() => setDebounced(query), 200);
+ return () => window.clearTimeout(timer);
+ }, [query]);
+ const result = useInfiniteQuery({
+ queryKey: ["notebook-site-search", token, debounced, tag],
+ queryFn: ({ pageParam }) => api.searchPublicNotebook(token, { q: debounced, tag, cursor: pageParam }),
+ initialPageParam: null as string | null,
+ getNextPageParam: (page) => page.nextCursor,
+ enabled: open,
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ });
+ const visible = useMemo(() => new Set(share.memos.map((memo) => memo.id)), [share.memos]);
+ const matches = result.isError ? [] : (result.data?.pages.flatMap((page) => page.memos).filter((memo) => visible.has(memo.id)) ?? []);
+ return <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="max-h-[85dvh] overflow-y-auto sm:max-w-2xl"
+ onOpenAutoFocus={() => { returnFocus.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }}
+ onCloseAutoFocus={(event) => { event.preventDefault(); returnFocus.current?.focus(); }}>
+ <DialogHeader><DialogTitle>{t("notebookSite.search")}</DialogTitle><DialogDescription>{t("notebookSite.searchHint")}</DialogDescription></DialogHeader>
+ <Input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("sharing.siteSearch")} aria-label={t("sharing.siteSearch")} />
+ {tag && <Button variant="outline" className="justify-start" onClick={() => setTag("")}>#{tag} · {t("notebookSite.allTags")}</Button>}
+ <div role="status" className="text-xs text-muted-foreground">{result.isFetching ? t("sharing.publicLoading") : t("sharing.siteResults", { count: matches.length })}</div>
+ <ul className="space-y-2">{matches.map((memo) => <li key={memo.id}><Link className="block rounded-md border p-3 hover:bg-muted focus-visible:ring-2" to={`${root}/${encodeURIComponent(memo.id)}`} onClick={() => setOpen(false)}>
+ <span className="block font-medium"><Highlight text={getMemoDisplayTitle(memo.title, t("common.untitledMemo"))} terms={memo.highlights} /></span>
+ <span className="mt-1 line-clamp-3 block whitespace-pre-wrap text-sm text-muted-foreground"><Highlight text={memo.excerpt} terms={memo.highlights} /></span>
+ </Link></li>)}</ul>
+ {result.isError ? <div role="alert">{t("sharing.error")} <Button variant="outline" onClick={() => void result.refetch()}>{t("sharing.retry")}</Button></div> : !result.isPending && !matches.length ? <p>{t("sharing.siteNoResults")}</p> : null}
+ {result.hasNextPage && <Button variant="outline" disabled={result.isFetchingNextPage} onClick={() => void result.fetchNextPage()}>{t("notebookSite.more")}</Button>}
+ </DialogContent>
+ </Dialog>;
+};
diff --git a/apps/web/src/components/NotebookSiteSettings.tsx b/apps/web/src/components/NotebookSiteSettings.tsx
new file mode 100644
index 00000000..4dbea23e
--- /dev/null
+++ b/apps/web/src/components/NotebookSiteSettings.tsx
@@ -0,0 +1,90 @@
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { getMemoDisplayTitle, readNotebookSiteSettings, type NotebookShare } from "@edgeever/shared";
+import { useState, type FormEvent } from "react";
+import { useTranslation } from "react-i18next";
+import { api, ApiRequestError, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import { Button } from "./ui/button";
+import { Input } from "./ui/input";
+import { Textarea } from "./ui/textarea";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
+import { NotebookSiteMemoBrowser } from "./NotebookSiteMemoBrowser";
+import { memoNotebookSitesQueryKey } from "./MemoNotebookSites";
+
+export const NotebookSiteSettings = ({ notebookId, share, onSaved }: {
+ notebookId: string; share: NotebookShare; onSaved: (data: { share: NotebookShare }) => void;
+}) => {
+ const { t } = useTranslation();
+ const [settings, setSettings] = useState(() => share.siteSettings ?? readNotebookSiteSettings());
+ const [slug, setSlug] = useState(share.siteSlug ?? "");
+ const [choosingHome, setChoosingHome] = useState(false);
+ const selectedHome = useQuery({
+ queryKey: ["notebook-site-home-title", getConfiguredDesktopApiBaseUrl(), notebookId, settings.homeMemoId],
+ queryFn: () => api.getMemo(settings.homeMemoId!),
+ enabled: Boolean(settings.homeMemoId),
+ retry: false,
+ });
+ const homeSites = useQuery({
+ queryKey: memoNotebookSitesQueryKey(settings.homeMemoId ?? ""),
+ queryFn: () => api.getMemoNotebookSites(settings.homeMemoId!),
+ enabled: Boolean(settings.homeMemoId),
+ retry: false,
+ staleTime: 0,
+ });
+ const homeUnavailable = Boolean(settings.homeMemoId) && (
+ [selectedHome.error, homeSites.error].some((error) => error instanceof ApiRequestError && error.status === 404)
+ || (homeSites.isSuccess && !homeSites.data.sites.some((site) => site.notebookId === notebookId && !site.excluded))
+ );
+ const homeError = Boolean(settings.homeMemoId) && !homeUnavailable && (selectedHome.isError || homeSites.isError);
+ const save = useMutation({
+ mutationFn: () => {
+ const { homeMemoId, ...otherSettings } = settings;
+ return api.updateNotebookSite(notebookId, { siteSlug: slug || null, settings: {
+ ...otherSettings,
+ ...(homeMemoId !== share.siteSettings?.homeMemoId ? { homeMemoId } : {}),
+ } });
+ },
+ onSuccess: onSaved,
+ });
+ const label = (key: string) => t(`notebookSite.${key}`);
+ const submit = (event: FormEvent) => { event.preventDefault(); save.mutate(); };
+ const edit = (patch: Partial<typeof settings>) => { setSettings((previous) => ({ ...previous, ...patch })); save.reset(); };
+ return <Dialog open={choosingHome} onOpenChange={setChoosingHome}>
+ <form onSubmit={submit} className="space-y-6">
+ <section className="space-y-4 rounded-xl border bg-card p-4 sm:p-6">
+ <h2 className="font-semibold">{label("homepage")}</h2>
+ <p className="break-words text-sm text-muted-foreground">{settings.homeMemoId && !homeUnavailable ? (selectedHome.data?.memo ? getMemoDisplayTitle(selectedHome.data.memo.title, t("common.untitledMemo")) : label("homepageSelected")) : label("directory")}</p>
+ {homeUnavailable && <p role="status" className="text-xs text-muted-foreground">{label("homepageFallback")}</p>}
+ {homeError && <div className="space-y-2"><p role="alert" className="text-xs text-destructive">{t("sharing.error")}</p><Button type="button" size="sm" variant="outline" onClick={() => { void selectedHome.refetch(); void homeSites.refetch(); }}>{t("sharing.retry")}</Button></div>}
+ <div className="flex flex-wrap gap-2">
+ <DialogTrigger asChild><Button type="button" variant="outline">{label("chooseHomepage")}</Button></DialogTrigger>
+ <Button type="button" variant="ghost" disabled={!settings.homeMemoId} onClick={() => edit({ homeMemoId: null })}>{label("useDirectory")}</Button>
+ </div>
+ </section>
+ <section className="grid gap-5 rounded-xl border bg-card p-4 sm:grid-cols-2 sm:p-6">
+ <label className="space-y-2 text-sm">{label("slug")}<Input value={slug} onChange={(event) => { setSlug(event.target.value); save.reset(); }} autoCapitalize="none" /></label>
+ <label className="space-y-2 text-sm">{label("logo")}<Input type="url" value={settings.logoUrl ?? ""} onChange={(event) => edit({ logoUrl: event.target.value || null })} /></label>
+ <div className="space-y-2 text-sm"><label htmlFor="notebook-site-order">{label("sort")}</label><Select value={settings.sortMode} onValueChange={(value) => edit({ sortMode: value as "existing" | "title" })}><SelectTrigger id="notebook-site-order"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="existing">{label("existingOrder")}</SelectItem><SelectItem value="title">{label("titleOrder")}</SelectItem></SelectContent></Select></div>
+ <div className="space-y-2 text-sm"><label className="flex items-center gap-2"><input type="checkbox" disabled={share.passwordProtected} checked={!share.passwordProtected && settings.allowIndexing} onChange={(event) => edit({ allowIndexing: event.target.checked })} />{label("indexing")}</label><p className="text-xs text-muted-foreground">{label("indexingHint")}</p></div>
+ <label className="space-y-2 text-sm sm:col-span-2">{label("footer")}<Textarea value={settings.footerText} onChange={(event) => edit({ footerText: event.target.value })} /></label>
+ <fieldset className="space-y-3 sm:col-span-2"><legend className="mb-2 text-sm">{label("headerLinks")}</legend>
+ {settings.headerLinks.map((link, index) => <div className="grid gap-2 rounded-lg border p-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto]" key={index}>
+ <Input aria-label={label("label")} placeholder={label("label")} value={link.label} required onChange={(event) => edit({ headerLinks: settings.headerLinks.map((item, i) => i === index ? { ...item, label: event.target.value } : item) })} />
+ <Input aria-label={label("url")} placeholder={label("url")} type="url" required value={link.url} onChange={(event) => edit({ headerLinks: settings.headerLinks.map((item, i) => i === index ? { ...item, url: event.target.value } : item) })} />
+ <Button type="button" variant="outline" onClick={() => edit({ headerLinks: settings.headerLinks.filter((_, i) => i !== index) })}>{label("remove")}</Button>
+ </div>)}
+ <Button type="button" variant="outline" onClick={() => edit({ headerLinks: [...settings.headerLinks, { label: "", url: "" }] })}>{label("addLink")}</Button>
+ </fieldset>
+ </section>
+ <div className="flex flex-wrap items-center gap-4 pb-2">
+ <Button type="submit" variant="solid" disabled={save.isPending}>{label("save")}</Button><span className="text-xs text-muted-foreground">{label("saveHint")}</span>
+ {save.isSuccess && <p role="status" className="text-sm">{label("saved")}</p>}
+ {save.isError && <p role="alert" className="text-sm text-destructive">{save.error.message}</p>}
+ </div>
+ </form>
+ <DialogContent className="flex max-h-[85dvh] flex-col sm:max-w-2xl">
+ <DialogHeader><DialogTitle>{label("chooseHomepage")}</DialogTitle><DialogDescription>{label("homepageHint")}</DialogDescription></DialogHeader>
+ <div className="min-h-0 overflow-y-auto"><NotebookSiteMemoBrowser notebookId={notebookId} token={share.token} selectedId={settings.homeMemoId} onSelect={(memo) => { edit({ homeMemoId: memo.id }); setChoosingHome(false); }} /></div>
+ </DialogContent>
+ </Dialog>;
+};
diff --git a/apps/web/src/components/NotebookTreeItem.tsx b/apps/web/src/components/NotebookTreeItem.tsx
index b1d05c9e..4df072fa 100644
--- a/apps/web/src/components/NotebookTreeItem.tsx
+++ b/apps/web/src/components/NotebookTreeItem.tsx
@@ -69,13 +69,7 @@ export const NotebookTreeItem = ({
const [shareOpen, setShareOpen] = useState(false);
const directlyShared = Boolean(sharedNotebookIds?.has(node.id));
const publicNotebook = inheritedPublic || directlyShared;
- const shareActionLabel = t(
- directlyShared
- ? "sharing.manage"
- : inheritedPublic
- ? "sharing.notebookInheritedAction"
- : "sharing.notebookTitle",
- );
+ const shareActionLabel = t("sharing.notebookTitle");
const open = !collapsedNotebookIds.has(node.id);
const hasChildren = node.children.length > 0;
const showsSplitCount = !showDescendantNotes && hasChildren;
@@ -314,7 +308,8 @@ export const NotebookTreeItem = ({
<TooltipProvider><Tooltip><TooltipTrigger asChild>
<button
className={cn(
- "edgeever-reveal-on-touch hidden h-6 w-6 items-center justify-center rounded-md group-focus-within:flex group-hover:flex transition-colors duration-150",
+ "edgeever-reveal-on-touch h-6 w-6 items-center justify-center rounded-md transition-colors duration-150",
+ directlyShared ? "flex" : "hidden group-focus-within:flex group-hover:flex",
selected ? "hover:bg-slate-200" : "hover:bg-slate-100"
)}
type="button"
diff --git a/apps/web/src/components/PublicNotebookSharePage.tsx b/apps/web/src/components/PublicNotebookSharePage.tsx
index f99da502..21fe4787 100644
--- a/apps/web/src/components/PublicNotebookSharePage.tsx
+++ b/apps/web/src/components/PublicNotebookSharePage.tsx
@@ -2,24 +2,35 @@ import { useQuery } from "@tanstack/react-query";
import { LoaderCircle } from "lucide-react";
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
-import { useParams } from "react-router";
+import { useLocation, useParams } from "react-router";
import { api } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { isSharePasswordError, PublicSharePasswordForm, PublicShareArticle } from "./PublicSharePage";
import { PublicNotebookSite } from "./PublicNotebookSite";
import { withEnvironmentTitlePrefix } from "@/lib/environment-title";
+import { PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
export const PublicNotebookSharePage = () => {
const { t } = useTranslation();
- const { token = "", memoId } = useParams();
+ const { token: routeToken = "", memoId: routeMemoId, slug } = useParams();
+ const location = useLocation();
+ const identity = useQuery({
+ queryKey: ["notebook-site-alias", slug],
+ queryFn: () => api.resolveNotebookSite(slug!),
+ enabled: Boolean(slug), retry: false, staleTime: 0, refetchOnMount: "always",
+ });
+ const token = slug ? (identity.isError ? "" : identity.data?.token ?? "") : routeToken;
const directory = useQuery({
queryKey: ["public-notebook-share", token],
queryFn: () => api.getPublicNotebookShare(token),
+ enabled: Boolean(token),
retry: false,
staleTime: 0,
refetchOnMount: "always",
refetchInterval: 30_000,
});
+ const share = directory.isError || identity.isError ? undefined : directory.data?.share;
+ const memoId = routeMemoId || (new URLSearchParams(location.search).has("contents") ? undefined : share?.settings?.homeMemoId ?? undefined);
const memo = useQuery({
queryKey: ["public-notebook-memo", token, memoId],
queryFn: () => api.getPublicNotebookMemo(token, memoId!),
@@ -29,7 +40,6 @@ export const PublicNotebookSharePage = () => {
refetchOnMount: "always",
refetchInterval: 30_000,
});
- const share = directory.isError ? undefined : directory.data?.share;
const note = memo.isError ? undefined : memo.data?.share;
const access = useMemo(
() => ({
@@ -39,9 +49,16 @@ export const PublicNotebookSharePage = () => {
[token, memo.data?.memoUrls],
);
useEffect(() => {
+ // The server head already applies the visibility/indexing policy. Keep it
+ // until the identity, directory and selected article have resolved.
+ if ((slug && identity.isPending) || (token && directory.isPending) ||
+ (share && memoId && (memo.isPending || memo.isFetching))) return;
const robots = document.createElement("meta");
robots.name = "robots";
- robots.content = "noindex,nofollow,noarchive";
+ robots.content = slug && share?.settings?.allowIndexing && !directory.isError && !memo.isError ? "index,follow" : PUBLIC_PAGE_ROBOTS;
+ const existingRobots = [...document.head.querySelectorAll<HTMLMetaElement>('meta[name="robots"]')];
+ const existingContents = existingRobots.map((meta) => meta.content);
+ existingRobots.forEach((meta) => { meta.content = robots.content; });
document.head.appendChild(robots);
const previous = document.title;
document.title = withEnvironmentTitlePrefix(
@@ -53,10 +70,11 @@ export const PublicNotebookSharePage = () => {
);
return () => {
robots.remove();
+ existingRobots.forEach((meta, index) => { meta.content = existingContents[index]; });
document.title = previous;
};
- }, [note?.title, share?.name, t]);
- if (directory.isPending)
+ }, [note?.title, share, slug, token, memoId, identity.isPending, directory.isPending, directory.isError, memo.isPending, memo.isFetching, memo.isError, t]);
+ if ((slug && identity.isPending) || (Boolean(token) && directory.isPending))
return (
<main className="flex min-h-[100dvh] items-center justify-center">
<LoaderCircle
@@ -82,7 +100,7 @@ export const PublicNotebookSharePage = () => {
{t("sharing.notebookUnavailable")}
</h1>
<p>{t("sharing.notebookUnavailableHint")}</p>
- <Button variant="outline" onClick={() => void directory.refetch()}>
+ <Button variant="outline" onClick={() => void (slug && identity.isError ? identity.refetch() : directory.refetch())}>
{t("sharing.retry")}
</Button>
</main>
diff --git a/apps/web/src/components/PublicNotebookSite.tsx b/apps/web/src/components/PublicNotebookSite.tsx
index eaa8c9db..780752ec 100644
--- a/apps/web/src/components/PublicNotebookSite.tsx
+++ b/apps/web/src/components/PublicNotebookSite.tsx
@@ -1,4 +1,8 @@
import type { PublicNotebookShare } from "@edgeever/shared";
+import { NotebookSiteSearch, NotebookSiteSearchContext } from "./NotebookSiteSearch";
+import { useAppearanceTheme, type ThemePreference } from "./ThemeProvider";
+import { ButtonTooltip } from "./ui/button-tooltip";
+import "./notebook-site.css";
import { getMemoDisplayTitle } from "@edgeever/shared";
import {
ArrowLeft,
@@ -9,7 +13,6 @@ import {
PanelLeftClose,
PanelLeftOpen,
Search,
- X,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
@@ -29,7 +32,6 @@ import {
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer";
-import { Input } from "@/components/ui/input";
import {
Tooltip,
TooltipContent,
@@ -152,21 +154,16 @@ const NoteTitle = ({ memo }: { memo: Memo }) => {
const HomepageContents = ({
sections,
- matchingIds,
- filtering,
href,
onNavigate,
}: {
sections: Section[];
- matchingIds: ReadonlySet<string>;
- filtering: boolean;
href: (id: string) => string;
onNavigate: () => void;
}) => {
const { t } = useTranslation();
- const { children, visibleSections } = useMemo(() => {
+ const children = useMemo(() => {
const children = new Map<string, Section[]>();
- const visibleSections = new Set<string>();
for (const section of sections) {
const parent = section.path.at(-2);
if (parent) {
@@ -174,15 +171,9 @@ const HomepageContents = ({
siblings.push(section);
children.set(parent.id, siblings);
}
- if (
- !filtering ||
- section.memos.some((memo) => matchingIds.has(memo.id))
- ) {
- for (const ancestor of section.path) visibleSections.add(ancestor.id);
- }
}
- return { children, visibleSections };
- }, [sections, matchingIds, filtering]);
+ return children;
+ }, [sections]);
const renderContents = (section: Section, nested: boolean): ReactNode => (
<ul
className={cn(
@@ -191,7 +182,6 @@ const HomepageContents = ({
)}
>
{section.memos
- .filter((memo) => matchingIds.has(memo.id))
.map((memo) => (
<li key={memo.id} className="pl-1 marker:text-slate-400">
<Link
@@ -207,7 +197,6 @@ const HomepageContents = ({
</li>
))}
{(children.get(section.notebook.id) ?? [])
- .filter((child) => visibleSections.has(child.notebook.id))
.map((child) => (
<li
key={child.notebook.id}
@@ -217,10 +206,7 @@ const HomepageContents = ({
<span className="break-words font-semibold text-slate-900">
{child.notebook.name}
</span>
- {(child.memos.some((memo) => matchingIds.has(memo.id)) ||
- children
- .get(child.notebook.id)
- ?.some((item) => visibleSections.has(item.notebook.id))) &&
+ {(child.memos.length > 0 || children.has(child.notebook.id)) &&
renderContents(child, true)}
</li>
))}
@@ -240,23 +226,23 @@ const HomepageContents = ({
);
};
-export const PublicNotebookSite = ({
- share,
- token,
- selectedId,
- children,
-}: {
- share: PublicNotebookShare;
- token: string;
- selectedId?: string;
- children?: ReactNode;
+const SiteLogo = ({ src }: { src?: string | null }) => {
+ const [failed, setFailed] = useState(false);
+ return src && !failed ? <img src={src} alt="" className="size-8 shrink-0 rounded-lg object-contain" onError={() => setFailed(true)} /> : <BookOpen className="size-6 shrink-0" />;
+};
+
+export const PublicNotebookSite = ({ share, token, selectedId, children }: {
+ share: PublicNotebookShare; token: string; selectedId?: string; children?: ReactNode;
}) => {
const { t } = useTranslation();
const { hash } = useLocation();
- const [search, setSearch] = useState("");
+ const { preference, setPreference } = useAppearanceTheme();
const [mobileOpen, setMobileOpen] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(true);
- const root = `/share/notebook/${encodeURIComponent(token)}`;
+ const [searchOpen, setSearchOpen] = useState(false);
+ const [tag, setTag] = useState("");
+ const root = share.siteSlug ? `/s/${encodeURIComponent(share.siteSlug)}` : `/share/notebook/${encodeURIComponent(token)}`;
+ const directory = `${root}?contents=1`;
const href = (id: string) => `${root}/${encodeURIComponent(id)}`;
const sections = useMemo(() => {
const result: Section[] = [];
@@ -266,408 +252,77 @@ export const PublicNotebookSite = ({
for (const notebook of share.notebooks) {
if (!notebook.parentId) continue;
const siblings = children.get(notebook.parentId) ?? [];
- siblings.push(notebook);
- children.set(notebook.parentId, siblings);
+ siblings.push(notebook); children.set(notebook.parentId, siblings);
}
for (const memo of share.memos) {
const siblings = memos.get(memo.notebookId) ?? [];
- siblings.push(memo);
- memos.set(memo.notebookId, siblings);
+ siblings.push(memo); memos.set(memo.notebookId, siblings);
}
const visited = new Set<string>();
const visit = (notebook: Notebook, path: Notebook[]) => {
if (visited.has(notebook.id)) return;
visited.add(notebook.id);
const nextPath = [...path, notebook];
- result.push({
- notebook,
- path: nextPath,
- memos: memos.get(notebook.id) ?? [],
- });
- for (const child of children.get(notebook.id) ?? [])
- visit(child, nextPath);
+ result.push({ notebook, path: nextPath, memos: memos.get(notebook.id) ?? [] });
+ for (const child of children.get(notebook.id) ?? []) visit(child, nextPath);
};
- visit(
- notebooks.get(share.notebookId) ?? {
- id: share.notebookId,
- parentId: null,
- name: share.name,
- },
- [],
- );
+ visit(notebooks.get(share.notebookId) ?? { id: share.notebookId, parentId: null, name: share.name }, []);
return result;
}, [share]);
- const notes = useMemo(
- () =>
- sections.flatMap((section) =>
- section.memos.map((memo) => ({ memo, section })),
- ),
- [sections],
- );
- const query = search.trim().toLocaleLowerCase();
- const matches = useMemo(
- () =>
- notes.filter(({ memo }) =>
- getMemoDisplayTitle(memo.title, t("common.untitledMemo"))
- .toLocaleLowerCase()
- .includes(query),
- ),
- [notes, query, t],
- );
- const matchingIds = useMemo(
- () => new Set(matches.map(({ memo }) => memo.id)),
- [matches],
- );
+ const notes = useMemo(() => sections.flatMap((section) => section.memos.map((memo) => ({ memo, section }))), [sections]);
const index = notes.findIndex(({ memo }) => memo.id === selectedId);
const current = notes[index];
- const navigate = () => {
- setMobileOpen(false);
- setSearch("");
- };
+ const navigate = () => setMobileOpen(false);
useEffect(() => {
- // Reset reading position only on navigation, never on the periodic content refresh.
- if (!selectedId && hash) {
- try {
- document
- .getElementById(decodeURIComponent(hash.slice(1)))
- ?.scrollIntoView({ block: "start", behavior: "instant" });
- } catch {
- // A malformed fragment must not prevent the site from rendering.
+ const shortcut = (event: KeyboardEvent) => {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
+ event.preventDefault(); setSearchOpen((open) => !open);
}
- } else {
- window.scrollTo({ top: 0, behavior: "instant" });
- }
+ };
+ window.addEventListener("keydown", shortcut);
+ return () => window.removeEventListener("keydown", shortcut);
+ }, []);
+ useEffect(() => {
+ if (hash && !selectedId) {
+ try { document.getElementById(decodeURIComponent(hash.slice(1)))?.scrollIntoView({ block: "start", behavior: "instant" }); } catch { /* Ignore malformed fragments. */ }
+ } else if (!hash) window.scrollTo({ top: 0, behavior: "instant" });
}, [selectedId, token, hash]);
- const contents = (
- <TooltipProvider delayDuration={400}>
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="px-6 pb-4">
- <div className="relative">
- <Search className="pointer-events-none absolute left-3 top-2.5 size-3.5 text-slate-400" />
- <Input
- type="search"
- value={search}
- onChange={(event) => setSearch(event.target.value)}
- placeholder={t("sharing.siteSearch")}
- aria-label={t("sharing.siteSearch")}
- className="h-9 border-transparent bg-slate-100/70 pl-9 pr-9 text-xs focus-visible:border-slate-300"
- />
- {search && (
- <Button
- variant="ghost"
- size="icon-sm"
- className="absolute right-1.5 top-1"
- aria-label={t("sharing.siteClearSearch")}
- onClick={() => setSearch("")}
- >
- <X className="size-3.5" />
- </Button>
- )}
- </div>
- </div>
- <nav
- aria-label={t("sharing.notebookContents")}
- className="min-h-0 flex-1 overflow-y-auto px-5 pb-6"
- >
- <Link
- to={root}
- onClick={navigate}
- aria-current={!selectedId ? "page" : undefined}
- className={cn(
- linkClass,
- "block px-3 py-2 text-[13px] font-medium",
- !selectedId
- ? "text-slate-900"
- : "text-slate-600 hover:bg-slate-100",
- )}
- >
- {t("sharing.siteHome")}
- </Link>
- {query ? (
- <>
- <p className="px-2 py-2 text-xs text-slate-500" role="status">
- {t("sharing.siteResults", { count: matches.length })}
- </p>
- <ul>
- {matches.map(({ memo, section }) => (
- <li key={memo.id}>
- <Link
- to={href(memo.id)}
- onClick={navigate}
- className={cn(
- linkClass,
- "block px-3 py-2 text-[13px] leading-5 text-slate-600 hover:bg-slate-100/70",
- )}
- >
- <NoteTitle memo={memo} />
- <span className="mt-1 block text-xs text-slate-400">
- {section.path.map((item) => item.name).join(" / ")}
- </span>
- </Link>
- </li>
- ))}
- </ul>
- {!matches.length && (
- <p className="px-2 py-4 text-sm text-slate-500">
- {t("sharing.siteNoResults")}
- </p>
- )}
- </>
- ) : (
- <>
- {sections[0] && (
- <NavigationNotes
- memos={sections[0].memos}
- selectedId={selectedId}
- href={href}
- onNavigate={navigate}
- />
- )}
- {sections
- .slice(1)
- .filter((section) => section.memos.length)
- .map((section) => (
- <NavigationSection
- key={section.notebook.id}
- section={section}
- selectedId={selectedId}
- containsSelection={
- current?.section.notebook.id === section.notebook.id
- }
- href={href}
- onNavigate={navigate}
- />
- ))}
- </>
- )}
- </nav>
- <div className="px-8 py-5 text-[11px] text-slate-400">
- {t("sharing.sitePoweredBy")}
- </div>
- </div>
- </TooltipProvider>
- );
- return (
- <div
- data-site-theme="default"
- className="min-h-[100dvh] bg-card text-slate-900"
- >
- <a
- href="#notebook-site-content"
- className="sr-only z-[60] rounded-md bg-card p-3 focus:not-sr-only focus:fixed focus:left-4 focus:top-4"
- >
- {t("sharing.siteSkipToContent")}
- </a>
- <header className="sticky top-0 z-30 flex h-16 items-center justify-between gap-4 border-b border-slate-200 bg-card/95 px-4 backdrop-blur sm:px-6">
- <Link
- to={root}
- onClick={navigate}
- className={cn(
- linkClass,
- "flex min-w-0 items-center gap-3 font-semibold",
- )}
- >
- <span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-slate-100 text-slate-700">
- <BookOpen className="size-5" />
- </span>
- <span className="truncate">{share.name}</span>
- </Link>
- <div className="flex shrink-0 items-center gap-3">
- <Button
- variant="ghost"
- size="icon"
- className="hidden lg:inline-flex"
- aria-label={t(
- sidebarOpen
- ? "sharing.siteHideContents"
- : "sharing.siteShowContents",
- )}
- title={t(
- sidebarOpen
- ? "sharing.siteHideContents"
- : "sharing.siteShowContents",
- )}
- aria-expanded={sidebarOpen}
- aria-controls="notebook-site-sidebar"
- onClick={() => setSidebarOpen((open) => !open)}
- >
- {sidebarOpen ? (
- <PanelLeftClose className="size-4" />
- ) : (
- <PanelLeftOpen className="size-4" />
- )}
- </Button>
- <span className="hidden text-xs text-slate-500 sm:block">
- {t("sharing.readOnly")}
- </span>
- <Drawer
- open={mobileOpen}
- onOpenChange={setMobileOpen}
- shouldScaleBackground={false}
- >
- <DrawerTrigger asChild>
- <Button variant="outline" size="sm" className="lg:hidden">
- <Menu className="size-4" />
- {t("sharing.notebookContents")}
- </Button>
- </DrawerTrigger>
- <DrawerContent className="h-[85dvh] bg-card">
- <DrawerHeader className="relative pr-12">
- <DrawerClose asChild>
- <Button
- variant="ghost"
- size="icon"
- aria-label={t("common.close")}
- className="absolute right-3 top-2"
- >
- <X className="size-4" />
- </Button>
- </DrawerClose>
- <DrawerTitle>{share.name}</DrawerTitle>
- <DrawerDescription>
- {t("sharing.siteNoteCount", { count: notes.length })}
- </DrawerDescription>
- </DrawerHeader>
- {contents}
- </DrawerContent>
- </Drawer>
+ const contents = <div className="flex min-h-0 flex-1 flex-col">
+ <div className="px-6 pb-4"><Button variant="outline" className="w-full justify-start text-xs" onClick={() => setSearchOpen(true)}><Search className="size-4" />{t("sharing.siteSearch")}</Button></div>
+ <nav aria-label={t("sharing.notebookContents")} className="min-h-0 flex-1 overflow-y-auto px-5 pb-6">
+ <Link to={root} onClick={navigate} className={`${linkClass} block px-3 py-2 text-sm font-medium`}>{t("sharing.siteHome")}</Link>
+ {share.settings?.homeMemoId && <Link to={directory} onClick={navigate} className={`${linkClass} block px-3 py-2 text-sm`}>{t("notebookSite.directory")}</Link>}
+ {sections[0] && <NavigationNotes memos={sections[0].memos} selectedId={selectedId} href={href} onNavigate={navigate} />}
+ {sections.slice(1).filter((section) => section.memos.length).map((section) => <NavigationSection key={section.notebook.id} section={section} selectedId={selectedId} containsSelection={section.memos.some((memo) => memo.id === selectedId)} href={href} onNavigate={navigate} />)}
+ </nav><div className="px-8 py-5 text-[11px] text-muted-foreground">{t("sharing.sitePoweredBy")}</div>
+ </div>;
+ return <NotebookSiteSearchContext.Provider value={(selectedTag) => { setTag(selectedTag ?? ""); setSearchOpen(true); }}><TooltipProvider delayDuration={400}>
+ <div data-site-theme="default" className="edgeever-notebook-site min-h-[100dvh] bg-card text-foreground">
+ <a href="#notebook-site-content" className="sr-only z-[60] rounded-md bg-card p-3 focus:not-sr-only focus:fixed focus:left-4 focus:top-4">{t("sharing.siteSkipToContent")}</a>
+ <header className="sticky top-0 z-30 flex min-h-16 flex-wrap items-center justify-between gap-3 border-b bg-card/95 px-4 py-3 backdrop-blur sm:px-6">
+ <Link to={root} onClick={navigate} className={`${linkClass} flex min-w-0 items-center gap-3 font-semibold`}><SiteLogo key={share.settings?.logoUrl} src={share.settings?.logoUrl} /><span className="max-w-[40vw] truncate">{share.name}</span></Link>
+ <div className="flex flex-wrap items-center gap-3">
+ <nav className="flex flex-wrap gap-3 text-xs">{share.settings?.headerLinks.map((link, i) => <a key={i} href={link.url} target="_blank" rel="noopener noreferrer" className="underline underline-offset-4">{link.label}</a>)}</nav>
+ <select aria-label={t("notebookSite.theme")} value={preference} onChange={(event) => setPreference(event.target.value as ThemePreference)} className="max-w-28 rounded border bg-background px-1 py-1 text-xs">{(["light", "dark", "system"] as const).map((value) => <option key={value} value={value}>{t(`notebookSite.${value}`)}</option>)}</select>
+ <ButtonTooltip title={t(sidebarOpen ? "sharing.siteHideContents" : "sharing.siteShowContents")}><Button variant="ghost" size="icon" className="hidden lg:inline-flex" aria-label={t(sidebarOpen ? "sharing.siteHideContents" : "sharing.siteShowContents")} aria-expanded={sidebarOpen} aria-controls="notebook-site-sidebar" onClick={() => setSidebarOpen((open) => !open)}>{sidebarOpen ? <PanelLeftClose className="size-4" /> : <PanelLeftOpen className="size-4" />}</Button></ButtonTooltip>
+ <Drawer open={mobileOpen} onOpenChange={setMobileOpen} shouldScaleBackground={false}><DrawerTrigger asChild><Button variant="outline" size="sm" className="lg:hidden"><Menu className="size-4" />{t("sharing.notebookContents")}</Button></DrawerTrigger><DrawerContent className="h-[85dvh] bg-card"><DrawerHeader><DrawerTitle>{share.name}</DrawerTitle><DrawerDescription>{t("sharing.siteNoteCount", { count: notes.length })}</DrawerDescription><DrawerClose asChild><Button variant="outline" size="sm">{t("common.close")}</Button></DrawerClose></DrawerHeader>{contents}</DrawerContent></Drawer>
</div>
</header>
<div className="mx-auto flex max-w-[1600px] items-start">
- <aside
- id="notebook-site-sidebar"
- className={cn(
- "sticky top-16 hidden h-[calc(100dvh-4rem)] w-72 shrink-0 flex-col border-r border-slate-200/70 bg-card pt-6",
- sidebarOpen && "lg:flex",
- )}
- >
- {contents}
- </aside>
- <main
- id="notebook-site-content"
- tabIndex={-1}
- className="min-w-0 flex-1 outline-none"
- >
- {!selectedId ? (
- <div className="mx-auto max-w-5xl px-5 py-10 sm:px-10 sm:py-14">
- <p className="mb-4 text-sm font-medium text-slate-500">
- {t("sharing.siteNoteCount", { count: notes.length })}
- </p>
- <h1 className="break-words text-3xl font-bold tracking-tight sm:text-4xl">
- {share.name}
- </h1>
- {!notes.length && (
- <p className="mt-4 text-sm text-slate-500">
- {t("sharing.notebookEmpty")}
- </p>
- )}
- {query && (
- <p className="mt-6 text-sm text-slate-500" role="status">
- {t("sharing.siteResults", { count: matches.length })}
- </p>
- )}
- {(!query || matches.length > 0) && (
- <HomepageContents
- sections={sections}
- matchingIds={matchingIds}
- filtering={Boolean(query)}
- href={href}
- onNavigate={navigate}
- />
- )}
- {query && !matches.length && (
- <p className="py-10 text-sm text-slate-500">
- {t("sharing.siteNoResults")}
- </p>
- )}
- </div>
- ) : (
- <>
- <nav
- aria-label={t("sharing.siteBreadcrumb")}
- className="mx-auto flex max-w-4xl flex-wrap items-center gap-2 px-5 pt-7 text-xs leading-6 text-slate-500 sm:px-10"
- >
- <Link
- to={root}
- onClick={navigate}
- className={cn(linkClass, "hover:text-slate-900")}
- >
- {t("sharing.siteHome")}
- </Link>
- {current?.section.path.map((notebook) => (
- <span key={notebook.id} className="contents">
- <ChevronRight className="size-3 shrink-0" />
- <Link
- to={`${root}#section-${notebook.id}`}
- onClick={navigate}
- className={cn(
- linkClass,
- "break-words hover:text-slate-900",
- )}
- >
- {notebook.name}
- </Link>
- </span>
- ))}
- {current && (
- <>
- <ChevronRight className="size-3 shrink-0" />
- <span
- aria-current="page"
- className="break-words text-slate-700"
- >
- <NoteTitle memo={current.memo} />
- </span>
- </>
- )}
- </nav>
- {children}
- {current && (
- <nav
- aria-label={t("sharing.siteReadingNavigation")}
- className="mx-auto grid max-w-4xl grid-cols-2 gap-4 border-t border-slate-200 px-5 py-8 sm:px-10"
- >
- {notes[index - 1] ? (
- <Link
- to={href(notes[index - 1].memo.id)}
- onClick={navigate}
- className={cn(linkClass, "min-w-0 p-3 hover:bg-slate-50")}
- >
- <span className="mb-2 flex items-center gap-2 text-xs text-slate-500">
- <ArrowLeft className="size-3.5" />
- {t("sharing.sitePrevious")}
- </span>
- <span className="text-sm font-medium">
- <NoteTitle memo={notes[index - 1].memo} />
- </span>
- </Link>
- ) : (
- <span />
- )}
- {notes[index + 1] && (
- <Link
- to={href(notes[index + 1].memo.id)}
- onClick={navigate}
- className={cn(
- linkClass,
- "min-w-0 p-3 text-right hover:bg-slate-50",
- )}
- >
- <span className="mb-2 flex items-center justify-end gap-2 text-xs text-slate-500">
- {t("sharing.siteNext")}
- <ArrowRight className="size-3.5" />
- </span>
- <span className="text-sm font-medium">
- <NoteTitle memo={notes[index + 1].memo} />
- </span>
- </Link>
- )}
- </nav>
- )}
- </>
- )}
+ <aside id="notebook-site-sidebar" className={cn("sticky top-16 hidden h-[calc(100dvh-4rem)] w-72 shrink-0 flex-col border-r bg-card pt-6", sidebarOpen && "lg:flex")}>{contents}</aside>
+ <main id="notebook-site-content" tabIndex={-1} className="min-w-0 flex-1 outline-none">
+ {!selectedId ? <div className="mx-auto max-w-5xl px-5 py-10 sm:px-10 sm:py-14"><p className="mb-4 text-sm text-muted-foreground">{t("sharing.siteNoteCount", { count: notes.length })}</p><h1 className="break-words text-3xl font-bold">{share.name}</h1>{!notes.length && <p className="mt-4">{t("sharing.notebookEmpty")}</p>}<HomepageContents sections={sections} href={href} onNavigate={navigate} /></div> : <>
+ <nav aria-label={t("sharing.siteBreadcrumb")} className="flex flex-wrap items-center gap-2 border-b px-5 py-3 text-xs text-muted-foreground"><Link to={root} onClick={navigate}>{t("sharing.siteHome")}</Link>{current?.section.path.map((notebook) => <span key={notebook.id} className="contents"><ChevronRight className="size-3" /><Link to={`${directory}#section-${notebook.id}`} onClick={navigate}>{notebook.name}</Link></span>)}{current && <span aria-current="page"><NoteTitle memo={current.memo} /></span>}</nav>
+ {children}
+ {current && <nav aria-label={t("sharing.siteReadingNavigation")} className="mx-auto grid max-w-4xl grid-cols-2 gap-4 border-t px-5 py-8 sm:px-10">
+ {notes[index - 1] ? <Link to={href(notes[index - 1].memo.id)} onClick={navigate} className={`${linkClass} min-w-0 p-3 hover:bg-muted`}><span className="mb-2 flex items-center gap-2 text-xs text-muted-foreground"><ArrowLeft className="size-3.5" />{t("sharing.sitePrevious")}</span><NoteTitle memo={notes[index - 1].memo} /></Link> : <span />}
+ {notes[index + 1] && <Link to={href(notes[index + 1].memo.id)} onClick={navigate} className={`${linkClass} min-w-0 p-3 text-right hover:bg-muted`}><span className="mb-2 flex items-center justify-end gap-2 text-xs text-muted-foreground">{t("sharing.siteNext")}<ArrowRight className="size-3.5" /></span><NoteTitle memo={notes[index + 1].memo} /></Link>}
+ </nav>}
+ </>}
+ {share.settings?.footerText && <footer className="whitespace-pre-wrap border-t px-5 py-6 text-sm text-muted-foreground">{share.settings.footerText}</footer>}
</main>
</div>
</div>
- );
+ <NotebookSiteSearch token={token} share={share} root={root} open={searchOpen} setOpen={setSearchOpen} tag={tag} setTag={setTag} />
+ </TooltipProvider></NotebookSiteSearchContext.Provider>;
};
diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsx
index 3b65ed36..75a35806 100644
--- a/apps/web/src/components/PublicSharePage.tsx
+++ b/apps/web/src/components/PublicSharePage.tsx
@@ -1,10 +1,10 @@
import "katex/dist/katex.min.css";
import { Node, mergeAttributes } from "@tiptap/core";
import Image from "@tiptap/extension-image";
-import { EditorContent, useEditor } from "@tiptap/react";
+import { EditorContent, useEditor, ReactNodeViewRenderer } from "@tiptap/react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Clock3, FileText, LoaderCircle, LockKeyhole, ShieldCheck } from "lucide-react";
-import { lazy, Suspense, useEffect, useMemo, useState, type CSSProperties, type FormEvent, type MouseEvent } from "react";
+import { lazy, Suspense, useContext, useEffect, useMemo, useRef, useState, type CSSProperties, type FormEvent, type MouseEvent } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router";
import { cn } from "@/lib/utils";
@@ -32,6 +32,10 @@ import { applyEditorBodyFontPreference } from "@/lib/editor-body-font";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
import { PdfAttachment } from "@/components/editor/PdfAttachment";
import { FileAttachment } from "@/components/editor/FileAttachment";
+import { NotebookSiteCodeBlock } from "./NotebookSiteCodeBlock";
+import { NotebookSiteArticleTools } from "./NotebookSiteArticleTools";
+import { NotebookSiteSearchContext } from "./NotebookSiteSearch";
+import { useAppearanceTheme } from "./ThemeProvider";
const ReadOnlyX6Diagram = lazy(() => import("@/components/ReadOnlyX6Diagram"));
const ImageViewer = lazy(() => import("@/components/editor/ImageViewer").then((module) => ({ default: module.ImageViewer })));
@@ -86,9 +90,11 @@ const SharedThemeBlock = Node.create({
},
});
-const SharedRichText = ({ content }: { content: PublicMemoShare["contentJson"] }) => {
+const SiteCodeBlock = EdgeEverCodeBlock.extend({ addNodeView() { return ReactNodeViewRenderer(NotebookSiteCodeBlock); } });
+const SharedRichText = ({ content, site = false }: { content: PublicMemoShare["contentJson"]; site?: boolean }) => {
const { t } = useTranslation();
const [imagePreview, setImagePreview] = useState<{ alt: string; url: string } | null>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
const editor = useEditor({
extensions: [
...createEdgeEverDocumentExtensions({
@@ -99,7 +105,7 @@ const SharedRichText = ({ content }: { content: PublicMemoShare["contentJson"] }
file: FileAttachment,
table: { table: { renderWrapper: true } },
}),
- EdgeEverCodeBlock.configure({ lowlight: codeBlockLowlight, defaultLanguage: "plaintext" }),
+ (site ? SiteCodeBlock : EdgeEverCodeBlock).configure({ lowlight: codeBlockLowlight, defaultLanguage: "plaintext" }),
SharedThemeBlock,
],
content,
@@ -111,6 +117,13 @@ const SharedRichText = ({ content }: { content: PublicMemoShare["contentJson"] }
},
},
}, [content]);
+ useEffect(() => {
+ if (!site || !editor) return;
+ containerRef.current?.querySelectorAll("img").forEach((img) => {
+ img.tabIndex = 0; img.setAttribute("role", "button");
+ img.setAttribute("aria-label", img.alt || t("editor.imageViewer"));
+ });
+ }, [editor, site, content, t]);
const previewImage = (event: MouseEvent<HTMLDivElement>) => {
const target = event.target;
@@ -124,7 +137,11 @@ const SharedRichText = ({ content }: { content: PublicMemoShare["contentJson"] }
};
return (
- <div onClickCapture={jumpToHeading} onDoubleClick={previewImage}>
+ <div ref={containerRef} onClickCapture={jumpToHeading} onClick={site ? previewImage : undefined} onDoubleClick={site ? undefined : previewImage} onKeyDown={site ? (event) => {
+ if ((event.key === "Enter" || event.key === " ") && event.target instanceof HTMLImageElement) {
+ event.preventDefault(); setImagePreview({ alt: event.target.alt, url: event.target.currentSrc });
+ }
+ } : undefined}>
<EditorContent editor={editor} />
{imagePreview ? (
<Suspense fallback={null}>
@@ -149,12 +166,15 @@ const SharedDocument = ({
share,
token,
access,
+ site = false,
}: {
locale: "zh-CN" | "en-US" | "ja" | "pl";
share: PublicMemoShare;
token: string;
access?: ShareBodyAccess;
+ site?: boolean;
}) => {
+ const { resolvedTheme } = useAppearanceTheme();
const body = useMemo(() => resolvePublicShareBody(share, token, access), [share, token, access]);
if (body.type === "diagram") {
return (
@@ -165,11 +185,11 @@ const SharedDocument = ({
</div>
}
>
- <ReadOnlyX6Diagram diagram={body.diagram} locale={locale} theme="light" />
+ <ReadOnlyX6Diagram diagram={body.diagram} locale={locale} theme={site ? resolvedTheme : "light"} controls={site} />
</Suspense>
);
}
- return <SharedRichText content={body.content} />;
+ return <SharedRichText content={body.content} site={site} />;
};
export const isSharePasswordError = (error: unknown, code: string) =>
@@ -300,6 +320,8 @@ export const PublicShareArticle = ({
layout?: "standalone" | "site";
}) => {
const { t, i18n } = useTranslation();
+ const containerRef = useRef<HTMLDivElement>(null);
+ const openSearch = useContext(NotebookSiteSearchContext);
const publishedBodyFont = parsePublishedNoteBodyFont(share.bodyFont);
useEffect(() => {
@@ -323,9 +345,10 @@ export const PublicShareArticle = ({
const prose = resolveNoteProse(share.prose);
return (
<div
+ ref={containerRef}
className={cn(
"edgeever-public-share",
- layout === "site" ? "py-6 sm:py-8" : "px-4 py-6 sm:px-8 sm:py-10",
+ layout === "site" ? "py-6 sm:py-8 xl:pr-56" : "px-4 py-6 sm:px-8 sm:py-10",
)}
>
<article
@@ -380,14 +403,15 @@ export const PublicShareArticle = ({
layout === "site" && "order-3",
)}
>
- {share.tags.map((tag) => (
- <span
+ {share.tags.map((tag) => layout === "site" ? (
+ <button type="button"
key={tag}
+ onClick={() => openSearch(tag)}
className="rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-600"
>
#{tag}
- </span>
- ))}
+ </button>
+ ) : <span key={tag} className="rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-600">#{tag}</span>)}
</div>
) : null}
</header>
@@ -412,9 +436,11 @@ export const PublicShareArticle = ({
share={share}
token={token}
access={access}
+ site={layout === "site"}
/>
</div>
</article>
+ {layout === "site" && <NotebookSiteArticleTools containerRef={containerRef} token={token} memoUrls={access?.memoUrls ?? {}} />}
</div>
);
};
diff --git a/apps/web/src/components/ReadOnlyX6Diagram.tsx b/apps/web/src/components/ReadOnlyX6Diagram.tsx
index ed3669f4..44b25655 100644
--- a/apps/web/src/components/ReadOnlyX6Diagram.tsx
+++ b/apps/web/src/components/ReadOnlyX6Diagram.tsx
@@ -1,4 +1,7 @@
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "./ui/button";
+import { ButtonTooltip } from "./ui/button-tooltip";
import { Graph } from "@antv/x6";
import {
attachDiagramReader,
@@ -26,12 +29,25 @@ export const ReadOnlyX6Diagram = ({
diagram,
locale,
theme,
+ controls = false,
}: {
diagram: DiagramDocument;
locale: "zh-CN" | "en-US" | "ja" | "pl";
theme: "light" | "dark";
+ controls?: boolean;
}) => {
+ const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
+ const graphRef = useRef<Graph | null>(null);
+ const [fullscreen, setFullscreen] = useState(false);
+ useEffect(() => {
+ if (!fullscreen) return;
+ const previous = document.body.style.overflow;
+ document.body.style.overflow = "hidden";
+ const escape = (event: KeyboardEvent) => { if (event.key === "Escape") setFullscreen(false); };
+ window.addEventListener("keydown", escape);
+ return () => { document.body.style.overflow = previous; window.removeEventListener("keydown", escape); };
+ }, [fullscreen]);
useEffect(() => {
const container = containerRef.current;
@@ -65,6 +81,7 @@ export const ReadOnlyX6Diagram = ({
panning: { enabled: true },
mousewheel: { enabled: true, minScale: 0.1, maxScale: 2.5 },
});
+ graphRef.current = graph;
graph.addNodes(cells.nodes);
graph.addEdges(cells.edges);
const sized = {
@@ -85,11 +102,12 @@ export const ReadOnlyX6Diagram = ({
observer.disconnect();
reader.dispose();
graph.dispose();
+ graphRef.current = null;
};
}, [diagram, locale, theme]);
return (
- <section className="edgeever-x6-document">
+ <section className={`edgeever-x6-document${fullscreen ? " edgeever-x6-fullscreen" : ""}`}>
<style>{`
.edgeever-x6-document, .edgeever-diagram-reader-host {
display: flex;
@@ -99,6 +117,10 @@ export const ReadOnlyX6Diagram = ({
padding: 8px 12px 16px;
}
.edgeever-diagram-reader-controls { flex: 0 0 auto; }
+ .edgeever-x6-document.edgeever-x6-fullscreen {
+ position: fixed; inset: 0; z-index: 60; height: 100dvh; min-height: 100dvh;
+ background: ${theme === "dark" ? DIAGRAM_CANVAS_DARK : DIAGRAM_CANVAS_LIGHT};
+ }
.edgeever-x6-diagram {
flex: 1 1 auto;
width: 100%;
@@ -113,6 +135,10 @@ export const ReadOnlyX6Diagram = ({
.edgeever-x6-diagram .x6-graph-svg { overflow: hidden; }
.edgeever-x6-diagram .x6-node { cursor: pointer; }
`}</style>
+ {controls && <div className="flex shrink-0 justify-end gap-2 pb-2">
+ <ButtonTooltip title={t("notebookSite.fit")}><Button variant="outline" size="sm" onClick={() => { graphRef.current?.zoomToFit({ maxScale: 1, padding: 28 }); graphRef.current?.centerContent(); }}>{t("notebookSite.fit")}</Button></ButtonTooltip>
+ <ButtonTooltip title={t(fullscreen ? "notebookSite.exitFullscreen" : "notebookSite.fullscreen")}><Button variant="outline" size="sm" aria-pressed={fullscreen} onClick={() => setFullscreen((value) => !value)}>{t(fullscreen ? "notebookSite.exitFullscreen" : "notebookSite.fullscreen")}</Button></ButtonTooltip>
+ </div>}
<div
aria-label={diagramTitle(diagram, locale)}
className="edgeever-x6-diagram"
diff --git a/apps/web/src/components/dialogs/ShareMemoDialog.tsx b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
index cd14049b..4c5b78f0 100644
--- a/apps/web/src/components/dialogs/ShareMemoDialog.tsx
+++ b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
@@ -11,6 +11,7 @@ import { ShareQrCode } from "./ShareQrCode";
import { SHARE_DIALOG_PRIMARY_BUTTON_CLASS_NAME, SHARE_DIALOG_WIDTH_CLASS_NAME } from "./share-dialog-layout";
import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
import { copyTextToClipboard } from "@/lib/clipboard";
+import { MemoNotebookSites } from "../MemoNotebookSites";
export const getPublicShareUrl = (token: string) => {
const baseUrl = getConfiguredDesktopApiBaseUrl() || window.location.origin;
@@ -35,7 +36,6 @@ export const ShareMemoDialog = ({
const [copyTarget, setCopyTarget] = useState<"link" | "password" | "both">("link");
const copyResetTimerRef = useRef<number | null>(null);
const dialogContentRef = useRef<HTMLDivElement>(null);
- const autoCreateAttemptRef = useRef<string | null>(null);
const queryKey = memoShareQueryKey(memoId);
const shareQuery = useQuery({
queryKey,
@@ -60,11 +60,10 @@ export const ShareMemoDialog = ({
},
});
const revokeMutation = useMutation({
- mutationFn: () => api.revokeMemoShare(memoId),
- onSuccess: () => {
- queryClient.setQueryData(queryKey, { share: null });
+ mutationFn: (targetMemoId: string) => api.revokeMemoShare(targetMemoId),
+ onSuccess: (_, targetMemoId) => {
+ queryClient.setQueryData(memoShareQueryKey(targetMemoId), { share: null });
void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });
- onOpenChange(false);
},
});
useEffect(() => {
@@ -85,20 +84,6 @@ export const ShareMemoDialog = ({
const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.isPending || revokeMutation.isPending;
const error = shareQuery.error || createMutation.error || passwordMutation.error || revokeMutation.error;
- useEffect(() => {
- if (!open) {
- autoCreateAttemptRef.current = null;
- return;
- }
- // Wait for a successful read: a failed lookup must not enable public access.
- // Attempt once per opening, including under StrictMode and after refetches.
- if (shareQuery.isSuccess && !shareQuery.isFetching && !share &&
- !revokeMutation.isSuccess && autoCreateAttemptRef.current !== memoId) {
- autoCreateAttemptRef.current = memoId;
- createMutation.mutate();
- }
- }, [open, memoId, shareQuery.isSuccess, shareQuery.isFetching, share, revokeMutation.isSuccess, createMutation.mutate]);
-
const markCopied = (target: "link" | "password" | "both", copied: boolean) => {
setCopyTarget(target);
setCopyState(copied ? "copied" : "error");
@@ -118,7 +103,7 @@ export const ShareMemoDialog = ({
<DialogContent
ref={dialogContentRef}
aria-describedby={undefined}
- className={`${SHARE_DIALOG_WIDTH_CLASS_NAME} space-y-4`}
+ className={`${SHARE_DIALOG_WIDTH_CLASS_NAME} max-h-[85dvh] space-y-4 overflow-y-auto`}
onOpenAutoFocus={(event) => {
event.preventDefault();
dialogContentRef.current?.focus({ preventScroll: true });
@@ -131,7 +116,9 @@ export const ShareMemoDialog = ({
</DialogTitle>
</DialogHeader>
- {shareQuery.isLoading || (!share && !error) ? (
+ <MemoNotebookSites key={memoId} memoId={memoId} />
+ <h2 className="text-sm font-semibold">{t("sharing.individual")}</h2>
+ {shareQuery.isLoading ? (
<div className="flex min-h-20 items-center justify-center text-slate-500" role="status">
<LoaderCircle className="h-5 w-5 animate-spin" aria-label={t("sharing.publicLoading")} />
</div>
@@ -180,7 +167,7 @@ export const ShareMemoDialog = ({
)}
<div className="flex items-center justify-between pt-2">
- <Button variant="danger" disabled={isWorking} onClick={() => revokeMutation.mutate()}>
+ <Button variant="danger" disabled={isWorking} onClick={() => revokeMutation.mutate(memoId, { onSuccess: () => onOpenChange(false) })}>
<Trash2 className="h-4 w-4" />
{t("sharing.revoke")}
</Button>
@@ -201,7 +188,7 @@ export const ShareMemoDialog = ({
}}
>
{createMutation.isPending ? <LoaderCircle className="h-4 w-4 animate-spin" /> : null}
- {t("sharing.retry")}
+ {t(shareQuery.isError ? "sharing.retry" : "sharing.createIndividual")}
</Button>
)}
{error ? <p className="text-xs leading-5 text-rose-600" role="alert">{t("sharing.error")}</p> : null}
diff --git a/apps/web/src/components/dialogs/ShareNotebookDialog.tsx b/apps/web/src/components/dialogs/ShareNotebookDialog.tsx
index 6d6bee26..40b21757 100644
--- a/apps/web/src/components/dialogs/ShareNotebookDialog.tsx
+++ b/apps/web/src/components/dialogs/ShareNotebookDialog.tsx
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Check, Copy, ExternalLink, LoaderCircle, Share2, Trash2 } from "lucide-react";
+import { Check, ChevronDown, Copy, ExternalLink, LoaderCircle, Settings2, Share2, Trash2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router";
@@ -15,11 +15,13 @@ import { SharePasswordControls } from "./SharePasswordControls";
import { ShareQrCode } from "./ShareQrCode";
import { SHARE_DIALOG_PRIMARY_BUTTON_CLASS_NAME, SHARE_DIALOG_WIDTH_CLASS_NAME } from "./share-dialog-layout";
import { Input } from "@/components/ui/input";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { NotebookSiteSettings } from "../NotebookSiteSettings";
import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
import { copyTextToClipboard } from "@/lib/clipboard";
-export const getPublicNotebookShareUrl = (token: string) =>
- `${(getConfiguredDesktopApiBaseUrl() || window.location.origin).replace(/\/$/, "")}/share/notebook/${encodeURIComponent(token)}`;
+export const getPublicNotebookShareUrl = (token: string, slug?: string | null) =>
+ `${(getConfiguredDesktopApiBaseUrl() || window.location.origin).replace(/\/$/, "")}${slug ? `/s/${encodeURIComponent(slug)}` : `/share/notebook/${encodeURIComponent(token)}`}`;
export const ShareNotebookDialog = ({
notebookId,
@@ -100,7 +102,8 @@ export const ShareNotebookDialog = ({
const revealedPassword = share?.passwordProtected ? share.password ?? "" : "";
- const shareUrl = share ? getPublicNotebookShareUrl(share.token) : "";
+ const shareUrl = share ? getPublicNotebookShareUrl(share.token, share.siteSlug) : "";
+ const sitePath = `/notebooks/${encodeURIComponent(notebookId)}/site`;
const busy = query.isFetching || create.isPending || revoke.isPending || passwordMutation.isPending;
const failed = query.isError || create.isError || revoke.isError || passwordMutation.isError;
const hasPassword = Boolean(share?.passwordProtected && revealedPassword);
@@ -122,7 +125,7 @@ export const ShareNotebookDialog = ({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
ref={dialogContentRef}
- className={`${SHARE_DIALOG_WIDTH_CLASS_NAME} space-y-4`}
+ className={`${SHARE_DIALOG_WIDTH_CLASS_NAME} max-h-[90dvh] overflow-y-auto space-y-4`}
onOpenAutoFocus={(event) => {
event.preventDefault();
dialogContentRef.current?.focus({ preventScroll: true });
@@ -131,7 +134,7 @@ export const ShareNotebookDialog = ({
<DialogHeader className="space-y-1.5 text-left">
<DialogTitle className="flex items-center gap-2 text-base font-semibold">
<Share2 className="h-5 w-5 text-slate-700" />
- {t(share ? "sharing.manage" : inherited ? "sharing.notebookInheritedAction" : "sharing.notebookTitle")}
+ {t("sharing.notebookTitle")}
</DialogTitle>
<DialogDescription className="text-xs leading-5 text-slate-500">
<span className="font-medium text-slate-800">{notebookName}</span>
@@ -189,6 +192,22 @@ export const ShareNotebookDialog = ({
{share.passwordProtected ? null : (
<ShareQrCode key={`qr-${share.token}`} url={shareUrl} hint={t("sharing.qrCodeNotebookHint")} />
)}
+ {location.pathname !== sitePath && <Collapsible key={`site-settings-${share.token}`}>
+ <CollapsibleTrigger asChild>
+ <Button type="button" variant="outline" className="group w-full justify-between">
+ <span className="flex items-center gap-2"><Settings2 className="h-4 w-4" />{t("notebookSite.advancedSettings")}</span>
+ <ChevronDown className="h-4 w-4 transition-transform group-data-[state=open]:rotate-180" />
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent forceMount className="pt-4 data-[state=closed]:hidden">
+ <NotebookSiteSettings
+ key={`${share.token}-${share.passwordProtected}`}
+ notebookId={notebookId}
+ share={share}
+ onSaved={(data) => { queryClient.setQueryData(queryKey, data); void invalidate(); }}
+ />
+ </CollapsibleContent>
+ </Collapsible>}
<div className="flex items-center justify-between pt-2">
<Button
diff --git a/apps/web/src/components/notebook-site.css b/apps/web/src/components/notebook-site.css
new file mode 100644
index 00000000..a0994f99
--- /dev/null
+++ b/apps/web/src/components/notebook-site.css
@@ -0,0 +1,7 @@
+.edgeever-notebook-site .edgeever-public-share { position: relative; }
+.edgeever-notebook-site .edgeever-notebook-code pre { margin: 0; border: 0; border-radius: 0; overflow-x: auto; padding: 1rem; }
+.edgeever-notebook-site .tiptap img { cursor: zoom-in; }
+.edgeever-notebook-site .tiptap img:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
+html:has(.edgeever-notebook-site) body,
+html:has(.edgeever-notebook-site) #root { overflow: visible; }
+html:has(.edgeever-notebook-site) body.yarl__no_scroll { overflow: hidden; }
diff --git a/apps/web/src/components/settings/NotebookShareManagement.tsx b/apps/web/src/components/settings/NotebookShareManagement.tsx
index 673c90f1..a179c984 100644
--- a/apps/web/src/components/settings/NotebookShareManagement.tsx
+++ b/apps/web/src/components/settings/NotebookShareManagement.tsx
@@ -135,7 +135,7 @@ export const NotebookShareManagement = ({
{share.notebookName}
</span>
<ShareManagementActions
- onOpen={() => window.open(getPublicNotebookShareUrl(share.token), "_blank", "noopener,noreferrer")}
+ onOpen={() => window.open(getPublicNotebookShareUrl(share.token, share.siteSlug), "_blank", "noopener,noreferrer")}
onManage={() => setManaged(share)}
/>
</div>
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index b7ed2303..a4a86017 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -197,6 +197,7 @@ export default defineConfig({
{
urlPattern: ({ request, url }) =>
request.mode === "navigate" &&
+ !/^\/(?:share\/notebook|s)\//.test(url.pathname) &&
!["/mobile-edit.html", "/note-print.html", "/tiptap-ime-test.html"].includes(url.pathname),
handler: "NetworkFirst",
options: {
diff --git a/docs/changes/2026-10-21-public-notebook-site.md b/docs/changes/2026-10-21-public-notebook-site.md
new file mode 100644
index 00000000..62121ff4
--- /dev/null
+++ b/docs/changes/2026-10-21-public-notebook-site.md
@@ -0,0 +1,76 @@
+# Issue 591 public notebook site implementation checklist
+
+[简体中文](2026-10-21-public-notebook-site.zh-CN.md)
+
+Requirements: [Issue #591](https://github.com/tianma-if/edgeever/issues/591). Design: [site plan](../public-notebook-site-plan.md). Baseline: official `e15792d0`. This document records final behavior, boundaries and acceptance.
+
+## Problem, objective and risk
+
+Public sites need article navigation, body search, per-note exclusion, homepages and presentation settings. Implement R01–R13 with exclusions scoped independently to each share; tags retain classification semantics.
+
+Scope includes public Web reading, author sharing, shared API/client types, migration 0072, and Cloudflare/self-hosted page entries. The worst outcome is disclosure of excluded or password-protected content. After exclusions are enabled, rollback must retain filtering or first revoke affected shares; an older server that ignores the exclusion table is unsafe.
+
+## Allowed behavior and acceptance
+
+| ID | Allowed behavior | Acceptance |
+| --- | --- | --- |
+| C01 | Add the next migration: nullable share `site_slug`, valid-object JSON defaulting to `{}`, and case-insensitive alias uniqueness. Add an exclusion relation with two foreign keys, composite primary key, and physical-delete cascades. Legacy shares start without exclusions. | Upgrade old data with real tokens/passwords, read/unlock existing shares, and verify defaults, collisions, and cascades. |
+| C02 | Share settings expose alias, homepage, HTTPS logo, HTTPS header links, plain-text footer, indexing, and existing/title ordering. Accept only the six settings keys; merged JSON is at most 16 KiB. Empty aliases clear; others normalize to lowercase letters/digits/hyphens. Reject invalid URLs, ordering, homepages, and unknown keys. Explicit homepages must be visible; invalid stored references fall back on reads. | API management and real UI saves followed by anonymous readback, invalid inputs, partial writes, and invalidated homepages. |
+| C03 | Authors can paginate exclusions and exclude/restore notes. Operations require user identity and an active share in the current workspace; setting an exclusion also requires a live subtree note, while restoring deletes only this share's relation. Both operations are idempotent. Moves/soft deletion retain exclusions; restored notes remain excluded. Recreated shares do not inherit exclusions. | Actual Hono routes covering authorization, independent child shares, moves/restores, deletion, and revocation. |
+| C04 | Directory, article, resources, link resolution, search, preview, homepage, and metadata share live-scope/exclusion checks. Tags remain classification/search metadata. Filter before pagination using existing FTS, Chinese substring matching, and pagination limits; return body excerpts/highlights. Preview returns only visible note titles and existing short excerpts. | API-to-database/resource readback covering disclosure, Chinese/body hits, pagination, combined tags, preview, and password gates. |
+| C05 | Visitors get a shortcut search dialog, highlights/excerpts, tag filtering, pagination, and retry feedback. Keep directory access alongside custom homepages. Apply natural title/number ordering consistently to navigation, contents, and previous/next. | Real author-to-anonymous-page flow. |
+| C06 | Add H1–H4 outlines, duplicate-safe anchors, scrollspy, smooth navigation, and fragment reloads. Support mobile drawers, keyboards, and reduced motion. | Long-article anchors, reload, scroll, mobile viewport, and keyboard checks. |
+| C07 | Notebook sites reuse local light/dark/system preference across article/code/diagrams. Code shows language, full-source copying, and collapse; images open a lightbox on click with gesture zoom; reuse diagram fitting/fullscreen. | Actual article/code/image/diagram interactions; preserve individual-note sharing behavior. |
+| C08 | Internal links show on-demand HoverCard previews on hover/focus. Use Tooltip instead of native title. Invalid/excluded targets disclose no titles/excerpts or independent-share bypasses. | Actual hover/focus, rejected APIs, and filtered links. |
+| C09 | Logo failures fall back to the current icon; render header links/footer. `/s/:slug/:memoId?` resolves only the token and reuses canonical links, password cookies, and revocation. | Canonical/alias links, unlocking, collisions, and invalidated access. |
+| C10 | Indexing defaults off and requires an alias URL, no password and explicit opt-in. Token pages always retain the complete shared noindex policy and canonical points to the alias when configured. Render server HTML head/canonical/OG/Twitter; protected pages remain generic. Invalid/excluded articles return unavailable status and the complete noindex policy. The client preserves server robots while identity, directory or the selected article is pending, and uses the complete shared policy after errors or when indexing is disabled. Preserve private/no-store and no-referrer; JSON APIs always remain noindex. Setting/rotating passwords disables indexing; clearing does not re-enable it. Reject enabling indexing with a password. | Raw HTML/headers for alias and Token roots/articles, canonical links, escaping, password changes and privacy; browser regression with delayed successful/failed articles and full noindex readback. The shared page service serves Cloudflare/Docker entries. |
+
+
+| ID | Author interaction and supporting APIs | Acceptance |
+| --- | --- | --- |
+| C11 | Notebook context/more menus consistently use Share notebook; directly shared notebooks keep their more button visible. Reopening reuses the token; settings retain the aggregate share entry. | Create, close and reopen from the original location; check token, copying and existing aliases. |
+| C12, C19, C23 | Site settings expand in Advanced settings within the share dialog, collapsed by default and preserving unsaved input across collapse. Reuse one settings form; `/notebooks/:notebookId/site` remains directly accessible, while normal sharing stays in place. No second content-management list. | Desktop/390px expansion, retained edits, save-to-anonymous readback, direct access and login boundaries; rerenders retain one password control. |
+| C13 | A separate homepage picker selects only notes visible in the current site; selection still requires saving. Invalid stored references show directory fallback; saving unrelated fields preserves an unchanged reference, allowing restoration when visible again. State-read failures show an error and retry. | Select/save, exclude homepage, save other fields, restore and delete; Escape closes only the picker and returns focus. |
+| C14–C15 | Author `GET /api/v1/notebooks/:id/share/memos` returns IDs, titles, notebook identity, exclusion state and a cursor, without bodies. Require user identity and an active current-workspace share. Filter keywords/state before pagination. Only all/public/excluded are accepted, default all, otherwise 400; limit defaults to 50 within 1–100, UI pages contain 20, ordered by ID cursor. | Chinese/body search, filtering before pagination, cross-page selection, authorization and inactive shares. Replace each page rather than accumulating list DOM. |
+| C16 | `GET /api/v1/memos/:id/notebook-sites` returns only valid direct/ancestor site names, IDs and exclusion states to current-workspace users. It creates no individual share and returns no token or password. | Valid/no sites, independent parent/child sites, moves, deleted ancestors, identity and workspace boundaries. |
+| C17–C18 | The original note dialog and list context menu share per-site controls. Disable writes while pending, update on server confirmation, and retain prior state on failure; reads show retry. Hide empty controls without sites, and omit them for trash/local unsynced notes. Opening the dialog no longer creates an individual link; creation is explicit. Existing links, passwords, copying and revocation remain available. Revocation callbacks affect only the original note. | Original-page exclude/restore and anonymous readback, parent/child independence, consistent entries, failure/retry, explicit individual creation/revocation, delayed revocation, narrow viewports and keyboards. |
+
+## Boundaries retained
+
+- Preserve note content, global state, tag semantics, sync, author hierarchy/order, and access rules for independent note shares and public forms.
+- Preserve upstream in-note heading-link navigation when integrating the shared reader; keep site outlines and single-click image previews. Verify the existing heading-anchor tests and the browser article click path.
+- Preserve existing tokens, password hashes/ciphertext/encryption root, authorization cookie paths and password APIs. Saving settings does not rotate passwords.
+- No manual drag ordering, review/scheduled publication, snapshots, full article SSR, sitemap, uploads or screenshot service. Names derive from root notebooks; descriptions derive from visible excerpts.
+- Reuse existing 30-second refresh, themes and viewers. Add no polling mechanism or event bus, and promise neither retrieval of downloaded content nor immediate removal from external indexes.
+- Cloudflare and self-hosting share business logic with thin runtime entries. Wrangler only adds public-page Worker routing and updates the existing configuration fingerprint; instance binding rules, native runtimes, versions and release workflows remain unchanged. No new dependencies.
+
+## Completion check and validation
+
+R01–R13 and the final behavior above are implemented. Product changes map to this checklist. Main evidence:
+
+| Scope | Completed acceptance |
+| --- | --- |
+| Migration/compatibility | Real old routes and 0001–0071 data upgraded with 0072 retain tokens, password hashes and unlock cookies. Cover alias conflicts, defaults, cascades and share recreation. |
+| Public scope/search | Actual Hono routes and database checks cover workspaces, live subtrees, exclusions, resources, links, homepages, previews, Chinese/body search, tags and pagination; parent exclusions preserve independent child access. |
+| Author to visitor | Homepage/settings UI saves followed by anonymous readback; original-note exclude/restore; invalid-home fallback/restoration, read error/retry and late revocation responses. |
+| Reading | Local long articles cover H1–H4, duplicate headings, fragment reload/scrollspy, code copy/collapse, themes, images and diagrams. Drawers/dialogs fit a 390px viewport without horizontal overflow. |
+| HTML/cache | Local Cloudflare Worker and self-hosted Bun entries verify metadata, canonical URLs, escaping, indexing, passwords and excluded-article 404s. Public pages bypass PWA app-shell caching. C10 regression checks confirm that Token roots/articles keep the complete noindex policy and alias canonical, and delayed successful/failed article requests preserve server robots until completion. |
+| Cloudflare | Independent Worker/D1/R2 deployment; 35 real HTTP checks cover Chinese search, R2, exclusions, parent/child independence, homepages, metadata, passwords and unlock cookies. Browser acceptance covers login, share settings, original-note controls and main reading interactions. |
+
+Reproducible required checks:
+
+```sh
+bun test apps/api/src/notebook-share-routes.test.mjs tests/note-sharing-menu.test.ts packages/shared/src/i18n/catalog.test.mjs apps/web/src/components/dialogs/ShareQrCode.test.mjs
+bun test tests/deployment-entrypoints.test.ts
+bun test apps/web/src/lib/editor-heading-anchor.test.mjs
+bunx playwright test tests/e2e/public-notebook-indexing.spec.ts
+bun run typecheck
+bun run typecheck:mobile
+bun run build:web
+```
+
+These relevant checks passed, together with targeted lint and `git diff --check`. Old-route migration and browser flows are separate acceptance steps; a build or one successful HTTP response does not replace them. Reuse unaffected verification.
+
+C10 corrections are complete: 30 notebook-sharing API tests and 3 browser regressions pass. The browser tests use real sharing APIs and an injected HTML head for Vite's bare app shell; actual local Worker responses also confirm headers, robots and canonical for alias, excluded-article and Token pages. Upstream integration preserves heading-link capture alongside site image controls; 7 existing heading-anchor tests and the browser heading-jump/single-click image flow pass. Changes are limited to metadata policy, reader integration, regression coverage and matching documentation; no data, permission, migration or deployment changes are included.
+
+Remaining limits: CF acceptance uses a separate new database rather than a production upgrade. The self-hosted entry was exercised, but Docker containers, Android/iOS native devices, real search/social crawlers and concurrent writers remain unverified. Articles retain SPA rendering without full SSR or sitemap; indexing outcomes are not guaranteed. The corresponding PR/workflows track merge, CI and release status.
diff --git a/docs/changes/2026-10-21-public-notebook-site.zh-CN.md b/docs/changes/2026-10-21-public-notebook-site.zh-CN.md
new file mode 100644
index 00000000..0fb45579
--- /dev/null
+++ b/docs/changes/2026-10-21-public-notebook-site.zh-CN.md
@@ -0,0 +1,76 @@
+# Issue 591 公开笔记本站点实施清单
+
+[English](2026-10-21-public-notebook-site.md)
+
+需求见 [Issue #591](https://github.com/tianma-if/edgeever/issues/591),设计见[公开站点方案](../public-notebook-site-plan.zh-CN.md)。基线为官方 `e15792d0`。本文记录最终行为、边界与验收方式。
+
+## 问题、目标与风险
+
+公开站点需要长文导航、正文检索、逐篇排除、首页和外观配置。本次覆盖方案R01~R13,逐篇排除独立作用于每个分享,标签保留分类语义。
+
+影响Web公开阅读、作者分享设置、共用API/客户端类型、迁移0072,以及Cloudflare和自托管页面入口。最坏后果是公开被排除或受密码保护的内容。启用排除后,回滚必须保留过滤逻辑,或先撤销受影响分享;不能直接部署忽略排除表的旧服务。
+
+## 允许的行为与验收
+
+| 编号 | 允许的行为变化 | 验收方式 |
+| --- | --- | --- |
+| C01 | 新增递增迁移:分享表增加可空 `site_slug` 和默认 `{}` 的合法对象 JSON;别名按小写唯一。新增只有分享/笔记两个外键的排除表,复合主键,级联物理删除。旧数据默认没有排除项。 | 在旧迁移数据、真实 Token/密码上升级并通过旧分享读取/解锁;验证默认值、别名冲突及级联。 |
+| C02 | 作者分享设置支持别名、首页、HTTPS Logo、HTTPS 页眉外链、纯文本页脚、收录开关和 existing/title 排序。仅接受这六项配置键,合并后的 JSON 不超过 16 KiB;别名为空时清除,否则规范为小写字母/数字/连字符;非法 URL、排序、首页或未知键拒绝。首页只能选当前范围未排除笔记,无效旧引用读取时回退目录。 | API 管理操作及真实界面保存后匿名读回,覆盖非法输入、部分更新和首页失效。 |
+| C03 | 作者可分页查看排除列表并逐篇排除/恢复。操作需用户身份和当前工作区的有效分享;设置排除时还需有效子树笔记,恢复仅删除本分享的关系。排除幂等,恢复幂等;移动/软删除保留关系,返回范围后仍排除;撤销重建不继承。 | 通过实际 Hono 路由检查越权、独立子分享、移动恢复、删除和撤销。 |
+| C04 | 当前分享的目录、正文、附件、链接解析、搜索、预览、首页和元数据共用实时范围及排除检查。标签只用于分类/搜索。搜索先过滤再分页,复用现有 FTS/中文子串和分页约束,返回正文命中摘要及高亮信息。预览仅返回可见笔记标题与现有短摘要。 | API 请求到数据库及资源读取,验证被排除内容无泄漏、中文和正文命中、分页、组合标签、预览与密码门禁。 |
+| C05 | 访客支持搜索弹窗和快捷键、命中高亮/摘要、标签筛选、分页及失败重试;自定义首页与目录入口并存。标题数字自然排序对侧栏、目录和前后篇一致。 | 作者设置到匿名页面的真实操作流程。 |
+| C06 | 公开笔记本站点支持 H1~H4 大纲、重复标题锚点、滚动高亮、平滑定位和刷新定位;移动端抽屉、键盘和减少动态效果设置可用。 | 长文页面锚点、刷新、滚动、移动视口及键盘检查。 |
+| C07 | 笔记本站点复用本机浅色/深色/系统偏好;正文、代码、图表与画板适配。代码展示语言、复制完整源码及折叠;图片单击灯箱和手势缩放;复用画板适应窗口及全屏。 | 实际正文、代码、图片和画板操作;保留单篇分享原行为。 |
+| C08 | 本站内部笔记链接悬停或聚焦时按需预览,复用 HoverCard;提示使用 Tooltip,不增加原生 title。失效/排除目标不给标题摘要,也不跳到独立分享绕过。 | 实际悬停/聚焦、API 拒绝及过滤链接读回。 |
+| C09 | Logo 失败回退原图标;展示页眉外链和页脚。别名 `/s/:slug/:memoId?` 只解析 Token,原 Token 链接可用,共用密码 Cookie 和撤销边界。 | 原链接、别名、密码解锁、别名冲突及失效访问流程。 |
+| C10 | 默认禁止收录;只有别名页面无密码且显式允许时可收录。Token 页面始终使用共用的完整 noindex 策略,已配置别名时 canonical 指向别名。输出服务端 HTML head/canonical/OG/Twitter,密码页面只输出通用信息;无效/排除文章返回不可用状态和完整 noindex 策略。前端在身份、目录或选中文章请求未完成时保留服务端 robots;失败或禁止收录时使用共用的完整策略。页面和 API 保持 private/no-store、no-referrer,JSON API 始终 noindex。设置/重置密码关闭收录,清除密码不重开;有密码时拒绝开启收录。 | 别名和 Token 首页/文章的原始 HTML/响应头、canonical、转义、密码修改及隐私检查;浏览器延迟正文成功/失败回归并读回完整 noindex。共享页面服务经 Cloudflare 与 Docker 入口调用。 |
+
+
+| 编号 | 作者交互及配套接口 | 验收方式 |
+| --- | --- | --- |
+| C11 | 笔记本右键及更多菜单统一使用“分享笔记本”;已直接分享的笔记本更多按钮常显。再次打开复用原Token,个人中心保留汇总入口。 | 创建、关闭、从原位置重开,核对Token、复制及已有别名。 |
+| C12、C19、C23 | 站点配置在分享弹窗的“进阶设置”中展开,默认收起,折叠后保留未保存输入。复用同一设置表单;独立 `/notebooks/:notebookId/site` 路由仍可直接访问,正常分享不跳页。没有第二份内容管理列表。 | 桌面及390px展开/收起、保留编辑、保存后匿名读回、直接访问和登录边界;重复渲染只保留一个密码开关。 |
+| C13 | 首页使用独立选择器,只允许选择当前站点未排除笔记;选择后仍需保存。无效旧引用显示目录回退提示,保存其他设置不删除未修改的原首页引用;恢复可见后原首页可生效。状态读取失败报错并允许重试。 | 选择、保存、排除首页、保存其他配置、恢复及删除首页;Escape只关闭选择器并恢复焦点。 |
+| C14~C15 | 作者 `GET /api/v1/notebooks/:id/share/memos` 返回ID、标题、笔记本、排除状态和游标,不返回正文。需用户身份及当前工作区有效分享;关键词和状态过滤先于分页。状态仅all/public/excluded,省略为all,非法值400;limit默认50、范围1~100,界面每页20条,ID升序游标。 | 中文/正文搜索、过滤后分页、跨页选择、越权和无效分享。页面替换当前页,不累计列表DOM。 |
+| C16 | `GET /api/v1/memos/:id/notebook-sites` 仅向当前工作区用户返回有效笔记的直接/祖先站点名称、ID及排除状态;不创建单篇分享,不返回Token或密码。 | 有效/无站点、独立父子站点、移动、删除祖先、身份及跨工作区检查。 |
+| C17~C18 | 原笔记分享弹窗和列表右键共用逐站点展示开关。写入期间禁用操作,服务端确认后更新,失败保留原状态并反馈;读取失败显示重试。没有所属站点时不显示空控制;回收站和本地未同步笔记不提供操作。打开弹窗不再自动创建单篇链接,必须明确点击创建;已有链接、密码、复制及撤销保留。撤销回调只影响原笔记。 | 原页排除/恢复后匿名读回,父子独立,两个入口状态一致;失败/重试、显式单篇创建/撤销、延迟撤销响应及窄屏/键盘操作。 |
+
+## 保持不变的边界
+
+- 保留笔记内容、全局状态、标签语义、同步协议、作者层级和笔记本顺序,以及独立单篇分享和公开表单的访问规则。
+- 整合共享阅读组件时保留上游文内标题链接跳转,同时保留站点大纲和图片单击预览;通过已有标题锚点测试及浏览器正文点击流程验证。
+- 保留已有Token、密码散列/密文及加密根、授权Cookie路径和密码接口;配置保存不旋转密码。
+- 不增加手动拖拽排序、审核/定时发布、快照、完整正文SSR、sitemap、资产上传或截图生成服务。名称来自根笔记本,描述来自可见内容摘要。
+- 复用现有30秒刷新、主题及查看器;不增加轮询机制或事件总线,不承诺收回已下载内容或即时清除外部索引。
+- Cloudflare与自托管共用业务逻辑,仅适配运行入口。Wrangler只增加公开页面Worker路由并同步现有配置指纹;不改实例绑定规则、原生运行时、版本号或发布工作流,不增加依赖。
+
+## 完成核对与验证
+
+R01~R13及上表最终行为均已有实现,实际产品diff与清单对应。主要验收结果:
+
+| 范围 | 已有验收证据 |
+| --- | --- |
+| 迁移与兼容 | 真实旧路由及0001~0071数据追加0072后,原Token、密码散列和解锁Cookie仍可使用;覆盖别名冲突、默认值、级联及撤销重建。 |
+| 公开边界与检索 | 实际Hono路由和数据库验证工作区、实时子树、排除、资源、链接、首页、预览、中文/正文搜索、标签与分页;父站点排除不影响独立子站点。 |
+| 作者到访客 | 界面选择首页及保存配置后匿名读回;原笔记开关排除/恢复;无效首页回退与恢复、读取失败/重试及迟到撤销响应均验证。 |
+| 阅读交互 | 本地长文覆盖H1~H4、重复标题、刷新定位、滚动高亮、代码复制/折叠、主题、图片及画板操作;390px抽屉和弹窗无横向溢出。 |
+| HTML与缓存 | Cloudflare本地Worker及自托管Bun入口验证元数据、canonical、转义、收录、密码及排除文章404。公开页绕过PWA应用壳缓存。C10回归确认Token首页/文章保持完整noindex及别名canonical;正文成功/失败请求延迟期间保留服务端robots。 |
+| Cloudflare | 独立Worker/D1/R2实例部署成功;35项真实HTTP检查覆盖中文搜索、R2资源、排除、父子独立、首页、元数据、密码门禁及解锁Cookie;浏览器完成登录、分享配置、原页开关和主要阅读流程。 |
+
+可复现的必要检查:
+
+```sh
+bun test apps/api/src/notebook-share-routes.test.mjs tests/note-sharing-menu.test.ts packages/shared/src/i18n/catalog.test.mjs apps/web/src/components/dialogs/ShareQrCode.test.mjs
+bun test tests/deployment-entrypoints.test.ts
+bun test apps/web/src/lib/editor-heading-anchor.test.mjs
+bunx playwright test tests/e2e/public-notebook-indexing.spec.ts
+bun run typecheck
+bun run typecheck:mobile
+bun run build:web
+```
+
+上述相关检查已通过;改动文件定向lint及 `git diff --check` 通过。旧路由迁移和浏览器验收另按上表执行,不能用构建或单个HTTP成功代替。未受影响的验证直接复用。
+
+C10修正已完成:30项笔记本分享API测试和3项浏览器回归通过。浏览器测试使用真实分享API,为Vite的空白应用壳注入HTML head;实际本地Worker响应另行确认别名、排除文章及Token页面的响应头、robots和canonical。与上游整合时保留标题链接捕获及站点图片操作;7项已有标题锚点测试、浏览器标题跳转和单击图片流程通过。变更仅涉及元数据策略、阅读组件整合、对应回归及配套文档;没有数据、权限、迁移或部署变更。
+
+剩余限制:CF是独立新库验收,没有执行生产实例升级;自托管入口已验证,但Docker容器、Android/iOS原生真机、真实搜索/社交爬虫及并发竞争尚未验收。正文继续由SPA渲染,没有完整SSR或sitemap,不能保证搜索收录结果。发布、合并和CI状态以对应PR及工作流为准。
diff --git a/docs/public-notebook-site-plan-ablation.json b/docs/public-notebook-site-plan-ablation.json
new file mode 100644
index 00000000..29353975
--- /dev/null
+++ b/docs/public-notebook-site-plan-ablation.json
@@ -0,0 +1,507 @@
+{
+ "generatedAt": "2026-10-20T08:34:12.642Z",
+ "baselineCommit": "d966052002889729c6850732f2baeb75c342a2e6",
+ "environment": {
+ "bun": "1.3.14",
+ "sqlite": "3.54.0"
+ },
+ "method": "Actual migrations plus disposable SQLite/data models. Decision rows distinguish executed evidence, source facts, issue alternatives, external documentation, and judgment. Not a user experiment, runtime implementation, browser acceptance, or crawler test.",
+ "migrations": [
+ "migrations/0001_initial.sql",
+ "migrations/0002_auth.sql",
+ "migrations/0003_search_and_trash.sql",
+ "migrations/0004_memo_revision_metadata.sql",
+ "migrations/0005_default_uncategorized_notebook.sql",
+ "migrations/0006_default_notebook_set.sql",
+ "migrations/0007_api_token_value.sql",
+ "migrations/0009_drop_profile_snapshots.sql",
+ "migrations/0010_restore_default_inbox_notebook.sql",
+ "migrations/0011_memo_edit_sessions.sql",
+ "migrations/0012_multi_user_workspaces.sql",
+ "migrations/0013_mobile_sync_changes.sql",
+ "migrations/0014_repair_seed_memo_content_hash.sql",
+ "migrations/0015_auth_session_devices.sql",
+ "migrations/0016_templates.sql",
+ "migrations/0017_seed_default_templates.sql",
+ "migrations/0018_fix_seed_template_markdown.sql",
+ "migrations/0019_auth_session_metadata.sql",
+ "migrations/0020_auth_login_attempts.sql",
+ "migrations/0021_memo_import_sources.sql",
+ "migrations/0022_memo_shares.sql",
+ "migrations/0023_instance_object_storage.sql",
+ "migrations/0024_ai_model_configs.sql",
+ "migrations/0025_ai_providers_and_models.sql",
+ "migrations/0026_ai_prompt_templates.sql",
+ "migrations/0027_seed_default_ai_prompts.sql",
+ "migrations/0028_seed_remaining_ai_prompts.sql",
+ "migrations/0029_ai_prompt_behavior_and_localization.sql",
+ "migrations/0030_unify_editable_note_templates.sql",
+ "migrations/0031_limit_default_memo_templates.sql",
+ "migrations/0032_limit_default_ai_prompts.sql",
+ "migrations/0033_ai_tag_suggestion_prompt.sql",
+ "migrations/0034_search_documents_and_maintenance_leases.sql",
+ "migrations/0035_normalized_memo_tags.sql",
+ "migrations/0036_resource_multipart_uploads.sql",
+ "migrations/0037_scheduled_plugin_tasks.sql",
+ "migrations/0038_plugin_owned_schedules.sql",
+ "migrations/0039_scheduled_task_run_retention.sql",
+ "migrations/0040_companion_memory.sql",
+ "migrations/0041_companion_actions.sql",
+ "migrations/0042_companion_tool_execution.sql",
+ "migrations/0043_companion_discovery.sql",
+ "migrations/0044_companion_discovery_input_hash.sql",
+ "migrations/0045_companion_learning.sql",
+ "migrations/0046_restore_workspace_inbox_identity.sql",
+ "migrations/0047_replace_social_ai_prompts.sql",
+ "migrations/0048_workspace_extensions.sql",
+ "migrations/0049_companion_agent_run.sql",
+ "migrations/0050_companion_process_text.sql",
+ "migrations/0051_companion_agent_session.sql",
+ "migrations/0052_memo_share_passwords.sql",
+ "migrations/0053_collapse_duplicate_inbox_notebooks.sql",
+ "migrations/0054_user_note_body_font.sql",
+ "migrations/0055_table_forms.sql",
+ "migrations/0056_user_note_prose.sql",
+ "migrations/0057_companion_attachments.sql",
+ "migrations/0058_retire_emerald_note_palette.sql",
+ "migrations/0059_retire_custom_note_palette.sql",
+ "migrations/0060_ai_transcription_settings.sql",
+ "migrations/0061_video_transcript_jobs.sql",
+ "migrations/0062_ai_transcription_providers.sql",
+ "migrations/0063_ai_transcription_provider_standard.sql",
+ "migrations/0064_retire_video_transcription.sql",
+ "migrations/0065_restore_speech_transcription.sql",
+ "migrations/0066_poster_render_jobs.sql",
+ "migrations/0067_notebook_shares.sql",
+ "migrations/0068_notebook_share_passwords.sql",
+ "migrations/0069_share_password_encryption.sql",
+ "migrations/0070_workspace_seed_localization.sql",
+ "migrations/0071_fix_welcome_memo_markdown.sql"
+ ],
+ "executedChecks": [
+ "zero_new_tables_two_added_columns",
+ "old_share_defaults_unchanged",
+ "default_tag_policy_does_not_hide_old_drafts",
+ "tag_exclusion_filters_directory_note_and_resource",
+ "independent_child_share_keeps_its_own_tag_policy",
+ "english_body_search_filters_before_pagination",
+ "chinese_body_substring_and_tag_filter",
+ "title_natural_order_needs_no_rank_rows",
+ "atomic_settings_patch_preserves_other_fields_and_password",
+ "invalid_homepage_write_rejected",
+ "homepage_validated_against_merged_tag_policy",
+ "unknown_item_overrides_are_not_silently_supported",
+ "json_homepage_move_falls_back_without_foreign_key",
+ "json_homepage_delete_falls_back_without_cleanup_job",
+ "cross_workspace_and_outside_notes_denied",
+ "deleted_ancestor_denies_descendants",
+ "alias_database_uniqueness_is_case_insensitive",
+ "alias_resolution_only_returns_identity_not_protected_metadata",
+ "password_overrides_indexing_flag",
+ "explicit_unprotected_indexing_can_be_enabled",
+ "clearing_password_does_not_reenable_indexing",
+ "site_title_derived_from_existing_root_name",
+ "server_metadata_model_escapes_untrusted_text",
+ "metadata_size_independent_of_note_count",
+ "on_demand_preview_avoids_directory_and_full_body_payload",
+ "revocation_denies_token_and_alias_paths"
+ ],
+ "executedCheckCount": 26,
+ "expectedCounterexamples": [
+ {
+ "ablation": "remove_server_tag_filter",
+ "observed": "hidden_note_returned",
+ "criterionViolated": "exclude_drafts"
+ },
+ {
+ "ablation": "keep_title_only_search",
+ "observed": "body_only_matches_lost",
+ "criterionViolated": "full_text_search"
+ },
+ {
+ "ablation": "filter_after_pagination",
+ "observed": "empty_page_despite_visible_matches",
+ "criterionViolated": "complete_visible_search_page"
+ }
+ ],
+ "issueCoverage": {
+ "requirementGroups": 13,
+ "exclusionAlternative": "tags",
+ "orderingAlternative": "title/number",
+ "removedAdvancedBehaviors": [
+ "per-site arbitrary note overrides",
+ "site-specific drag ordering",
+ "independent site title/description",
+ "non-JS full article HTML",
+ "sitemap discovery"
+ ],
+ "userUsabilityMeasured": false
+ },
+ "persistence": {
+ "newTables": 0,
+ "newColumns": [
+ "site_slug",
+ "site_settings_json"
+ ],
+ "settingsBudgetBytes": 16384,
+ "configurationSizes": [
+ {
+ "noteCount": 100,
+ "settingsBytes": 256
+ },
+ {
+ "noteCount": 1000,
+ "settingsBytes": 256
+ },
+ {
+ "noteCount": 10000,
+ "settingsBytes": 256
+ },
+ {
+ "noteCount": 50000,
+ "settingsBytes": 256
+ }
+ ]
+ },
+ "previewPayloads": [
+ {
+ "noteCount": 100,
+ "directoryBytes": 12293,
+ "directoryWithPreviewBytes": 22893,
+ "onePreviewBytes": 125,
+ "fullArticleBytes": 210140
+ },
+ {
+ "noteCount": 1000,
+ "directoryBytes": 123894,
+ "directoryWithPreviewBytes": 229894,
+ "onePreviewBytes": 125,
+ "fullArticleBytes": 210140
+ },
+ {
+ "noteCount": 10000,
+ "directoryBytes": 1248895,
+ "directoryWithPreviewBytes": 2308895,
+ "onePreviewBytes": 125,
+ "fullArticleBytes": 210140
+ }
+ ],
+ "reusedPriorEvidence": {
+ "file": "docs/public-notebook-site-schema-ablation.json",
+ "baselineCommit": "d966052002889729c6850732f2baeb75c342a2e6",
+ "commonFunctionalScenarios": 19,
+ "benchmarkGroups": 12,
+ "rerun": false,
+ "limitation": "Prior override-table necessity was conditional on retaining per-item manual state; that premise is removed here."
+ },
+ "decisions": [
+ {
+ "id": "R01",
+ "subject": "article_toc",
+ "decision": "keep",
+ "evidenceType": "issue_requirement",
+ "rationale": "H1-H4 navigation and scrollspy are explicit requirements."
+ },
+ {
+ "id": "R02",
+ "subject": "light_dark_system",
+ "decision": "keep_reuse",
+ "evidenceType": "source_inspection",
+ "rationale": "Reuse ThemeProvider and edgeever.theme; no second preference system."
+ },
+ {
+ "id": "R03",
+ "subject": "code_copy_language_collapse",
+ "decision": "keep_reuse",
+ "evidenceType": "issue_and_source",
+ "rationale": "Copy/highlighting already exist; add only missing labels and collapse controls."
+ },
+ {
+ "id": "R04",
+ "subject": "internal_hover_preview",
+ "decision": "keep",
+ "evidenceType": "payload_measurement",
+ "rationale": "Keep a bounded on-demand preview; do not inflate every directory item or fetch complete articles."
+ },
+ {
+ "id": "R05",
+ "subject": "image_and_diagram_controls",
+ "decision": "keep_reuse",
+ "evidenceType": "issue_and_source",
+ "rationale": "Reuse lightbox/zoom/fit; add single-click entry and fullscreen, not another viewer."
+ },
+ {
+ "id": "R06",
+ "subject": "body_full_text_search",
+ "decision": "keep_reuse",
+ "evidenceType": "executed_counterexample",
+ "rationale": "Title-only search loses body matches; reuse existing FTS and Chinese fallback."
+ },
+ {
+ "id": "R07",
+ "subject": "tag_filter",
+ "decision": "keep",
+ "evidenceType": "executed_model",
+ "rationale": "Use the same search endpoint with a tag predicate; no global tag cloud/count API."
+ },
+ {
+ "id": "R08",
+ "subject": "custom_homepage",
+ "decision": "keep",
+ "evidenceType": "executed_model",
+ "rationale": "One JSON homeMemoId checked against live visibility; invalid targets fall back to directory."
+ },
+ {
+ "id": "R09",
+ "subject": "draft_exclusion",
+ "decision": "choose_tag_policy",
+ "evidenceType": "issue_alternative_and_executed_model",
+ "rationale": "The issue permits draft state OR tags. Use existing note tags plus site excludedTags."
+ },
+ {
+ "id": "R10",
+ "subject": "custom_ordering",
+ "decision": "choose_title_order",
+ "evidenceType": "issue_alternative_and_executed_model",
+ "rationale": "The issue permits manual OR title/number order. Use existing/title modes and numeric title sorting."
+ },
+ {
+ "id": "R11",
+ "subject": "custom_slug",
+ "decision": "keep",
+ "evidenceType": "executed_model",
+ "rationale": "Keep a unique slug and identity resolver; do not alter token-scoped unlock cookies."
+ },
+ {
+ "id": "R12",
+ "subject": "logo_header_footer",
+ "decision": "keep",
+ "evidenceType": "issue_requirement",
+ "rationale": "Keep structured display settings and HTTPS logo URL; no independent upload pipeline."
+ },
+ {
+ "id": "R13",
+ "subject": "seo_and_social_cards",
+ "decision": "keep_metadata",
+ "evidenceType": "external_primary_documentation",
+ "rationale": "Keep server HTML head and indexing controls; crawler acceptance remains unverified."
+ },
+ {
+ "id": "D01",
+ "subject": "two_or_one_item_override_tables",
+ "decision": "remove_for_selected_scope",
+ "evidenceType": "issue_alternatives_and_executed_model",
+ "rationale": "No per-item state remains when exclusion uses tags and sorting uses titles."
+ },
+ {
+ "id": "D02",
+ "subject": "independent_site_title",
+ "decision": "derive",
+ "evidenceType": "source_and_design_judgment",
+ "rationale": "Use root notebook name; independent override is an additional product choice."
+ },
+ {
+ "id": "D03",
+ "subject": "independent_site_description",
+ "decision": "derive",
+ "evidenceType": "source_and_design_judgment",
+ "rationale": "Use visible homepage or article excerpt; no separate description field."
+ },
+ {
+ "id": "D04",
+ "subject": "site_slug_column",
+ "decision": "keep",
+ "evidenceType": "executed_model",
+ "rationale": "One column with a case-insensitive unique index keeps lookup and uniqueness simple."
+ },
+ {
+ "id": "D05",
+ "subject": "home_memo_id_column",
+ "decision": "move_to_settings_json",
+ "evidenceType": "executed_model",
+ "rationale": "Live validation already handles moves and soft deletion; a single stale pointer is bounded."
+ },
+ {
+ "id": "D06",
+ "subject": "logo_url_column",
+ "decision": "move_to_settings_json",
+ "evidenceType": "executed_model",
+ "rationale": "Bounded display metadata does not need an independent SQL column."
+ },
+ {
+ "id": "D07",
+ "subject": "header_links_column",
+ "decision": "move_to_settings_json",
+ "evidenceType": "executed_model",
+ "rationale": "Preserve structured links in the bounded settings object."
+ },
+ {
+ "id": "D08",
+ "subject": "footer_text_column",
+ "decision": "move_to_settings_json",
+ "evidenceType": "executed_model",
+ "rationale": "Preserve footer text in settings."
+ },
+ {
+ "id": "D09",
+ "subject": "allow_indexing_column",
+ "decision": "move_to_settings_json",
+ "evidenceType": "executed_model",
+ "rationale": "Effective indexing checks the JSON flag and current password; setting passwords clears the flag."
+ },
+ {
+ "id": "D10",
+ "subject": "excluded_tags_column",
+ "decision": "move_to_settings_json",
+ "evidenceType": "executed_model",
+ "rationale": "JSON tags are filtered against existing memo_tags before pagination."
+ },
+ {
+ "id": "D11",
+ "subject": "two_sort_mode_columns",
+ "decision": "one_json_sort_mode",
+ "evidenceType": "executed_model",
+ "rationale": "Use one existing/title mode for the site; no separate note/chapter controls."
+ },
+ {
+ "id": "A01",
+ "subject": "separate_site_get",
+ "decision": "reuse_existing_get",
+ "evidenceType": "source_inspection",
+ "rationale": "Extend authenticated share GET with owner settings."
+ },
+ {
+ "id": "A02",
+ "subject": "site_settings_patch",
+ "decision": "keep_separate",
+ "evidenceType": "source_and_executed_model",
+ "rationale": "Preserve existing password PATCH semantics; config-only writes do not rotate passwords."
+ },
+ {
+ "id": "A03",
+ "subject": "content_management_get",
+ "decision": "remove",
+ "evidenceType": "selected_scope",
+ "rationale": "No site-specific item editor is needed."
+ },
+ {
+ "id": "A04",
+ "subject": "per_note_exclusion_patch",
+ "decision": "remove",
+ "evidenceType": "selected_scope",
+ "rationale": "Use existing note tag editing."
+ },
+ {
+ "id": "A05",
+ "subject": "manual_order_put",
+ "decision": "remove",
+ "evidenceType": "selected_scope",
+ "rationale": "Title order requires no rank persistence or drag/drop command."
+ },
+ {
+ "id": "A06",
+ "subject": "public_search",
+ "decision": "keep",
+ "evidenceType": "executed_model",
+ "rationale": "Needed for body/tag search with server visibility and pagination."
+ },
+ {
+ "id": "A07",
+ "subject": "public_preview",
+ "decision": "keep",
+ "evidenceType": "payload_measurement",
+ "rationale": "Keeps preview responses bounded and avoids eager directory growth."
+ },
+ {
+ "id": "A08",
+ "subject": "alias_resolver",
+ "decision": "make_explicit",
+ "evidenceType": "source_and_executed_model",
+ "rationale": "Return token identity only so SPA aliases use existing canonical API/cookie paths."
+ },
+ {
+ "id": "I01",
+ "subject": "complete_article_ssr",
+ "decision": "defer",
+ "evidenceType": "external_primary_documentation_and_judgment",
+ "rationale": "Keep SPA article rendering and server head; non-JS full-body crawlability is not retained."
+ },
+ {
+ "id": "I02",
+ "subject": "sitemap",
+ "decision": "defer",
+ "evidenceType": "issue_not_explicit_and_primary_documentation",
+ "rationale": "It can improve discovery, but is not needed to implement the requested indexing switch/cards."
+ },
+ {
+ "id": "I03",
+ "subject": "new_content_index",
+ "decision": "remove",
+ "evidenceType": "source_inspection",
+ "rationale": "Existing FTS and normalized tags already cover the queries."
+ },
+ {
+ "id": "I04",
+ "subject": "second_theme_storage",
+ "decision": "remove",
+ "evidenceType": "source_inspection",
+ "rationale": "Same-origin app and public site share this device's appearance preference."
+ },
+ {
+ "id": "I05",
+ "subject": "second_image_diagram_renderer",
+ "decision": "remove",
+ "evidenceType": "source_inspection",
+ "rationale": "Reuse existing renderers."
+ },
+ {
+ "id": "I06",
+ "subject": "publication_snapshot_version",
+ "decision": "exclude",
+ "evidenceType": "existing_live_share_contract",
+ "rationale": "Keep live sharing; no review/publish lifecycle."
+ },
+ {
+ "id": "I07",
+ "subject": "new_polling_or_push_invalidation",
+ "decision": "remove",
+ "evidenceType": "source_inspection",
+ "rationale": "Reuse current refresh and error handling; do not claim instantaneous recall of loaded text."
+ },
+ {
+ "id": "I08",
+ "subject": "public_cdn_cache",
+ "decision": "exclude",
+ "evidenceType": "existing_privacy_contract",
+ "rationale": "Keep no-store and no-referrer."
+ },
+ {
+ "id": "I09",
+ "subject": "duplicate_runtime_business_logic",
+ "decision": "remove",
+ "evidenceType": "project_contract",
+ "rationale": "Cloudflare/Docker share visibility and metadata services with thin entry adapters."
+ },
+ {
+ "id": "V01",
+ "subject": "all_validation_layers_each_phase",
+ "decision": "replace_with_affected_flows",
+ "evidenceType": "user_instruction",
+ "rationale": "Reuse unchanged checks and use three actual-flow acceptance scenarios after implementation."
+ }
+ ],
+ "notVerified": [
+ "Product UI and usability",
+ "Real password unlock and upgrade",
+ "Cloudflare/Docker page handlers",
+ "Crawler indexing and social previews",
+ "Production query/network performance",
+ "Concurrent writer contention"
+ ],
+ "externalReferences": [
+ "https://github.com/tianma-if/edgeever/issues/591",
+ "https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics",
+ "https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview",
+ "https://ogp.me/"
+ ]
+}
diff --git a/docs/public-notebook-site-plan.md b/docs/public-notebook-site-plan.md
new file mode 100644
index 00000000..6450396d
--- /dev/null
+++ b/docs/public-notebook-site-plan.md
@@ -0,0 +1,179 @@
+# Public notebook site improvement plan
+
+[简体中文](public-notebook-site-plan.zh-CN.md)
+
+Related: [Issue #591](https://github.com/tianma-if/edgeever/issues/591). Updated: 2026-10-21.
+
+Status: R01–R13 are implemented. Site settings expand in the notebook share dialog; original-note controls manage per-site visibility, and a separate search picker selects the homepage. Local and independent Cloudflare acceptance are recorded in the [implementation checklist](changes/2026-10-21-public-notebook-site.md). Baseline: official `5d1a0661`. Historical ablations used `4ad082b5` and remain separate from product validation. Real crawlers, native devices and Docker containers remain unverified.
+
+## 1. Design choices and boundaries
+
+**Use an explicit per-note exclusion control for the current site: add one exclusion relation table and two columns on `notebook_shares`.** Authors select notes that visitors to this site must not access. Chapters keep existing or natural title/number order. Keep live sharing without editorial review, publication snapshots, or a site builder.
+
+Explicit per-site exclusion is a relation between a share and a note, independent of classification tags. Retain its minimum relation table without manual ordering or a general item-override model. Earlier tag-based experiments establish filtering feasibility but do not validate this exclusion model.
+
+The resulting behavior and limits are:
+
+- The original note-share dialog and note-list context menu provide per-site switches for excluding or restoring individual notes. Exclusion applies only to the current share. Parent sites and independent child sites each have their own settings; note content, tags, and other shares retain their access rules. Start with no exclusions, preserving old public scope by default.
+- Keep existing order and title/number order, without site-specific drag ordering or changes to notebook hierarchy.
+- Derive the site name from the root notebook and descriptions from a visible homepage or article excerpt; do not add independent name/description overrides.
+- Reuse the device appearance preference. The public site and same-origin app share that local preference without writing to the author's account.
+- Keep server metadata and the indexing switch in the first version; defer complete article SSR and sitemap. This reduces non-JavaScript body crawlability and proactive discovery; equivalent SEO outcomes have not been established.
+
+The benefits remain better reading, body search, and site presentation. Principal risks remain incomplete public-visibility filtering, incorrect indexing policy, and rollback to an older server that ignores new policies. Delivery now includes the plan, retained historical experiments, and product implementation. Migration compatibility was verified locally; a separate Cloudflare acceptance database also applied 0001–0072.
+
+## 2. Minimum implementation of the 13 requirements
+
+| ID | Requirement | Minimum implementation and ablation decision |
+| --- | --- | --- |
+| R01 | Article outline | Keep body H1–H4, scrollspy, and smooth positioning. Distinguish duplicate anchors, support direct fragment reloads, and do not edit note content. Removing it loses an explicit requirement. |
+| R02 | Dark mode | Reuse ThemeProvider and `edgeever.theme` with light/dark/system choices. Do not introduce another preference controller or storage key. Articles, code, and diagrams use the same resolved theme. |
+| R03 | Code blocks | Reuse copying/highlighting; add language labels and collapse controls. Collapsed blocks still copy complete source; collapse state is not persisted. |
+| R04 | Internal previews | Keep bounded on-demand title/excerpt reads for hover and keyboard focus. Removing previews loses a requirement; fetching complete articles is not an equivalent lightweight replacement. |
+| R05 | Images and diagrams | Reuse the lightbox, gesture zoom, X6 fitting, and reader. Add single-click enlargement, fit, and fullscreen without a second viewer or duplicate reset tools. |
+| R06 | Body search | Reuse existing FTS, Chinese matching, and excerpt logic with a shortcut dialog, highlighting, pagination, and error feedback. Title filtering does not replace body search. |
+| R07 | Tag aggregation | Clicking an article tag filters through the same search endpoint and can combine with keywords. Do not add a global tag cloud, counts, or another aggregation API. |
+| R08 | Homepage | Store one homepage note ID and retain a directory entry. Hidden, deleted, or out-of-scope homepages fall back without disclosing their titles or excerpts. |
+| R09 | Exclude notes from the site | Authors explicitly select “Exclude from this site”; the server denies access to that note through this site. Start with no exclusions. Do not add global draft status or use `#draft` tags to control public scope. |
+| R10 | Custom ordering | Choose the title/number alternative allowed by the issue. One site `sortMode` selects existing or natural title order; numeric 2 precedes 10, and IDs break equal-title ties. |
+| R11 | URL alias | Keep an instance-unique alias, original token links, and one revocation boundary. Resolving aliases identifies shares without granting access. |
+| R12 | Branding | Keep HTTPS logos, structured header links, and plain-text footers in a small settings object. Do not add asset uploads or arbitrary HTML. |
+| R13 | SEO and cards | Keep explicit indexing permission, server HTML head, canonical URLs, and OpenGraph / Twitter Card metadata. Articles retain SPA rendering; complete SSR and sitemap are outside the first delivery. |
+
+Desktop retains the header, left chapters, central article, and a wide-screen right outline. Mobile uses drawers for chapters and article headings. Reuse article/image/diagram renderers, author fonts, font size, line height, palette, and sanitized article CSS. Tooltip and HoverCard support keyboard interaction; positioning respects reduced motion.
+
+Use one `Intl.Collator('zh-CN', { numeric: true, sensitivity: 'base' })` helper to order same-type siblings. Navigation, homepage contents, and previous/next links share the result. Ordering affects site presentation only, not stored hierarchy or author notebook order.
+
+## 3. Reduced persistence and interfaces
+
+### 3.1 Two site columns and one exclusion table
+
+| Table and column | Type and default | Purpose |
+| --- | --- | --- |
+| `notebook_shares.site_slug` | `TEXT NULL` | Optional alias; unique index on non-NULL `lower(site_slug)`. Normalize to lowercase letters, digits, and hyphens. |
+| `notebook_shares.site_settings_json` | `TEXT NOT NULL DEFAULT '{}'` | Small site settings; constrain to a valid JSON object. The API limits the merged object to 16 KiB. |
+
+Add `notebook_share_excluded_memos`, containing excluded notes only:
+
+| Column | Constraint and purpose |
+| --- | --- |
+| `share_id` | `TEXT NOT NULL`, referencing `notebook_shares.id` with cascade deletion when the share is deleted. |
+| `memo_id` | `TEXT NOT NULL`, referencing `memos.id` with cascade deletion when the note is physically deleted. |
+
+Use `(share_id, memo_id)` as the composite primary key and index `memo_id`. A row means excluded from this site; restoring inclusion deletes the row. Do not add a boolean, chapter type, ordering, or version fields. The absence of a row still requires existing workspace, live-subtree, and deletion checks; it does not grant unconditional public access.
+
+Before setting an exclusion, validate the author's share-management permission and the note's workspace, live-subtree membership, and deletion state. Live-scope checks deny notes moved outside or soft-deleted. Retained exclusion rows take effect again when a note is restored and re-enters scope. Revoking and recreating a share creates a new share ID without inheriting old exclusions.
+
+The site settings object contains only these six keys. Do not store per-note lists, manual-rank maps, or article bodies:
+
+| Key | Default | Behavior |
+| --- | --- | --- |
+| `homeMemoId` | `null` | Validate an explicit selection against this site's exclusion rows and revalidate on every public read. |
+| `logoUrl` | `null` | HTTPS image URL, with the existing icon as fallback. |
+| `headerLinks` | `[]` | Link labels and HTTPS destinations. |
+| `footerText` | `''` | Plain-text footer. |
+| `allowIndexing` | `false` | Effective permission always requires explicit opt-in and no current password. |
+| `sortMode` | `'existing'` | Only `existing` or `title`; existing behavior remains the default. |
+
+Do not add separate `site_title`, `site_description`, `home_memo_id`, logo/header/footer, indexing, excluded-tag, or two sort-mode columns. The exclusion table relates this site to notes without a general item-override model. Use the root notebook name and visible homepage/article excerpts for metadata; without a homepage, use the root notebook name as the description.
+
+An invalid `homeMemoId` is one bounded pointer. After moves, soft deletion, or physical deletion, reads fall back to the directory without a foreign key, new cleanup job, or database writes from public GETs. The shared service still enforces workspace and live-subtree scope.
+
+Apply partial configuration writes with database-side `json_patch`, preserving other fields, and reuse `updated_at`. Setting or rotating a password writes JSON `false` to `allowIndexing`; removing a password does not re-enable it. Preserve password hashes, ciphertext, tokens, and cookie paths.
+
+Reuse `memos`, `memo_contents`, `memo_tags`, `memo_search_documents`, `memos_fts`, and `resources`. The plan baseline ended at `0071`; implementation adds `0072_public_notebook_sites.sql` without editing earlier migrations.
+
+### 3.2 Eight new API operations; reuse the rest
+
+| Interface | Handling |
+| --- | --- |
+| Existing `GET /api/v1/notebooks/:id/share` | Include owner-managed site settings; do not add another site GET. |
+| Existing share create/revoke/password PATCH | Preserve meaning. Password PATCH continues to handle password operations only; configuration saves do not enter that branch. |
+| `PATCH /api/v1/notebooks/:id/share/site` | New. Save an alias and partial settings and return the merged configuration, without generating or clearing passwords. |
+| `GET /api/v1/notebooks/:id/share/excluded-memos` | Retain the first-version endpoint for paginated excluded IDs/titles accessible to the author. The current UI does not display a separate exclusions list. Do not return complete bodies or put the list in site settings. |
+| `GET /api/v1/notebooks/:id/share/memos` | Retain filtered owner pagination, now used only by the included-note homepage picker without rendering a separate management list. |
+| `GET /api/v1/memos/:id/notebook-sites` | New. Return applicable live direct/ancestor site names, notebook IDs, and independent exclusion states for the current user's note, without bodies/passwords/tokens or creating shares. |
+| `PATCH /api/v1/notebooks/:id/share/memos/:memoId` | New. Accept `{ excluded: boolean }`. Idempotently insert the exclusion for `true` or delete it for `false`; return this note's exclusion state in this site. |
+| `GET /api/public/notebook-shares/:token/search` | New. Combine keyword/tag filtering and pagination; return titles, matching excerpts, and highlights. Build chapter paths from the existing directory. |
+| `GET /api/public/notebook-shares/:token/memos/:memoId/preview` | New. Fetch title/existing short excerpt on demand without reading complete bodies or adding previews to every initial directory entry. |
+| `GET /api/public/notebook-sites/:slug/resolve` | New, making the previously implicit identity operation explicit. Return only `{ token }`; then use canonical token APIs and password gates. Do not expose protected site names, bodies, or settings. |
+| Existing public directory/article/resource endpoints | Return required visitor settings and consistently enforce live scope and per-note exclusions. Do not expose the list of excluded notes to visitors. |
+
+Use dedicated exclusion reads/writes rather than growing site settings JSON. Read accurate states for the current note's applicable sites without scanning directories or partially loaded exclusion pages. Do not add a general item-override model, manual-order PUT, or redundant site GET. Existing unlock cookies remain scoped to canonical token API paths, which aliases continue to use without changing the password protocol.
+
+### 3.3 Service boundaries that remain necessary
+
+- Share workspace, live-subtree, deletion, and current-share exclusion checks across directory, articles, resources, search, previews, internal links, homepage, and metadata. Filter before pagination on the server, not through client-side hiding. Tags remain classification and search metadata rather than publishing controls.
+- Reuse full-text indexing and Chinese matching rather than another client index or full-body download. Internal links resolve only currently visible site targets, without bypasses through independent shares.
+- Reuse the current 30-second refresh and query-error handling. Do not add polling, WebSockets, site versions, or an event bus. The next server request denies invalid targets; clients clear views on failed requests or refresh, without promising instantaneous recall of downloaded text.
+- Cloudflare and Docker share visibility and metadata services, with thin template/static-resource/entry adapters. Individual note shares and public forms retain existing policy.
+
+### 3.4 Minimum indexing boundary
+
+Only alias pages of unprotected sites with explicit permission are indexable. Token pages retain the complete shared noindex policy and canonical points to the alias when configured. Protected initial HTML always contains generic sharing information. Indexing defaults off, JSON APIs remain non-indexable, and pages/APIs retain `private, no-store` and `no-referrer`. The client preserves server robots until the selected article request completes; errors and non-indexable pages use the complete shared policy. Other sharing types retain their existing policy.
+
+Initial server HTML contains escaped title, description, canonical URL, and social metadata. Inaccessible articles return a real unavailable status and no-index headers. Use an available logo as the card image or existing brand resources; do not build a screenshot-generation service.
+
+SPA body rendering is a tradeoff, not experimentally equivalent SEO. [Google documentation](https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics) describes JavaScript rendering and notes that not every crawler executes JavaScript; eligible initial responses must not start with noindex and rely on client removal. Put [Open Graph](https://ogp.me/) metadata in the initial head. A [sitemap](https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview) can improve discovery, but no measured crawler need establishes it for this iteration, so defer it. Do not promise that every article is or will be indexed.
+
+### 3.5 Author sharing and site management
+
+Notebook context and more menus consistently use “Share notebook.” Directly shared notebooks keep the more button visible. Reopening reuses the original URL/token, with copying, password controls, and Advanced settings that expand in place. Personal settings retain an overview entry. Advanced settings start collapsed and contain homepage, logo, navigation, ordering, and indexing configuration. Collapsing/reopening retains unsaved input. The share dialog has no note management list.
+
+Per-note controls appear in the original note-share dialog and note-list context submenu as “Show in the ‘name’ site.” Parent and child sites have distinct switches, and changes apply immediately without affecting other sites or individual-note shares. Read errors offer retry; failed writes retain the original state. Opening the dialog no longer creates an individual-note share automatically: authors explicitly click “Create individual note link.” Existing links retain copying, passwords, and revocation.
+
+Settings save explicitly. The separate homepage picker searches included notes, supports directory home, and returns to the share dialog when closed. It replaces20 rows per page and supports body-keyword search without a second management list. The historical `/notebooks/:notebookId/site` address retains direct access and refresh, while the share dialog no longer navigates there. This revision adds no tables or columns.
+
+## 4. Whole-plan ablation evidence
+
+The following scripts and raw results remain historical comparisons for the previous tag-filtered, zero-new-table plan. They were neither rerun nor rewritten when explicit exclusions were selected or during implementation. They do not verify the current exclusion table, management endpoints, or UI; see the implementation checklist for product acceptance.
+
+Script: [public-notebook-site-plan-ablation.mjs](../scripts/public-notebook-site-plan-ablation.mjs). Raw results and 42 individual decisions: [public-notebook-site-plan-ablation.json](public-notebook-site-plan-ablation.json). Run `bun scripts/public-notebook-site-plan-ablation.mjs > docs/public-notebook-site-plan-ablation.json`.
+
+### 4.1 Executed comparisons
+
+An in-memory SQLite database built from actual migrations `0001`–`0071` passed **26 model checks and reproduced three expected failures after removing behavior**. Checks include two-column/zero-table migration shape, legacy row fields, tag filtering, body/Chinese-substring search, combined tags, natural ordering, homepage moves/deletion, partial settings writes, alias uniqueness, password/indexing policy, metadata escaping, and payload sizes.
+
+The three counterexamples are: removing server exclusion returns a draft; title-only search loses body matches; filtering after pagination returns an empty page despite visible matches. Retain these behaviors rather than removing them for simplicity.
+
+For a fixed sample of the old tag-based plan, settings occupy 256 bytes at 100/1,000/10,000/50,000 associated notes. This measures the old configuration encoding, not the current six-key object or runtime performance at 50,000 notes. Current exclusion relations are stored separately as rows that grow with the number of excluded notes.
+
+| Synthetic payload | 1,000 notes | 10,000 notes |
+| --- | --- | --- |
+| Basic directory JSON | 123,894 bytes | 1,248,895 bytes |
+| Short excerpts added to every directory item | 229,894 bytes | 2,308,895 bytes |
+| One on-demand preview | 125 bytes | 125 bytes |
+
+The same synthetic long article produces a 210,140-byte full response. Keeping lightweight previews has a measured payload rationale: removing the endpoint transfers cost to the initial directory or complete article reads. These are uncompressed JSON sizes; real request counts, compression, network latency, and hover behavior were not measured.
+
+Keep the previous [script](../scripts/public-notebook-site-schema-ablation.mjs) and [raw results](public-notebook-site-schema-ablation.json) unchanged. Its 19 common scenarios and 12 timing groups were not rerun for this review. Its preference for one override table applies only when per-item state is retained.
+
+### 4.2 Requirement mapping and design judgments
+
+The 42 decisions cover section 2's 13 requirement groups, the original 11 fields, override tables, management/public interfaces, SSR/sitemap, theme, renderers, indexing, refresh, caching, cross-runtime design, and verification. Each raw decision identifies executed evidence, source facts, issue alternatives, official documentation, or judgment. Do not describe every decision as a passing runtime test.
+
+The original decisions to remove per-note override storage and the exclusion endpoint are superseded by the explicit-exclusion decision; keep the raw JSON unchanged. Still remove or merge the general item-override model, manual-order endpoints, independent site name/description, scattered display columns, dual ordering settings, redundant site GET, duplicate themes/viewers/indexes, additional refresh, and publication versions.
+
+Retain the selected path for all 13 requirements, current-site per-note exclusions and management operations, live server access filtering, filtering before pagination, existing password protocols, alias uniqueness/resolution, lightweight previews, server metadata, and thin Cloudflare/Docker adapters. Full article SSR, sitemap, and standalone asset upload remain future capabilities, not features proven worthless.
+
+These historical experiments did not verify real UI, password upgrades, page handling through both runtimes, remote D1, crawlers, or concurrency races. Subsequent implementation separately verified local UI, old-route migration compatibility, and both runtime entries. The implementation checklist records that coverage and its remaining limits; model checks do not extend those conclusions.
+
+## 5. Implementation and minimum acceptance
+
+| Phase | Delivery | Acceptance focus |
+| --- | --- | --- |
+| 1. Reading | Outline, reused theme, code blocks, image/diagram interaction | One real desktop/mobile reading flow covers positioning, copying, zooming, keyboard actions, and focus restoration. No database changes. |
+| 2. Settings and discovery | Migration for two columns and the exclusion table, excluded-note management, natural order, homepage, search, preview, and settings saves | Existing-share upgrade and author-to-anonymous-readback flows; real access boundaries and Chinese search. |
+| 3. Branding and public pages | Logo/header/footer, aliases, initial metadata, and indexing switch | Token/alias/password/HTML policies agree; each runtime needs only its entry-specific checks. |
+
+After implementation, verify three real flows without automatically stacking per-component unit tests, full integration suites, and repeated reviews:
+
+1. **Old-version upgrade and reading:** fix real old data and expected public content, migrate, then check original tokens, passwords, and grants. Exercise article/code/image/diagram controls in the actual page. Layout may change; defaults must not change existing public scope.
+2. **Author edits to visitor readback:** exclude a note and verify no disclosure through directory, direct article, resources, search, previews, links, homepage, or metadata; remove the exclusion and verify normal access returns. Ordinary tag edits must not change exclusion state. The same note in an independent child share follows that share's own settings. Reuse the fixture for exclusions surviving moves out and back, cascade deletion, revocation/recreation, management permissions, and workspace boundaries. Check numeric ordering and filtered pagination; HTTP 200 alone is insufficient.
+3. **Aliases and indexing:** check collisions, resolution, canonical API-cookie unlocking, and canonical URLs. Request raw HTML for metadata/status/privacy. Reuse shared-service checks, checking each Cloudflare/Docker entry and its headers; builds do not establish crawler acceptance.
+
+Reuse existing tests and still-applicable results, adding checks only for concrete gaps. Run required `bun run typecheck`, `bun run typecheck:mobile`, and `bun run build:web` when relevant premises change, not repeatedly for documentation or unchanged inputs. Any Android native debugging must use a USB-connected physical device, not an emulator.
+
+Add columns, the exclusion table, and relevant indexes; migrate before deploying the server and preserve shares/tokens. Start with an empty exclusion table. Back up the database and password encryption root. Phase 1 can revert presentation commits. Once per-note exclusions are enabled, an older server ignoring the exclusion table can republish content; retain filtering on rollback or revoke affected sites first. Disabling indexing cannot guarantee immediate removal from external indexes.
+
+Track implementation, automated checks, browser acceptance, commits, pushes, deployment, and release separately. This document records the plan and historical model experiments; the task's change checklist records implementation and acceptance results.
diff --git a/docs/public-notebook-site-plan.zh-CN.md b/docs/public-notebook-site-plan.zh-CN.md
new file mode 100644
index 00000000..876b549c
--- /dev/null
+++ b/docs/public-notebook-site-plan.zh-CN.md
@@ -0,0 +1,179 @@
+# 笔记本公开分享站点改造方案
+
+[English](public-notebook-site-plan.md)
+
+关联:[Issue #591](https://github.com/tianma-if/edgeever/issues/591)。更新日期:2026-10-21。
+
+状态:R01~R13 已实现。站点配置在笔记本分享弹窗中展开,原笔记页控制逐站点展示,首页使用独立搜索选择器。本地及独立 Cloudflare 验收见[实施清单](changes/2026-10-21-public-notebook-site.zh-CN.md)。代码基线为官方 `5d1a0661`;历史消融使用 `4ad082b5`,实验材料与产品验收分别记录。真实爬虫、原生真机和 Docker 容器仍未验收。
+
+## 1. 设计选择与边界
+
+**采用当前站点的逐篇排除开关:新增一张排除关系表,并扩展 `notebook_shares` 的两个字段。** 作者在分享设置中选择不对本站访客开放的笔记,章节仍按现有顺序或标题/数字自然排序。保留实时分享,不增加审核、发布快照或站点搭建器。
+
+逐站点排除是分享与笔记之间的关系,与分类标签独立。保留所需的最小关系表,不增加手动排序或通用条目覆盖模型。历史标签实验只证明筛选可行,不作为当前排除模型的验收。
+
+最终行为与边界:
+
+- 原笔记分享弹窗及笔记列表右键菜单按所属站点展示开关,逐篇排除或恢复。排除仅作用于当前分享;父站点、独立子站点各自配置,不改变笔记内容、标签或其他分享的访问规则。默认没有排除项,旧分享的公开范围不自动变化。
+- 保留现有顺序及标题/数字排序,不提供站点专属拖拽顺序,也不改作者原有笔记本层级。
+- 站点名称来自根笔记本名称,简介来自当前可见首页或文章摘要;不提供独立的名称、简介覆盖设置。
+- 复用设备现有主题偏好。公开站点与同源应用使用同一个本机外观选择,不写入作者账号。
+- 首版保留服务端元数据和收录开关;完整正文 SSR、sitemap 延后。这会减少无 JavaScript 爬虫的正文可读性和主动发现入口,不宣称与原方案的 SEO 效果等同。
+
+主要价值不变:改善长文阅读、正文检索和站点外观。主要风险仍是公开范围过滤遗漏、收录策略错误及旧服务回滚后忽略新策略。当前交付包括方案、保留的历史实验材料和产品实现;旧数据迁移兼容已在本地验证,独立 Cloudflare 验收库也已执行0001~0072。
+
+## 2. 13 项需求的最小实现
+
+| 编号 | 需求 | 最小实现与消融结论 |
+| --- | --- | --- |
+| R01 | 文章大纲 | 保留正文 H1~H4、滚动高亮及平滑定位。锚点区分同名标题,支持刷新直达,不改写笔记内容。不能删除,否则缺少明确需求。 |
+| R02 | 深色模式 | 复用现有 ThemeProvider 与 `edgeever.theme`,提供浅色、深色、跟随系统三选项,不另建主题状态和存储键。正文、代码和画板使用同一有效主题。 |
+| R03 | 代码块增强 | 复用复制与高亮,只补语言标识和折叠;折叠后仍复制完整源码,不保存折叠状态到数据库。 |
+| R04 | 站内链接预览 | 保留按需的轻量标题、摘要接口,悬停和键盘聚焦都可用。取消预览既不满足需求,也不能用全量正文预取替代。 |
+| R05 | 图片与画板 | 复用图片灯箱、手势缩放、X6 自适应及阅读器。补单击放大入口、适应窗口和全屏,不再建设第二套查看器或重复的重置工具。 |
+| R06 | 正文全文检索 | 复用现有 FTS、中文匹配及文本摘要能力,支持快捷键、命中高亮、分页和失败反馈。标题过滤不能替代正文搜索。 |
+| R07 | 标签聚合 | 点击文章标签,使用同一个搜索接口按标签过滤,可叠加关键词。不增加全站标签云、计数或独立标签聚合接口。 |
+| R08 | 自定义首页 | 保存一个首页笔记 ID;始终保留目录入口。首页隐藏、删除或移出范围后回退目录,不返回它的标题或摘要。 |
+| R09 | 不公开笔记排除 | 作者显式设置“从此站点排除”,服务端统一拒绝通过本站读取该笔记。默认无排除项;不增加全局草稿状态,也不使用 `#draft` 标签控制公开范围。 |
+| R10 | 自定义排序 | 选择 Issue 允许的标题/序号方案。一个站点级 `sortMode` 控制现有顺序或标题自然排序;数字按 2 在 10 前排列,同名用 ID 稳定排序。 |
+| R11 | URL 别名 | 保留实例内唯一别名、原 Token 链接和同一撤销边界。别名只解析身份,不新增访问授权。 |
+| R12 | 站点外观 | 保留 HTTPS Logo 地址、结构化页眉外链和纯文本页脚,放在小型配置对象中。不增加资产上传服务或任意 HTML。 |
+| R13 | SEO 与社交卡片 | 保留显式收录开关、服务端 HTML head、canonical、OpenGraph / Twitter Card。正文继续用现有 SPA 渲染,完整 SSR 和 sitemap 不列入首版交付。 |
+
+桌面保留顶部导航、左侧章节、中间正文和宽屏右侧大纲;移动端通过抽屉访问章节与本文大纲。继续使用现有文章、图片、画板、作者字体/字号/行距/配色及过滤后的正文 CSS。Tooltip 和 HoverCard 支持键盘,定位尊重减少动态效果设置。
+
+自然排序使用统一的 `Intl.Collator('zh-CN', { numeric: true, sensitivity: 'base' })` 帮助函数,分别排列同一父章节下的同类条目,目录、首页目录和前后篇共用结果。排序只改变站点展示;正文和原笔记本顺序不被改写。
+
+## 3. 数据与接口的收敛方案
+
+### 3.1 两个站点字段和一张排除表
+
+| 表与字段 | 类型及默认值 | 用途 |
+| --- | --- | --- |
+| `notebook_shares.site_slug` | `TEXT NULL` | 可选别名;对非空 `lower(site_slug)` 建唯一索引,保存时统一为小写字母、数字和连字符。 |
+| `notebook_shares.site_settings_json` | `TEXT NOT NULL DEFAULT '{}'` | 站点级小型配置,数据库约束为合法 JSON 对象;接口限制合并后的配置不超过 16 KiB。 |
+
+新增 `notebook_share_excluded_memos`,只保存被排除的笔记:
+
+| 字段 | 约束与用途 |
+| --- | --- |
+| `share_id` | `TEXT NOT NULL`,外键引用 `notebook_shares.id`,分享删除时级联删除。 |
+| `memo_id` | `TEXT NOT NULL`,外键引用 `memos.id`,笔记物理删除时级联删除。 |
+
+以 `(share_id, memo_id)` 为复合主键,并为 `memo_id` 建索引。存在记录表示本站排除,取消排除直接删除记录,不增加布尔列、章节类型、排序或版本字段。没有记录仍须通过原有工作区、实时子树和删除状态检查,并不代表无条件公开。
+
+设置排除时校验作者的分享管理权限、笔记所属工作区、实时子树及删除状态。笔记移出或软删除后,由实时范围检查拒绝访问;保留的排除记录在笔记恢复并重新进入范围时继续生效。撤销并重新创建分享使用新的分享 ID,不继承旧排除项。
+
+站点配置对象只包含以下六项,禁止放入逐篇笔记列表、手动排序映射或正文:
+
+| 配置键 | 默认值 | 行为 |
+| --- | --- | --- |
+| `homeMemoId` | `null` | 首页笔记;显式选择时校验本站排除记录,每次公开读取再次校验。 |
+| `logoUrl` | `null` | HTTPS 图片地址;加载失败回退现有图标。 |
+| `headerLinks` | `[]` | 文字与 HTTPS 地址组成的外链数组。 |
+| `footerText` | `''` | 页脚纯文本。 |
+| `allowIndexing` | `false` | 有效收录条件始终是显式允许且当前无密码。 |
+| `sortMode` | `'existing'` | 只允许 `existing`、`title`。已有偏好默认不变化。 |
+
+不再增加独立 `site_title`、`site_description`、`home_memo_id`、Logo/导航/页脚列、收录列、排除标签列和两种排序列;排除表只维护本站与笔记的关系,不建立通用条目覆盖表。名称使用现有根笔记本名称,描述使用可见首页或文章的现有摘要;没有首页时使用根笔记本名称。
+
+`homeMemoId` 的无效引用只涉及一个固定大小的指针。移出、软删除或物理删除后,读取时回退目录,不依赖外键或新增清理任务,也不在公开 GET 中改写数据库。工作区和实时子树校验继续由共享服务执行。
+
+配置通过数据库内 `json_patch` 部分更新,保留其他字段;复用 `updated_at`。设置或重置密码时,把 `allowIndexing` 写为 JSON `false`;取消密码不自动重新开启。密码散列、密文、Token 和 Cookie 路径保持现有含义。
+
+正文、标签、搜索和资源继续复用 `memos`、`memo_contents`、`memo_tags`、`memo_search_documents`、`memos_fts` 和 `resources`。方案基线的迁移截止 `0071`;实现新增 `0072_public_notebook_sites.sql`,没有修改旧迁移。
+
+### 3.2 新增八个 API 操作,其余复用
+
+| 接口 | 处理 |
+| --- | --- |
+| 现有 `GET /api/v1/notebooks/:id/share` | 扩展返回作者可管理的站点配置,不新增另一个站点 GET。 |
+| 现有分享创建、撤销、密码 PATCH | 保留语义;密码 PATCH 继续只执行密码操作,不把配置保存混入密码重置分支。 |
+| `PATCH /api/v1/notebooks/:id/share/site` | 新增。只保存别名及部分站点设置,返回合并后的配置,不生成或清除密码。 |
+| `GET /api/v1/notebooks/:id/share/excluded-memos` | 保留首版接口,分页返回作者可访问的排除笔记 ID 和标题;当前界面不单独展示此列表,不返回完整正文或把列表塞进站点配置。 |
+| `GET /api/v1/notebooks/:id/share/memos` | 保留作者关键词/状态过滤后分页接口,当前只供首页选择器读取未排除笔记,不再渲染独立内容管理列表。 |
+| `GET /api/v1/memos/:id/notebook-sites` | 新增。返回当前用户笔记所属的有效直接/祖先站点名称、笔记本ID和各自排除状态;不返回正文、密码或Token,不创建分享。 |
+| `PATCH /api/v1/notebooks/:id/share/memos/:memoId` | 新增。接受 `{ excluded: boolean }`;设为 `true` 时幂等写入排除关系,设为 `false` 时幂等删除,返回该笔记在本站的排除状态。 |
+| `GET /api/public/notebook-shares/:token/search` | 新增。关键词、标签、分页共用一个接口,返回标题、命中摘要及高亮信息;章节路径由现有目录构造。 |
+| `GET /api/public/notebook-shares/:token/memos/:memoId/preview` | 新增。按需返回标题和现有短摘要,不读完整正文,不把摘要附到每一条初始目录。 |
+| `GET /api/public/notebook-sites/:slug/resolve` | 新增并明确此前遗漏的身份解析操作。只返回 `{ token }`,然后使用原 Token API 及密码门禁;不返回受保护站点的名称、正文或设置。 |
+| 现有公开目录、正文和资源接口 | 返回必要的访客配置,统一执行实时范围和逐篇排除。排除笔记列表不下发给访客。 |
+
+逐篇排除使用独立的读取和修改操作,避免扩大站点配置 JSON。原笔记页读取其对应站点的准确状态,不扫描笔记目录或用多页排除列表猜测。仍不增加通用条目覆盖模型、手动排序 PUT 或独立站点 GET。已有解锁 Cookie 绑定在原 Token API 路径,别名仍回到同一路径读取内容,不改变密码协议。
+
+### 3.3 必须保留的服务边界
+
+- 统一过滤工作区、实时子树、删除状态及当前分享的排除记录,覆盖目录、正文、附件、搜索、预览、内部链接、首页和元数据。搜索先过滤再分页;共享服务执行过滤,不依赖浏览器隐藏。标签继续用于分类和搜索,不承担发布控制。
+- 搜索直接使用现有全文索引和中文匹配,不建设客户端全站索引,不下载全部正文做筛选。正文链接继续只解析本站当前可见目标,不借独立分享绕过本网站点策略。
+- 复用现有 30 秒刷新和查询失败处理,不新增轮询、WebSocket、站点版本或事件总线。下一次服务端请求必须拒绝失效目标;客户端在收到失效响应或刷新时清理视图,不承诺瞬间收回已经下载的文本。
+- Cloudflare 与 Docker 共用过滤和 HTML 元数据服务,只保留读取模板、静态资源和运行入口适配。单篇分享和公开表单继续保持原有策略。
+
+### 3.4 收录的最小边界
+
+只有无密码且显式允许的站点别名页面可以收录;Token 页面保留共用的完整 noindex 策略,已配置别名时 canonical 指向别名。密码站点的初始 HTML 始终只有通用分享信息。默认禁止收录,JSON API 继续禁止收录,页面与 API 继续 `private, no-store`、`no-referrer`。前端在选中文章请求完成前保留服务端 robots;失败或禁止收录时使用共用的完整策略。其他分享类型保持原有策略。
+
+服务端初始 HTML 输出转义后的 title、description、canonical 和社交卡片元数据。不可访问文章返回真实不可用状态与禁止收录头;Logo 可用时用于卡片图片,否则使用现有品牌资源,不建设截图生成服务。
+
+正文沿用 SPA 是取舍,不是相同 SEO 效果的实验证明。[Google 文档](https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics)说明其可以渲染 JavaScript,也说明不是所有爬虫都能执行 JavaScript;允许收录的原始响应不能先带 noindex 再靠前端删除。[Open Graph](https://ogp.me/)元数据放在初始 head 中。[sitemap](https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview)可以改善发现,但本轮没有实际爬虫证据要求建设它,因此延后;不承诺所有文章已经或必然被收录。
+
+### 3.5 作者分享与站点管理
+
+笔记本右键和更多菜单固定使用“分享笔记本”。已直接分享的笔记本常显更多按钮,打开后复用原链接及Token,可复制链接、设置密码或原地展开“进阶设置”;个人中心保留汇总入口。进阶设置默认收起,包含首页、Logo、外链、排序和收录等整体配置,折叠/重新展开保留未保存输入。分享弹窗不展示笔记管理列表。
+
+逐篇控制放在原笔记页的分享弹窗及列表右键子菜单中,以“在「名称」站点中展示”表达范围;父、子笔记本站点分别显示,修改立即生效,不影响其他站点或单篇分享。读取失败时显示错误与重试,写入失败保留原状态。打开分享弹窗不再自动创建单篇分享,必须明确点击“创建单篇分享链接”,已有链接仍可复制、设密码和撤销。
+
+配置显式保存;首页通过独立搜索选择器选择当前未排除笔记,也可使用目录首页。关闭选择器返回分享弹窗。选择器每页替换显示20条,支持正文关键词,不展示第二份内容管理列表。历史 `/notebooks/:notebookId/site` 地址保留直接访问及刷新,分享弹窗不再跳转到该页。本次修订不增加表或字段。
+
+## 4. 整份方案的消融证据
+
+以下脚本与原始结果保留为历史对照,针对上轮标签过滤与零新增表方案;改为明确排除及后续实施时均未重跑或改写这些历史实验。它们不证明当前排除表、管理接口或交互已通过验证;产品验收见实施清单。
+
+脚本:[public-notebook-site-plan-ablation.mjs](../scripts/public-notebook-site-plan-ablation.mjs)。原始结果及 42 条逐项决策:[public-notebook-site-plan-ablation.json](public-notebook-site-plan-ablation.json)。运行:`bun scripts/public-notebook-site-plan-ablation.mjs > docs/public-notebook-site-plan-ablation.json`。
+
+### 4.1 已执行的对照
+
+在实际 `0001`~`0071` Migration 建出的内存 SQLite 上,**26 项模型检查通过,另复现 3 个删除后失败的反例**。检查包括两字段/零新表、旧行字段保留、标签过滤、正文和中文子串搜索、标签组合、自然排序、首页移动及删除回退、配置部分更新、别名唯一性、密码与收录策略、元数据转义及负载大小。
+
+三项反例分别是:去掉服务端排除后返回草稿;仅保留标题搜索丢失正文命中;先分页再过滤导致明明有可见命中却返回空页。这些行为应保留,不能为了精简而删除。
+
+旧标签方案的固定样本中,站点配置在关联 100/1,000/10,000/50,000 篇笔记时均为 256 字节。这是旧配置编码大小对照,不是当前六项配置的测量,也不是五万篇笔记的运行或性能验收。当前排除关系单独按行保存,行数随排除笔记数增长。
+
+| 合成负载 | 1,000 篇 | 10,000 篇 |
+| --- | --- | --- |
+| 基础目录 JSON | 123,894 字节 | 1,248,895 字节 |
+| 每条目录都附短摘要 | 229,894 字节 | 2,308,895 字节 |
+| 一次按需预览 | 125 字节 | 125 字节 |
+
+同一合成长文的完整正文响应为 210,140 字节。因此保留轻量预览接口有实际负载依据,删除它会把开销转移到初始目录或完整正文读取。数值是未压缩 JSON,未测真实请求数、压缩、网络时延或用户悬停习惯。
+
+上一轮[脚本](../scripts/public-notebook-site-schema-ablation.mjs)及[原始结果](public-notebook-site-schema-ablation.json)保持原样,19 项公共场景和 12 组计时没有因本次审查重复运行;其中“一张覆盖表优于两张”的结论只在保留逐篇状态时适用。
+
+### 4.2 需求映射和设计判断
+
+42 条决策覆盖第 2 节的 13 个需求组、原 11 个字段、覆盖表、管理和公开接口、SSR/sitemap、主题、渲染器、索引、刷新、缓存、跨运行时和验证方式。原始结果为每条标明实测、源码事实、Issue 替代项、官方文档或设计判断,不能把全部决策称为运行测试通过。
+
+原始决策中删除逐篇覆盖表和逐篇隐藏接口的结论,已由本次明确排除的决定取代;原始 JSON 不改写。当前仍可删除或合并:通用条目覆盖模型、手动排序接口、独立站点名称/简介、分散的显示配置列、双排序配置、冗余站点 GET、第二套主题及查看器、第二套全文索引、额外刷新和发布版本体系。
+
+仍需保留:13 项需求选定的最小路径、当前站点逐篇排除及管理操作、实时服务端访问过滤、分页前过滤、现有密码协议、别名唯一性与解析、轻量预览、服务端元数据和 Cloudflare/Docker 薄适配。完整正文 SSR、sitemap 和独立资产上传列为后续能力,不伪装成已经验证无价值。
+
+上述历史实验未验证真实 UI、实际密码升级、两个运行时页面、远端 D1、搜索引擎或社交抓取及并发竞争。后续实施已单独完成本地 UI、旧路由迁移兼容及两个运行入口验收;其范围和剩余限制见实施清单,不能据模型检查扩大结论。
+
+## 5. 实施与最小验收
+
+| 阶段 | 交付 | 验收重点 |
+| --- | --- | --- |
+| 1. 阅读 | 大纲、复用主题、代码块、图片与画板交互 | 一个真实桌面/手机阅读流程覆盖定位、复制、缩放、键盘及焦点恢复;没有数据库改动。 |
+| 2. 配置与发现 | 两字段及排除表迁移、排除笔记管理、自然排序、首页、搜索、预览及设置保存 | 旧分享升级和作者设置到匿名读取完整流程;验证真实访问边界和中文检索。 |
+| 3. 外观与公开页面 | Logo/导航/页脚、别名、初始元数据与收录开关 | 原 Token、别名、密码及原始 HTML 策略一致;两个运行时只补入口差异验证。 |
+
+实现后围绕三条实际流程验收,不默认叠加每个组件的单测、全套集成和多轮审查:
+
+1. **旧版本升级与阅读**:固定真实旧数据及预期公开内容,迁移后验证原 Token、密码和解锁授权;在实际页面完成长文、代码、图片和画板操作。布局可以变化,原公开范围不能因默认设置变化。
+2. **编辑到访客读回**:作者排除一篇笔记,验证目录、直达正文、附件、搜索、预览、内部链接、首页和元数据均不泄露该笔记;取消排除后恢复正常读取。普通标签修改不得改变排除状态;同一篇在独立子分享中仍按子分享自己的配置处理。用同一组数据覆盖移入移出后排除仍生效、删除级联、撤销重建、管理权限及工作区边界。检查标题数字排序和过滤后分页,不用仅有 HTTP 200 作为完成证据。
+3. **别名和收录**:验证别名冲突、解析、原 API Cookie 解锁和 canonical;直接请求 HTML 检查元数据、状态码及隐私。共享服务验证复用,Cloudflare/Docker 各检查入口与响应头;不把构建通过当作爬虫验收。
+
+优先复用现有测试和仍适用的结果,只为具体缺口补检查。必要的 `bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web` 在相关前提变化时运行;不为文档或未变输入重复执行。Android 原生调测若涉及,必须使用 USB 真机,不能用模拟器替代。
+
+迁移只新增列、排除表及相关索引,先迁移再部署服务,不重建分享或轮换 Token;排除表初始为空。备份数据库及现有密码加密根。阶段 1 可回退展示提交;启用逐篇排除后,旧服务忽略排除表会重新公开内容,回滚必须保留过滤逻辑或先撤销受影响站点。关闭收录不能保证外部索引立即消失。
+
+功能实现、自动化验证、浏览器验收、提交、推送、部署和发布分别记录。此文档记录方案及历史模型实验,具体实施与验收结果记录在本次变更清单中。
diff --git a/docs/public-notebook-site-schema-ablation.json b/docs/public-notebook-site-schema-ablation.json
new file mode 100644
index 00000000..e80c8d6b
--- /dev/null
+++ b/docs/public-notebook-site-schema-ablation.json
@@ -0,0 +1,947 @@
+{
+ "generatedAt": "2026-10-20T08:09:19.336Z",
+ "baselineCommit": "d966052002889729c6850732f2baeb75c342a2e6",
+ "environment": {
+ "bun": "1.3.14",
+ "sqlite": "3.54.0",
+ "platform": "darwin",
+ "arch": "arm64"
+ },
+ "method": {
+ "actualMigrations": [
+ "migrations/0001_initial.sql",
+ "migrations/0002_auth.sql",
+ "migrations/0003_search_and_trash.sql",
+ "migrations/0004_memo_revision_metadata.sql",
+ "migrations/0005_default_uncategorized_notebook.sql",
+ "migrations/0006_default_notebook_set.sql",
+ "migrations/0007_api_token_value.sql",
+ "migrations/0009_drop_profile_snapshots.sql",
+ "migrations/0010_restore_default_inbox_notebook.sql",
+ "migrations/0011_memo_edit_sessions.sql",
+ "migrations/0012_multi_user_workspaces.sql",
+ "migrations/0013_mobile_sync_changes.sql",
+ "migrations/0014_repair_seed_memo_content_hash.sql",
+ "migrations/0015_auth_session_devices.sql",
+ "migrations/0016_templates.sql",
+ "migrations/0017_seed_default_templates.sql",
+ "migrations/0018_fix_seed_template_markdown.sql",
+ "migrations/0019_auth_session_metadata.sql",
+ "migrations/0020_auth_login_attempts.sql",
+ "migrations/0021_memo_import_sources.sql",
+ "migrations/0022_memo_shares.sql",
+ "migrations/0023_instance_object_storage.sql",
+ "migrations/0024_ai_model_configs.sql",
+ "migrations/0025_ai_providers_and_models.sql",
+ "migrations/0026_ai_prompt_templates.sql",
+ "migrations/0027_seed_default_ai_prompts.sql",
+ "migrations/0028_seed_remaining_ai_prompts.sql",
+ "migrations/0029_ai_prompt_behavior_and_localization.sql",
+ "migrations/0030_unify_editable_note_templates.sql",
+ "migrations/0031_limit_default_memo_templates.sql",
+ "migrations/0032_limit_default_ai_prompts.sql",
+ "migrations/0033_ai_tag_suggestion_prompt.sql",
+ "migrations/0034_search_documents_and_maintenance_leases.sql",
+ "migrations/0035_normalized_memo_tags.sql",
+ "migrations/0036_resource_multipart_uploads.sql",
+ "migrations/0037_scheduled_plugin_tasks.sql",
+ "migrations/0038_plugin_owned_schedules.sql",
+ "migrations/0039_scheduled_task_run_retention.sql",
+ "migrations/0040_companion_memory.sql",
+ "migrations/0041_companion_actions.sql",
+ "migrations/0042_companion_tool_execution.sql",
+ "migrations/0043_companion_discovery.sql",
+ "migrations/0044_companion_discovery_input_hash.sql",
+ "migrations/0045_companion_learning.sql",
+ "migrations/0046_restore_workspace_inbox_identity.sql",
+ "migrations/0047_replace_social_ai_prompts.sql",
+ "migrations/0048_workspace_extensions.sql",
+ "migrations/0049_companion_agent_run.sql",
+ "migrations/0050_companion_process_text.sql",
+ "migrations/0051_companion_agent_session.sql",
+ "migrations/0052_memo_share_passwords.sql",
+ "migrations/0053_collapse_duplicate_inbox_notebooks.sql",
+ "migrations/0054_user_note_body_font.sql",
+ "migrations/0055_table_forms.sql",
+ "migrations/0056_user_note_prose.sql",
+ "migrations/0057_companion_attachments.sql",
+ "migrations/0058_retire_emerald_note_palette.sql",
+ "migrations/0059_retire_custom_note_palette.sql",
+ "migrations/0060_ai_transcription_settings.sql",
+ "migrations/0061_video_transcript_jobs.sql",
+ "migrations/0062_ai_transcription_providers.sql",
+ "migrations/0063_ai_transcription_provider_standard.sql",
+ "migrations/0064_retire_video_transcription.sql",
+ "migrations/0065_restore_speech_transcription.sql",
+ "migrations/0066_poster_render_jobs.sql",
+ "migrations/0067_notebook_shares.sql",
+ "migrations/0068_notebook_share_passwords.sql",
+ "migrations/0069_share_password_encryption.sql",
+ "migrations/0070_workspace_seed_localization.sql",
+ "migrations/0071_fix_welcome_memo_markdown.sql"
+ ],
+ "unchangedCommonSiteColumns": [
+ "site_title TEXT",
+ "site_description TEXT NOT NULL DEFAULT ''",
+ "site_slug TEXT",
+ "home_memo_id TEXT REFERENCES memos(id) ON DELETE SET NULL",
+ "logo_url TEXT",
+ "header_links_json TEXT NOT NULL DEFAULT '[]'",
+ "footer_text TEXT NOT NULL DEFAULT ''",
+ "allow_indexing INTEGER NOT NULL DEFAULT 0 CHECK(allow_indexing IN (0, 1))",
+ "excluded_tags_json TEXT NOT NULL DEFAULT '[]'",
+ "notebook_sort_mode TEXT NOT NULL DEFAULT 'existing'",
+ "memo_sort_mode TEXT NOT NULL DEFAULT 'existing'"
+ ],
+ "variants": [
+ "two_tables",
+ "one_table",
+ "json_column"
+ ],
+ "noteIdFormat": "memo_ followed by 32 hex characters (same length as createId('memo'))",
+ "functionalScope": "Local SQL policy and persistence model, not HTTP/browser/authentication acceptance",
+ "benchmarkScope": "In-memory SQLite; warm prepared statements; 2 warmups and up to 15 samples (at least 3, stop after 500 ms of measured work); no network, D1 billing, disk I/O, or concurrent-writer throughput measured",
+ "jsonReadStrategy": "SQL hidden-ID set filters before pagination; directory includes a second SQL read plus one server-side JSON parse/map/sort; direct JSON path extraction for individual notes/resources",
+ "searchOrder": "Identical FTS term in every candidate body; tie by note ID for all variants. Manual directory order is not search relevance.",
+ "updateStrategy": "Relational field upserts vs atomic json_patch of the existing row; no client read-modify-write replacement",
+ "order": "Variants run sequentially; absolute timings are illustrative, not a production SLO",
+ "remeasurement": "Reused unchanged relational directory/point/update measurements. Remeasured the optimized JSON strategy and relational search after standardizing FTS tie order. The discarded JSON join had a SCAN e LEFT-JOIN plan; those timings are not used as evidence against JSON."
+ },
+ "functional": [
+ {
+ "variant": "two_tables",
+ "casesPassed": 19,
+ "cases": [
+ "default_scope",
+ "per_share_exclusion",
+ "direct_note_denied",
+ "resource_denied",
+ "independent_child_share",
+ "tag_exclusion",
+ "hidden_homepage_fallback",
+ "memo_manual_order",
+ "chapter_manual_order",
+ "new_note_appends",
+ "fts_exclusion_before_limit",
+ "moved_out_denied",
+ "deleted_ancestor_denied",
+ "cross_workspace_denied",
+ "disjoint_field_updates_preserved",
+ "physical_delete_homepage_cleared",
+ "revocation_denies_reads",
+ "independent_share_survives_revocation",
+ "revocation_cleans_overrides"
+ ],
+ "databaseIntegrity": {
+ "rejectsMissingTarget": true,
+ "automaticallyRemovesDeletedTarget": true,
+ "rejectsBothTargets": null
+ },
+ "legacyTokenAndHashPreserved": true
+ },
+ {
+ "variant": "one_table",
+ "casesPassed": 21,
+ "cases": [
+ "default_scope",
+ "per_share_exclusion",
+ "direct_note_denied",
+ "resource_denied",
+ "independent_child_share",
+ "tag_exclusion",
+ "hidden_homepage_fallback",
+ "memo_manual_order",
+ "chapter_manual_order",
+ "new_note_appends",
+ "fts_exclusion_before_limit",
+ "moved_out_denied",
+ "deleted_ancestor_denied",
+ "cross_workspace_denied",
+ "disjoint_field_updates_preserved",
+ "physical_delete_homepage_cleared",
+ "one_table_exactly_one_target",
+ "one_table_chapter_cannot_be_excluded",
+ "revocation_denies_reads",
+ "independent_share_survives_revocation",
+ "revocation_cleans_overrides"
+ ],
+ "databaseIntegrity": {
+ "rejectsMissingTarget": true,
+ "automaticallyRemovesDeletedTarget": true,
+ "rejectsBothTargets": true
+ },
+ "legacyTokenAndHashPreserved": true
+ },
+ {
+ "variant": "json_column",
+ "casesPassed": 19,
+ "cases": [
+ "default_scope",
+ "per_share_exclusion",
+ "direct_note_denied",
+ "resource_denied",
+ "independent_child_share",
+ "tag_exclusion",
+ "hidden_homepage_fallback",
+ "memo_manual_order",
+ "chapter_manual_order",
+ "new_note_appends",
+ "fts_exclusion_before_limit",
+ "moved_out_denied",
+ "deleted_ancestor_denied",
+ "cross_workspace_denied",
+ "disjoint_field_updates_preserved",
+ "physical_delete_homepage_cleared",
+ "revocation_denies_reads",
+ "independent_share_survives_revocation",
+ "revocation_cleans_overrides"
+ ],
+ "databaseIntegrity": {
+ "rejectsMissingTarget": false,
+ "automaticallyRemovesDeletedTarget": false,
+ "rejectsBothTargets": null
+ },
+ "legacyTokenAndHashPreserved": true
+ }
+ ],
+ "benchmarks": [
+ {
+ "variant": "two_tables",
+ "noteCount": 100,
+ "overrideCount": 10,
+ "configJsonBytes": 717,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 0.0595,
+ "p95Ms": 0.0692
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0133,
+ "p95Ms": 0.142
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 0.1138,
+ "p95Ms": 0.1735
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0025,
+ "p95Ms": 0.0048
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "one_table",
+ "noteCount": 100,
+ "overrideCount": 10,
+ "configJsonBytes": 717,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 0.0604,
+ "p95Ms": 0.0722
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0117,
+ "p95Ms": 0.0154
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 0.1122,
+ "p95Ms": 0.232
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.002,
+ "p95Ms": 0.0042
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "json_column",
+ "noteCount": 100,
+ "overrideCount": 10,
+ "configJsonBytes": 717,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 0.0832,
+ "p95Ms": 0.1847
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0124,
+ "p95Ms": 0.0134
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 0.1019,
+ "p95Ms": 0.1206
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0036,
+ "p95Ms": 0.0103
+ },
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "LIST SUBQUERY 3",
+ "SEARCH cfg USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SCAN j VIRTUAL TABLE INDEX 3:",
+ "CREATE BLOOM FILTER",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 4",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ],
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t"
+ ]
+ },
+ {
+ "variant": "two_tables",
+ "noteCount": 1000,
+ "overrideCount": 100,
+ "configJsonBytes": 7018,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 0.6742,
+ "p95Ms": 0.8593
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0137,
+ "p95Ms": 0.0243
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 0.4637,
+ "p95Ms": 0.5256
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0018,
+ "p95Ms": 0.0047
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "one_table",
+ "noteCount": 1000,
+ "overrideCount": 100,
+ "configJsonBytes": 7018,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 0.5508,
+ "p95Ms": 0.7784
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0126,
+ "p95Ms": 0.0382
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 0.5009,
+ "p95Ms": 0.5832
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0017,
+ "p95Ms": 0.0052
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "json_column",
+ "noteCount": 1000,
+ "overrideCount": 100,
+ "configJsonBytes": 7018,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 0.7777,
+ "p95Ms": 0.9995
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0214,
+ "p95Ms": 0.0795
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 0.6839,
+ "p95Ms": 1.0468
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.012,
+ "p95Ms": 0.0223
+ },
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "LIST SUBQUERY 3",
+ "SEARCH cfg USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SCAN j VIRTUAL TABLE INDEX 3:",
+ "CREATE BLOOM FILTER",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 4",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ],
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t"
+ ]
+ },
+ {
+ "variant": "two_tables",
+ "noteCount": 10000,
+ "overrideCount": 1000,
+ "configJsonBytes": 70919,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 5.5652,
+ "p95Ms": 5.9131
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0127,
+ "p95Ms": 0.0275
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 4.1289,
+ "p95Ms": 4.4661
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0017,
+ "p95Ms": 0.0036
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "one_table",
+ "noteCount": 10000,
+ "overrideCount": 1000,
+ "configJsonBytes": 70919,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 5.8717,
+ "p95Ms": 6.4982
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.013,
+ "p95Ms": 0.02
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 3.7865,
+ "p95Ms": 4.0996
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.002,
+ "p95Ms": 0.0053
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "json_column",
+ "noteCount": 10000,
+ "overrideCount": 1000,
+ "configJsonBytes": 70919,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 6.3594,
+ "p95Ms": 8.4825
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0695,
+ "p95Ms": 0.0784
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 4.1332,
+ "p95Ms": 4.4292
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0754,
+ "p95Ms": 0.0909
+ },
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "LIST SUBQUERY 3",
+ "SEARCH cfg USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SCAN j VIRTUAL TABLE INDEX 3:",
+ "CREATE BLOOM FILTER",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 4",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ],
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t"
+ ]
+ },
+ {
+ "variant": "two_tables",
+ "noteCount": 10000,
+ "overrideCount": 10000,
+ "configJsonBytes": 718920,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 5.1214,
+ "p95Ms": 5.9272
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0126,
+ "p95Ms": 0.0151
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 4.0203,
+ "p95Ms": 4.4488
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0015,
+ "p95Ms": 0.0075
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX sqlite_autoindex_ab_memo_settings_1 (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "one_table",
+ "noteCount": 10000,
+ "overrideCount": 10000,
+ "configJsonBytes": 718920,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 5.6033,
+ "p95Ms": 6.4393
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.0136,
+ "p95Ms": 0.02
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 4.1953,
+ "p95Ms": 4.4987
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.0021,
+ "p95Ms": 0.0032
+ },
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR LAST 3 TERMS OF ORDER BY"
+ ],
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SEARCH e USING INDEX ab_item_memo (share_id=? AND memo_id=?) LEFT-JOIN",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ]
+ },
+ {
+ "variant": "json_column",
+ "noteCount": 10000,
+ "overrideCount": 10000,
+ "configJsonBytes": 718920,
+ "directory": {
+ "samples": 15,
+ "p50Ms": 9.2974,
+ "p95Ms": 11.7198
+ },
+ "point": {
+ "samples": 15,
+ "p50Ms": 0.5821,
+ "p95Ms": 0.6379
+ },
+ "search": {
+ "samples": 15,
+ "p50Ms": 6.4183,
+ "p95Ms": 6.6666
+ },
+ "update": {
+ "samples": 15,
+ "p50Ms": 0.7673,
+ "p95Ms": 0.819
+ },
+ "directoryQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX idx_memos_trash_feed (is_deleted=?)",
+ "LIST SUBQUERY 3",
+ "SEARCH cfg USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SCAN j VIRTUAL TABLE INDEX 3:",
+ "CREATE BLOOM FILTER",
+ "SEARCH t USING AUTOMATIC COVERING INDEX (id=? AND workspace_id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 4",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "USE TEMP B-TREE FOR ORDER BY"
+ ],
+ "pointQueryPlan": [
+ "CO-ROUTINE tree",
+ "SETUP",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "SEARCH n USING INDEX sqlite_autoindex_notebooks_1 (id=?)",
+ "RECURSIVE STEP",
+ "SEARCH n USING INDEX idx_notebooks_deleted (is_deleted=?)",
+ "SCAN t",
+ "SEARCH m USING INDEX sqlite_autoindex_memos_1 (id=?)",
+ "SEARCH ns USING INDEX sqlite_autoindex_notebook_shares_1 (id=?)",
+ "CORRELATED SCALAR SUBQUERY 3",
+ "SEARCH mt USING COVERING INDEX sqlite_autoindex_memo_tags_1 (memo_id=?)",
+ "SCAN tags VIRTUAL TABLE INDEX 1:",
+ "SCAN t"
+ ]
+ }
+ ],
+ "configurationSizes": [
+ {
+ "overrideCount": 1000,
+ "bytes": 70919
+ },
+ {
+ "overrideCount": 10000,
+ "bytes": 718920
+ },
+ {
+ "overrideCount": 50000,
+ "bytes": 3638920
+ }
+ ]
+}
diff --git a/migrations/0072_public_notebook_sites.sql b/migrations/0072_public_notebook_sites.sql
new file mode 100644
index 00000000..20c9350f
--- /dev/null
+++ b/migrations/0072_public_notebook_sites.sql
@@ -0,0 +1,12 @@
+ALTER TABLE notebook_shares ADD COLUMN site_slug TEXT;
+ALTER TABLE notebook_shares ADD COLUMN site_settings_json TEXT NOT NULL DEFAULT '{}'
+ CHECK (json_valid(site_settings_json) AND json_type(site_settings_json) = 'object');
+CREATE UNIQUE INDEX idx_notebook_shares_site_slug
+ ON notebook_shares(lower(site_slug)) WHERE site_slug IS NOT NULL;
+
+CREATE TABLE notebook_share_excluded_memos (
+ share_id TEXT NOT NULL REFERENCES notebook_shares(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ memo_id TEXT NOT NULL REFERENCES memos(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ PRIMARY KEY (share_id, memo_id)
+);
+CREATE INDEX idx_notebook_share_excluded_memos_memo ON notebook_share_excluded_memos(memo_id);
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index a9174de7..55417753 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -33,6 +33,12 @@ import type {
MemoShare,
NotebookShare,
PublicNotebookShare,
+ NotebookSiteUpdate,
+ NotebookSiteSearchResult,
+ NotebookSiteExclusions,
+ NotebookSiteContents,
+ MemoNotebookSite,
+ NotebookSiteMemoPreview,
ManagedMemoShare,
PublicTableForm,
TableFormSettings,
@@ -754,6 +760,27 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
getPublicNotebookShare: (token: string) =>
request<{ share: PublicNotebookShare }>(`/api/public/notebook-shares/${encodeURIComponent(token)}`),
+ resolveNotebookSite: (slug: string) => request<{ token: string }>(`/api/public/notebook-sites/${encodeURIComponent(slug)}/resolve`),
+ searchPublicNotebook: (token: string, input: { q?: string; tag?: string; cursor?: string | null }) => {
+ const params = new URLSearchParams();
+ if (input.q) params.set("q", input.q);
+ if (input.tag) params.set("tag", input.tag);
+ if (input.cursor) params.set("cursor", input.cursor);
+ return request<NotebookSiteSearchResult>(`/api/public/notebook-shares/${encodeURIComponent(token)}/search?${params}`);
+ },
+ previewPublicNotebookMemo: (token: string, memoId: string) => request<{ memo: NotebookSiteMemoPreview }>(`/api/public/notebook-shares/${encodeURIComponent(token)}/memos/${encodeURIComponent(memoId)}/preview`),
+ updateNotebookSite: (id: string, input: NotebookSiteUpdate) => request<{ share: NotebookShare }>(`/api/v1/notebooks/${encodeURIComponent(id)}/share/site`, { method: "PATCH", body: JSON.stringify(input) }),
+ getMemoNotebookSites: (memoId: string) => request<{ sites: MemoNotebookSite[] }>(`/api/v1/memos/${encodeURIComponent(memoId)}/notebook-sites`),
+ listNotebookSiteMemos: (id: string, input: { q?: string; visibility?: "all" | "public" | "excluded"; cursor?: string | null; limit?: number }) => {
+ const params = new URLSearchParams();
+ if (input.q) params.set("q", input.q);
+ if (input.visibility) params.set("visibility", input.visibility);
+ if (input.cursor) params.set("cursor", input.cursor);
+ if (input.limit !== undefined) params.set("limit", String(input.limit));
+ return request<NotebookSiteContents>(`/api/v1/notebooks/${encodeURIComponent(id)}/share/memos?${params}`);
+ },
+ listNotebookSiteExclusions: (id: string, cursor?: string | null) => request<NotebookSiteExclusions>(`/api/v1/notebooks/${encodeURIComponent(id)}/share/excluded-memos${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`),
+ setNotebookSiteExclusion: (id: string, memoId: string, excluded: boolean) => request<{ memoId: string; excluded: boolean }>(`/api/v1/notebooks/${encodeURIComponent(id)}/share/memos/${encodeURIComponent(memoId)}`, { method: "PATCH", body: JSON.stringify({ excluded }) }),
getPublicNotebookMemo: (token: string, memoId: string) =>
request<{ share: PublicMemoShare; memoUrls: Record<string, string> }>(`/api/public/notebook-shares/${encodeURIComponent(token)}/memos/${encodeURIComponent(memoId)}`),
unlockPublicNotebookShare: (token: string, password: string) =>
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index aeacb756..645cca88 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2632,7 +2632,77 @@ export const enUS = {
collapseOutlineHeading: "Collapse {{name}}",
expandOutlineHeading: "Expand {{name}}",
},
+ notebookSite: {
+ advancedSettings: "Advanced settings",
+ noteSites: "Notebook site visibility",
+ showInSite: "Show in the ‘{{name}}’ site",
+ noteSitesHint: "Changes apply immediately to the selected site. Other share links are managed separately.",
+ manage: "Manage site",
+ backToNotes: "Back to notes",
+ content: "Content",
+ chooseHomepage: "Choose homepage note",
+ useDirectory: "Use directory home",
+ saveHint: "Save to apply site settings.",
+ homepageHint: "Search included notes, choose a homepage, then save settings.",
+ homepageFallback: "The selected homepage is unavailable, so visitors see the directory. Restoring its visibility reactivates it as the homepage.",
+ findNotes: "Search note titles or text",
+ visibility: "Visibility",
+ allNotes: "All notes",
+ included: "Public",
+ excludedState: "Excluded",
+ immediateHint: "Exclusions and restores apply immediately to this site only.",
+ page: "Page {{page}}",
+ previousPage: "Previous",
+ nextPage: "Next",
+ noNotes: "No matching notes",
+ selectNote: "Select",
+ contentSaved: "Visibility updated",
+ noActiveShare: "Sharing is not enabled for this notebook, or the share was revoked.",
+ fit: "Fit to window",
+ fullscreen: "Fullscreen",
+ exitFullscreen: "Exit fullscreen",
+
+ settings: "Site settings",
+ slug: "URL alias",
+ homepage: "Homepage",
+ directory: "Directory",
+ logo: "Logo URL (HTTPS)",
+ headerLinks: "Header links",
+ label: "Label",
+ url: "URL (HTTPS)",
+ addLink: "Add link",
+ remove: "Remove",
+ footer: "Footer",
+ indexing: "Allow search engine indexing",
+ indexingHint: "Only available without a password. Public content may appear in search results.",
+ sort: "Chapter order",
+ existingOrder: "Existing order",
+ titleOrder: "Title / number",
+ save: "Save settings",
+ saved: "Settings saved",
+ chooseNotes: "Find notes to select a homepage or exclude from this site",
+ exclude: "Exclude",
+ restore: "Restore",
+ excluded: "Excluded notes",
+ exclusionHint: "Exclusions apply only to this site. Other share links keep their own access rules.",
+ more: "Load more",
+ outline: "On this page",
+ collapse: "Collapse code",
+ expand: "Expand code",
+ language: "Language",
+ search: "Search this site",
+ allTags: "All tags",
+ searchHint: "Search titles and article text · ⌘/Ctrl K",
+ light: "Light",
+ dark: "Dark",
+ system: "System",
+ theme: "Appearance",
+ previewUnavailable: "Preview unavailable",
+ homepageSelected: "Selected homepage",
+ },
sharing: {
+ individual: "Individual note link",
+ createIndividual: "Create individual note link",
qrCode: "QR code",
qrCodeLabel: "QR code for the share link",
qrCodeHint: "Scan with a phone camera to open this note.",
@@ -2641,7 +2711,7 @@ export const enUS = {
siteHideContents: "Hide contents",
siteShowContents: "Show contents",
siteHome: "Home",
- siteSearch: "Search note titles",
+ siteSearch: "Search titles and text",
siteClearSearch: "Clear search",
siteNoteCount: "{{count}} notes",
siteWelcome: "Explore the notes and topics, and find something that interests you.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 3006bbd1..1c736eca 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2621,7 +2621,77 @@ export const ja = {
collapseOutlineHeading: "{{name}} を閉じる",
expandOutlineHeading: "{{name}} を開く",
},
+ notebookSite: {
+ advancedSettings: "詳細設定",
+ noteSites: "ノートブックサイトでの表示",
+ showInSite: "「{{name}}」サイトに表示",
+ noteSitesHint: "変更は対象サイトだけに直ちに反映されます。他の共有リンクは個別に管理します。",
+ manage: "サイト管理",
+ backToNotes: "ノートに戻る",
+ content: "コンテンツ管理",
+ chooseHomepage: "ホームのノートを選択",
+ useDirectory: "目次をホームにする",
+ saveHint: "サイト設定は保存後に反映されます。",
+ homepageHint: "除外されていないノートを検索して選び、設定を保存してください。",
+ homepageFallback: "選択したホームのノートは現在利用できないため、訪問者には目次が表示されます。表示を復元すると、再びホームになります。",
+ findNotes: "ノートのタイトルや本文を検索",
+ visibility: "公開状態",
+ allNotes: "すべてのノート",
+ included: "公開",
+ excludedState: "除外済み",
+ immediateHint: "除外と復元は、このサイトだけに直ちに反映されます。",
+ page: "{{page}} ページ",
+ previousPage: "前へ",
+ nextPage: "次へ",
+ noNotes: "一致するノートがありません",
+ selectNote: "選択",
+ contentSaved: "公開状態を更新しました",
+ noActiveShare: "このノートブックは未共有か、共有が取り消されています。",
+ fit: "ウィンドウに合わせる",
+ fullscreen: "全画面表示",
+ exitFullscreen: "全画面表示を終了",
+
+ settings: "サイト設定",
+ slug: "URL エイリアス",
+ homepage: "ホームページ",
+ directory: "目次",
+ logo: "ロゴ URL(HTTPS)",
+ headerLinks: "ヘッダーリンク",
+ label: "表示名",
+ url: "URL(HTTPS)",
+ addLink: "リンクを追加",
+ remove: "削除",
+ footer: "フッター",
+ indexing: "検索エンジンの登録を許可",
+ indexingHint: "パスワードのないサイトのみ利用できます。公開内容が検索結果に表示される場合があります。",
+ sort: "章の順序",
+ existingOrder: "既存の順序",
+ titleOrder: "タイトル / 番号",
+ save: "設定を保存",
+ saved: "保存しました",
+ chooseNotes: "ノートを検索してホームページの選択や公開の除外を行います",
+ exclude: "除外",
+ restore: "復元",
+ excluded: "除外したノート",
+ exclusionHint: "除外はこのサイトのみ有効です。他の共有リンクは各自のアクセス設定に従います。",
+ more: "さらに読み込む",
+ outline: "このページの目次",
+ collapse: "コードを折りたたむ",
+ expand: "コードを展開",
+ language: "言語",
+ search: "サイト内を検索",
+ allTags: "すべてのタグ",
+ searchHint: "タイトルと本文を検索 · ⌘/Ctrl K",
+ light: "ライト",
+ dark: "ダーク",
+ system: "システム",
+ theme: "外観",
+ previewUnavailable: "プレビューを表示できません",
+ homepageSelected: "選択中のホームページ",
+ },
sharing: {
+ individual: "個別ノートの共有リンク",
+ createIndividual: "個別ノートの共有リンクを作成",
qrCode: "QR コード",
qrCodeLabel: "共有リンクの QR コード",
qrCodeHint: "スマートフォンのカメラで読み取ると、このノートを開けます。",
@@ -2630,7 +2700,7 @@ export const ja = {
siteHideContents: "目次を隠す",
siteShowContents: "目次を表示",
siteHome: "ホーム",
- siteSearch: "ノートのタイトルを検索",
+ siteSearch: "タイトルと本文を検索",
siteClearSearch: "検索をクリア",
siteNoteCount: "{{count}} 件のノート",
siteWelcome: "ノートやカテゴリから、興味のある内容を見つけてください。",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index fa49f909..29239096 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2621,7 +2621,77 @@ export const pl = {
collapseOutlineHeading: "Zwiń {{name}}",
expandOutlineHeading: "Rozwiń {{name}}",
},
+ notebookSite: {
+ advancedSettings: "Ustawienia zaawansowane",
+ noteSites: "Widoczność w witrynach notatników",
+ showInSite: "Pokaż w witrynie „{{name}}”",
+ noteSitesHint: "Zmiana działa od razu tylko w wybranej witrynie. Pozostałymi linkami zarządza się osobno.",
+ manage: "Zarządzaj witryną",
+ backToNotes: "Wróć do notatek",
+ content: "Zawartość",
+ chooseHomepage: "Wybierz notatkę strony głównej",
+ useDirectory: "Użyj spisu treści",
+ saveHint: "Zapisz, aby zastosować ustawienia witryny.",
+ homepageHint: "Wyszukaj niewykluczoną notatkę, wybierz stronę główną i zapisz ustawienia.",
+ homepageFallback: "Wybrana strona główna jest niedostępna, więc odwiedzający widzą spis treści. Przywrócenie widoczności ponownie ustawi ją jako stronę główną.",
+ findNotes: "Szukaj w tytułach lub treści notatek",
+ visibility: "Widoczność",
+ allNotes: "Wszystkie notatki",
+ included: "Publiczna",
+ excludedState: "Wykluczona",
+ immediateHint: "Wykluczenie i przywrócenie działa od razu, tylko w tej witrynie.",
+ page: "Strona {{page}}",
+ previousPage: "Poprzednia",
+ nextPage: "Następna",
+ noNotes: "Brak pasujących notatek",
+ selectNote: "Wybierz",
+ contentSaved: "Zaktualizowano widoczność",
+ noActiveShare: "Ten notatnik nie jest udostępniony lub udostępnienie zostało cofnięte.",
+ fit: "Dopasuj do okna",
+ fullscreen: "Pełny ekran",
+ exitFullscreen: "Opuść pełny ekran",
+
+ settings: "Ustawienia witryny",
+ slug: "Alias URL",
+ homepage: "Strona główna",
+ directory: "Spis treści",
+ logo: "Adres logo (HTTPS)",
+ headerLinks: "Łącza nagłówka",
+ label: "Etykieta",
+ url: "Adres URL (HTTPS)",
+ addLink: "Dodaj łącze",
+ remove: "Usuń",
+ footer: "Stopka",
+ indexing: "Zezwól na indeksowanie",
+ indexingHint: "Dostępne tylko bez hasła. Publiczna treść może pojawić się w wynikach wyszukiwania.",
+ sort: "Kolejność rozdziałów",
+ existingOrder: "Obecna kolejność",
+ titleOrder: "Tytuł / numer",
+ save: "Zapisz ustawienia",
+ saved: "Ustawienia zapisane",
+ chooseNotes: "Znajdź notatki, aby wybrać stronę główną lub wykluczyć je z witryny",
+ exclude: "Wyklucz",
+ restore: "Przywróć",
+ excluded: "Wykluczone notatki",
+ exclusionHint: "Wykluczenia dotyczą tylko tej witryny. Inne łącza zachowują własne reguły dostępu.",
+ more: "Wczytaj więcej",
+ outline: "Na tej stronie",
+ collapse: "Zwiń kod",
+ expand: "Rozwiń kod",
+ language: "Język",
+ search: "Szukaj w witrynie",
+ allTags: "Wszystkie tagi",
+ searchHint: "Szukaj w tytułach i treści · ⌘/Ctrl K",
+ light: "Jasny",
+ dark: "Ciemny",
+ system: "Systemowy",
+ theme: "Wygląd",
+ previewUnavailable: "Podgląd niedostępny",
+ homepageSelected: "Wybrana strona główna",
+ },
sharing: {
+ individual: "Link do pojedynczej notatki",
+ createIndividual: "Utwórz link do pojedynczej notatki",
qrCode: "Kod QR",
qrCodeLabel: "Kod QR linku udostępniania",
qrCodeHint: "Zeskanuj aparatem telefonu, aby otworzyć tę notatkę.",
@@ -2630,7 +2700,7 @@ export const pl = {
siteHideContents: "Ukryj spis treści",
siteShowContents: "Pokaż spis treści",
siteHome: "Strona główna",
- siteSearch: "Szukaj tytułów notatek",
+ siteSearch: "Szukaj w tytułach i treści",
siteClearSearch: "Wyczyść wyszukiwanie",
siteNoteCount: "Notatki: {{count}}",
siteWelcome: "Przeglądaj notatki i tematy, aby znaleźć interesujące treści.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 9058b965..9e4ab74a 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2630,7 +2630,77 @@ export const zhCN = {
collapseOutlineHeading: "收起 {{name}}",
expandOutlineHeading: "展开 {{name}}",
},
+ notebookSite: {
+ advancedSettings: "进阶设置",
+ noteSites: "笔记本站点展示",
+ showInSite: "在「{{name}}」站点中展示",
+ noteSitesHint: "立即生效,仅影响对应站点。其他分享链接单独管理。",
+ manage: "管理站点",
+ backToNotes: "返回笔记",
+ content: "内容管理",
+ chooseHomepage: "选择首页笔记",
+ useDirectory: "使用目录首页",
+ saveHint: "站点设置需保存后生效。",
+ homepageHint: "搜索当前站点未排除的笔记,选择后保存设置。",
+ homepageFallback: "所选首页笔记当前不可用,访客将看到目录。恢复展示后,原首页会重新生效。",
+ findNotes: "搜索笔记标题或正文",
+ visibility: "公开状态",
+ allNotes: "全部笔记",
+ included: "公开",
+ excludedState: "已排除",
+ immediateHint: "排除与恢复立即生效,仅影响此站点。",
+ page: "第 {{page}} 页",
+ previousPage: "上一页",
+ nextPage: "下一页",
+ noNotes: "没有符合条件的笔记",
+ selectNote: "选择",
+ contentSaved: "公开状态已更新",
+ noActiveShare: "此笔记本尚未启用分享,或分享已撤销。",
+ fit: "适应窗口",
+ fullscreen: "全屏查看",
+ exitFullscreen: "退出全屏",
+
+ settings: "站点设置",
+ slug: "URL 别名",
+ homepage: "站点首页",
+ directory: "目录",
+ logo: "Logo 地址(HTTPS)",
+ headerLinks: "页眉外链",
+ label: "文字",
+ url: "地址(HTTPS)",
+ addLink: "添加外链",
+ remove: "移除",
+ footer: "页脚",
+ indexing: "允许搜索引擎收录",
+ indexingHint: "仅无密码站点可开启,公开内容可能出现在搜索结果中。",
+ sort: "章节排序",
+ existingOrder: "现有顺序",
+ titleOrder: "标题 / 序号",
+ save: "保存设置",
+ saved: "设置已保存",
+ chooseNotes: "搜索笔记,选择首页或从此站点排除",
+ exclude: "排除",
+ restore: "恢复",
+ excluded: "已排除的笔记",
+ exclusionHint: "排除仅对当前站点生效,其他分享链接仍按各自规则访问。",
+ more: "加载更多",
+ outline: "本文大纲",
+ collapse: "折叠代码",
+ expand: "展开代码",
+ language: "语言",
+ search: "搜索本站",
+ allTags: "全部标签",
+ searchHint: "搜索标题和正文 · ⌘/Ctrl K",
+ light: "浅色",
+ dark: "深色",
+ system: "跟随系统",
+ theme: "外观",
+ previewUnavailable: "预览不可用",
+ homepageSelected: "当前首页",
+ },
sharing: {
+ individual: "单篇分享链接",
+ createIndividual: "创建单篇分享链接",
qrCode: "二维码",
qrCodeLabel: "分享链接二维码",
qrCodeHint: "用手机相机扫码即可打开这篇笔记。",
@@ -2639,7 +2709,7 @@ export const zhCN = {
siteHideContents: "收起目录",
siteShowContents: "展开目录",
siteHome: "首页",
- siteSearch: "搜索笔记标题",
+ siteSearch: "搜索标题和正文",
siteClearSearch: "清除搜索",
siteNoteCount: "{{count}} 篇笔记",
siteWelcome: "浏览这里的笔记与栏目,找到你感兴趣的内容。",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 1bb31def..95dea438 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -31,6 +31,7 @@ export * from "./revision-diff";
export * from "./resource-links";
export * from "./schemas";
export * from "./sharing";
+export * from "./notebook-site";
export * from "./sync";
export * from "./desktop-rpc";
export * from "./details";
diff --git a/packages/shared/src/notebook-site.ts b/packages/shared/src/notebook-site.ts
new file mode 100644
index 00000000..e547b036
--- /dev/null
+++ b/packages/shared/src/notebook-site.ts
@@ -0,0 +1,56 @@
+import { z } from "zod";
+
+const httpsUrl = z.url({ protocol: /^https$/ });
+export const NotebookSiteSettingsSchema = z.object({
+ homeMemoId: z.string().nullable().default(null),
+ logoUrl: httpsUrl.nullable().default(null),
+ headerLinks: z.array(z.object({ label: z.string().trim().min(1), url: httpsUrl }).strict()).default([]),
+ footerText: z.string().default(""),
+ allowIndexing: z.boolean().default(false),
+ sortMode: z.enum(["existing", "title"]).default("existing"),
+}).strict();
+export type NotebookSiteSettings = z.infer<typeof NotebookSiteSettingsSchema>;
+export const NotebookSiteUpdateSchema = z.object({
+ siteSlug: z.string().trim().toLowerCase().regex(/^[a-z0-9-]*$/).nullable().optional(),
+ settings: z.object({
+ homeMemoId: NotebookSiteSettingsSchema.shape.homeMemoId.removeDefault().optional(),
+ logoUrl: NotebookSiteSettingsSchema.shape.logoUrl.removeDefault().optional(),
+ headerLinks: NotebookSiteSettingsSchema.shape.headerLinks.removeDefault().optional(),
+ footerText: NotebookSiteSettingsSchema.shape.footerText.removeDefault().optional(),
+ allowIndexing: NotebookSiteSettingsSchema.shape.allowIndexing.removeDefault().optional(),
+ sortMode: NotebookSiteSettingsSchema.shape.sortMode.removeDefault().optional(),
+ }).strict().optional(),
+}).strict();
+export type NotebookSiteUpdate = z.infer<typeof NotebookSiteUpdateSchema>;
+export const NotebookSiteExclusionSchema = z.object({ excluded: z.boolean() }).strict();
+export const readNotebookSiteSettings = (raw?: string | null): NotebookSiteSettings => {
+ try {
+ const result = NotebookSiteSettingsSchema.safeParse(JSON.parse(raw || "{}"));
+ if (result.success) return result.data;
+ } catch { /* Malformed legacy settings retain conservative defaults. */ }
+ return NotebookSiteSettingsSchema.parse({});
+};
+
+const collator = new Intl.Collator("zh-CN", { numeric: true, sensitivity: "base" });
+export const compareNotebookSiteTitles = (a: { id: string; title?: string | null; name?: string }, b: { id: string; title?: string | null; name?: string }) =>
+ collator.compare(a.title ?? a.name ?? "", b.title ?? b.name ?? "") || a.id.localeCompare(b.id);
+
+export type NotebookSiteMemoPreview = { id: string; title: string | null; excerpt: string };
+export type NotebookSiteSearchResult = {
+ memos: Array<NotebookSiteMemoPreview & { notebookId: string; highlights: string[] }>;
+ nextCursor: string | null;
+};
+export type NotebookSiteExclusions = {
+ memos: Array<{ id: string; title: string | null }>;
+ nextCursor: string | null;
+};
+
+export type NotebookSiteMemo = {
+ id: string;
+ title: string | null;
+ notebookId: string;
+ notebookName: string;
+ excluded: boolean;
+};
+export type NotebookSiteContents = { memos: NotebookSiteMemo[]; nextCursor: string | null };
+export type MemoNotebookSite = { notebookId: string; notebookName: string; excluded: boolean };
diff --git a/packages/shared/src/sharing.ts b/packages/shared/src/sharing.ts
index 02cf0bd3..729a0f74 100644
--- a/packages/shared/src/sharing.ts
+++ b/packages/shared/src/sharing.ts
@@ -2,6 +2,7 @@ import { FONT_IDS } from "./font-catalog";
import type { TiptapDoc, TiptapNode, TiptapTextNode } from "./content";
import type { PublicNoteProse } from "./note-prose";
import { parseMemoLinkHref } from "./note-links";
+import type { NotebookSiteSettings } from "./notebook-site";
export type MemoShare = {
memoId: string;
@@ -20,6 +21,8 @@ export type ManagedMemoShare = MemoShare & {
};
export type NotebookShare = {
+ siteSlug?: string | null;
+ siteSettings?: NotebookSiteSettings;
notebookId: string;
notebookName: string;
token: string;
@@ -31,6 +34,8 @@ export type NotebookShare = {
};
export type PublicNotebookShare = {
+ siteSlug?: string | null;
+ settings?: NotebookSiteSettings;
notebookId: string;
name: string;
notebooks: Array<{ id: string; parentId: string | null; name: string }>;
diff --git a/scripts/public-notebook-site-plan-ablation.mjs b/scripts/public-notebook-site-plan-ablation.mjs
new file mode 100644
index 00000000..9d6cfd8f
--- /dev/null
+++ b/scripts/public-notebook-site-plan-ablation.mjs
@@ -0,0 +1,251 @@
+// Whole-plan ablation: executed local SQL/data models plus explicitly labelled
+// requirement/source-based decisions. This is not product or browser acceptance.
+// Run: bun scripts/public-notebook-site-plan-ablation.mjs > docs/public-notebook-site-plan-ablation.json
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { globSync, readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { Database } from "bun:sqlite";
+import { z } from "zod";
+import { createExcerpt } from "../packages/shared/src/content.ts";
+import { escapeLike, toFtsQuery } from "../apps/api/src/memo-list-service.ts";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const db = new Database(":memory:");
+const checks = [];
+const counterexamples = [];
+const check = (name, run) => { run(); checks.push(name); };
+const share = "plan_root";
+const child = "plan_child";
+const Settings = z.object({
+ homeMemoId: z.string().nullable().optional(),
+ logoUrl: z.string().url().refine((value) => new URL(value).protocol === "https:").nullable().optional(),
+ headerLinks: z.array(z.object({ label: z.string(), url: z.string().url().refine((value) => new URL(value).protocol === "https:") }).strict()).optional(),
+ footerText: z.string().optional(),
+ allowIndexing: z.boolean().optional(),
+ excludedTags: z.array(z.string()).optional(),
+ sortMode: z.enum(["existing", "title"]).optional(),
+}).strict();
+const MAX_SETTINGS_BYTES = 16 * 1024;
+const collator = new Intl.Collator("zh-CN", { numeric: true, sensitivity: "base" });
+const sortTitles = (items) => [...items].sort((a, b) => collator.compare(a.title, b.title) || a.id.localeCompare(b.id));
+const bytes = (value) => Buffer.byteLength(JSON.stringify(value));
+const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
+
+try {
+ const migrations = globSync("migrations/*.sql", { cwd: root }).sort();
+ for (const path of migrations) db.exec(readFileSync(new URL(`../${path}`, import.meta.url), "utf8"));
+ db.exec("PRAGMA foreign_keys=ON");
+ db.exec("INSERT INTO workspaces(id,name) VALUES('plan_ws','Plan'),('plan_other','Other')");
+ for (const [id, parent, workspace, name] of [
+ ["plan_root_nb", null, "plan_ws", "Knowledge"], ["plan_2", "plan_root_nb", "plan_ws", "第2章"],
+ ["plan_10", "plan_root_nb", "plan_ws", "第10章"], ["plan_out", null, "plan_ws", "Outside"],
+ ["plan_foreign", "plan_root_nb", "plan_other", "Other workspace"],
+ ]) db.run("INSERT INTO notebooks(id,parent_id,workspace_id,name) VALUES(?,?,?,?)", [id, parent, workspace, name]);
+ db.run("INSERT INTO notebook_shares(id,notebook_id,workspace_id,token,password_hash) VALUES(?, 'plan_root_nb','plan_ws',?,'legacy-hash'),(?, 'plan_2','plan_ws',?,NULL)", [share, "p".repeat(43), child, "c".repeat(43)]);
+ const legacy = db.query("SELECT token,password_hash FROM notebook_shares WHERE id=?").get(share);
+ const oldTables = db.query("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();
+ const oldColumns = db.query("PRAGMA table_info(notebook_shares)").all().map((x) => x.name);
+ db.exec("ALTER TABLE notebook_shares ADD COLUMN site_slug TEXT; ALTER TABLE notebook_shares ADD COLUMN site_settings_json TEXT NOT NULL DEFAULT '{}' CHECK(json_valid(site_settings_json) AND json_type(site_settings_json)='object'); CREATE UNIQUE INDEX plan_site_slug ON notebook_shares(lower(site_slug)) WHERE site_slug IS NOT NULL");
+ check("zero_new_tables_two_added_columns", () => {
+ assert.deepEqual(db.query("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all(), oldTables);
+ assert.deepEqual(db.query("PRAGMA table_info(notebook_shares)").all().map((x) => x.name).filter((name) => !oldColumns.includes(name)), ["site_slug", "site_settings_json"]);
+ assert.deepEqual(db.query("SELECT token,password_hash FROM notebook_shares WHERE id=?").get(share), legacy);
+ });
+ check("old_share_defaults_unchanged", () => assert.deepEqual(JSON.parse(db.query("SELECT site_settings_json FROM notebook_shares WHERE id=?").get(share).site_settings_json), {}));
+
+ const text = "正文中有唯一检索词和 ablationbody,标题不含这些词。";
+ for (const [id, notebook, workspace, title, tags] of [
+ ["a_hidden", "plan_2", "plan_ws", "第1节", ["draft"]],
+ ["b_ten", "plan_2", "plan_ws", "第10节", ["topic"]],
+ ["c_two", "plan_2", "plan_ws", "第2节", ["topic"]],
+ ["d_home", "plan_10", "plan_ws", "概览", []],
+ ["outside", "plan_out", "plan_ws", "Outside", []],
+ ["foreign", "plan_foreign", "plan_other", "Foreign", []],
+ ]) {
+ db.run("INSERT INTO memos(id,notebook_id,workspace_id,title,excerpt,tags_json) VALUES(?,?,?,?,?,?)", [id, notebook, workspace, title, createExcerpt(text), JSON.stringify(tags)]);
+ db.run("INSERT INTO memo_contents(memo_id,content_json,content_markdown,content_text,content_hash) VALUES(?,?,?,?,?)", [id, '{"type":"doc","content":[]}', text, text, id]);
+ db.run("INSERT INTO memo_search_documents(memo_id,title,content_text,tags) VALUES(?,?,?,?)", [id, title, text, tags.join(" ")]);
+ db.run("INSERT INTO resources(id,memo_id,object_key,kind) VALUES(?,?,?,'image')", [`res_${id}`, id, id]);
+ }
+ const tree = `WITH RECURSIVE tree(id,workspace_id) AS (
+ SELECT n.id,n.workspace_id FROM notebook_shares ns JOIN notebooks n ON n.id=ns.notebook_id AND n.workspace_id=ns.workspace_id WHERE ns.id=$share AND n.is_deleted=0
+ UNION SELECT n.id,n.workspace_id FROM notebooks n JOIN tree t ON n.parent_id=t.id WHERE n.workspace_id=t.workspace_id AND n.is_deleted=0)`;
+ const scope = `FROM memos m JOIN tree t ON t.id=m.notebook_id AND t.workspace_id=m.workspace_id JOIN notebook_shares ns ON ns.id=$share
+ WHERE m.is_deleted=0`;
+ const visible = `AND NOT EXISTS(SELECT 1 FROM memo_tags mt JOIN json_each(ns.site_settings_json,'$.excludedTags') et ON mt.name=et.value WHERE mt.memo_id=m.id)`;
+ const rows = (sid = share) => db.query(`${tree} SELECT m.id,m.notebook_id,m.title ${scope} ${visible} ORDER BY m.id`).all({ $share: sid });
+ const point = (id, sid = share) => db.query(`${tree} SELECT m.id,m.title,m.excerpt ${scope} ${visible} AND m.id=$id`).get({ $share: sid, $id: id });
+ const resource = (id) => db.query(`${tree} SELECT m.id ${scope} ${visible} AND m.id=(SELECT memo_id FROM resources WHERE id=$id AND is_deleted=0)`).get({ $share: share, $id: id });
+ function search(query, tag = null, limit = 2) {
+ return db.query(`${tree} SELECT m.id ${scope} ${visible}
+ AND ($tag IS NULL OR EXISTS(SELECT 1 FROM memo_tags mt WHERE mt.memo_id=m.id AND mt.name=$tag))
+ AND (m.id IN(SELECT memo_id FROM memos_fts WHERE memos_fts MATCH $fts) OR m.id IN(SELECT memo_id FROM memo_contents WHERE content_text LIKE $like ESCAPE '\\'))
+ ORDER BY m.id LIMIT $limit`).all({ $share: share, $tag: tag, $fts: toFtsQuery(query), $like: `%${escapeLike(query)}%`, $limit: limit });
+ }
+ const settings = () => JSON.parse(db.query("SELECT site_settings_json FROM notebook_shares WHERE id=?").get(share).site_settings_json);
+ function save(patch) {
+ Settings.parse(patch);
+ const next = { ...settings(), ...patch };
+ assert(bytes(next) <= MAX_SETTINGS_BYTES, "Site settings exceed the metadata budget");
+ if (Object.hasOwn(patch, "homeMemoId") && patch.homeMemoId !== null) {
+ const target = db.query(`${tree} SELECT m.id,m.tags_json ${scope} AND m.id=$id`).get({ $share: share, $id: patch.homeMemoId });
+ assert(target && !JSON.parse(target.tags_json).some((tag) => (next.excludedTags ?? []).includes(tag)), "Homepage outside the merged visible scope");
+ }
+ db.run("UPDATE notebook_shares SET site_settings_json=json_patch(site_settings_json,?) WHERE id=?", [JSON.stringify(patch), share]);
+ }
+ check("default_tag_policy_does_not_hide_old_drafts", () => assert(rows().some((x) => x.id === "a_hidden")));
+ save({ excludedTags: ["draft"], sortMode: "title" });
+ check("tag_exclusion_filters_directory_note_and_resource", () => {
+ assert(!rows().some((x) => x.id === "a_hidden"));
+ assert.equal(point("a_hidden"), null);
+ assert.equal(resource("res_a_hidden"), null);
+ });
+ check("independent_child_share_keeps_its_own_tag_policy", () => assert.equal(point("a_hidden", child)?.id, "a_hidden"));
+ check("english_body_search_filters_before_pagination", () => assert.deepEqual(search("ablationbody").map((x) => x.id), ["b_ten", "c_two"]));
+ check("chinese_body_substring_and_tag_filter", () => assert.deepEqual(search("唯一检索", "topic").map((x) => x.id), ["b_ten", "c_two"]));
+ check("title_natural_order_needs_no_rank_rows", () => {
+ assert.deepEqual(sortTitles(rows().filter((x) => x.notebook_id === "plan_2")).map((x) => x.id), ["c_two", "b_ten"]);
+ const chapters = db.query("SELECT id,name AS title FROM notebooks WHERE parent_id='plan_root_nb' AND workspace_id='plan_ws'").all();
+ assert.deepEqual(sortTitles(chapters).map((x) => x.id), ["plan_2", "plan_10"]);
+ });
+ save({ homeMemoId: "d_home", allowIndexing: true });
+ save({ footerText: "Copyright" });
+ check("atomic_settings_patch_preserves_other_fields_and_password", () => {
+ assert.equal(settings().homeMemoId, "d_home");
+ assert.equal(settings().footerText, "Copyright");
+ assert.deepEqual(db.query("SELECT token,password_hash FROM notebook_shares WHERE id=?").get(share), legacy);
+ });
+ check("invalid_homepage_write_rejected", () => assert.throws(() => save({ homeMemoId: "outside" })));
+ check("homepage_validated_against_merged_tag_policy", () => {
+ save({ excludedTags: [], homeMemoId: "a_hidden" });
+ assert.equal(point(settings().homeMemoId)?.id, "a_hidden");
+ save({ excludedTags: ["draft"], homeMemoId: "d_home" });
+ });
+ check("unknown_item_overrides_are_not_silently_supported", () => assert.throws(() => save({ hiddenMemoIds: ["b_ten"] })));
+ const homepage = () => point(settings().homeMemoId ?? "");
+ db.run("UPDATE memos SET notebook_id='plan_out' WHERE id='d_home'");
+ check("json_homepage_move_falls_back_without_foreign_key", () => assert.equal(homepage(), null));
+ db.run("DELETE FROM resources WHERE memo_id='d_home'");
+ db.run("DELETE FROM memos WHERE id='d_home'");
+ check("json_homepage_delete_falls_back_without_cleanup_job", () => {
+ assert.equal(settings().homeMemoId, "d_home");
+ assert.equal(homepage(), null);
+ });
+ check("cross_workspace_and_outside_notes_denied", () => { assert.equal(point("foreign"), null); assert.equal(point("outside"), null); });
+ db.run("UPDATE notebooks SET is_deleted=1 WHERE id='plan_2'");
+ check("deleted_ancestor_denies_descendants", () => assert.equal(point("b_ten"), null));
+ db.run("UPDATE notebooks SET is_deleted=0 WHERE id='plan_2'");
+ db.run("UPDATE notebook_shares SET site_slug='knowledge' WHERE id=?", [share]);
+ check("alias_database_uniqueness_is_case_insensitive", () => assert.throws(() => db.run("UPDATE notebook_shares SET site_slug='KNOWLEDGE' WHERE id=?", [child])));
+ const resolve = (slug) => db.query("SELECT ns.token FROM notebook_shares ns JOIN notebooks n ON n.id=ns.notebook_id AND n.workspace_id=ns.workspace_id WHERE lower(ns.site_slug)=lower(?) AND n.is_deleted=0").get(slug);
+ check("alias_resolution_only_returns_identity_not_protected_metadata", () => assert.deepEqual(resolve("knowledge"), { token: "p".repeat(43) }));
+
+ const indexable = () => !db.query("SELECT password_hash FROM notebook_shares WHERE id=?").get(share).password_hash && settings().allowIndexing === true;
+ check("password_overrides_indexing_flag", () => assert.equal(indexable(), false));
+ db.run("UPDATE notebook_shares SET password_hash=NULL WHERE id=?", [share]);
+ check("explicit_unprotected_indexing_can_be_enabled", () => assert.equal(indexable(), true));
+ db.run("UPDATE notebook_shares SET password_hash='rotated-hash', site_settings_json=json_set(site_settings_json,'$.allowIndexing',json('false')) WHERE id=?", [share]);
+ db.run("UPDATE notebook_shares SET password_hash=NULL WHERE id=?", [share]);
+ check("clearing_password_does_not_reenable_indexing", () => assert.equal(indexable(), false));
+ const siteTitle = () => db.query("SELECT name FROM notebooks WHERE id='plan_root_nb'").get().name;
+ db.run("UPDATE notebooks SET name='Renamed knowledge' WHERE id='plan_root_nb'");
+ check("site_title_derived_from_existing_root_name", () => assert.equal(siteTitle(), "Renamed knowledge"));
+ const meta = (title) => `<title>${escapeHtml(title)}</title><meta property="og:title" content="${escapeHtml(title)}">`;
+ check("server_metadata_model_escapes_untrusted_text", () => {
+ const head = meta('<img src=x onerror="bad">');
+ assert(!head.includes("<img")); assert(head.includes("&lt;img")); assert(head.includes("&quot;"));
+ });
+ const minimalSettings = { homeMemoId: "memo_" + "a".repeat(32), logoUrl: "https://example.invalid/logo.png", headerLinks: [{ label: "Home", url: "https://example.invalid/" }], footerText: "Copyright", excludedTags: ["draft"], sortMode: "title", allowIndexing: false };
+ const configurationSizes = [100, 1000, 10000, 50000].map((noteCount) => ({ noteCount, settingsBytes: bytes(minimalSettings) }));
+ check("metadata_size_independent_of_note_count", () => assert.equal(new Set(configurationSizes.map((x) => x.settingsBytes)).size, 1));
+
+ const fullBody = "这是正文内容。".repeat(5000);
+ const preview = { title: "Example", excerpt: createExcerpt(fullBody) };
+ const fullArticle = { title: "Example", contentMarkdown: fullBody, contentJson: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: fullBody }] }] } };
+ const payloads = [100, 1000, 10000].map((count) => {
+ const directory = Array.from({ length: count }, (_, i) => ({ id: `memo_${i.toString(16).padStart(32, "0")}`, notebookId: "nb_" + "a".repeat(32), title: `第${i + 1}篇笔记` }));
+ return { noteCount: count, directoryBytes: bytes(directory), directoryWithPreviewBytes: bytes(directory.map((x) => ({ ...x, excerpt: preview.excerpt }))), onePreviewBytes: bytes(preview), fullArticleBytes: bytes(fullArticle) };
+ });
+ check("on_demand_preview_avoids_directory_and_full_body_payload", () => {
+ assert(payloads[2].directoryWithPreviewBytes > payloads[2].directoryBytes + 500000);
+ assert(payloads[2].fullArticleBytes > payloads[2].onePreviewBytes * 100);
+ });
+
+ // Expected failures of removals, rather than claims that the omitted behavior works.
+ const unfiltered = db.query(`${tree} SELECT m.id ${scope} ORDER BY m.id`).all({ $share: share });
+ assert(unfiltered.some((x) => x.id === "a_hidden"));
+ counterexamples.push({ ablation: "remove_server_tag_filter", observed: "hidden_note_returned", criterionViolated: "exclude_drafts" });
+ assert.equal(db.query(`${tree} SELECT m.id ${scope} ${visible} AND m.title LIKE '%ablationbody%'`).all({ $share: share }).length, 0);
+ assert.equal(search("ablationbody").length, 2);
+ counterexamples.push({ ablation: "keep_title_only_search", observed: "body_only_matches_lost", criterionViolated: "full_text_search" });
+ const firstThenFilter = db.query(`${tree} SELECT m.id,m.tags_json ${scope} ORDER BY m.id LIMIT 1`).all({ $share: share }).filter((x) => !JSON.parse(x.tags_json).includes("draft"));
+ assert.equal(firstThenFilter.length, 0);
+ counterexamples.push({ ablation: "filter_after_pagination", observed: "empty_page_despite_visible_matches", criterionViolated: "complete_visible_search_page" });
+ db.run("DELETE FROM notebook_shares WHERE id=?", [share]);
+ check("revocation_denies_token_and_alias_paths", () => { assert.deepEqual(rows(), []); assert.equal(resolve("knowledge"), null); });
+
+ const decisions = [
+ ["R01", "article_toc", "keep", "issue_requirement", "H1-H4 navigation and scrollspy are explicit requirements."],
+ ["R02", "light_dark_system", "keep_reuse", "source_inspection", "Reuse ThemeProvider and edgeever.theme; no second preference system."],
+ ["R03", "code_copy_language_collapse", "keep_reuse", "issue_and_source", "Copy/highlighting already exist; add only missing labels and collapse controls."],
+ ["R04", "internal_hover_preview", "keep", "payload_measurement", "Keep a bounded on-demand preview; do not inflate every directory item or fetch complete articles."],
+ ["R05", "image_and_diagram_controls", "keep_reuse", "issue_and_source", "Reuse lightbox/zoom/fit; add single-click entry and fullscreen, not another viewer."],
+ ["R06", "body_full_text_search", "keep_reuse", "executed_counterexample", "Title-only search loses body matches; reuse existing FTS and Chinese fallback."],
+ ["R07", "tag_filter", "keep", "executed_model", "Use the same search endpoint with a tag predicate; no global tag cloud/count API."],
+ ["R08", "custom_homepage", "keep", "executed_model", "One JSON homeMemoId checked against live visibility; invalid targets fall back to directory."],
+ ["R09", "draft_exclusion", "choose_tag_policy", "issue_alternative_and_executed_model", "The issue permits draft state OR tags. Use existing note tags plus site excludedTags."],
+ ["R10", "custom_ordering", "choose_title_order", "issue_alternative_and_executed_model", "The issue permits manual OR title/number order. Use existing/title modes and numeric title sorting."],
+ ["R11", "custom_slug", "keep", "executed_model", "Keep a unique slug and identity resolver; do not alter token-scoped unlock cookies."],
+ ["R12", "logo_header_footer", "keep", "issue_requirement", "Keep structured display settings and HTTPS logo URL; no independent upload pipeline."],
+ ["R13", "seo_and_social_cards", "keep_metadata", "external_primary_documentation", "Keep server HTML head and indexing controls; crawler acceptance remains unverified."],
+ ["D01", "two_or_one_item_override_tables", "remove_for_selected_scope", "issue_alternatives_and_executed_model", "No per-item state remains when exclusion uses tags and sorting uses titles."],
+ ["D02", "independent_site_title", "derive", "source_and_design_judgment", "Use root notebook name; independent override is an additional product choice."],
+ ["D03", "independent_site_description", "derive", "source_and_design_judgment", "Use visible homepage or article excerpt; no separate description field."],
+ ["D04", "site_slug_column", "keep", "executed_model", "One column with a case-insensitive unique index keeps lookup and uniqueness simple."],
+ ["D05", "home_memo_id_column", "move_to_settings_json", "executed_model", "Live validation already handles moves and soft deletion; a single stale pointer is bounded."],
+ ["D06", "logo_url_column", "move_to_settings_json", "executed_model", "Bounded display metadata does not need an independent SQL column."],
+ ["D07", "header_links_column", "move_to_settings_json", "executed_model", "Preserve structured links in the bounded settings object."],
+ ["D08", "footer_text_column", "move_to_settings_json", "executed_model", "Preserve footer text in settings."],
+ ["D09", "allow_indexing_column", "move_to_settings_json", "executed_model", "Effective indexing checks the JSON flag and current password; setting passwords clears the flag."],
+ ["D10", "excluded_tags_column", "move_to_settings_json", "executed_model", "JSON tags are filtered against existing memo_tags before pagination."],
+ ["D11", "two_sort_mode_columns", "one_json_sort_mode", "executed_model", "Use one existing/title mode for the site; no separate note/chapter controls."],
+ ["A01", "separate_site_get", "reuse_existing_get", "source_inspection", "Extend authenticated share GET with owner settings."],
+ ["A02", "site_settings_patch", "keep_separate", "source_and_executed_model", "Preserve existing password PATCH semantics; config-only writes do not rotate passwords."],
+ ["A03", "content_management_get", "remove", "selected_scope", "No site-specific item editor is needed."],
+ ["A04", "per_note_exclusion_patch", "remove", "selected_scope", "Use existing note tag editing."],
+ ["A05", "manual_order_put", "remove", "selected_scope", "Title order requires no rank persistence or drag/drop command."],
+ ["A06", "public_search", "keep", "executed_model", "Needed for body/tag search with server visibility and pagination."],
+ ["A07", "public_preview", "keep", "payload_measurement", "Keeps preview responses bounded and avoids eager directory growth."],
+ ["A08", "alias_resolver", "make_explicit", "source_and_executed_model", "Return token identity only so SPA aliases use existing canonical API/cookie paths."],
+ ["I01", "complete_article_ssr", "defer", "external_primary_documentation_and_judgment", "Keep SPA article rendering and server head; non-JS full-body crawlability is not retained."],
+ ["I02", "sitemap", "defer", "issue_not_explicit_and_primary_documentation", "It can improve discovery, but is not needed to implement the requested indexing switch/cards."],
+ ["I03", "new_content_index", "remove", "source_inspection", "Existing FTS and normalized tags already cover the queries."],
+ ["I04", "second_theme_storage", "remove", "source_inspection", "Same-origin app and public site share this device's appearance preference."],
+ ["I05", "second_image_diagram_renderer", "remove", "source_inspection", "Reuse existing renderers."],
+ ["I06", "publication_snapshot_version", "exclude", "existing_live_share_contract", "Keep live sharing; no review/publish lifecycle."],
+ ["I07", "new_polling_or_push_invalidation", "remove", "source_inspection", "Reuse current refresh and error handling; do not claim instantaneous recall of loaded text."],
+ ["I08", "public_cdn_cache", "exclude", "existing_privacy_contract", "Keep no-store and no-referrer."],
+ ["I09", "duplicate_runtime_business_logic", "remove", "project_contract", "Cloudflare/Docker share visibility and metadata services with thin entry adapters."],
+ ["V01", "all_validation_layers_each_phase", "replace_with_affected_flows", "user_instruction", "Reuse unchanged checks and use three actual-flow acceptance scenarios after implementation."],
+ ].map(([id, subject, decision, evidenceType, rationale]) => ({ id, subject, decision, evidenceType, rationale }));
+ assert.equal(decisions.filter((x) => /^R\d+$/.test(x.id)).length, 13);
+ const sourceTheme = readFileSync(new URL("../apps/web/src/components/ThemeProvider.tsx", import.meta.url), "utf8");
+ assert(sourceTheme.includes('THEME_STORAGE_KEY = "edgeever.theme"'));
+ const sourcePage = readFileSync(new URL("../apps/web/src/components/PublicNotebookSharePage.tsx", import.meta.url), "utf8");
+ assert(sourcePage.includes("refetchInterval: 30_000"));
+ const previous = JSON.parse(readFileSync(new URL("../docs/public-notebook-site-schema-ablation.json", import.meta.url), "utf8"));
+ process.stdout.write(`${JSON.stringify({
+ generatedAt: new Date().toISOString(), baselineCommit: execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(),
+ environment: { bun: Bun.version, sqlite: db.query("SELECT sqlite_version() AS version").get().version },
+ method: "Actual migrations plus disposable SQLite/data models. Decision rows distinguish executed evidence, source facts, issue alternatives, external documentation, and judgment. Not a user experiment, runtime implementation, browser acceptance, or crawler test.",
+ migrations, executedChecks: checks, executedCheckCount: checks.length, expectedCounterexamples: counterexamples,
+ issueCoverage: { requirementGroups: 13, exclusionAlternative: "tags", orderingAlternative: "title/number", removedAdvancedBehaviors: ["per-site arbitrary note overrides", "site-specific drag ordering", "independent site title/description", "non-JS full article HTML", "sitemap discovery"], userUsabilityMeasured: false },
+ persistence: { newTables: 0, newColumns: ["site_slug", "site_settings_json"], settingsBudgetBytes: MAX_SETTINGS_BYTES, configurationSizes },
+ previewPayloads: payloads,
+ reusedPriorEvidence: { file: "docs/public-notebook-site-schema-ablation.json", baselineCommit: previous.baselineCommit, commonFunctionalScenarios: 19, benchmarkGroups: previous.benchmarks.length, rerun: false, limitation: "Prior override-table necessity was conditional on retaining per-item manual state; that premise is removed here." },
+ decisions,
+ notVerified: ["Product UI and usability", "Real password unlock and upgrade", "Cloudflare/Docker page handlers", "Crawler indexing and social previews", "Production query/network performance", "Concurrent writer contention"],
+ externalReferences: ["https://github.com/tianma-if/edgeever/issues/591", "https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics", "https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview", "https://ogp.me/"],
+ }, null, 2)}\n`);
+} finally { db.close(); }
diff --git a/scripts/public-notebook-site-schema-ablation.mjs b/scripts/public-notebook-site-schema-ablation.mjs
new file mode 100644
index 00000000..9fe3fab7
--- /dev/null
+++ b/scripts/public-notebook-site-schema-ablation.mjs
@@ -0,0 +1,307 @@
+// Standalone design experiment. Uses disposable in-memory databases only.
+// Run: bun scripts/public-notebook-site-schema-ablation.mjs > docs/public-notebook-site-schema-ablation.json
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { globSync, readFileSync } from "node:fs";
+import { arch, platform } from "node:os";
+import { fileURLToPath } from "node:url";
+import { Database } from "bun:sqlite";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const variants = ["two_tables", "one_table", "json_column"];
+const selectedVariants = process.argv.includes("--json-only") ? ["json_column"]
+ : process.argv.includes("--relational-only") ? ["two_tables", "one_table"] : variants;
+const searchOnly = process.argv.includes("--search-only");
+const share = "ab_share_root";
+const childShare = "ab_share_child";
+const idFor = (index) => `memo_${index.toString(16).padStart(32, "0")}`;
+const timestamp = "2026-10-20T00:00:00.000Z";
+const commonColumns = [
+ "site_title TEXT", "site_description TEXT NOT NULL DEFAULT ''", "site_slug TEXT",
+ "home_memo_id TEXT REFERENCES memos(id) ON DELETE SET NULL", "logo_url TEXT",
+ "header_links_json TEXT NOT NULL DEFAULT '[]'", "footer_text TEXT NOT NULL DEFAULT ''",
+ "allow_indexing INTEGER NOT NULL DEFAULT 0 CHECK(allow_indexing IN (0, 1))",
+ "excluded_tags_json TEXT NOT NULL DEFAULT '[]'",
+ "notebook_sort_mode TEXT NOT NULL DEFAULT 'existing'", "memo_sort_mode TEXT NOT NULL DEFAULT 'existing'",
+];
+
+function fixture(variant) {
+ const db = new Database(":memory:");
+ for (const path of globSync("migrations/*.sql", { cwd: root }).sort()) {
+ db.exec(readFileSync(new URL(`../${path}`, import.meta.url), "utf8"));
+ }
+ db.exec("PRAGMA foreign_keys = ON");
+ db.run("INSERT INTO workspaces (id, name) VALUES ('ab_ws', 'Experiment'), ('ab_other', 'Other')");
+ for (const [id, parent, workspace, rank] of [
+ ["ab_root", null, "ab_ws", 0], ["ab_a", "ab_root", "ab_ws", 20],
+ ["ab_b", "ab_root", "ab_ws", 10], ["ab_out", null, "ab_ws", 0],
+ ["ab_foreign", "ab_root", "ab_other", 0],
+ ]) db.run("INSERT INTO notebooks (id, parent_id, workspace_id, name, sort_order) VALUES (?, ?, ?, ?, ?)", [id, parent, workspace, id, rank]);
+ db.run("INSERT INTO notebook_shares (id, notebook_id, workspace_id, token, password_hash) VALUES (?, 'ab_root', 'ab_ws', ?, 'legacy-hash-sentinel'), (?, 'ab_a', 'ab_ws', ?, NULL)", [share, "n".repeat(43), childShare, "c".repeat(43)]);
+ const legacy = db.query("SELECT token, password_hash FROM notebook_shares WHERE id = ?").get(share);
+ for (const column of commonColumns) db.exec(`ALTER TABLE notebook_shares ADD COLUMN ${column}`);
+ db.exec("CREATE UNIQUE INDEX ab_site_slug ON notebook_shares(site_slug) WHERE site_slug IS NOT NULL");
+ if (variant === "two_tables") {
+ db.exec(`CREATE TABLE ab_memo_settings (
+ share_id TEXT NOT NULL REFERENCES notebook_shares(id) ON DELETE CASCADE,
+ memo_id TEXT NOT NULL REFERENCES memos(id) ON DELETE CASCADE,
+ excluded INTEGER NOT NULL DEFAULT 0 CHECK(excluded IN (0, 1)),
+ sort_order INTEGER CHECK(sort_order >= 0),
+ created_at TEXT NOT NULL DEFAULT '${timestamp}', updated_at TEXT NOT NULL DEFAULT '${timestamp}',
+ PRIMARY KEY(share_id, memo_id));
+ CREATE INDEX ab_memo_target ON ab_memo_settings(memo_id);
+ CREATE TABLE ab_notebook_settings (
+ share_id TEXT NOT NULL REFERENCES notebook_shares(id) ON DELETE CASCADE,
+ notebook_id TEXT NOT NULL REFERENCES notebooks(id) ON DELETE CASCADE,
+ sort_order INTEGER CHECK(sort_order >= 0),
+ created_at TEXT NOT NULL DEFAULT '${timestamp}', updated_at TEXT NOT NULL DEFAULT '${timestamp}',
+ PRIMARY KEY(share_id, notebook_id));
+ CREATE INDEX ab_notebook_target ON ab_notebook_settings(notebook_id);`);
+ } else if (variant === "one_table") {
+ db.exec(`CREATE TABLE ab_item_settings (
+ id INTEGER PRIMARY KEY,
+ share_id TEXT NOT NULL REFERENCES notebook_shares(id) ON DELETE CASCADE,
+ memo_id TEXT REFERENCES memos(id) ON DELETE CASCADE,
+ notebook_id TEXT REFERENCES notebooks(id) ON DELETE CASCADE,
+ excluded INTEGER NOT NULL DEFAULT 0 CHECK(excluded IN (0, 1)),
+ sort_order INTEGER CHECK(sort_order >= 0),
+ created_at TEXT NOT NULL DEFAULT '${timestamp}', updated_at TEXT NOT NULL DEFAULT '${timestamp}',
+ CHECK((memo_id IS NOT NULL) <> (notebook_id IS NOT NULL)),
+ CHECK(notebook_id IS NULL OR excluded = 0));
+ CREATE UNIQUE INDEX ab_item_memo ON ab_item_settings(share_id, memo_id) WHERE memo_id IS NOT NULL;
+ CREATE UNIQUE INDEX ab_item_notebook ON ab_item_settings(share_id, notebook_id) WHERE notebook_id IS NOT NULL;
+ CREATE INDEX ab_item_memo_target ON ab_item_settings(memo_id) WHERE memo_id IS NOT NULL;
+ CREATE INDEX ab_item_notebook_target ON ab_item_settings(notebook_id) WHERE notebook_id IS NOT NULL;`);
+ } else {
+ db.exec("ALTER TABLE notebook_shares ADD COLUMN content_settings_json TEXT NOT NULL DEFAULT '{}' CHECK(json_valid(content_settings_json) AND json_type(content_settings_json) = 'object')");
+ }
+ assert.deepEqual(db.query("SELECT token, password_hash FROM notebook_shares WHERE id = ?").get(share), legacy);
+
+ const addMemo = db.query("INSERT INTO memos (id, notebook_id, workspace_id, title, tags_json) VALUES (?, ?, ?, ?, ?)");
+ const addContent = db.query("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash) VALUES (?, ?, ?, ?, ?)");
+ const addSearch = db.query("INSERT INTO memo_search_documents (memo_id, title, content_text, tags) VALUES (?, ?, ?, ?)");
+ const addResource = db.query("INSERT INTO resources (id, memo_id, object_key, kind) VALUES (?, ?, ?, 'image')");
+ function seedMemo(id, notebook = "ab_a", tags = [], workspace = "ab_ws", resource = false) {
+ addMemo.run(id, notebook, workspace, id, JSON.stringify(tags));
+ addContent.run(id, '{"type":"doc","content":[]}', "ablationword", "ablationword", id);
+ addSearch.run(id, id, "ablationword", tags.join(" "));
+ if (resource) addResource.run(`res_${id}`, id, id);
+ }
+ function patch(kind, target, changes, sid = share) {
+ if (variant === "json_column") {
+ const value = Object.fromEntries(Object.entries(changes).map(([key, value]) => [key === "sort_order" ? "sortOrder" : key, value]));
+ const doc = { [kind === "memo" ? "memos" : "notebooks"]: { [target]: value } };
+ db.query("UPDATE notebook_shares SET content_settings_json = json_patch(content_settings_json, ?) WHERE id = ?").run(JSON.stringify(doc), sid);
+ } else {
+ const table = variant === "one_table" ? "ab_item_settings" : kind === "memo" ? "ab_memo_settings" : "ab_notebook_settings";
+ const key = kind === "memo" ? "memo_id" : "notebook_id";
+ const columns = Object.keys(changes);
+ const partial = variant === "one_table" ? ` WHERE ${key} IS NOT NULL` : "";
+ db.query(`INSERT INTO ${table} (share_id, ${key}, ${columns.join(", ")}) VALUES (?, ?, ${columns.map(() => "?").join(", ")})
+ ON CONFLICT(share_id, ${key})${partial} DO UPDATE SET ${columns.map((c) => `${c}=excluded.${c}`).join(", ")}`).run(sid, target, ...Object.values(changes));
+ }
+ }
+ function overrides(kind, sid = share) {
+ if (variant === "json_column") {
+ const doc = JSON.parse(db.query("SELECT content_settings_json AS doc FROM notebook_shares WHERE id = ?").get(sid)?.doc ?? "{}");
+ return Object.entries(doc[kind === "memo" ? "memos" : "notebooks"] ?? {}).map(([id, item]) => ({ id, excluded: item.excluded ?? 0, sort_order: item.sortOrder ?? null }));
+ }
+ const table = variant === "one_table" ? "ab_item_settings" : kind === "memo" ? "ab_memo_settings" : "ab_notebook_settings";
+ const key = kind === "memo" ? "memo_id" : "notebook_id";
+ return db.query(`SELECT ${key} AS id, ${kind === "memo" ? "excluded" : "0"} AS excluded, sort_order FROM ${table} WHERE share_id = ? AND ${key} IS NOT NULL`).all(sid);
+ }
+ const tree = `WITH RECURSIVE tree(id, workspace_id) AS (
+ SELECT n.id, n.workspace_id FROM notebook_shares ns JOIN notebooks n ON n.id=ns.notebook_id AND n.workspace_id=ns.workspace_id WHERE ns.id=$share AND n.is_deleted=0
+ UNION SELECT n.id, n.workspace_id FROM notebooks n JOIN tree t ON n.parent_id=t.id WHERE n.workspace_id=t.workspace_id AND n.is_deleted=0)`;
+ const statements = new Map();
+ function query(mode) {
+ if (statements.has(mode)) return statements.get(mode);
+ const point = mode === "point" || mode === "resource";
+ let cte = tree;
+ let join, excluded, rank;
+ if (variant === "json_column" && point) {
+ excluded = `json_extract(ns.content_settings_json, '$.memos."' || m.id || '".excluded')`;
+ rank = `json_extract(ns.content_settings_json, '$.memos."' || m.id || '".sortOrder')`;
+ join = "";
+ } else if (variant === "json_column") {
+ // Materialize only the hidden-ID set for SQL filtering before pagination.
+ // Directory ranking parses the configuration once in the server process.
+ join = "";
+ excluded = `(m.id IN (SELECT j.key FROM notebook_shares cfg, json_each(cfg.content_settings_json, '$.memos') j WHERE cfg.id=$share AND json_extract(j.value, '$.excluded')=1))`;
+ rank = "NULL";
+ } else {
+ join = `LEFT JOIN ${variant === "one_table" ? "ab_item_settings" : "ab_memo_settings"} e ON e.share_id=ns.id AND e.memo_id=m.id`;
+ excluded = "e.excluded";
+ rank = "e.sort_order";
+ }
+ const extra = mode === "point" ? "AND m.id=$target" : mode === "resource" ? "AND m.id=(SELECT memo_id FROM resources WHERE id=$target AND is_deleted=0)"
+ : mode === "search" ? "AND m.id IN (SELECT memo_id FROM memos_fts WHERE memos_fts MATCH $search)" : "";
+ const sql = `${cte} SELECT m.id, m.notebook_id, ${rank} AS sort_order FROM memos m JOIN tree t ON t.id=m.notebook_id AND t.workspace_id=m.workspace_id
+ JOIN notebook_shares ns ON ns.id=$share ${join}
+ WHERE m.is_deleted=0 AND COALESCE(${excluded}, 0)=0
+ AND NOT EXISTS (SELECT 1 FROM memo_tags mt JOIN json_each(ns.excluded_tags_json) tags ON mt.name=tags.value WHERE mt.memo_id=m.id)
+ ${extra} ORDER BY ${mode === "search" ? "m.id" : `m.notebook_id, (${rank} IS NULL), ${rank}, m.id`} ${mode === "search" ? "LIMIT $limit" : ""}`;
+ const statement = db.query(sql);
+ statements.set(mode, statement);
+ return statement;
+ }
+ const bindings = (sid, extra = {}) => ({ $share: sid, ...extra });
+ const list = (sid = share) => {
+ const rows = query("list").all(bindings(sid));
+ if (variant !== "json_column") return rows;
+ const ranks = new Map(overrides("memo", sid).map((item) => [item.id, item.sort_order]));
+ for (const row of rows) row.sort_order = ranks.get(row.id) ?? null;
+ return rows.sort((a, b) => a.notebook_id.localeCompare(b.notebook_id)
+ || (a.sort_order === null) - (b.sort_order === null)
+ || (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id.localeCompare(b.id));
+ };
+ const point = (id, sid = share) => query("point").get(bindings(sid, { $target: id }));
+ const resource = (id) => query("resource").get(bindings(share, { $target: id }));
+ const search = (limit = 2) => query("search").all(bindings(share, { $search: "ablationword", $limit: limit }));
+ function chapters() {
+ const rows = db.query(`${tree} SELECT n.id, n.parent_id, n.sort_order FROM notebooks n JOIN tree t ON n.id=t.id AND n.workspace_id=t.workspace_id`).all(bindings(share));
+ const ranks = new Map(overrides("notebook").map((item) => [item.id, item.sort_order]));
+ return rows.filter((n) => n.parent_id === "ab_root").sort((a, b) => (ranks.get(a.id) ?? Infinity) - (ranks.get(b.id) ?? Infinity) || a.sort_order - b.sort_order || a.id.localeCompare(b.id)).map((n) => n.id);
+ }
+ return { db, variant, seedMemo, patch, overrides, list, point, resource, search, chapters, query, bindings };
+}
+
+function functional(variant) {
+ const f = fixture(variant);
+ const cases = [];
+ const check = (name, fn) => { fn(); cases.push(name); };
+ try {
+ for (const id of ["a", "b", "c"]) f.seedMemo(id, "ab_a", [], "ab_ws", true);
+ f.seedMemo("tagged", "ab_b", ["draft"]);
+ f.seedMemo("root_note", "ab_root");
+ f.seedMemo("outside", "ab_out");
+ f.seedMemo("foreign", "ab_foreign", [], "ab_other");
+ const ids = (rows) => rows.map((r) => r.id).sort();
+ check("default_scope", () => assert.deepEqual(ids(f.list()), ["a", "b", "c", "root_note", "tagged"]));
+ f.patch("memo", "c", { excluded: 1 });
+ check("per_share_exclusion", () => assert.deepEqual(ids(f.list()), ["a", "b", "root_note", "tagged"]));
+ check("direct_note_denied", () => assert.equal(f.point("c"), null));
+ check("resource_denied", () => assert.equal(f.resource("res_c"), null));
+ check("independent_child_share", () => assert.equal(f.point("c", childShare)?.id, "c"));
+ f.db.run("UPDATE notebook_shares SET excluded_tags_json='[\"draft\"]', home_memo_id='c' WHERE id=?", [share]);
+ check("tag_exclusion", () => assert.deepEqual(ids(f.list()), ["a", "b", "root_note"]));
+ check("hidden_homepage_fallback", () => assert.equal(f.point(f.db.query("SELECT home_memo_id FROM notebook_shares WHERE id=?").get(share).home_memo_id), null));
+ f.patch("memo", "a", { sort_order: 20 });
+ f.patch("memo", "b", { sort_order: 10 });
+ check("memo_manual_order", () => assert.deepEqual(f.list().filter((m) => m.notebook_id === "ab_a").map((m) => m.id), ["b", "a"]));
+ f.patch("notebook", "ab_a", { sort_order: 0 });
+ f.patch("notebook", "ab_b", { sort_order: 1 });
+ check("chapter_manual_order", () => assert.deepEqual(f.chapters(), ["ab_a", "ab_b"]));
+ f.seedMemo("new");
+ check("new_note_appends", () => assert.deepEqual(f.list().filter((m) => m.notebook_id === "ab_a").map((m) => m.id), ["b", "a", "new"]));
+ check("fts_exclusion_before_limit", () => assert.deepEqual(f.search().map((m) => m.id), ["a", "b"]));
+ f.db.run("UPDATE memos SET notebook_id='ab_out' WHERE id='a'");
+ check("moved_out_denied", () => assert.equal(f.point("a"), null));
+ f.db.run("UPDATE memos SET notebook_id='ab_a' WHERE id='a'");
+ f.db.run("UPDATE notebooks SET is_deleted=1 WHERE id='ab_a'");
+ check("deleted_ancestor_denied", () => assert.equal(f.point("b"), null));
+ f.db.run("UPDATE notebooks SET is_deleted=0 WHERE id='ab_a'");
+ check("cross_workspace_denied", () => assert.equal(f.point("foreign"), null));
+ f.patch("memo", "a", { excluded: 1 });
+ f.patch("memo", "a", { sort_order: 99 });
+ check("disjoint_field_updates_preserved", () => assert.deepEqual(f.overrides("memo").find((m) => m.id === "a"), { id: "a", excluded: 1, sort_order: 99 }));
+ let rejectsMissingTarget = false;
+ try { f.patch("memo", "missing", { excluded: 1 }); } catch { rejectsMissingTarget = true; }
+ f.db.run("DELETE FROM resources WHERE memo_id='c'");
+ f.db.run("DELETE FROM memos WHERE id='c'");
+ check("physical_delete_homepage_cleared", () => assert.equal(f.db.query("SELECT home_memo_id FROM notebook_shares WHERE id=?").get(share).home_memo_id, null));
+ const automaticallyRemovesDeletedTarget = !f.overrides("memo").some((m) => m.id === "c");
+ let rejectsBothTargets = null;
+ if (variant === "one_table") {
+ try { f.db.run("INSERT INTO ab_item_settings(share_id, memo_id, notebook_id) VALUES (?, 'b', 'ab_b')", [share]); rejectsBothTargets = false; } catch { rejectsBothTargets = true; }
+ check("one_table_exactly_one_target", () => assert.equal(rejectsBothTargets, true));
+ check("one_table_chapter_cannot_be_excluded", () => assert.throws(() => f.db.run("UPDATE ab_item_settings SET excluded=1 WHERE notebook_id='ab_a'")));
+ }
+ f.db.run("DELETE FROM notebook_shares WHERE id=?", [share]);
+ check("revocation_denies_reads", () => assert.deepEqual(f.list(), []));
+ check("independent_share_survives_revocation", () => assert.equal(f.point("b", childShare)?.id, "b"));
+ check("revocation_cleans_overrides", () => assert.deepEqual(f.overrides("memo"), []));
+ return { variant, casesPassed: cases.length, cases, databaseIntegrity: { rejectsMissingTarget, automaticallyRemovesDeletedTarget, rejectsBothTargets }, legacyTokenAndHashPreserved: true };
+ } finally { f.db.close(); }
+}
+
+function measure(fn) {
+ for (let i = 0; i < 2; i++) fn(i);
+ const samples = [];
+ // Keep the experiment bounded when a candidate has an expensive query.
+ for (let i = 0; i < 15; i++) {
+ const start = performance.now();
+ fn(i);
+ samples.push(performance.now() - start);
+ if (samples.length >= 3 && samples.reduce((sum, ms) => sum + ms, 0) >= 500) break;
+ }
+ samples.sort((a, b) => a - b);
+ return { samples: samples.length, p50Ms: Number(samples[Math.floor(samples.length * 0.5)].toFixed(4)), p95Ms: Number(samples[Math.min(samples.length - 1, Math.floor(samples.length * 0.95))].toFixed(4)) };
+}
+
+function benchmark(variant, noteCount, overrideCount) {
+ const f = fixture(variant);
+ try {
+ f.db.transaction(() => { for (let i = 0; i < noteCount; i++) f.seedMemo(idFor(i)); })();
+ const overrides = {};
+ for (let i = 0; i < overrideCount; i++) overrides[idFor(i)] = { excluded: i % 5 === 0 ? 1 : 0, sortOrder: overrideCount - i };
+ const doc = JSON.stringify({ memos: overrides, notebooks: {} });
+ if (variant === "json_column") f.db.run("UPDATE notebook_shares SET content_settings_json=? WHERE id=?", [doc, share]);
+ else f.db.transaction(() => { for (const [id, item] of Object.entries(overrides)) f.patch("memo", id, { excluded: item.excluded, sort_order: item.sortOrder }); })();
+ const pointId = idFor(noteCount - 1);
+ assert.equal(f.list().length, noteCount - Math.ceil(overrideCount / 5));
+ assert.equal(f.point(pointId)?.id, pointId);
+ assert.equal(f.search(20).length, 20);
+ const directory = searchOnly ? null : measure(() => f.list());
+ const point = searchOnly ? null : measure(() => f.point(pointId));
+ const search = measure(() => f.search(20));
+ const update = searchOnly ? null : measure((i) => f.patch("memo", idFor(1), { sort_order: i % 2 }));
+ return { variant, noteCount, overrideCount, configJsonBytes: Buffer.byteLength(doc), directory, point, search, update,
+ directoryQueryPlan: f.db.query(`EXPLAIN QUERY PLAN ${f.query("list").toString()}`).all(f.bindings(share)).map((r) => r.detail),
+ pointQueryPlan: f.db.query(`EXPLAIN QUERY PLAN ${f.query("point").toString()}`).all(f.bindings(share, { $target: pointId })).map((r) => r.detail) };
+ } finally { f.db.close(); }
+}
+
+if (process.argv.includes("--explain-json")) {
+ const f = fixture("json_column");
+ try {
+ f.seedMemo("a");
+ f.patch("memo", "a", { excluded: 0, sort_order: 1 });
+ f.list();
+ const sql = f.query("list").toString();
+ process.stdout.write(`${JSON.stringify({ sql, plan: f.db.query(`EXPLAIN QUERY PLAN ${sql}`).all(f.bindings(share)) }, null, 2)}\n`);
+ } finally { f.db.close(); }
+ process.exit(0);
+}
+
+const result = {
+ generatedAt: new Date().toISOString(),
+ baselineCommit: execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(),
+ environment: { bun: Bun.version, sqlite: new Database(":memory:").query("SELECT sqlite_version() AS version").get().version, platform: platform(), arch: arch() },
+ method: {
+ actualMigrations: globSync("migrations/*.sql", { cwd: root }).sort(),
+ unchangedCommonSiteColumns: commonColumns,
+ variants: selectedVariants, noteIdFormat: "memo_ followed by 32 hex characters (same length as createId('memo'))",
+ functionalScope: "Local SQL policy and persistence model, not HTTP/browser/authentication acceptance",
+ benchmarkScope: "In-memory SQLite; warm prepared statements; 2 warmups and up to 15 samples (at least 3, stop after 500 ms of measured work); no network, D1 billing, disk I/O, or concurrent-writer throughput measured",
+ jsonReadStrategy: "SQL hidden-ID set filters before pagination; directory includes a second SQL read plus one server-side JSON parse/map/sort; direct JSON path extraction for individual notes/resources",
+ searchOrder: "Identical FTS term in every candidate body; tie by note ID for all variants. Manual directory order is not search relevance.",
+ updateStrategy: "Relational field upserts vs atomic json_patch of the existing row; no client read-modify-write replacement",
+ order: "Variants run sequentially; absolute timings are illustrative, not a production SLO",
+ },
+ functional: selectedVariants.map(functional),
+ benchmarks: [],
+ configurationSizes: [1000, 10000, 50000].map((n) => {
+ const doc = { memos: Object.fromEntries(Array.from({ length: n }, (_, i) => [idFor(i), { excluded: i % 5 === 0 ? 1 : 0, sortOrder: n - i }])), notebooks: {} };
+ return { overrideCount: n, bytes: Buffer.byteLength(JSON.stringify(doc)) };
+ }),
+};
+for (const [n, k] of [[100, 10], [1000, 100], [10000, 1000], [10000, 10000]]) {
+ for (const variant of selectedVariants) {
+ process.stderr.write(`Measuring ${variant}: ${n} notes, ${k} overrides\n`);
+ const row = benchmark(variant, n, k);
+ result.benchmarks.push(row);
+ process.stderr.write(` directory=${row.directory?.p50Ms ?? "reused"} ms; point=${row.point?.p50Ms ?? "reused"} ms; search=${row.search.p50Ms} ms; update=${row.update?.p50Ms ?? "reused"} ms\n`);
+ }
+}
+process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
diff --git a/scripts/self-hosted-server.mjs b/scripts/self-hosted-server.mjs
index aab95aa4..e8adc1f7 100644
--- a/scripts/self-hosted-server.mjs
+++ b/scripts/self-hosted-server.mjs
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
import { hasBootstrapCredential } from "../apps/api/src/auth-bootstrap.ts";
import { isUnauthenticatedAccessEnabled } from "../apps/api/src/auth-state.ts";
import { fetchEdgeEverApp } from "../apps/api/src/index.ts";
+import { isNotebookSitePagePath, renderNotebookSitePage } from "../apps/api/src/notebook-site-page.ts";
import { isPublicPagePath, PUBLIC_PAGE_HEADERS } from "../packages/shared/src/public-page-headers.ts";
import { nodePublicFetch } from "../apps/api/src/node-public-network.ts";
import { createSelfHostedStorageAdapter } from "../apps/api/src/self-hosted-storage-adapter.ts";
@@ -162,6 +163,10 @@ const server = Bun.serve({
idleTimeout: config.idleTimeout,
async fetch(request) {
const pathname = new URL(request.url).pathname;
+ if (isNotebookSitePagePath(pathname)) {
+ return renderNotebookSitePage(request, storage.db,
+ () => serveStatic(new Request(new URL("/index.html", request.url))));
+ }
if (pathname.startsWith("/api/") || pathname === "/mcp" || pathname.startsWith("/mcp/")) {
return fetchEdgeEverApp(request, env, executionContext);
}
diff --git a/scripts/wrangler-runner.mjs b/scripts/wrangler-runner.mjs
index 99797bfd..53b9694d 100644
--- a/scripts/wrangler-runner.mjs
+++ b/scripts/wrangler-runner.mjs
@@ -13,7 +13,7 @@ const REPOSITORY_WRANGLER_VALUES = {
bucket_name: "edgeever-resources",
preview_bucket_name: "edgeever-resources-preview",
};
-const REPOSITORY_WRANGLER_SHA256 = "7817c91538634a2aa2eebaae990ea9d11870d92486f522939f2e02c8eee30c09";
+const REPOSITORY_WRANGLER_SHA256 = "55b5f99e86f4d752c44560a6e392d8b52d782c8cdb0311faec9544e6cb883af7";
const configValue = (config, key) => {
const match = config.match(new RegExp(`^${key}\\s*=\\s*(?:"([^"]*)"|(true|false))`, "m"));
diff --git a/tests/e2e/public-notebook-indexing.spec.ts b/tests/e2e/public-notebook-indexing.spec.ts
new file mode 100644
index 00000000..9f6cab21
--- /dev/null
+++ b/tests/e2e/public-notebook-indexing.spec.ts
@@ -0,0 +1,120 @@
+import { expect, test, type Page, type APIRequestContext } from "@playwright/test";
+import { PUBLIC_PAGE_ROBOTS } from "../../packages/shared/src/public-page-headers";
+
+const createSite = async (request: APIRequestContext) => {
+ const slug = `robots-${crypto.randomUUID()}`;
+ const notebookResponse = await request.post("/api/v1/notebooks", { data: { name: slug } });
+ expect(notebookResponse.status()).toBe(201);
+ const { notebook } = await notebookResponse.json();
+ const memoResponse = await request.post("/api/v1/memos", {
+ data: {
+ notebookId: notebook.id,
+ title: "Indexing regression",
+ contentMarkdown: [
+ "[Jump to section](#target-section)",
+ "![Preview image](/apple-touch-icon.png)",
+ ...Array.from({ length: 30 }, () => "Article paragraph before the target heading."),
+ "## Target section",
+ "Visible article body.",
+ ].join("\n\n"),
+ },
+ });
+ expect(memoResponse.status()).toBe(201);
+ const { memo } = await memoResponse.json();
+ const shareResponse = await request.post(`/api/v1/notebooks/${notebook.id}/share`);
+ expect(shareResponse.ok()).toBe(true);
+ const { share } = await shareResponse.json();
+ const managementPath = `/api/v1/notebooks/${notebook.id}/share`;
+ expect((await request.patch(`${managementPath}/site`, {
+ data: { siteSlug: slug, settings: { allowIndexing: true } },
+ })).ok()).toBe(true);
+ return { slug, notebook, memo, share, managementPath };
+};
+
+const robots = (page: Page) => page.locator('meta[name="robots"]');
+const expectRobots = async (page: Page, value: string) => {
+ await expect.poll(() => robots(page).evaluateAll((elements) => [...new Set(elements.map((element) => element.getAttribute("content")))]))
+ .toEqual([value]);
+};
+
+// Vite serves the bare app shell. Supply the server head for these client
+// lifecycle tests; notebook-share-routes.test.mjs checks the real HTML policy.
+const withServerHead = async (page: Page, path: string) => {
+ await page.route(path, async (route) => {
+ const response = await route.fetch();
+ const html = (await response.text()).replace(/<meta\b[^>]*name=["']robots["'][^>]*>/gi, "");
+ await route.fulfill({ response, body: html.replace("</head>", `<meta name="robots" content="${PUBLIC_PAGE_ROBOTS}"></head>`) });
+ });
+};
+
+for (const excluded of [false, true]) {
+ test(`preserves server robots until the article ${excluded ? "fails" : "loads"}`, async ({ page, request }) => {
+ const site = await createSite(request);
+ let release = () => {};
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ try {
+ if (excluded) {
+ expect((await request.patch(`${site.managementPath}/memos/${site.memo.id}`, { data: { excluded: true } })).ok()).toBe(true);
+ }
+ const path = `/s/${site.slug}/${site.memo.id}`;
+ await withServerHead(page, path);
+ await page.route(`**/api/public/notebook-shares/${site.share.token}/memos/${site.memo.id}`, async (route) => {
+ await gate;
+ await route.continue();
+ });
+ await page.goto(path);
+ await expect(page.locator("header").getByText(site.slug, { exact: true })).toBeVisible();
+ await expect(page.getByLabel("正在加载分享笔记")).toBeVisible();
+ await expect(robots(page)).toHaveCount(1);
+ await expectRobots(page, PUBLIC_PAGE_ROBOTS);
+ release();
+ if (excluded) {
+ await expect(page.getByRole("heading", { name: "这篇分享笔记不可用", exact: true })).toBeVisible();
+ } else {
+ await expect(page.getByText("Visible article body.", { exact: true })).toBeVisible();
+ }
+ await expectRobots(page, excluded ? PUBLIC_PAGE_ROBOTS : "index,follow");
+ if (!excluded) {
+ // Keep upstream heading links alongside the site's single-click images
+ // when both handlers share the read-only article wrapper.
+ await page.getByRole("button", { name: "Preview image", exact: true }).click();
+ await expect(page.locator(".yarl__portal")).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(page.locator(".yarl__portal")).toHaveCount(0);
+ await page.getByRole("link", { name: "Jump to section", exact: true }).click();
+ const heading = page.getByRole("heading", { name: "Target section", exact: true });
+ await expect(heading).toBeInViewport();
+ expect(new URL(page.url()).hash).toBe("");
+ }
+ } finally {
+ release();
+ await request.delete(site.managementPath);
+ await request.delete(`/api/v1/memos/${site.memo.id}`);
+ await request.delete(`/api/v1/memos/${site.memo.id}?permanent=1`);
+ await request.delete(`/api/v1/notebooks/${site.notebook.id}`);
+ }
+ });
+}
+
+test("Token URLs and opted-out aliases retain the complete noindex policy", async ({ page, request }) => {
+ const site = await createSite(request);
+ try {
+ for (const path of [`/share/notebook/${site.share.token}`, `/share/notebook/${site.share.token}/${site.memo.id}`]) {
+ await withServerHead(page, path);
+ await page.goto(path);
+ await expect(page.locator("header").getByText(site.slug, { exact: true })).toBeVisible();
+ await expectRobots(page, PUBLIC_PAGE_ROBOTS);
+ }
+ expect((await request.patch(`${site.managementPath}/site`, { data: { settings: { allowIndexing: false } } })).ok()).toBe(true);
+ const alias = `/s/${site.slug}`;
+ await withServerHead(page, alias);
+ await page.goto(alias);
+ await expect(page.locator("header").getByText(site.slug, { exact: true })).toBeVisible();
+ await expectRobots(page, PUBLIC_PAGE_ROBOTS);
+ } finally {
+ await request.delete(site.managementPath);
+ await request.delete(`/api/v1/memos/${site.memo.id}`);
+ await request.delete(`/api/v1/memos/${site.memo.id}?permanent=1`);
+ await request.delete(`/api/v1/notebooks/${site.notebook.id}`);
+ }
+});
diff --git a/wrangler.toml b/wrangler.toml
index 0f9fd306..963876a1 100644
--- a/wrangler.toml
+++ b/wrangler.toml
@@ -19,7 +19,7 @@ watch_dir = ["apps/api/src", "packages/shared/src"]
directory = "apps/web/dist"
binding = "ASSETS"
not_found_handling = "single-page-application"
-run_worker_first = ["/api/*", "/mcp", "/__scheduled"]
+run_worker_first = ["/api/*", "/mcp", "/__scheduled", "/share/notebook/*", "/s/*"]
[[d1_databases]]
binding = "DB"