An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support built-in lock screen wallpapers https://github.com/siyuan-note/siyuan/issues/20797
Daniel5947557acfb7
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.syindex 9c5a45b23f..12f4778afd 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy@@ -6,7 +6,7 @@"id": "20201004194026-s8h2cog","title": "Use on browser","type": "doc",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210104091447-8iiuxlt",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -277,7 +277,7 @@"HeadingLevel": 3,"Properties": {"id": "20210104091447-dluat0m",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -352,7 +352,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022093855-9vgq1sq",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -393,7 +393,7 @@},{"Type": "NodeText",- "Data": ", upload one JPEG, PNG or WebP image (up to 10 MiB and 16 megapixels) to customize the authentication page shown at startup and after locking. Uploading another image replaces it; click Reset to restore the default background. The wallpaper setting is shown when a password is configured or OIDC sign-in is enabled. With a custom wallpaper, the authentication page first shows the wallpaper and local time. Click, tap, or press a key to reveal the login panel; typing your password also keeps the first character. Without a wallpaper, or if the image fails to load, the usual login page appears directly."+ "Data": ", upload one JPEG, PNG or WebP image (up to 10 MiB and 16 megapixels) to customize the authentication page shown at startup and after locking. Click Built-in to choose a picture from the categorized document cover gallery. Built-in pictures are wide and are centered and cropped to fill the screen; portrait screens crop more of the picture. Selecting or uploading another image replaces it; click Reset to restore the default background. The wallpaper setting is shown when a password is configured or OIDC sign-in is enabled. With a custom wallpaper, the authentication page first shows the wallpaper and local time. Click, tap, or press a key to reveal the login panel; typing your password also keeps the first character. Without a wallpaper, or if the image fails to load, the usual login page appears directly."},{"Type": "NodeText",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.syindex 305c818af8..a20b7420f1 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy@@ -6,7 +6,7 @@"id": "20201004184819-nj8ibyg","title": "在浏览器上使用","type": "doc",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210104090909-6pyfjgx",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -284,7 +284,7 @@"HeadingLevel": 3,"Properties": {"id": "20210104090909-9x9sqe8",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -352,7 +352,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022093855-t2z1xoy",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -393,7 +393,7 @@},{"Type": "NodeText",- "Data": " 中上传一张 JPEG、PNG 或 WebP 图片(最大 10 MiB、1600 万像素),即可自定义启动和锁屏后的认证页背景。上传新图片会替换旧图片,点击“重置”恢复默认背景。设置密码或启用 OIDC 登录后显示壁纸设置项。使用自定义壁纸时,认证页先显示壁纸和本机时间;点击、触摸屏幕或按键后显示登录面板。直接键入密码时,首个字符也会进入密码框。未设置壁纸或图片加载失败时,直接显示原有登录界面。"+ "Data": " 中上传一张 JPEG、PNG 或 WebP 图片(最大 10 MiB、1600 万像素),即可自定义启动和锁屏后的认证页背景。也可点击“内置”,从分类图库中选择一张题头图。内置图片为宽图,铺满屏幕时会居中裁切,竖屏裁切范围更大。选择或上传新图片会替换旧图片,点击“重置”恢复默认背景。设置密码或启用 OIDC 登录后显示壁纸设置项。使用自定义壁纸时,认证页先显示壁纸和本机时间;点击、触摸屏幕或按键后显示登录面板。直接键入密码时,首个字符也会进入密码框。未设置壁纸或图片加载失败时,直接显示原有登录界面。"},{"Type": "NodeText",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.syindex b6a92927c8..84fa2580d3 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy@@ -6,7 +6,7 @@"id": "20211226122523-rl8356a","title": "在瀏覽器上使用","type": "doc",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226122545-a65v8e1",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -273,7 +273,7 @@"HeadingLevel": 3,"Properties": {"id": "20211226122545-lsv6dhu",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -337,7 +337,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022093855-oc11gow",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -378,7 +378,7 @@},{"Type": "NodeText",- "Data": " 中上傳一張 JPEG、PNG 或 WebP 圖片(最大 10 MiB、1600 萬像素),即可自訂啟動及鎖定後的驗證頁面背景。上傳新圖片會取代舊圖片,點擊「重置」恢復預設背景。設定密碼或啟用 OIDC 登入後顯示桌布設定項目。使用自訂桌布時,驗證頁面先顯示桌布與本機時間;點擊、觸控畫面或按鍵後顯示登入面板。直接輸入密碼時,第一個字元也會進入密碼欄位。未設定桌布或圖片載入失敗時,直接顯示原有登入介面。"+ "Data": " 中上傳一張 JPEG、PNG 或 WebP 圖片(最大 10 MiB、1600 萬像素),即可自訂啟動及鎖定後的驗證頁面背景。也可點擊「內置」,從分類圖庫中選擇一張題頭圖。內置圖片為寬圖,填滿螢幕時會置中裁切,直向螢幕的裁切範圍更大。選擇或上傳新圖片會取代舊圖片,點擊「重置」恢復預設背景。設定密碼或啟用 OIDC 登入後顯示桌布設定項目。使用自訂桌布時,驗證頁面先顯示桌布與本機時間;點擊、觸控畫面或按鍵後顯示登入面板。直接輸入密碼時,第一個字元也會進入密碼欄位。未設定桌布或圖片載入失敗時,直接顯示原有登入介面。"},{"Type": "NodeText",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.syindex 295e72f02f..934662e66c 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.sy@@ -7,7 +7,7 @@"id": "20240530101000-40hohog","title": "ブラウザ","type": "doc",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-vn1tvf6","id": "20240530101000-yllodqo",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -300,7 +300,7 @@"Properties": {"ID": "20240530101000-zvy840s","id": "20240530101000-b6ssy52",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -369,7 +369,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022093855-2gm31el",- "updated": "20261024102323"+ "updated": "20261024111110"},"Children": [{@@ -406,7 +406,7 @@},{"Type": "NodeText",- "Data": " で JPEG、PNG、WebP の画像を1枚アップロードすると(最大 10 MiB、1600万画素)、起動時やロック後の認証画面の背景を変更できます。新しい画像をアップロードすると置き換わります。「リセット」で既定の背景に戻せます。パスワードの設定後、または OIDC ログインを有効にすると、壁紙の設定項目が表示されます。カスタム壁紙を設定すると、認証ページに壁紙と端末の時刻が先に表示されます。クリック、タップ、キー操作でログインパネルを表示します。パスワードを直接入力すると、最初の文字も入力欄に入ります。壁紙が未設定の場合や画像の読み込みに失敗した場合は、通常のログイン画面を直接表示します。"+ "Data": " で JPEG、PNG、WebP の画像を1枚アップロードすると(最大 10 MiB、1600万画素)、起動時やロック後の認証画面の背景を変更できます。「組み込み」から、カテゴリ別の題頭画像ギャラリーで画像を1枚選ぶこともできます。組み込み画像は横長で、画面全体を埋めるように中央で切り抜かれるため、縦画面では切り抜かれる範囲が広くなります。別の画像を選択またはアップロードすると置き換わります。「リセット」で既定の背景に戻せます。パスワードの設定後、または OIDC ログインを有効にすると、壁紙の設定項目が表示されます。カスタム壁紙を設定すると、認証ページに壁紙と端末の時刻が先に表示されます。クリック、タップ、キー操作でログインパネルを表示します。パスワードを直接入力すると、最初の文字も入力欄に入ります。壁紙が未設定の場合や画像の読み込みに失敗した場合は、通常のログイン画面を直接表示します。"},{"Type": "NodeText",diff --git a/app/src/config/tabs/lockScreenWallpaper.test.ts b/app/src/config/tabs/lockScreenWallpaper.test.tsindex e2118e20ea..288179021e 100644--- a/app/src/config/tabs/lockScreenWallpaper.test.ts+++ b/app/src/config/tabs/lockScreenWallpaper.test.ts@@ -9,7 +9,7 @@ const fixture = () => {const listeners = new Map<string, () => void>();const controls = new Map<string, {disabled?: boolean; value?: string; files?: Blob[]; click?: () => void;addEventListener: (type: string, fn: () => void) => void}>();- for (const selector of ["[data-wallpaper-file]", "[data-wallpaper-upload]", "[data-wallpaper-reset]"]) {+ for (const selector of ["[data-wallpaper-file]", "[data-wallpaper-upload]", "[data-wallpaper-reset]", "[data-wallpaper-built-in]"]) {controls.set(selector, {value: "", addEventListener: (type, fn) => listeners.set(selector + type, fn)});}const hidden = new Set<string>();@@ -22,17 +22,32 @@ const fixture = () => {const messages: string[] = [];let responseCode = 0;let patchFails = false;+ let readFails = false;+ let readSize = 4;+ let finishRead: () => void;+ let pickerOptions: {select: (name: string) => void; destroyCallback: () => void};+ const files: File[] = [];const exports = {} as {mountLockScreenWallpaper: (root: unknown) => void; syncLockScreenWallpaper: () => void};const compiled = transpileModule(readFileSync("src/config/tabs/lockScreenWallpaper.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;runInNewContext(compiled, {- exports, Error, Date,+ exports, Error, Date, File,+ fetch: async (path: string) => {+ calls.push(`read:${path}`);+ await new Promise<void>(resolve => { finishRead = resolve; });+ return {ok: !readFails, blob: async () => new Blob([new Uint8Array(readSize)], {type: "image/webp"})};+ },document: {querySelectorAll: () => [element]},- window: {siyuan: {config, languages: {_kernel: {438: "invalid image"}}}},+ window: {siyuan: {config, languages: {_kernel: {438: "invalid image", 258: "operation failed"}}}},require: (name: string) => {if (name.endsWith("contractFormData")) return {ContractFormData};if (name.endsWith("message")) return {showMessage: (text: string) => messages.push(text)};+ if (name.endsWith("coverPicker")) return {openCoverPicker: (options: typeof pickerOptions) => {+ calls.push("picker");+ pickerOptions = options;+ return {};+ }};if (name.endsWith("appearanceRuntime")) return {appearanceConfigApi: {patch: async (key: string, value: boolean) => {calls.push(`patch:${key}:${value}`);@@ -42,13 +57,26 @@ const fixture = () => {}};return {fetchSyncPost: async (path: string, form?: ContractFormData<{file: Blob}>) => {calls.push(path);- if (form) assert.ok(form.get("file") instanceof Blob);+ if (form) {+ assert.ok(form.get("file") instanceof Blob);+ files.push(form.get("file") as File);+ }return {code: responseCode, msg: "upload failed"};}};},});exports.mountLockScreenWallpaper({querySelector: () => element});- return {config, calls, messages, controls, preview, hidden, exports,+ const settle = () => new Promise(resolve => setImmediate(resolve));+ return {config, calls, messages, controls, preview, hidden, exports, files,+ openBuiltIn: () => listeners.get("[data-wallpaper-built-in]click")(),+ select: (name = "cover_001.webp") => pickerOptions.select(name),+ closePicker: () => pickerOptions.destroyCallback(),+ finishRead: async (fail = false, size = 4) => {+ readFails = fail;+ readSize = size;+ finishRead();+ await settle();+ },setResponse: (code: number) => { responseCode = code; },failPatch: () => { patchFails = true; },change: async (size = 4) => {@@ -79,6 +107,58 @@ test("wallpaper uploads one file before enabling its preference and resets beforassert.equal(f.controls.get("[data-wallpaper-upload]").disabled, false);});+test("built-in covers use the same single-file save path and block concurrent changes", async () => {+ const f = fixture();+ f.openBuiltIn();+ f.openBuiltIn();+ assert.deepEqual(f.calls, ["picker"], "repeated clicks share one picker");+ f.select();+ for (const selector of ["[data-wallpaper-upload]", "[data-wallpaper-reset]", "[data-wallpaper-built-in]"]) {+ assert.equal(f.controls.get(selector).disabled, true);+ }+ await f.reset();+ f.openBuiltIn();+ assert.deepEqual(f.calls, ["picker", "read:/appearance/covers/cover_001.webp"]);+ await f.finishRead();+ assert.deepEqual(f.calls.slice(2), ["/api/system/uploadLockScreenWallpaper", "patch:lockScreenWallpaper:true"]);+ assert.equal(f.files[0].name, "cover_001.webp");+ assert.equal(f.files[0].type, "image/webp");+ assert.equal(f.config.appearance.lockScreenWallpaper, true);+ assert.match(f.preview.src, /^\/api\/system\/getLockScreenWallpaper\?v=/);+ assert.equal(f.controls.get("[data-wallpaper-built-in]").disabled, false);+ f.closePicker();+ f.openBuiltIn();+ assert.equal(f.calls.at(-1), "picker");+});++test("failed built-in reads, oversized covers and rejected uploads do not enable a wallpaper", async () => {+ for (const failure of ["read", "size", "upload"]) {+ const f = fixture();+ f.openBuiltIn();+ if (failure === "upload") f.setResponse(-1);+ f.select("cover 2.webp");+ await f.finishRead(failure === "read", failure === "size" ? 10 * 1024 * 1024 + 1 : 4);+ assert.equal(f.calls[1], "read:/appearance/covers/cover%202.webp");+ assert.equal(f.calls.includes("patch:lockScreenWallpaper:true"), false);+ assert.equal(f.config.appearance.lockScreenWallpaper, false);+ assert.deepEqual(f.messages, [failure === "read" ? "operation failed" :+ failure === "size" ? "invalid image" : "upload failed"]);+ assert.equal(f.controls.get("[data-wallpaper-built-in]").disabled, false);+ }+});++test("cancelled built-in selection and readonly settings preserve the wallpaper", () => {+ const f = fixture();+ f.config.appearance.lockScreenWallpaper = true;+ f.openBuiltIn();+ f.closePicker();+ assert.deepEqual(f.calls, ["picker"]);+ assert.equal(f.config.appearance.lockScreenWallpaper, true);+ f.config.readonly = true;+ f.openBuiltIn();+ assert.deepEqual(f.calls, ["picker"]);+});+test("failed uploads and oversized files do not enable the wallpaper", async () => {const f = fixture();f.setResponse(-1);diff --git a/app/src/config/tabs/lockScreenWallpaper.ts b/app/src/config/tabs/lockScreenWallpaper.tsindex dcab7ac5de..b99c34f1d2 100644--- a/app/src/config/tabs/lockScreenWallpaper.ts+++ b/app/src/config/tabs/lockScreenWallpaper.ts@@ -2,6 +2,7 @@ import {ContractFormData} from "../../util/contractFormData";import {fetchSyncPost} from "../../util/fetch";import {showMessage} from "../../dialog/message";import {appearanceConfigApi} from "./appearanceRuntime";+import {openCoverPicker} from "../../protyle/header/coverPicker";const wallpaperURL = "/api/system/getLockScreenWallpaper";@@ -15,6 +16,8 @@ export const genLockScreenWallpaperHtml = () => {</div><span class="fn__space"></span><div class="fn__flex fn__flex-column fn__flex-center fn__size200">+ <button class="b3-button b3-button--outline fn__flex-center fn__size200" data-wallpaper-built-in><svg><use xlink:href="#iconImage"></use></svg>${lang.builtIn}</button>+ <div class="fn__hr--small"></div><button class="b3-button b3-button--outline fn__flex-center fn__size200" data-wallpaper-upload><svg><use xlink:href="#iconUpload"></use></svg>${lang.upload}</button><div class="fn__hr--small"></div><button class="b3-button b3-button--outline fn__flex-center fn__size200" data-wallpaper-reset><svg><use xlink:href="#iconUndo"></use></svg>${lang.reset}</button>@@ -46,7 +49,9 @@ export const mountLockScreenWallpaper = (root: HTMLElement) => {const input = element.querySelector<HTMLInputElement>("[data-wallpaper-file]");const upload = element.querySelector<HTMLButtonElement>("[data-wallpaper-upload]");const reset = element.querySelector<HTMLButtonElement>("[data-wallpaper-reset]");+ const builtIn = element.querySelector<HTMLButtonElement>("[data-wallpaper-built-in]");let busy = false;+ let picker: ReturnType<typeof openCoverPicker>;const run = async (operation: () => Promise<void>) => {if (busy || window.siyuan.config.readonly) {return;@@ -54,6 +59,7 @@ export const mountLockScreenWallpaper = (root: HTMLElement) => {busy = true;upload.disabled = true;reset.disabled = true;+ builtIn.disabled = true;try {await operation();syncLockScreenWallpaper();@@ -63,6 +69,7 @@ export const mountLockScreenWallpaper = (root: HTMLElement) => {busy = false;upload.disabled = false;reset.disabled = false;+ builtIn.disabled = false;input.value = "";}};@@ -71,19 +78,38 @@ export const mountLockScreenWallpaper = (root: HTMLElement) => {throw new Error(response.msg);}};+ const save = async (file: File) => {+ if (file.size > 10 * 1024 * 1024) {+ throw new Error(window.siyuan.languages._kernel[438]);+ }+ checkResponse(await fetchSyncPost("/api/system/uploadLockScreenWallpaper", new ContractFormData({file})));+ await appearanceConfigApi.patch("lockScreenWallpaper", true);+ };+ builtIn.addEventListener("click", () => {+ if (busy || picker || window.siyuan.config.readonly) {+ return;+ }+ picker = openCoverPicker({+ select: name => {+ void run(async () => {+ const response = await fetch(`/appearance/covers/${encodeURIComponent(name)}`);+ if (!response.ok) {+ throw new Error(window.siyuan.languages._kernel[258]);+ }+ const blob = await response.blob();+ await save(new File([blob], name, {type: blob.type}));+ });+ },+ destroyCallback: () => { picker = undefined; },+ });+ });upload.addEventListener("click", () => input.click());input.addEventListener("change", () => {const file = input.files?.[0];if (!file) {return;}- void run(async () => {- if (file.size > 10 * 1024 * 1024) {- throw new Error(window.siyuan.languages._kernel[438]);- }- checkResponse(await fetchSyncPost("/api/system/uploadLockScreenWallpaper", new ContractFormData({file})));- await appearanceConfigApi.patch("lockScreenWallpaper", true);- });+ void run(() => save(file));});reset.addEventListener("click", () => {void run(async () => {diff --git a/app/src/protyle/header/Background.ts b/app/src/protyle/header/Background.tsindex 58ae04e8ff..7b7e0eca3f 100644--- a/app/src/protyle/header/Background.ts+++ b/app/src/protyle/header/Background.ts@@ -1,6 +1,6 @@import {toggleMenu} from "../../menus/menuToggle";import {hasClosestByClassName} from "../util/hasClosest";-import {getRandom, isMobile} from "../../util/functions";+import {getRandom} from "../../util/functions";import {hideElements} from "../ui/hideElements";import {uploadFiles} from "../upload";import {fetchPost} from "../../util/fetch";@@ -18,7 +18,8 @@ import {assetMenu} from "../../menus/protyle";import {previewImages} from "../preview/image";import {Menu} from "../../plugin/Menu";import {escapeHtml} from "../../util/escape";-import {fetchCoverData, getCategoryLabel} from "./coverData";+import {fetchCoverData} from "./coverData";+import {openCoverPicker} from "./coverPicker";import {getAssetUploadSuccesses} from "../upload/uploadResult";import {hasDataTransferFiles} from "../upload/localDropFiles";import {showMessage} from "../../dialog/message";@@ -297,18 +298,6 @@ export class Background {break;} else if (type === "show-random" && !protyle.disabled) {window.siyuan.menus.menu.remove();- // 内置题头图对话框:优先展示封面图片,加载失败时回退到 CSS 图案- const dialog = new Dialog({- title: window.siyuan.languages.builtIn,- content: `<div class="b3-cards" style="padding:16px;justify-content:center;align-items:center;min-height:200px">- <span class="b3-loading" aria-hidden="true"></span>- </div>`,- width: isMobile() ? "92vw" : "912px",- height: isMobile() ? "80vh" : "70vh",- });- dialog.element.setAttribute("data-key", Constants.DIALOG_BACKGROUNDRANDOM);- bindPopoverDialog(dialog, protyle.element);-const renderCSSPatterns = (d: Dialog) => {let html = "";bgs.forEach((item: string, index: number) => {@@ -332,64 +321,12 @@ export class Background {});};- fetchCoverData().then((coverData) => {- if (!coverData) {- renderCSSPatterns(dialog);- return;- }- const { categories, coversByCategory, allCovers } = coverData;-- const buildCards = (category: string): string => {- const covers = category === "all" ? allCovers : (coversByCategory.get(category) || []);- return covers.map(c => {- const url = `/appearance/covers/${c.file}`;- return `<div class="b3-card b3-cover__card" data-name="${c.file}"><img src="${url}" loading="lazy"></div>`;- }).join("");- };-- const buildTabs = (activeCategory: string): string => {- let tabs = `<span class="b3-chip b3-chip--hover${activeCategory === "all" ? " b3-chip--current" : ""}" data-category="all">${window.siyuan.languages.coverAll}</span>`;- for (const cat of categories) {- tabs += `<span class="b3-chip b3-chip--hover${activeCategory === cat ? " b3-chip--current" : ""}" data-category="${cat}">${getCategoryLabel(cat)}</span>`;- }- return `<div class="b3-cover__tabs">${tabs}</div>`;- };-- let activeCategory = "all";- const bodyEl = dialog.element.querySelector(".b3-dialog__body") as HTMLElement;- bodyEl.innerHTML = `<div class="b3-cover">- ${buildTabs(activeCategory)}- <div class="b3-cards b3-cover__cards">${buildCards(activeCategory)}</div>-</div>`;- const tabsEl = bodyEl.querySelector(".b3-cover__tabs") as HTMLElement;- const cardsEl = bodyEl.querySelector(".b3-cover__cards") as HTMLElement;-- // 点击事件委托- bodyEl.addEventListener("click", (event) => {- const target = event.target as HTMLElement;- const chip = target.closest<HTMLElement>(".b3-chip[data-category]");- if (chip && tabsEl.contains(chip)) {- const category = chip.dataset.category || "all";- if (category === activeCategory) {- return;- }- tabsEl.querySelector(".b3-chip--current")?.classList.remove("b3-chip--current");- chip.classList.add("b3-chip--current");- activeCategory = category;- cardsEl.innerHTML = buildCards(activeCategory);- cardsEl.scrollTop = 0;- } else if (target.closest(".b3-cover__card")) {- const card = target.closest(".b3-cover__card") as HTMLElement;- const name = card.getAttribute("data-name");- if (name) {- this.uploadBuiltInCover(protyle, name);- }- dialog.destroy();- }- });- }).catch(() => {- renderCSSPatterns(dialog);+ const dialog = openCoverPicker({+ select: name => this.uploadBuiltInCover(protyle, name),+ fallback: renderCSSPatterns,});+ dialog.element.setAttribute("data-key", Constants.DIALOG_BACKGROUNDRANDOM);+ bindPopoverDialog(dialog, protyle.element);event.preventDefault();event.stopPropagation();diff --git a/app/src/protyle/header/coverPicker.ts b/app/src/protyle/header/coverPicker.tsnew file mode 100644index 0000000000..8e98da4d29--- /dev/null+++ b/app/src/protyle/header/coverPicker.ts@@ -0,0 +1,97 @@+import {Dialog} from "../../dialog";+import {showMessage} from "../../dialog/message";+import {isMobile} from "../../util/functions";+import {escapeHtmlTextAndAttr} from "../../util/escape";+import {fetchCoverData, getCategoryLabel} from "./coverData";++export const openCoverPicker = (options: {+ select: (name: string) => void;+ fallback?: (dialog: Dialog) => void;+ destroyCallback?: () => void;+}) => {+ const dialog = new Dialog({+ title: window.siyuan.languages.builtIn,+ content: `<div class="b3-cards" style="padding:16px;justify-content:center;align-items:center;min-height:200px">+ <span class="b3-loading" aria-hidden="true"></span>+</div>`,+ width: isMobile() ? "92vw" : "912px",+ height: isMobile() ? "80vh" : "70vh",+ destroyCallback: options.destroyCallback,+ });+ const active = () => dialog.element.isConnected && dialog.element.dataset.dialogClosing !== "true";+ const unavailable = () => {+ if (!active()) {+ return;+ }+ if (options.fallback) {+ options.fallback(dialog);+ } else {+ dialog.destroy();+ showMessage(window.siyuan.languages._kernel[258], 7000, "error");+ }+ };+ void fetchCoverData().then(coverData => {+ if (!active()) {+ return;+ }+ if (!coverData?.allCovers.length) {+ unavailable();+ return;+ }+ const {categories, coversByCategory, allCovers} = coverData;+ const buildCards = (category: string) => {+ const covers = category === "all" ? allCovers : (coversByCategory.get(category) || []);+ return covers.map((cover, index) => `<div class="b3-card b3-cover__card" role="button" tabindex="0" data-name="${escapeHtmlTextAndAttr(cover.file)}" aria-label="${escapeHtmlTextAndAttr(getCategoryLabel(cover.category))} ${index + 1}"><img src="/appearance/covers/${encodeURIComponent(cover.file)}" loading="lazy" alt=""></div>`).join("");+ };+ const buildTab = (category: string, label: string) => {+ const current = category === "all";+ return `<span class="b3-chip b3-chip--hover${current ? " b3-chip--current" : ""}" role="button" tabindex="0" aria-pressed="${current}" data-category="${escapeHtmlTextAndAttr(category)}">${escapeHtmlTextAndAttr(label)}</span>`;+ };+ const body = dialog.element.querySelector<HTMLElement>(".b3-dialog__body");+ body.innerHTML = `<div class="b3-cover">+ <div class="b3-cover__tabs">${buildTab("all", window.siyuan.languages.coverAll)}${categories.map(category => buildTab(category, getCategoryLabel(category))).join("")}</div>+ <div class="b3-cards b3-cover__cards">${buildCards("all")}</div>+</div>`;+ const tabs = body.querySelector<HTMLElement>(".b3-cover__tabs");+ const cards = body.querySelector<HTMLElement>(".b3-cover__cards");+ let selected = false;+ body.addEventListener("click", event => {+ if (!active() || selected) {+ return;+ }+ const target = event.target as HTMLElement;+ const chip = target.closest<HTMLElement>(".b3-chip[data-category]");+ if (chip && tabs.contains(chip)) {+ if (chip.classList.contains("b3-chip--current")) {+ return;+ }+ const previous = tabs.querySelector(".b3-chip--current");+ previous?.classList.remove("b3-chip--current");+ previous?.setAttribute("aria-pressed", "false");+ chip.classList.add("b3-chip--current");+ chip.setAttribute("aria-pressed", "true");+ cards.innerHTML = buildCards(chip.dataset.category);+ cards.scrollTop = 0;+ return;+ }+ const card = target.closest<HTMLElement>(".b3-cover__card");+ if (card && cards.contains(card) && allCovers.some(cover => cover.file === card.dataset.name)) {+ selected = true;+ options.select(card.dataset.name);+ dialog.destroy();+ }+ });+ body.addEventListener("keydown", event => {+ if (event.isComposing || event.repeat || event.altKey || event.ctrlKey || event.metaKey ||+ (event.key !== "Enter" && event.key !== " ")) {+ return;+ }+ const target = (event.target as HTMLElement).closest<HTMLElement>('[role="button"]');+ if (target && body.contains(target)) {+ event.preventDefault();+ target.click();+ }+ });+ }).catch(unavailable);+ return dialog;+};diff --git a/app/tests/coverPicker.test.js b/app/tests/coverPicker.test.jsindex 1db018a4cf..f3a442fe41 100644--- a/app/tests/coverPicker.test.js+++ b/app/tests/coverPicker.test.js@@ -11,10 +11,20 @@ const runCases = async (sources, css, mobile, manifest, languages, image) => {style.textContent = css + "body {margin:0;} .b3-dialog__container {transition:none;}";document.head.replaceChildren(style);const menu = {element: document.createElement("div"), remove() {}};- window.siyuan = {languages, dialogs: [], storage: {}, zIndex: 0, menus: {menu}};+ window.siyuan = {languages, dialogs: [], storage: {}, zIndex: 0, menus: {menu},+ config: {readonly: false, appearance: {lockScreenWallpaper: false}}};+ const calls = [];+ const messages = [];+ const chosen = [];+ let readCover;+ const imageBlob = await (await fetch(image)).blob();window.fetch = async url => {- assert.equal(url, "/appearance/covers/manifest.json");- return {ok: true, json: async () => manifest};+ if (url === "/appearance/covers/manifest.json") {+ return {ok: true, json: async () => manifest};+ }+ calls.push(url);+ await new Promise(resolve => { readCover = resolve; });+ return {ok: true, blob: async () => imageBlob};};const stubs = {"block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},@@ -24,6 +34,21 @@ const runCases = async (sources, css, mobile, manifest, languages, image) => {"dialog/moveResize": {moveResize() {}},"protyle/ui/hideElements": {hideElements() {}},"constants": {Constants: {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},+ "dialog/message": {showMessage: text => messages.push(text)},+ "config/tabs/appearanceRuntime": {appearanceConfigApi: {patch: async (key, value) => {+ calls.push(`patch:${key}:${value}`);+ window.siyuan.config.appearance[key] = value;+ }}},+ "util/fetch": {fetchSyncPost: async (url, form) => {+ calls.push(url);+ if (form) {+ const file = form.get("file");+ assert.equal(file.name, manifest[0].file);+ assert.equal(file.type, "image/webp");+ assert.equal(file.size, imageBlob.size);+ }+ return {code: 0};+ }},};const cache = {};const load = name => {@@ -47,6 +72,7 @@ const runCases = async (sources, css, mobile, manifest, languages, image) => {const {Background} = load("protyle/header/Background");const owner = document.createElement("div");const background = new Background({element: owner, block: {rootID: "cover-document"}, disabled: false});+ background.uploadBuiltInCover = (_protyle, name) => chosen.push(name);owner.append(background.element);owner.hidden = true;document.body.append(owner);@@ -92,7 +118,7 @@ const runCases = async (sources, css, mobile, manifest, languages, image) => {"the last row is reachable");const category = tabs.children[1];- category.click();+ category.dispatchEvent(new KeyboardEvent("keydown", {key: " ", bubbles: true, cancelable: true}));await loadImages();assert.equal(body.querySelector(".b3-cover__tabs"), tabs);assert.equal(body.querySelector(".b3-cover__cards"), list);@@ -104,8 +130,83 @@ const runCases = async (sources, css, mobile, manifest, languages, image) => {await loadImages();assert.equal(list.children.length, manifest.length);checkGaps();- dialog.destroy();+ const firstCard = list.firstElementChild;+ firstCard.focus();+ firstCard.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true, cancelable: true}));+ firstCard.click();+ assert.deepEqual(chosen, [manifest[0].file], "keyboard selection runs the document callback only once");+ await settle();+ assert.equal(window.siyuan.dialogs.length, 0);++ const wallpaper = load("config/tabs/lockScreenWallpaper");+ const root = document.createElement("div");+ root.className = mobile ? "config config--mobile" : "config";+ root.innerHTML = wallpaper.genLockScreenWallpaperHtml();+ document.body.append(root);+ wallpaper.mountLockScreenWallpaper(root);+ const builtIn = root.querySelector("[data-wallpaper-built-in]");+ builtIn.click();+ builtIn.click();+ await settle();+ assert.equal(window.siyuan.dialogs.length, 1, "the setting shares one picker on repeated clicks");+ let picker = window.siyuan.dialogs[0];+ assert.equal(picker.element.querySelectorAll(".b3-cover__card").length, manifest.length);+ picker.element.querySelector(".b3-dialog__scrim").click();+ await settle();+ assert.deepEqual(calls, [], "closing the picker does not change the wallpaper");+ builtIn.click();+ await settle();+ picker = window.siyuan.dialogs[0];+ picker.element.querySelector(".b3-cover__card img").click();+ await settle();+ assert.equal(window.siyuan.dialogs.length, 0);+ assert.ok(builtIn.disabled, "selection is disabled while the file is being saved");+ root.querySelector("[data-wallpaper-reset]").click();+ readCover();+ await settle();+ assert.deepEqual(calls, [`/appearance/covers/${manifest[0].file}`,+ "/api/system/uploadLockScreenWallpaper", "patch:lockScreenWallpaper:true"]);+ assert.equal(window.siyuan.config.appearance.lockScreenWallpaper, true);+ assert.match(root.querySelector("[data-wallpaper-preview]").src, /\/api\/system\/getLockScreenWallpaper\?v=/);+ assert.equal(builtIn.disabled, false);+ assert.deepEqual(messages, []);+ root.querySelector("[data-wallpaper-reset]").click();+ await settle();+ assert.deepEqual(calls.slice(-2), ["patch:lockScreenWallpaper:false", "/api/system/removeLockScreenWallpaper"]);++ // 每次重新加载共享选择器,避免成功缓存掩盖失败和取消路径。+ const freshPicker = () => {+ delete cache["protyle/header/coverData"];+ delete cache["protyle/header/coverPicker"];+ return load("protyle/header/coverPicker").openCoverPicker;+ };+ window.fetch = async () => { throw new Error("offline"); };+ let fallbackCount = 0;+ let fallbackDialog;+ freshPicker()({select: () => assert.fail("unavailable covers cannot be selected"), fallback: d => {+ fallbackCount++;+ fallbackDialog = d;+ }});+ await settle();+ assert.equal(fallbackCount, 1, "document covers retain their pattern fallback");+ fallbackDialog.destroy();+ await settle();+ freshPicker()({select: () => assert.fail("unavailable covers cannot be selected")});+ await settle();+ assert.deepEqual(messages, [languages._kernel[258]], "wallpaper selection reports unavailable images");+ assert.equal(window.siyuan.dialogs.length, 0);+ window.fetch = async () => ({ok: true, json: async () => []});+ freshPicker()({select: () => assert.fail("an empty gallery cannot be selected")});+ await settle();+ assert.equal(messages.length, 2, "an empty gallery is handled as unavailable");+ let finishManifest;+ window.fetch = () => new Promise(resolve => { finishManifest = resolve; });+ const pending = freshPicker()({select: () => assert.fail("a cancelled picker cannot select"),+ fallback: () => assert.fail("a cancelled picker cannot show fallback")});+ pending.destroy();+ finishManifest({ok: false});await settle();+ assert.equal(window.siyuan.dialogs.length, 0);};const runElectron = async () => {@@ -127,7 +228,8 @@ const runElectron = async () => {const image = "data:image/webp;base64," + fs.readFileSync(path.join(root, "appearance/covers", manifest[0].file)).toString("base64");for (const mobile of [false, true]) {const sources = {};- for (const name of ["protyle/header/Background", "protyle/header/coverData", "dialog/index"]) {+ for (const name of ["protyle/header/Background", "protyle/header/coverData", "protyle/header/coverPicker",+ "dialog/index", "config/tabs/lockScreenWallpaper", "util/contractFormData", "util/escape"]) {const source = preprocess(fs.readFileSync(path.join(root, "src", name + ".ts"), "utf8"),{MOBILE: mobile, BROWSER: false}, false, true);sources[name] = ts.transpileModule(source, {@@ -161,7 +263,7 @@ if (process.versions.electron && process.type === "browser") {require("electron").app.exit(1);});} else {- require("node:test").it("keeps cover rows separated and category navigation fixed on desktop and mobile", {+ require("node:test").it("shares built-in covers between document headers and wallpapers on desktop and mobile", {skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,timeout: 60000,}, async () => {diff --git a/app/tests/lockScreenWallpaperLayout.test.js b/app/tests/lockScreenWallpaperLayout.test.jsindex a13e176fdc..1cd3f2ccd0 100644--- a/app/tests/lockScreenWallpaperLayout.test.js+++ b/app/tests/lockScreenWallpaperLayout.test.js@@ -40,15 +40,21 @@ const checkSettingsLayout = async (html, css, fontSize) => {const group = actions.getBoundingClientRect();const upload = item.querySelector("[data-wallpaper-upload]");const reset = item.querySelector("[data-wallpaper-reset]");+ const builtIn = item.querySelector("[data-wallpaper-built-in]");const uploadRect = upload.getBoundingClientRect();const resetRect = reset.getBoundingClientRect();+ const builtInRect = builtIn.getBoundingClientRect();check.ok(item.scrollWidth <= item.clientWidth, "wallpaper setting does not overflow horizontally");check.ok(group.left >= rect.left && group.right <= rect.right, "actions fit the setting row");check.ok(resetRect.top >= uploadRect.bottom, "reset appears below upload");+ check.ok(uploadRect.top >= builtInRect.bottom, "built-in selection appears above upload");+ check.ok(Math.abs(builtInRect.left - uploadRect.left) < 1 && Math.abs(builtInRect.right - uploadRect.right) < 1,+ "built-in selection aligns with upload and reset");check.ok(Math.abs(uploadRect.left - resetRect.left) < 1 && Math.abs(uploadRect.right - resetRect.right) < 1,"stacked actions share horizontal bounds");check.equal(upload.querySelector("use").getAttribute("xlink:href"), "#iconUpload");check.equal(reset.querySelector("use").getAttribute("xlink:href"), "#iconUndo");+ check.equal(builtIn.querySelector("use").getAttribute("xlink:href"), "#iconImage");if (innerWidth > 750) {const reference = document.querySelector("[data-reference]").getBoundingClientRect();const main = item.querySelector(".config-item__main").getBoundingClientRect();