An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Simplify map controls and classify blocked SDK resources https://github.com/siyuan-note/siyuan/issues/20129
Daniel565aafaf4099
diff --git a/app/electron/mapHostDiagnostics.js b/app/electron/mapHostDiagnostics.jsindex cd526bc0b6..47e575f7d6 100644--- a/app/electron/mapHostDiagnostics.js+++ b/app/electron/mapHostDiagnostics.js@@ -6,6 +6,50 @@ const mapDiagnosticCodes = Object.freeze(["storageUnavailable", "webglUnavailable", "amapInvalidKey", "amapInvalidSecurityCode","amapDomainMismatch", "amapPlatformMismatch",]);+const mapCSPDiagnosticCodes = Object.freeze(["cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm"]);+const mapCSPResourceCodes = Object.freeze([+ "blob", "data", "inline", "eval", "wasm", "other",+ "https:webapi.amap.com", "https:restapi.amap.com", "https:vdata.amap.com", "https:a.amap.com",+ "https:g.alicdn.com", "https:fourier.taobao.com", "https:autonavi-tile", "https:other",+ "http:webapi.amap.com", "http:restapi.amap.com", "http:vdata.amap.com", "http:a.amap.com",+ "http:g.alicdn.com", "http:fourier.taobao.com", "http:autonavi-tile", "http:other",+]);+const resourceHosts = Object.freeze(["webapi.amap.com", "restapi.amap.com", "vdata.amap.com", "a.amap.com",+ "g.alicdn.com", "fourier.taobao.com"]);++const classifyMapCSPResources = message => {+ if (typeof message !== "string" || !/content security policy/i.test(message)) return [];+ // Chromium 的 eval 文案在 directive 和实际策略之间还有原因,不能按资源 URL 解析。+ if (/^(?:Evaluating a string as JavaScript|Refused to evaluate a string as JavaScript)/i.test(message)) {+ return [{code: "cspEval", resource: "eval"}];+ }+ if (/^(?:Compiling or instantiating|Refused to compile or instantiate) a WebAssembly/i.test(message)) {+ return [{code: "cspWasm", resource: "wasm"}];+ }+ const directive = message.match(/content security policy directive:?\s*["'](worker-src|child-src|script-src(?:-elem|-attr)?|connect-src|img-src|style-src(?:-elem|-attr)?)\b/i)?.[1].toLowerCase();+ if (!directive) return [];+ const code = directive.startsWith("script-src") ? "cspScript" : directive.startsWith("style-src") ? "cspStyle" :+ ({"worker-src": "cspWorker", "child-src": "cspWorker", "connect-src": "cspConnect", "img-src": "cspImage"})[directive];+ let resource = "other";+ if (/^(?:Executing inline|Applying inline|Refused to execute inline|Refused to apply inline)/i.test(message)) {+ resource = "inline";+ } else {+ const target = message.match(/(?:loading the script|loading a script|load the script|connecting to|connect to|creating a worker from|create a worker from|loading the image|load the image|loading the stylesheet|load the stylesheet)\s*["']([^"']+)["']/i)?.[1];+ if (target?.startsWith("blob:")) resource = "blob";+ else if (target?.startsWith("data:")) resource = "data";+ else if (target) {+ try {+ const url = new URL(target);+ if (["https:", "http:"].includes(url.protocol)) {+ const host = url.port ? "other" : resourceHosts.includes(url.hostname) ? url.hostname :+ /^(?:webst|webrd)\d+\.is\.autonavi\.com$/.test(url.hostname) ? "autonavi-tile" : "other";+ resource = url.protocol + host;+ }+ } catch (_error) { /* 未识别资源只保留固定 other 类别。 */ }+ }+ }+ return mapCSPResourceCodes.includes(resource) ? [{code, resource}] : [];+};const classifyMapConsoleMessage = message => {if (typeof message !== "string") return [];@@ -26,4 +70,4 @@ const classifyMapConsoleMessage = message => {return ret;};-module.exports = {mapDiagnosticCodes, classifyMapConsoleMessage};+module.exports = {mapDiagnosticCodes, mapCSPDiagnosticCodes, mapCSPResourceCodes, classifyMapConsoleMessage, classifyMapCSPResources};diff --git a/app/electron/mapHostDiagnostics.test.js b/app/electron/mapHostDiagnostics.test.jsindex 494b4790a4..b819c63f39 100644--- a/app/electron/mapHostDiagnostics.test.js+++ b/app/electron/mapHostDiagnostics.test.js@@ -1,6 +1,7 @@const assert = require("node:assert/strict");const {test} = require("node:test");-const {mapDiagnosticCodes, classifyMapConsoleMessage} = require("./mapHostDiagnostics");+const {mapDiagnosticCodes, mapCSPDiagnosticCodes, mapCSPResourceCodes, classifyMapConsoleMessage,+ classifyMapCSPResources} = require("./mapHostDiagnostics");test("provider console diagnostics return fixed categories without SDK text, URL or credentials", () => {const cases = [@@ -18,3 +19,41 @@ test("provider console diagnostics return fixed categories without SDK text, URLassert.ok(result.every(code => mapDiagnosticCodes.includes(code)));}});++test("Chromium CSP messages identify fixed resource categories without retaining their URLs", () => {+ // Chromium 152 的三类资源拒绝文案,以及旧式 Refused to 文案。+ const cases = [+ ["Loading the script 'https://g.alicdn.com/private.js?key=secret' violates the following Content Security Policy directive: \"script-src https://webapi.amap.com\". The action has been blocked.", "cspScript", "https:g.alicdn.com"],+ ["Connecting to 'https://fourier.taobao.com/rp?secret=private' violates the following Content Security Policy directive: \"connect-src https://webapi.amap.com\".", "cspConnect", "https:fourier.taobao.com"],+ ["Creating a worker from 'blob:null/private-token' violates the following Content Security Policy directive: \"worker-src 'none'\".", "cspWorker", "blob"],+ ["Refused to create a worker from 'data:text/javascript,private' because it violates the following Content Security Policy directive: \"worker-src 'none'\".", "cspWorker", "data"],+ ["Refused to load the script 'https://[email protected]/log?key=secret' because it violates the following Content Security Policy directive: \"script-src https://webapi.amap.com\".", "cspScript", "https:restapi.amap.com"],+ ["Refused to connect to 'http://vdata.amap.com/private' because it violates the following Content Security Policy directive: \"connect-src https://vdata.amap.com\".", "cspConnect", "http:vdata.amap.com"],+ ["Connecting to 'https://webst02.is.autonavi.com/private' violates the following Content Security Policy directive: \"connect-src https://vdata.amap.com\".", "cspConnect", "https:autonavi-tile"],+ ["Loading the image 'http://webrd01.is.autonavi.com/private' violates the following Content Security Policy directive: \"img-src https://webapi.amap.com\".", "cspImage", "http:autonavi-tile"],+ ["Executing inline script violates the following Content Security Policy directive 'script-src https://webapi.amap.com'. Either the 'unsafe-inline' keyword, a hash, or a nonce is required.", "cspScript", "inline"],+ ["Evaluating a string as JavaScript violates the following Content Security Policy directive because 'unsafe-eval' is not an allowed source of script: \"script-src https://webapi.amap.com\".", "cspEval", "eval"],+ ["Compiling or instantiating a WebAssembly module violates the following Content Security policy directive because 'unsafe-eval' is not an allowed source of script: \"script-src https://webapi.amap.com\".", "cspWasm", "wasm"],+ ["Applying inline style violates the following Content Security Policy directive 'style-src-attr https://webapi.amap.com'.", "cspStyle", "inline"],+ ];+ for (const [message, code, resource] of cases) {+ const result = classifyMapCSPResources(message);+ assert.deepEqual(result, [{code, resource}]);+ assert.ok(result.every(item => mapCSPDiagnosticCodes.includes(item.code) && mapCSPResourceCodes.includes(item.resource)));+ assert.doesNotMatch(JSON.stringify(result), /secret|private|token|\/\/|\?/);+ }+});++test("unknown or malformed CSP resources stay bounded and URL contents cannot become diagnostic data", () => {+ for (const [url, resource] of [["https://webapi.amap.com.evil.invalid/path?key=secret", "https:other"],+ ["https://webapi.amap.com:8443/private", "https:other"],+ ["http://unknown.invalid/unsafe-eval?blob:secret", "http:other"], ["file:///secret", "other"],+ ["not a URL private", "other"], ["blob:https://private.invalid/secret", "blob"]]) {+ const result = classifyMapCSPResources(`Loading the script '${url}' violates the following Content Security Policy directive: "script-src https://webapi.amap.com".`);+ assert.deepEqual(result, [{code: "cspScript", resource}]);+ }+ for (const message of [undefined, {}, "provider secret text", "Content Security Policy unknown directive private",+ "Loading the script 'https://private.invalid' violates a made-up directive"]) {+ assert.deepEqual(classifyMapCSPResources(message), []);+ }+});diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.jsindex d994ff237b..bc0bc55e42 100644--- a/app/electron/mapHostManager.js+++ b/app/electron/mapHostManager.js@@ -5,7 +5,8 @@const path = require("node:path");const fs = require("node:fs/promises");const {randomBytes} = require("node:crypto");-const {mapDiagnosticCodes, classifyMapConsoleMessage} = require("./mapHostDiagnostics");+const {mapDiagnosticCodes, mapCSPDiagnosticCodes, mapCSPResourceCodes, classifyMapConsoleMessage,+ classifyMapCSPResources} = require("./mapHostDiagnostics");const {hasUnsafeMapSwitches, normalizeMapOrigin, parseMapCreate, parseMapCommand, parseMapReply, parseMapGeometry,isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy,@@ -308,10 +309,15 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents}let host, router, view, ses;let creationFailure = "hostSetupFailed";- const report = code => {- if (!host || host.destroyed || !mapDiagnosticCodes.includes(code) || host.diagnostics.has(code)) return;- host.diagnostics.add(code);- sendOwner(host, {version: 1, instanceID: init.instanceID, type: "diagnostic", code});+ const report = (code, resource) => {+ if (!host || host.destroyed || !mapDiagnosticCodes.includes(code) ||+ resource !== undefined && (!mapCSPDiagnosticCodes.includes(code) || !mapCSPResourceCodes.includes(resource))) return;+ // 两个有限白名单的组合去重,同一指令拒绝不同资源时也保留证据。+ const key = code + ":" + (resource || "");+ if (host.diagnostics.has(key)) return;+ host.diagnostics.add(key);+ sendOwner(host, {version: 1, instanceID: init.instanceID, type: "diagnostic", code,+ ...(resource === undefined ? {} : {resource})});};try {ses = session.fromPartition("siyuan-map-" + randomID(), {cache: false});@@ -336,7 +342,12 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentslisten(host, contents, "login", (event, _details, _auth, callback) => { event.preventDefault(); callback(); });listen(host, contents, "certificate-error", (_event, _url, _error, _certificate, callback) => callback(false));listen(host, contents, "console-message", (event, _level, legacyMessage) => {- for (const code of classifyMapConsoleMessage(event?.message ?? legacyMessage)) report(code);+ const message = event?.message ?? legacyMessage;+ const resources = classifyMapCSPResources(message);+ for (const code of classifyMapConsoleMessage(message)) {+ if (!resources.some(item => item.code === code)) report(code);+ }+ for (const {code, resource} of resources) report(code, resource);});listen(host, contents, "did-fail-load", (_event, _code, _description, _url, isMainFrame) => {if (isMainFrame === false) return;diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.jsindex 1d62004936..6b5b308d74 100644--- a/app/electron/mapHostManager.test.js+++ b/app/electron/mapHostManager.test.js@@ -180,6 +180,9 @@ const setup = (initialFault) => {getURL() { return this.url; },loadURL(url) {fault("loadSync"); this.url = url; order.push("load");+ if (faults.has("earlyConsole")) {+ this.emit("console-message", {message: "Creating a worker from 'blob:null/private' violates the following Content Security Policy directive: \"worker-src 'none'\"."});+ }return faults.has("loadAsync") ? Promise.reject(new Error("private load failure")) : Promise.resolve();},postMessage(...args) { fault("portTransfer"); this.transferred = args; },@@ -346,6 +349,28 @@ test("known host diagnostics are bounded fixed codes and stop on disposal", () =assert.equal(s.owner.sent.length, 1);});+test("CSP resources are captured before load, deduplicated by category and isolated from the map port", () => {+ const s = setup("earlyConsole"); s.create();+ assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "diagnostic", code: "cspWorker", resource: "blob"}]);+ const contents = s.views[0].webContents;+ const emit = url => contents.emit("console-message", {}, 2,+ `Connecting to '${url}' violates the following Content Security Policy directive: "connect-src https://webapi.amap.com".`);+ emit("https://g.alicdn.com/path?key=secret");+ emit("https://g.alicdn.com/another?key=another-secret");+ emit("blob:null/private");+ for (let index = 0; index < 100; index++) emit(`https://unknown-${index}.invalid/secret`);+ assert.deepEqual(s.owner.sent.map(entry => entry[1].resource), ["blob", "https:g.alicdn.com", "blob", "https:other"]);+ assert.equal(JSON.stringify(s.owner.sent).includes("secret"), false);+ const count = s.owner.sent.length;+ s.load();+ s.reply({type: "diagnostic", code: "cspWorker", resource: "https:g.alicdn.com"});+ s.owner.emit("console-message", {message: "Content Security Policy worker-src 'none'"});+ assert.equal(s.owner.sent.length, count, "only the known map contents can contribute diagnostics");+ s.manager.destroyAll();+ emit("https://fourier.taobao.com/private");+ assert.equal(s.owner.sent.length, count);+});+test("provider routing reports fixed transport failures without logging requests", async () => {const diagnostics = [];const {ses, router} = setupRouter({report: code => diagnostics.push(code)});diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.syindex 22faa03744..4599cb5574 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy@@ -3985,7 +3985,7 @@},{"Type": "NodeText",- "Data": ", then create a Map view and select a service and a Location field. Services are stored on the current device; each view saves only a service ID. On another device, explicitly add the same ID to restore the reference, or choose another service"+ "Data": ", then create a Map view and choose a map service and Location field in its view settings. Map views do not show a record list; switch to a Table view to browse or edit records. Services are stored on the current device; each view saves only a service ID. On another device, explicitly add the same ID to restore the reference, or choose another service"}]},@@ -4041,7 +4041,7 @@"Children": [{"Type": "NodeText",- "Data": "Map services use an external network connection. Only the selected service receives its runtime credentials, coordinates, and opaque record IDs; record titles and full contents are not passed to the map host. Browser SDK credentials are visible to the authorized browser and provider. Configuration exports omit map services and credentials; published pages and document exports retain records without a live map"+ "Data": "Map services use an external network connection. Only the selected service receives its runtime credentials, coordinates, and opaque record IDs; record titles and full contents are not passed to the map host. Browser SDK credentials are visible to the authorized browser and provider. Configuration exports omit map services and credentials; published pages do not load a live map, and document exports retain a table of records"}]},@@ -4055,7 +4055,7 @@"Children": [{"Type": "NodeText",- "Data": "The host follows the app theme. AMap also switches its basemap theme, and Baidu switches control appearance; OpenFreeMap and Tencent Maps currently retain their default basemap styles. Maps run in isolated Web pages. Desktop clients use a separate secure host; mobile clients require a matching app shell that restricts native bridges and navigation to trusted documents. Older shells or clients unable to establish these boundaries retain the record list. Desktop maps may hide briefly while scrolling or when menus and dialogs overlap them. When offline, unconfigured, incompatible with WebGL, or unable to load a provider, records remain available. Address search, geocoding, route planning, and clicking the map to write a location are not provided. Maps are also unavailable when authentication bypass is enabled; the record list remains accessible"+ "Data": "The host follows the app theme. AMap also switches its basemap theme, and Baidu switches control appearance; OpenFreeMap and Tencent Maps currently retain their default basemap styles. Maps run in isolated Web pages. Desktop clients use a separate secure host; mobile clients require a matching app shell that restricts native bridges and navigation to trusted documents. Older shells or clients unable to establish these boundaries do not load maps. Desktop maps follow page scrolling and clip the area covered by sticky tabs. They may hide temporarily when menus or dialogs overlap them. When offline, unconfigured, incompatible with WebGL, or unable to load a provider, switch to a Table view to access records. Address search, geocoding, route planning, and clicking the map to write a location are not provided. Maps are also unavailable when authentication bypass is enabled; records remain accessible in a Table view"}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.syindex 63c889249a..545618823e 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy@@ -3985,7 +3985,7 @@},{"Type": "NodeText",- "Data": " 中添加地图服务,再创建地图视图并选择服务和位置字段。服务保存在当前设备,每个视图仅保存服务 ID;在其他设备上使用时,需明确添加相同 ID 恢复引用,或选择另一项服务"+ "Data": " 中添加地图服务,再创建地图视图,并在视图设置中选择地图服务和位置字段。地图视图不显示记录列表;需要浏览或编辑记录时,可切换到表格视图。服务保存在当前设备,每个视图仅保存服务 ID;在其他设备上使用时,需明确添加相同 ID 恢复引用,或选择另一项服务"}]},@@ -4041,7 +4041,7 @@"Children": [{"Type": "NodeText",- "Data": "地图服务需要外部网络连接。隔离的地图页面只获得选中服务的运行时凭据、坐标和不含正文的记录 ID,不接收记录标题或完整内容。浏览器 SDK 凭据对获授权的浏览器和提供商可见。配置导出不包含地图服务和凭据,发布页面和文档导出保留记录展示,不加载实时地图"+ "Data": "地图服务需要外部网络连接。隔离的地图页面只获得选中服务的运行时凭据、坐标和不含正文的记录 ID,不接收记录标题或完整内容。浏览器 SDK 凭据对获授权的浏览器和提供商可见。配置导出不包含地图服务和凭据,发布页面不加载实时地图,文档导出保留记录表格"}]},@@ -4055,7 +4055,7 @@"Children": [{"Type": "NodeText",- "Data": "宿主配色跟随应用主题;高德同时切换底图主题,百度切换控件主题,OpenFreeMap 和腾讯目前保留默认底图样式。地图通过隔离的 Web 页面运行;桌面客户端使用独立的安全宿主,移动客户端需配套支持可信主文档桥接和导航限制的外壳。旧版外壳或无法建立隔离边界时保留记录列表。桌面地图在滚动或菜单、对话框遮挡时可能短暂隐藏。离线、未配置、WebGL 不兼容或服务加载失败时仍可访问记录。本功能不提供地址搜索、地理编码、路线规划或点击地图写入位置。启用鉴权绕过模式时也无法使用地图,记录列表仍可访问"+ "Data": "宿主配色跟随应用主题;高德同时切换底图主题,百度切换控件主题,OpenFreeMap 和腾讯目前保留默认底图样式。地图通过隔离的 Web 页面运行;桌面客户端使用独立的安全宿主,移动客户端需配套支持可信主文档桥接和导航限制的外壳。旧版外壳或无法建立隔离边界时不加载地图。桌面地图会随页面滚动并裁剪吸顶栏覆盖的区域,菜单或对话框遮挡时可能暂时隐藏。离线、未配置、WebGL 不兼容或服务加载失败时,可切换到表格视图访问记录。本功能不提供地址搜索、地理编码、路线规划或点击地图写入位置。启用鉴权绕过模式时也无法使用地图,可切换到表格视图访问记录"}]},diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.syindex 4d644507fd..0efc797503 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy@@ -3985,7 +3985,7 @@},{"Type": "NodeText",- "Data": " 中新增地圖服務,再建立地圖檢視並選擇服務和位置欄位。服務儲存在目前裝置,每個檢視僅儲存服務 ID;在其他裝置使用時,需明確新增相同 ID 恢復引用,或選擇另一項服務"+ "Data": " 中新增地圖服務,再建立地圖檢視,並在檢視設定中選擇地圖服務和位置欄位。地圖檢視不顯示記錄清單;需要瀏覽或編輯記錄時,可切換到表格檢視。服務儲存在目前裝置,每個檢視僅儲存服務 ID;在其他裝置使用時,需明確新增相同 ID 恢復引用,或選擇另一項服務"}]},@@ -4041,7 +4041,7 @@"Children": [{"Type": "NodeText",- "Data": "地圖服務需要外部網路連線。隔離的地圖頁面只取得所選服務的執行階段憑據、座標和不含正文的記錄 ID,不接收記錄標題或完整內容。瀏覽器 SDK 憑據對獲授權的瀏覽器和提供商可見。配置匯出不包含地圖服務和憑據,發佈頁面和文件匯出保留記錄展示,不載入即時地圖"+ "Data": "地圖服務需要外部網路連線。隔離的地圖頁面只取得所選服務的執行階段憑據、座標和不含正文的記錄 ID,不接收記錄標題或完整內容。瀏覽器 SDK 憑據對獲授權的瀏覽器和提供商可見。配置匯出不包含地圖服務和憑據,發佈頁面不載入即時地圖,文件匯出保留記錄表格"}]},@@ -4055,7 +4055,7 @@"Children": [{"Type": "NodeText",- "Data": "宿主配色跟隨應用程式主題;高德同時切換底圖主題,百度切換控制項主題,OpenFreeMap 和騰訊目前保留預設底圖樣式。地圖透過隔離的 Web 頁面執行;桌面客戶端使用獨立的安全宿主,行動客戶端需搭配支援可信主文件橋接與導覽限制的外殼。舊版外殼或無法建立隔離邊界時保留記錄清單。桌面地圖在捲動或選單、對話方塊遮擋時可能短暫隱藏。離線、未配置、WebGL 不相容或服務載入失敗時仍可存取記錄。本功能不提供地址搜尋、地理編碼、路線規劃或點擊地圖寫入位置。啟用鑑權繞過模式時也無法使用地圖,記錄清單仍可存取"+ "Data": "宿主配色跟隨應用程式主題;高德同時切換底圖主題,百度切換控制項主題,OpenFreeMap 和騰訊目前保留預設底圖樣式。地圖透過隔離的 Web 頁面執行;桌面客戶端使用獨立的安全宿主,行動客戶端需搭配支援可信主文件橋接與導覽限制的外殼。舊版外殼或無法建立隔離邊界時不載入地圖。桌面地圖會隨頁面捲動並裁剪置頂分頁列覆蓋的區域,選單或對話方塊遮擋時可能暫時隱藏。離線、未配置、WebGL 不相容或服務載入失敗時,可切換到表格視圖存取記錄。本功能不提供地址搜尋、地理編碼、路線規劃或點擊地圖寫入位置。啟用鑑權繞過模式時也無法使用地圖,可切換到表格視圖存取記錄"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.syindex 9e4388fdec..d829004dca 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy@@ -3991,7 +3991,7 @@},{"Type": "NodeText",- "Data": " で地図サービスを追加してから、マップビューを作成し、サービスと位置フィールドを選択します。サービスは現在の端末に保存され、各ビューにはサービス ID だけが保存されます。別の端末では同じ ID を明示的に追加して参照を復元するか、別のサービスを選択します"+ "Data": " で地図サービスを追加してから、マップビューを作成し、ビューの設定で地図サービスと位置フィールドを選択します。サービスは現在の端末に保存され、各ビューにはサービス ID だけが保存されます。別の端末では同じ ID を明示的に追加して参照を復元するか、別のサービスを選択します"}]},@@ -4047,7 +4047,7 @@"Children": [{"Type": "NodeText",- "Data": "地図サービスは外部ネットワークを使用します。隔離された地図ページに渡すのは、選択したサービスの実行時認証情報、座標、本文を含まないレコード ID だけです。タイトルやレコード全体は渡しません。ブラウザー SDK の認証情報は、許可されたブラウザーと提供元から見えます。設定のエクスポートに地図サービスと認証情報は含まれず、公開ページと文書のエクスポートではレコードだけを表示します"+ "Data": "地図サービスは外部ネットワークを使用します。隔離された地図ページに渡すのは、選択したサービスの実行時認証情報、座標、本文を含まないレコード ID だけです。タイトルやレコード全体は渡しません。ブラウザー SDK の認証情報は、許可されたブラウザーと提供元から見えます。設定のエクスポートに地図サービスと認証情報は含まれず、公開ページにはライブ地図を読み込まず、文書のエクスポートにはレコードの表を残します"}]},@@ -4061,7 +4061,7 @@"Children": [{"Type": "NodeText",- "Data": "ホストの配色はアプリのテーマに従います。AMap はベースマップのテーマも切り替え、Baidu Maps は操作部のテーマを切り替えます。OpenFreeMap と Tencent Maps は現在、既定のベースマップスタイルを維持します。地図は隔離された Web ページで動作します。デスクトップ版は独立した安全なホストを使用し、モバイル版には信頼された主文書だけにネイティブブリッジと画面遷移を許可する対応アプリが必要です。古いアプリや隔離を確立できない環境ではレコード一覧を表示します。デスクトップではスクロール中やメニュー、ダイアログが重なる間、地図が一時的に非表示になる場合があります。オフライン、未設定、WebGL 非対応、サービスの読み込み失敗時もレコードは利用できます。住所検索、ジオコーディング、経路案内、地図クリックによる位置の書き込みは提供しません。認証バイパスが有効な場合も地図は利用できませんが、レコード一覧は引き続き利用できます"+ "Data": "ホストの配色はアプリのテーマに従います。AMap はベースマップのテーマも切り替え、Baidu Maps は操作部のテーマを切り替えます。OpenFreeMap と Tencent Maps は現在、既定のベースマップスタイルを維持します。地図は隔離された Web ページで動作します。デスクトップ版は独立した安全なホストを使用し、モバイル版には信頼された主文書だけにネイティブブリッジと画面遷移を許可する対応アプリが必要です。古いアプリや隔離を確立できない環境では地図を読み込みません。地図ビューにレコード一覧は表示されません。レコードの閲覧や編集にはテーブルビューを使用してください。デスクトップでは地図がページのスクロールに追従し、固定タブに重なる部分を切り取ります。メニューやダイアログが重なる間は一時的に非表示になる場合があります。オフライン、未設定、WebGL 非対応、サービスの読み込み失敗時は、テーブルビューでレコードを利用できます。住所検索、ジオコーディング、経路案内、地図クリックによる位置の書き込みは提供しません。認証バイパスが有効な場合も地図は利用できませんが、テーブルビューでレコードを引き続き利用できます"}]},diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scssindex 2a06b2e20e..873034e8b6 100644--- a/app/src/assets/scss/business/_av.scss+++ b/app/src/assets/scss/business/_av.scss@@ -7,7 +7,6 @@margin: 8px 0;}-.av__map-settings,.av__map-actions {display: flex;flex-wrap: wrap;@@ -15,16 +14,9 @@gap: 8px;}-.av__map-setting {- display: flex;- align-items: center;- gap: 8px;- max-width: 100%;-- .b3-select {- min-width: 0;- max-width: min(240px, 50vw);- }+.av__map-setting-value {+ min-width: 0;+ max-width: min(160px, 45vw);}.av__map-status,@@ -38,13 +30,6 @@height: clamp(240px, 50vh, 480px);}-.av__map-records--hidden {- .av__row[data-id],- .av__spacer {- display: none;- }-}-.av__lunar-editor {width: 340px;max-width: 100%;@@ -411,6 +396,13 @@margin-top: 4px !important;margin-bottom: 4px !important;+ &[data-av-type="map"] > .av__container > .av__scroll {+ .av__row[data-id],+ .av__spacer {+ display: none;+ }+ }+&[data-av-type="list"],&[data-av-type="map"] {width: 100%;diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.tsindex 8e39270073..79dbdc67a6 100644--- a/app/src/protyle/render/av/action.ts+++ b/app/src/protyle/render/av/action.ts@@ -411,7 +411,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLElereturn true;} else if (type === "av-add-more" && !protyle.disabled) {const templateID = blockElement.querySelector<HTMLElement>(".av__header")?.dataset.defaultTemplateId;- if (templateID || blockElement.getAttribute("data-av-type") === "calendar") {+ if (templateID || ["calendar", "map"].includes(viewType)) {createAttributeViewItem({blockElement, protyle, templateID});} else {insertRows({@@ -522,7 +522,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEletarget.previousElementSibling?.getAttribute("data-id") || undefined;const groupID = bodyElement ? bodyElement.getAttribute("data-group-id") : "";const templateID = blockElement.querySelector<HTMLElement>(".av__header")?.dataset.defaultTemplateId;- if (templateID) {+ if (templateID || viewType === "map") {createAttributeViewItem({blockElement, protyle, templateID, position: {previousID, groupID}});} else {insertRows({blockElement, protyle, count: 1, previousID, groupID});diff --git a/app/src/protyle/render/av/calendar/state.test.ts b/app/src/protyle/render/av/calendar/state.test.tsindex 5528423816..ebc52b24b9 100644--- a/app/src/protyle/render/av/calendar/state.test.ts+++ b/app/src/protyle/render/av/calendar/state.test.ts@@ -104,7 +104,7 @@ test("calendar header creation supplies the browsing date with and without a temconst requests: {calendarDate?: number, templateID: string, viewID: string}[] = [];let inserted = 0;runInNewContext(compiled, {- blockElement, getCalendarCreationDate,+ blockElement, getCalendarCreationDate, viewType: layout,Constants: {CUSTOM_SY_AV_VIEW: "custom-sy-av-view"},protyle: {app: {appId: "app"}, id: "editor"},event: {preventDefault() {}, stopPropagation() {}},diff --git a/app/src/protyle/render/av/layout.ts b/app/src/protyle/render/av/layout.tsindex 0536f644b5..ff6b4340cc 100644--- a/app/src/protyle/render/av/layout.ts+++ b/app/src/protyle/render/av/layout.ts@@ -181,7 +181,7 @@ export const getLayoutHTML = (data: IAV) => {return html + getCalendarSettingsHTML(data.view as IAVTable, true) + "</div>";}if (data.viewType === "map") {- html += getMapSettingsHTML(data.view as IAVTable, true);+ html += getMapSettingsHTML(data.view as IAVTable);}return html + `<button class="b3-menu__item" data-type="set-page-size" data-size="${view.pageSize}"><span class="fn__flex-center">${window.siyuan.languages.entryNum}</span>diff --git a/app/src/protyle/render/av/locate.ts b/app/src/protyle/render/av/locate.tsindex 6d05b829c4..7945a986cb 100644--- a/app/src/protyle/render/av/locate.ts+++ b/app/src/protyle/render/av/locate.ts@@ -10,6 +10,7 @@ import {scrollCenter} from "../../../util/highlightById";import {setAVCellAnchor, setAVItemAnchor} from "./rangeSelect";import {updateAVRowSelect} from "./virtualScroll";import {getAVLocateViewChange} from "./locateView";+import {openMapRecord} from "./map/openRecord";import {applyAVColorPalette, getAVCustomColors} from "./color";import {getBacklinkScrollElement, revealBacklinkReference, scrollBacklinkTarget} from "./backlinkScroll";@@ -24,6 +25,7 @@ const queuedLocateRequests = new Map<string, {}>();const renderTokens = new WeakMap<HTMLElement, symbol>();const renderedAVData = new WeakMap<HTMLElement, IAV>();+const mapOpenTokens = new WeakMap<HTMLElement, symbol>();const highlightTokens = new WeakMap<HTMLElement, symbol>();const highlightStates = new WeakMap<HTMLElement, {element: HTMLElement, className: string, timer: number}>();@@ -320,7 +322,7 @@ export const prepareAVLocate = (blockElement: HTMLElement, data: IAV, resetData:if (request.viewID && request.previousViewID !== undefined && request.viewID !== request.previousViewID) {clearSelect(["row", "galleryItem"], blockElement);}- if (data.viewType === "calendar") {+ if (data.viewType === "calendar" || data.viewType === "map") {return;}const key = data.target.groupID || "all";@@ -376,6 +378,41 @@ export const finishAVLocate = (blockElement: HTMLElement, protyle: IProtyle, datclearAVLocateRequest(blockElement, request);return;}+ if (data.viewType === "map") {+ clearAVLocateRequest(blockElement, request);+ if (request.located) {+ return;+ }+ // 预览只定位地图容器,明确打开条目的操作复用记录详情,不展开记录列表。+ if (request.persistView === false) {+ if (request.scroll !== false && !scrollBacklinkTarget(blockElement, blockElement)) {+ scrollCenter(protyle, blockElement, "center");+ }+ } else {+ const row = (data.view as IAVTable).rows.find(item => item.id === request.itemID);+ const token = Symbol();+ const renderToken = renderTokens.get(blockElement);+ mapOpenTokens.set(blockElement, token);+ const failed = () => {+ if (blockElement.isConnected && mapOpenTokens.get(blockElement) === token &&+ renderTokens.get(blockElement) === renderToken && !getAVLocateRequest(blockElement) &&+ (!request.isValid || request.isValid()) && !request.messageShown) {+ request.messageShown = true;+ showMessage(window.siyuan.languages.databaseItemNotFound);+ }+ };+ void Promise.resolve(openMapRecord(protyle, blockElement, row, request.keyID)).then(opened => {+ if (!opened) {+ failed();+ }+ }).catch(failed).finally(() => {+ if (mapOpenTokens.get(blockElement) === token) {+ mapOpenTokens.delete(blockElement);+ }+ });+ }+ return;+ }const groupQuery = data.target.groupID ? `.av__body[data-group-id="${data.target.groupID}"]` : ".av__body";const bodyElement = blockElement.querySelector(groupQuery) as HTMLElement;if (bodyElement?.classList.contains("fn__none")) {diff --git a/app/src/protyle/render/av/map/createRecord.test.ts b/app/src/protyle/render/av/map/createRecord.test.tsnew file mode 100644index 0000000000..c34b6764be--- /dev/null+++ b/app/src/protyle/render/av/map/createRecord.test.ts@@ -0,0 +1,75 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import * as ts from "typescript";++const action = ts.createSourceFile("action.ts", readFileSync("src/protyle/render/av/action.ts", "utf8"),+ ts.ScriptTarget.Latest, true);+const template = ts.createSourceFile("newItemTemplate.ts", readFileSync("src/protyle/render/av/newItemTemplate.ts", "utf8"),+ ts.ScriptTarget.Latest, true);+const create = template.statements.find(statement => ts.isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => declaration.name.getText(template) === "createAttributeViewItem"));++for (const type of ["av-add-more", "av-add-bottom"]) {+ test(`map ${type} creates and opens records with optional templates and preserves insertion position`, () => {+ let branch: ts.Statement;+ const visit = (node: ts.Node) => {+ if (ts.isIfStatement(node) && node.expression.getText(action) === `type === "${type}" && !protyle.disabled`) {+ branch = node.thenStatement;+ }+ ts.forEachChild(node, visit);+ };+ visit(action);+ assert.ok(branch);+ const compiled = ts.transpileModule(create.getText(template).replace(/^export /, "") ++ `\n(() => ${branch.getText(action)})();`, {compilerOptions: {target: ts.ScriptTarget.ES2022}}).outputText;+ for (const layout of ["map", "table"]) {+ for (const templateID of ["", "template-id"]) {+ const requests: Array<{templateID: string; previousID: string; groupID: string}> = [];+ const opened: Array<{itemID: string; focusPrimary: boolean}> = [];+ let inserted = 0;+ let rendered = 0;+ const blockElement = {+ dataset: {avId: "database", nodeId: "carrier", avType: layout},+ getAttribute: (name: string) => name === "data-av-type" ? layout : "view",+ querySelector: () => ({dataset: {defaultTemplateId: templateID}}),+ removeAttribute() {},+ };+ runInNewContext(compiled, {+ blockElement, viewType: layout, target: {},+ Constants: {CUSTOM_SY_AV_VIEW: "custom-sy-av-view"},+ protyle: {app: {appId: "app"}, id: "editor", notebookId: "notebook"},+ event: {preventDefault() {}, stopPropagation() {}},+ hasClosestByClassName: () => ({getAttribute: () => ""}),+ getAvBodyData: () => ({rows: [{id: "previous-row"}]}),+ getCalendarCreationDate: (): number | undefined => undefined,+ fetchPost: (url: string, payload: typeof requests[number], callback: (response: unknown) => void) => {+ assert.equal(url, "/api/av/createAttributeViewItem");+ requests.push(payload);+ callback({code: 0, data: {itemID: "new-record", content: "New record", isDetached: true}});+ },+ insertRows: () => inserted++,+ avRender: () => rendered++,+ openDatabaseRowByData: (_protyle: unknown, record: typeof opened[number]) => opened.push(record),+ });+ if (layout === "table" && !templateID) {+ assert.equal(inserted, 1);+ assert.equal(requests.length, 0);+ } else {+ assert.equal(inserted, 0);+ assert.equal(requests.length, 1);+ assert.equal(requests[0].templateID, templateID);+ assert.equal(requests[0].previousID, type === "av-add-bottom" ? "previous-row" : "");+ assert.equal(requests[0].groupID, "");+ assert.equal(rendered, 1);+ }+ assert.equal(opened.length, layout === "map" ? 1 : 0);+ if (layout === "map") {+ assert.equal(opened[0].itemID, "new-record");+ assert.equal(opened[0].focusPrimary, true);+ }+ }+ }+ });+}diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.tsindex 01f1ae9c02..d0c55c5100 100644--- a/app/src/protyle/render/av/map/desktopTransport.test.ts+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts@@ -150,6 +150,27 @@ describe("desktop map transport", () => {const {mapDiagnosticCodes} = require("../../../../../electron/mapHostDiagnostics");for (const code of mapDiagnosticCodes) assert.ok(source.includes(`"${code}"`));});+ it("validates CSP resource categories and never logs arbitrary resource values", () => {+ const warnings: unknown[][] = [];+ const f = fixture(warnings);+ const {mapCSPResourceCodes, mapCSPDiagnosticCodes} = require("../../../../../electron/mapHostDiagnostics");+ for (const resource of mapCSPResourceCodes) {+ f.reply({type: "diagnostic", code: "cspConnect", resource, detail: "private-token"});+ }+ assert.deepEqual(warnings, mapCSPResourceCodes.map((resource: string) => ["Database map diagnostic:", "cspConnect", resource]));+ for (const code of mapCSPDiagnosticCodes) assert.ok(source.includes(`"${code}"`));+ for (const resource of ["https://webapi.amap.com/?key=secret", "https:private.invalid", "private-token", null,+ {toString: () => "secret"}, ["blob"]]) {+ f.reply({type: "diagnostic", code: "cspConnect", resource});+ }+ f.reply({type: "diagnostic", code: "storageUnavailable", resource: "blob"});+ f.reply({type: "diagnostic", code: "cspWorker", resource: "blob", instanceID: "wrong"});+ assert.equal(warnings.length, mapCSPResourceCodes.length);+ f.host.destroy();+ f.reply({type: "diagnostic", code: "cspWorker", resource: "data"});+ assert.equal(warnings.length, mapCSPResourceCodes.length);+ assert.equal(JSON.stringify(warnings).includes("secret"), false);+ });it("logs only approved capability reason codes and never exception or response details", async () => {for (const reason of ["ownerUnavailable", "notMainFrame", "notInitialized", "unregisteredOwner", "invalidKernelOrigin","originMismatch", "unsupportedDocument", "invalidDocument", "unsafeProcessSwitches"]) {diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.tsindex 8e85ba910b..0d27837d69 100644--- a/app/src/protyle/render/av/map/desktopTransport.ts+++ b/app/src/protyle/render/av/map/desktopTransport.ts@@ -57,9 +57,21 @@ const mapDiagnosticCodes = new Set(["storageUnavailable", "webglUnavailable", "amapInvalidKey", "amapInvalidSecurityCode","amapDomainMismatch", "amapPlatformMismatch",]);-const logMapDiagnostic = (code: unknown) => {+const mapCSPDiagnosticCodes = new Set(["cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm"]);+const mapCSPResourceCodes = new Set([+ "blob", "data", "inline", "eval", "wasm", "other",+ "https:webapi.amap.com", "https:restapi.amap.com", "https:vdata.amap.com", "https:a.amap.com",+ "https:g.alicdn.com", "https:fourier.taobao.com", "https:autonavi-tile", "https:other",+ "http:webapi.amap.com", "http:restapi.amap.com", "http:vdata.amap.com", "http:a.amap.com",+ "http:g.alicdn.com", "http:fourier.taobao.com", "http:autonavi-tile", "http:other",+]);+const logMapDiagnostic = (code: unknown, resource?: unknown) => {if (typeof code === "string" && mapDiagnosticCodes.has(code)) {- console.warn("Database map diagnostic:", code);+ if (resource === undefined) {+ console.warn("Database map diagnostic:", code);+ } else if (mapCSPDiagnosticCodes.has(code) && typeof resource === "string" && mapCSPResourceCodes.has(resource)) {+ console.warn("Database map diagnostic:", code, resource);+ }}};@@ -249,9 +261,9 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHosif (destroyed) {return;}- const diagnostic = value as {version?: unknown; instanceID?: unknown; type?: unknown; code?: unknown};+ const diagnostic = value as {version?: unknown; instanceID?: unknown; type?: unknown; code?: unknown; resource?: unknown};if (diagnostic?.version === AV_MAP_PROTOCOL_VERSION && diagnostic.instanceID === instanceID && diagnostic.type === "diagnostic") {- logMapDiagnostic(diagnostic.code);+ logMapDiagnostic(diagnostic.code, diagnostic.resource);return;}const reply = parseAVMapReply(value, instanceID);diff --git a/app/src/protyle/render/av/map/locate.test.ts b/app/src/protyle/render/av/map/locate.test.tsnew file mode 100644index 0000000000..2f84e3c3b0--- /dev/null+++ b/app/src/protyle/render/av/map/locate.test.ts@@ -0,0 +1,119 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as locateState from "../locateState";+import {isTableLikeView} from "../viewType";++const setup = (open: () => Promise<boolean> = () => Promise.resolve(true)) => {+ const opened: unknown[] = [];+ const scrolled: unknown[] = [];+ const messages: string[] = [];+ const block = {isConnected: true, dataset: {avId: "database", nodeId: "carrier"}} as unknown as HTMLElement;+ const protyle = {notebookId: "notebook"} as IProtyle;+ const data = {viewType: "map", view: {rows: [{id: "row", cells: [{id: "primary-value", valueType: "block",+ value: {type: "block", isDetached: true, block: {content: "Record"}}}]}]},+ target: {itemID: "row", status: "visible"}} as IAV;+ const languages = {databaseItemNotFound: "not found", databaseItemFiltered: "filtered"};+ const modules: Record<string, unknown> = {+ "./locateState": locateState,+ "./viewType": {isTableLikeView},+ "../../../dialog/message": {showMessage: (message: string) => messages.push(message)},+ "../../../util/highlightById": {scrollCenter: (_protyle: unknown, element: unknown) => scrolled.push(element)},+ "./backlinkScroll": {scrollBacklinkTarget: () => false},+ "../openDatabaseRow": {openDatabaseRowByData: (_protyle: unknown, record: unknown) => {+ opened.push(record);+ return open();+ }},+ };+ const load = (path: string) => {+ const exports = {};+ runInNewContext(transpileModule(readFileSync(path, "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+ }).outputText, {exports, require: (id: string) => modules[id] || {}, window: {siyuan: {languages}}});+ return exports;+ };+ modules["./map/openRecord"] = load("src/protyle/render/av/map/openRecord.ts");+ const methods = load("src/protyle/render/av/locate.ts") as typeof import("../locate");+ return {methods, opened, scrolled, messages, block, protyle, data};+};++test("explicit map record locating opens existing detail once without selecting hidden rows", () => {+ const scenario = setup();+ scenario.methods.setAVLocateRequest(scenario.block, {itemID: "row"});+ const reset = {virtualData: {}};+ scenario.methods.prepareAVLocate(scenario.block, scenario.data, reset);+ assert.deepEqual(reset.virtualData, {});+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ assert.equal(scenario.opened.length, 1);+ assert.equal((scenario.opened[0] as {itemID: string}).itemID, "row");+ assert.equal((scenario.opened[0] as {focusPrimary: boolean}).focusPrimary, true);+ assert.deepEqual(scenario.scrolled, []);+});++test("map backlink and search previews locate the container without opening row details", () => {+ for (const request of [+ {itemID: "row", keyID: "location", persistView: false, select: false, highlight: true, scroll: true, defIDs: ["ref"]},+ {itemID: "row", keyID: "location", persistView: false, select: false, highlight: true, isValid: () => true},+ ]) {+ const scenario = setup();+ scenario.methods.setAVLocateRequest(scenario.block, request);+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ assert.deepEqual(scenario.opened, []);+ assert.deepEqual(scenario.scrolled, [scenario.block]);+ assert.equal(locateState.locateRequests.has(scenario.block), false);+ }+});++test("invalid, filtered and previously located map requests never reopen a record", async () => {+ for (const mode of ["invalid", "filtered", "located", "missing"]) {+ const scenario = setup();+ scenario.methods.setAVLocateRequest(scenario.block, {itemID: "row", located: mode === "located",+ isValid: () => mode !== "invalid"});+ if (mode === "filtered") scenario.data.target.status = "filtered";+ if (mode === "missing") (scenario.data.view as IAVTable).rows = [];+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ await new Promise(resolve => setImmediate(resolve));+ assert.deepEqual(scenario.opened, []);+ assert.deepEqual(scenario.scrolled, []);+ assert.deepEqual(scenario.messages, mode === "missing" ? ["not found"] : []);+ }+});++test("failed or rejected map record opens report a current failure once", async () => {+ for (const open of [() => Promise.resolve(false), () => Promise.reject(new Error("unavailable"))]) {+ const scenario = setup(open);+ scenario.methods.setAVLocateRequest(scenario.block, {itemID: "row"});+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(scenario.opened.length, 1);+ assert.deepEqual(scenario.messages, ["not found"]);+ }+});++test("late map record failures cannot interrupt closed, invalidated or newer navigation", async () => {+ for (const mode of ["closed", "rendered", "invalid", "new-request", "opened"]) {+ let fail: (result: boolean) => void;+ let valid = true;+ const scenario = setup(() => new Promise(resolve => { fail = resolve; }));+ scenario.methods.setAVLocateRequest(scenario.block, {itemID: "row", isValid: () => valid});+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ const previousFail = fail;+ if (mode === "closed") Object.assign(scenario.block, {isConnected: false});+ if (mode === "rendered") scenario.methods.beginAVRender(scenario.block);+ if (mode === "invalid") valid = false;+ if (mode === "new-request" || mode === "opened") {+ scenario.methods.setAVLocateRequest(scenario.block, {itemID: "row"});+ }+ if (mode === "opened") {+ scenario.methods.finishAVLocate(scenario.block, scenario.protyle, scenario.data);+ fail(true);+ }+ previousFail(false);+ await new Promise(resolve => setImmediate(resolve));+ assert.deepEqual(scenario.messages, []);+ }+});diff --git a/app/src/protyle/render/av/map/openRecord.ts b/app/src/protyle/render/av/map/openRecord.tsnew file mode 100644index 0000000000..c5aa3efeb4--- /dev/null+++ b/app/src/protyle/render/av/map/openRecord.ts@@ -0,0 +1,15 @@+import {openDatabaseRowByData} from "../openDatabaseRow";++export const openMapRecord = (protyle: IProtyle, blockElement: HTMLElement, row: IAVRow, keyID?: string) => {+ const primary = row?.cells.find(cell => cell.valueType === "block" || cell.value?.type === "block");+ if (!primary?.value) {+ return false;+ }+ return openDatabaseRowByData(protyle, {+ avID: blockElement.dataset.avId, databaseBlockID: blockElement.dataset.nodeId, notebookID: protyle.notebookId,+ itemID: row.id, valueID: primary.id || primary.value.id,+ title: primary.value.block?.content || window.siyuan.languages.untitled,+ boundBlockID: primary.value.block?.id, isDetached: !!primary.value.isDetached,+ focusPrimary: !keyID, matchedKeyID: keyID,+ });+};diff --git a/app/src/protyle/render/av/map/render.test.ts b/app/src/protyle/render/av/map/render.test.tsindex 31476ed28a..031be5ead8 100644--- a/app/src/protyle/render/av/map/render.test.ts+++ b/app/src/protyle/render/av/map/render.test.ts@@ -75,7 +75,7 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:calls.push(url);return options.runtime ? options.runtime() : {code: 0, data: {provider: "openfreemap"}};}},- "./settings": {getMapSettingsHTML: () => "settings", bindMapSettings() {}, loadMapServices: async () => {+ "./settings": {loadMapServices: async () => {calls.push("/api/map/getConf");return [{id: "service", provider: "openfreemap", configured: true}];}},@@ -100,6 +100,11 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:.createAVMapHost(container, configuration);},};+ const openRecord = {} as typeof import("./openRecord");+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/openRecord.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+ }).outputText, {exports: openRecord, require: (id: string) => modules[id] || {}, window: {siyuan: {languages}}});+ modules["./openRecord"] = openRecord;runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/render.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},}).outputText, {exports: methods, require: (id: string) => modules[id] || {},@@ -114,13 +119,13 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:status: () => root.querySelector(".av__map-status").textContent};};-test("published maps render records without metadata, runtime credentials, or SDK calls", async () => {+test("published maps render a status without inline settings, runtime credentials, or SDK calls", async () => {const scenario = setup({published: true});await scenario.render();assert.deepEqual(scenario.calls, []);assert.equal(scenario.hosts.length, 0);assert.equal(scenario.status(), "mapPublicFallback");- assert.equal(scenario.records.classes.has("av__map-records--hidden"), false);+ assert.doesNotMatch(scenario.roots[0].innerHTML, /av__map-settings|data-map-setting|data-map-configure/);});test("unconfigured, unavailable host, offline and incompatible maps never request runtime credentials", async () => {@@ -130,7 +135,6 @@ test("unconfigured, unavailable host, offline and incompatible maps never requesawait scenario.render();assert.deepEqual(scenario.calls, ["/api/map/getConf"]);assert.equal(scenario.hosts.length, 0);- assert.equal(scenario.records.classes.has("av__map-records--hidden"), false);}const incompatible = setup();(incompatible.data.view as IAVTable).rows[0].cells[0].value.location.coordinateSystem = "unknown";@@ -147,7 +151,7 @@ test("map sends only IDs and coordinates and opens the existing row detail for aassert.equal(JSON.stringify(host.points), JSON.stringify([{id: "row", longitude: 0, latitude: 0, coordinateSystem: "wgs84"}]));assert.doesNotMatch(JSON.stringify(host.options), /Private|primary-value|notebook/);host.options.onReady();- assert.equal(scenario.records.classes.has("av__map-records--hidden"), true);+ assert.doesNotMatch(scenario.roots[0].innerHTML, /av__map-settings|data-map-setting|data-map-configure/);host.options.onMarkerClick("other", host.revision);host.options.onMarkerClick("row", host.revision - 1);assert.equal(scenario.opened.length, 0);@@ -156,7 +160,6 @@ test("map sends only IDs and coordinates and opens the existing row detail for ascenario.events.get("offline")();assert.equal(host.destroyed, true);assert.equal(scenario.status(), "mapOffline");- assert.equal(scenario.records.classes.has("av__map-records--hidden"), false);host.options.onMarkerClick("row", host.revision);assert.equal(scenario.opened.length, 1);scenario.destroyMap();@@ -194,7 +197,7 @@ test("stale runtime responses cannot mount a map after the view is removed", asyassert.equal(scenario.hosts.length, 0);});-test("history and oversized loaded pages retain the list without fetching runtime credentials", async () => {+test("history and oversized loaded pages report status without fetching runtime credentials", async () => {const history = setup();history.protyle.options.history = {created: "version"};await history.render();@@ -206,7 +209,6 @@ test("history and oversized loaded pages retain the list without fetching runtimassert.deepEqual(scenario.calls, ["/api/map/getConf"]);assert.equal(scenario.status(), "mapTooManyMarkers");assert.equal(scenario.hosts.length, 0);- assert.equal(scenario.records.classes.has("av__map-records--hidden"), false);});test("rerendering a map destroys the old host and invalidates its callbacks", async () => {@@ -230,5 +232,4 @@ test("authentication bypass reports its specific safe fallback without mountingawait scenario.render();assert.equal(scenario.status(), "mapAuthenticationBypass");assert.equal(scenario.hosts.length, 0);- assert.equal(scenario.records.classes.has("av__map-records--hidden"), false);});diff --git a/app/src/protyle/render/av/map/render.ts b/app/src/protyle/render/av/map/render.tsindex cbd9dc81a6..c0ad7f5c79 100644--- a/app/src/protyle/render/av/map/render.ts+++ b/app/src/protyle/render/av/map/render.ts@@ -1,8 +1,8 @@import {escapeAttr, escapeHtml} from "../../../../util/escape";import {fetchSyncPost} from "../../../../util/fetch";-import {openDatabaseRowByData} from "../openDatabaseRow";import {getAVData} from "../virtualScroll";-import {bindMapSettings, getMapSettingsHTML, loadMapServices} from "./settings";+import {loadMapServices} from "./settings";+import {openMapRecord} from "./openRecord";import {canLoadMapHost, destroyMap, getMapPoints, getMapSettings, registerMap} from "./state";import {createAVMapHost, isAVMapHostEnvironmentSupported} from "./host";import {createDesktopAVMapHost, isDesktopAVMapHostSupported} from "./desktopTransport";@@ -12,19 +12,6 @@ import {MAP_CONFIG_CHANGED_EVENT} from "../../../../config/mapRuntime";const getTheme = () => document.documentElement.getAttribute("data-theme-mode") === "dark" ? "dark" : "light";-const openMapRecord = (protyle: IProtyle, blockElement: HTMLElement, row: IAVRow) => {- const primary = row.cells.find(cell => cell.valueType === "block" || cell.value?.type === "block");- if (!primary?.value) {- return;- }- return openDatabaseRowByData(protyle, {- avID: blockElement.dataset.avId, databaseBlockID: blockElement.dataset.nodeId, notebookID: protyle.notebookId,- itemID: row.id, valueID: primary.id || primary.value.id,- title: primary.value.block?.content || window.siyuan.languages.untitled,- boundBlockID: primary.value.block?.id, isDetached: !!primary.value.isDetached, focusPrimary: true,- });-};-export const refreshMapReadonly = (protyle: IProtyle) => {protyle.wysiwyg.element.querySelectorAll<HTMLElement>('.av[data-av-type="map"]').forEach(block => {const data = getAVData(block);@@ -41,7 +28,6 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, daif (!records) {return;}- records.classList.remove("av__map-records--hidden");const view = data.view as IAVTable;const settings = getMapSettings(view);const root = document.createElement("div");@@ -50,8 +36,7 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, daroot.setAttribute("aria-label", window.siyuan.languages.mapView);const pageText = window.siyuan.languages.mapPageScope.replace("${shown}", view.rows.length.toString()).replace("${total}", view.rowCount.toString());- root.innerHTML = `<div class="av__map-settings"></div>-<div class="av__map-summary ft__smaller ft__on-surface">${escapeHtml(pageText)}</div>+ root.innerHTML = `<div class="av__map-summary ft__smaller ft__on-surface">${escapeHtml(pageText)}</div><div class="av__map-skipped ft__smaller ft__on-surface"></div><div class="av__map-status ft__on-surface" role="status"></div><div class="av__map-canvas fn__none"></div>@@ -92,7 +77,6 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, dastatus.textContent = message;canvas.classList.add("fn__none");fitButton.classList.add("fn__none");- records.classList.remove("av__map-records--hidden");};retryButton.addEventListener("click", () => { void renderMap(blockElement, protyle, data); });if (window.siyuan.isPublish) {@@ -111,10 +95,6 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, daif (!current()) {return;}- const settingsElement = root.querySelector<HTMLElement>(".av__map-settings");- settingsElement.innerHTML = getMapSettingsHTML(view, false, services);- bindMapSettings({protyle, blockElement, data, menuElement: settingsElement, services,- onChange: () => { void renderMap(blockElement, protyle, data); }});if (!settings.locationKeyID) {fallback(window.siyuan.languages.mapSelectLocationField);return;@@ -193,7 +173,6 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, dastatus.textContent = "";attribution.classList.remove("fn__none");fitButton.classList.remove("fn__none");- records.classList.toggle("av__map-records--hidden", !settings.showRecordList && data.target?.status !== "visible");},onError: () => fallback(navigator.onLine ? window.siyuan.languages.mapLoadError : window.siyuan.languages.mapOffline),onMarkerClick: (id, markerRevision) => {diff --git a/app/src/protyle/render/av/map/settings.test.ts b/app/src/protyle/render/av/map/settings.test.tsindex d6e6aa6b3c..1cc7e20c31 100644--- a/app/src/protyle/render/av/map/settings.test.ts+++ b/app/src/protyle/render/av/map/settings.test.ts@@ -6,12 +6,13 @@ import {ModuleKind, ScriptTarget, transpileModule} from "typescript";import * as escape from "../../../../util/escape";import * as state from "./state";-const setup = () => {+const setup = (loadServices: () => Promise<import("./settings").IMapServiceChoice[]> = async () => []) => {const operations: Array<{perform: IOperation[]; undo: IOperation[]}> = [];const menus: Array<Array<{label: string; checked: boolean; click: () => void}>> = [];- const opened: string[] = [];+ const requests: string[] = [];const languages = {mapService: "Service", mapLocationField: "Location", mapSelectService: "Select service",- mapSelectLocationField: "Select field", mapShowRecordList: "Show records", mapConfigureServices: "Configure"};+ mapSelectLocationField: "Select field", mapMissingService: "Missing service",+ mapMissingLocationField: "Missing field", loading: "Loading"};const methods = {} as typeof import("./settings");const context = {siyuan: {isPublish: false, languages}};runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/settings.ts", "utf8"), {@@ -21,8 +22,10 @@ const setup = () => {"../../../../util/escape": escape,"../../../wysiwyg/transaction": {transaction: (_protyle: IProtyle, perform: IOperation[], undo: IOperation[]) =>operations.push({perform, undo})},- "../../../../config": {openMapSettings: (_app: unknown, missing: string) => opened.push(missing)},- "../../../../util/fetch": {fetchSyncPost: async () => ({code: 0, data: {services: [] as import("./settings").IMapServiceChoice[]}})},+ "../../../../util/fetch": {fetchSyncPost: async (url: string) => {+ requests.push(url);+ return {code: 0, data: {services: await loadServices()}};+ }},"../viewSettingMenu": {openViewSettingMenu() {}},"../../../../plugin/Menu": {Menu: class {items: Array<{label: string; checked: boolean; click: () => void}> = [];@@ -30,7 +33,7 @@ const setup = () => {addItem(item: {label: string; checked: boolean; click: () => void}) { this.items.push(item); }}},})[id] || {}});- return {methods, operations, menus, opened, context};+ return {methods, operations, menus, requests, context};};const data = () => ({id: "database", viewID: "map-view", view: {@@ -38,10 +41,11 @@ const data = () => ({id: "database", viewID: "map-view", view: {columns: [{id: "location", type: "location", name: "<Location>"}, {id: "text", type: "text", name: "Text"}],}}) as IAV;-const control = (key: string, tagName = "BUTTON") => {+const control = (key: string) => {const handlers: Record<string, (event?: {preventDefault: () => void; stopPropagation: () => void}) => void> = {};- return {tagName, dataset: {mapSetting: key}, disabled: false, isConnected: true, value: "", checked: false,- hasAttribute: (name: string) => name === "data-map-configure" && key === "configure",+ const label = {textContent: "", title: ""};+ return {tagName: "BUTTON", dataset: {mapSetting: key}, disabled: false, isConnected: true,+ label, querySelector: () => label,addEventListener: (type: string, handler: typeof handlers[string]) => { handlers[type] = handler; }, handlers};};@@ -50,13 +54,15 @@ test("map settings preserve missing IDs, escape labels, and never automaticallyconst current = data();const view = current.view as IAVTable;const before = JSON.stringify(view);- const html = methods.getMapSettingsHTML(view, false, [{id: "service", name: "<Service>", provider: "openfreemap", configured: true}]);- assert.match(html, /value="missing-service" selected/);- assert.match(html, /value="missing-field" selected/);- assert.match(html, /<Service>/);- assert.match(html, /<Location>/);- assert.doesNotMatch(html, /value="text"/);- assert.doesNotMatch(methods.getMapSettingsHTML(view, true), /<select/);+ const html = methods.getMapSettingsHTML(view, []);+ assert.match(html, /Missing service/);+ assert.match(html, /Missing field/);+ const pendingHTML = methods.getMapSettingsHTML(view);+ assert.match(pendingHTML, /Loading/);+ for (const settingsHTML of [html, pendingHTML]) {+ assert.doesNotMatch(settingsHTML, /missing-service|missing-field|showRecordList|data-map-configure|checkbox|<select/);+ assert.equal((settingsHTML.match(/data-map-setting=/g) || []).length, 2);+ }assert.equal(JSON.stringify(view), before);assert.equal(operations.length, 0);});@@ -86,29 +92,54 @@ test("map selection uses an undoable full-settings transaction without changingassert.equal(JSON.stringify(undo.data), JSON.stringify({serviceID: "missing-service", locationKeyID: "missing-field", showRecordList: true}));});-test("readonly, history, and published maps cannot change settings or open configuration", () => {+test("readonly, history, and published maps cannot change settings", () => {for (const mode of ["disabled", "history", "published"]) {- const {methods, operations, opened, context} = setup();+ const {methods, operations, requests, context} = setup();const field = control("serviceID");- const configure = control("configure");context.siyuan.isPublish = mode === "published";methods.bindMapSettings({data: data(), protyle: {disabled: mode === "disabled",options: {history: mode === "history" ? {created: "version"} : undefined}} as IProtyle,- blockElement: {} as Element, menuElement: {querySelectorAll: () => [field, configure]} as unknown as Element});+ blockElement: {} as Element, menuElement: {querySelectorAll: () => [field]} as unknown as Element});assert.equal(field.disabled, true);- assert.equal(configure.disabled, true);assert.equal(Object.keys(field.handlers).length, 0);assert.equal(operations.length, 0);- assert.equal(opened.length, 0);+ assert.deepEqual(requests, mode === "disabled" ? ["/api/map/getConf"] : []);}});-test("map configuration forwards the preserved missing service ID for explicit device-local setup", () => {- const {methods, opened} = setup();- const configure = control("configure");+test("map menus resolve service names before interaction and retain IDs only for transactions", async () => {+ const serviceID = "19082d45-0536-457f-a57e-8c1ea5222222";+ const choices = [{id: serviceID, name: "<OFM>", provider: "openfreemap" as const, configured: true}];+ const {methods, requests, menus} = setup(async () => choices);+ const current = data();+ const view = current.view as IAVTable;+ view.map.serviceID = serviceID;+ view.map.locationKeyID = "location";+ const html = methods.getMapSettingsHTML(view, choices);+ assert.match(html, /<OFM>/);+ assert.match(html, /<Location>/);+ assert.match(html, /fn__ellipsis av__map-setting-value/);+ assert.doesNotMatch(html, new RegExp(serviceID));+ const service = control("serviceID");+ methods.bindMapSettings({data: current, protyle: {options: {}} as IProtyle,+ blockElement: {} as Element, menuElement: {querySelectorAll: () => [service]} as unknown as Element});+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(service.label.textContent, "<OFM>");+ assert.equal(service.label.title, "<OFM>");+ await service.handlers.click({preventDefault() {}, stopPropagation() {}});+ assert.deepEqual(requests, ["/api/map/getConf"]);+ assert.equal(menus[0].find(item => item.checked).label, "<OFM>");+ assert.equal(view.map.serviceID, serviceID);+});++test("late map service responses cannot update a dismissed menu", async () => {+ let respond: (services: import("./settings").IMapServiceChoice[]) => void;+ const {methods} = setup(() => new Promise(resolve => { respond = resolve; }));+ const service = control("serviceID");methods.bindMapSettings({data: data(), protyle: {options: {}} as IProtyle,- blockElement: {} as Element, menuElement: {querySelectorAll: () => [configure]} as unknown as Element,- services: []});- configure.handlers.click();- assert.deepEqual(opened, ["missing-service"]);+ blockElement: {} as Element, menuElement: {querySelectorAll: () => [service]} as unknown as Element});+ service.isConnected = false;+ respond([]);+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(service.label.textContent, "");});diff --git a/app/src/protyle/render/av/map/settings.ts b/app/src/protyle/render/av/map/settings.tsindex 77605828d6..128a058f08 100644--- a/app/src/protyle/render/av/map/settings.ts+++ b/app/src/protyle/render/av/map/settings.ts@@ -2,7 +2,6 @@ import {transaction} from "../../../wysiwyg/transaction";import {escapeAttr, escapeHtml} from "../../../../util/escape";import {fetchSyncPost} from "../../../../util/fetch";import {Menu} from "../../../../plugin/Menu";-import {openMapSettings} from "../../../../config";import {openViewSettingMenu} from "../viewSettingMenu";import {getMapSettings} from "./state";import type {AVMapProvider} from "./protocol";@@ -25,14 +24,14 @@ export const loadMapServices = async (): Promise<IMapServiceChoice[]> => {return response.data.services;};-const getItems = (view: IAVTable, services: IMapServiceChoice[]) => {+const getItems = (view: IAVTable, services?: IMapServiceChoice[]) => {const settings = getMapSettings(view);const fields = view.columns.filter(column => column.type === "location");const items: Array<{key: "serviceID" | "locationKeyID"; label: string;choices: Array<{value: string; label: string}>}> = [{key: "serviceID", label: window.siyuan.languages.mapService,choices: [{value: "", label: window.siyuan.languages.mapSelectService},- ...services.map(service => ({value: service.id, label: service.name}))],+ ...(services || []).map(service => ({value: service.id, label: service.name}))],}, {key: "locationKeyID", label: window.siyuan.languages.mapLocationField,choices: [{value: "", label: window.siyuan.languages.mapSelectLocationField},@@ -41,34 +40,25 @@ const getItems = (view: IAVTable, services: IMapServiceChoice[]) => {items.forEach(item => {const saved = settings[item.key];if (saved && !item.choices.some(choice => choice.value === saved)) {- item.choices.push({value: saved, label: saved});+ item.choices.push({value: saved, label: item.key === "serviceID" ?+ services ? window.siyuan.languages.mapMissingService : window.siyuan.languages.loading :+ window.siyuan.languages.mapMissingLocationField});}});return items;};-export const getMapSettingsHTML = (view: IAVTable, asMenu = false, services: IMapServiceChoice[] = []) => {+export const getMapSettingsHTML = (view: IAVTable, services?: IMapServiceChoice[]) => {const settings = getMapSettings(view);return getItems(view, services).map(item => {const value = settings[item.key];- const label = item.choices.find(choice => choice.value === value)?.label || value;- if (asMenu) {- return `<button class="b3-menu__item" data-map-setting="${item.key}">+ const label = item.choices.find(choice => choice.value === value).label;+ return `<button class="b3-menu__item" data-map-setting="${item.key}"><span class="fn__flex-center">${item.label}</span><span class="fn__flex-1"></span>- <span class="b3-menu__accelerator">${escapeHtml(label)}</span>+ <span class="b3-menu__accelerator fn__ellipsis av__map-setting-value" title="${escapeAttr(label)}">${escapeHtml(label)}</span><svg class="b3-menu__icon b3-menu__icon--small"><use xlink:href="#iconRight"></use></svg></button>`;- }- return `<label class="av__map-setting"><span>${item.label}</span>- <select class="b3-select" data-map-setting="${item.key}" aria-label="${escapeAttr(item.label)}">- ${item.choices.map(choice => `<option value="${escapeAttr(choice.value)}"${choice.value === value ? " selected" : ""}>${escapeHtml(choice.label)}</option>`).join("")}- </select></label>`;- }).join("") + `<label class="${asMenu ? "b3-menu__item" : "av__map-setting"}">- <span class="fn__flex-center">${window.siyuan.languages.mapShowRecordList}</span>- ${asMenu ? '<span class="fn__space fn__flex-1"></span>' : ""}- <input data-map-setting="showRecordList" type="checkbox" class="b3-switch${asMenu ? " b3-switch--menu" : ""}"${settings.showRecordList ? " checked" : ""}>-</label>-<button type="button" class="${asMenu ? "b3-menu__item" : "b3-button b3-button--outline"}" data-map-configure>${window.siyuan.languages.mapConfigureServices}</button>`;+ }).join("");};export const bindMapSettings = (options: {@@ -79,13 +69,38 @@ export const bindMapSettings = (options: {services?: IMapServiceChoice[];onChange?: () => void;}) => {- const controls = options.menuElement.querySelectorAll<HTMLSelectElement | HTMLButtonElement | HTMLInputElement>("[data-map-setting], [data-map-configure]");+ const controls = options.menuElement.querySelectorAll<HTMLButtonElement>("[data-map-setting]");+ const view = options.data.view as IAVTable;+ const services = options.services ? Promise.resolve(options.services) : window.siyuan.isPublish ||+ options.protyle.options.history?.created || options.protyle.options.history?.snapshot ?+ Promise.resolve([] as IMapServiceChoice[]) : loadMapServices();+ const updateLabels = (choices: IMapServiceChoice[]) => {+ const items = getItems(view, choices);+ controls.forEach(control => {+ if (!control.isConnected) {+ return;+ }+ const item = items.find(item => item.key === control.dataset.mapSetting);+ const label = item.choices.find(choice => choice.value === getMapSettings(view)[item.key]).label;+ const valueElement = control.querySelector<HTMLElement>(".av__map-setting-value");+ valueElement.textContent = label;+ valueElement.title = label;+ });+ };+ void services.then(updateLabels).catch(() => {+ controls.forEach(control => {+ if (control.isConnected && control.dataset.mapSetting === "serviceID") {+ const valueElement = control.querySelector<HTMLElement>(".av__map-setting-value");+ valueElement.textContent = window.siyuan.languages.mapSelectService;+ valueElement.title = window.siyuan.languages.mapSelectService;+ }+ });+ });if (!canEditMapSettings(options.protyle)) {controls.forEach(control => { control.disabled = true; });return;}- const view = options.data.view as IAVTable;- const update = (key: keyof IAVMapSettings, value: string | boolean) => {+ const update = (key: "serviceID" | "locationKeyID", value: string) => {if (!canEditMapSettings(options.protyle)) {return;}@@ -101,36 +116,19 @@ export const bindMapSettings = (options: {options.onChange?.();};controls.forEach(control => {- if (control.hasAttribute("data-map-configure")) {- control.addEventListener("click", async () => {- const services = options.services || await loadMapServices().catch((): IMapServiceChoice[] => undefined);- if (!control.isConnected) {- return;- }- const saved = getMapSettings(view).serviceID;- const missing = saved && services && !services.some(service => service.id === saved) ? saved : undefined;- openMapSettings(options.protyle.app, missing);- });- return;- }- const key = control.dataset.mapSetting as keyof IAVMapSettings;- if (control.tagName === "BUTTON") {- control.addEventListener("click", async event => {- event.preventDefault();- event.stopPropagation();- const services = options.services || await loadMapServices().catch(() => [] as IMapServiceChoice[]);- if (!control.isConnected) {- return;- }- const item = getItems(view, services).find(item => item.key === key);- const menu = new Menu();- item.choices.forEach(choice => menu.addItem({iconHTML: "", label: escapeHtml(choice.label),- checked: getMapSettings(view)[key] === choice.value, click: () => update(key, choice.value)}));- openViewSettingMenu(menu, control);- });- } else {- control.addEventListener("change", () => update(key, key === "showRecordList" ?- (control as HTMLInputElement).checked : control.value));- }+ const key = control.dataset.mapSetting as "serviceID" | "locationKeyID";+ control.addEventListener("click", async event => {+ event.preventDefault();+ event.stopPropagation();+ const choices = await services.catch(() => [] as IMapServiceChoice[]);+ if (!control.isConnected) {+ return;+ }+ const item = getItems(view, choices).find(item => item.key === key);+ const menu = new Menu();+ item.choices.forEach(choice => menu.addItem({iconHTML: "", label: escapeHtml(choice.label),+ checked: getMapSettings(view)[key] === choice.value, click: () => update(key, choice.value)}));+ openViewSettingMenu(menu, control);+ });});};diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.tsindex c503c1bf1a..773209e586 100644--- a/app/src/protyle/render/av/newItemTemplate.ts+++ b/app/src/protyle/render/av/newItemTemplate.ts@@ -665,7 +665,7 @@ export const createAttributeViewItem = (options: {}options.blockElement.removeAttribute("data-render");avRender(options.blockElement, options.protyle);- if (options.blockElement.dataset.avType === "calendar" && response.code === 0 &&+ if (["calendar", "map"].includes(options.blockElement.dataset.avType) && response.code === 0 &&response.data && "itemID" in response.data) {void openDatabaseRowByData(options.protyle, {avID: options.blockElement.dataset.avId, databaseBlockID: options.blockElement.dataset.nodeId,