Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Fix map attribution and focus behavior https://github.com/siyuan-note/siyuan/issues/20129

Danield83a4157b148
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 733b3c5271..0a92d70707 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "تم تحميل ${shown}/${total}",
+ "mapSkippedCount": "تم تخطي ${count}",
"databaseMapView": "عرض الخريطة لقاعدة البيانات",
"exportBlockRefMode": "مراجع الكتل وروابط الكتل",
"configGroupOCREngine": "محرّك التعرّف",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index cdb1469e08..670a7cd2c2 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Geladen ${shown}/${total}",
+ "mapSkippedCount": "Übersprungen ${count}",
"databaseMapView": "Datenbank-Kartenansicht",
"exportBlockRefMode": "Blockreferenzen und Blocklinks",
"configGroupOCREngine": "Erkennungs-Engine",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 11c77c525a..247a588f1c 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Loaded ${shown}/${total}",
+ "mapSkippedCount": "Skipped ${count}",
"databaseMapView": "Database map view",
"exportBlockRefMode": "Block refs and block links",
"configGroupOCREngine": "Recognition engine",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 45b139b878..2df314eabf 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Cargados ${shown}/${total}",
+ "mapSkippedCount": "Omitidos ${count}",
"databaseMapView": "Vista de mapa de la base de datos",
"exportBlockRefMode": "Referencias y enlaces de bloque",
"configGroupOCREngine": "Motor de reconocimiento",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index d483aaa29e..1a4e948e66 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Chargés ${shown}/${total}",
+ "mapSkippedCount": "Ignorés ${count}",
"databaseMapView": "Vue carte de la base de données",
"exportBlockRefMode": "Références et liens de blocs",
"configGroupOCREngine": "Moteur de reconnaissance",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 5a04979901..67b008d2be 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "נטענו ${shown}/${total}",
+ "mapSkippedCount": "דולגו ${count}",
"databaseMapView": "תצוגת מפה של מסד הנתונים",
"exportBlockRefMode": "הפניות לבלוקים וקישורי בלוקים",
"configGroupOCREngine": "מנוע זיהוי",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 71b3e6d331..126e2116b2 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "लोड हुए ${shown}/${total}",
+ "mapSkippedCount": "छोड़े गए ${count}",
"databaseMapView": "डेटाबेस मानचित्र दृश्य",
"exportBlockRefMode": "ब्लॉक रेफ़ और ब्लॉक लिंक",
"configGroupOCREngine": "पहचान इंजन",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 4106b19df6..2a36ee5654 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Dimuat ${shown}/${total}",
+ "mapSkippedCount": "Dilewati ${count}",
"databaseMapView": "Tampilan peta basis data",
"exportBlockRefMode": "Referensi blok dan tautan blok",
"configGroupOCREngine": "Mesin pengenalan",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 9fb990ad4a..cf8b2ac6fb 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Caricati ${shown}/${total}",
+ "mapSkippedCount": "Ignorati ${count}",
"databaseMapView": "Vista mappa del database",
"exportBlockRefMode": "Riferimenti e link ai blocchi",
"configGroupOCREngine": "Motore di riconoscimento",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 6a2d4a4453..de0ff5b8aa 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "読み込み済み ${shown}/${total}",
+ "mapSkippedCount": "スキップ ${count}",
"databaseMapView": "データベースの地図ビュー",
"exportBlockRefMode": "ブロック参照とブロックリンク",
"configGroupOCREngine": "認識エンジン",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 212fd18074..68ecd52c22 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "불러옴 ${shown}/${total}",
+ "mapSkippedCount": "건너뜀 ${count}",
"databaseMapView": "데이터베이스 지도 보기",
"exportBlockRefMode": "블록 참조와 블록 링크",
"configGroupOCREngine": "인식 엔진",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 8d1ad72775..b79800058f 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Geladen ${shown}/${total}",
+ "mapSkippedCount": "Overgeslagen ${count}",
"databaseMapView": "Kaartweergave van database",
"exportBlockRefMode": "Blokreferenties en bloklinks",
"configGroupOCREngine": "Herkenning-engine",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 3093838d96..69223d5da1 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Wczytano ${shown}/${total}",
+ "mapSkippedCount": "Pominięto ${count}",
"databaseMapView": "Widok mapy bazy danych",
"exportBlockRefMode": "Odwołania i łącza do bloków",
"configGroupOCREngine": "Silnik rozpoznawania",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 35685c3d97..f09d48c1af 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Carregados ${shown}/${total}",
+ "mapSkippedCount": "Ignorados ${count}",
"databaseMapView": "Visualização de mapa do banco de dados",
"exportBlockRefMode": "Referências e links de bloco",
"configGroupOCREngine": "Mecanismo de reconhecimento",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 2113e3ee14..ec405f873d 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Загружено ${shown}/${total}",
+ "mapSkippedCount": "Пропущено ${count}",
"databaseMapView": "Представление базы данных на карте",
"exportBlockRefMode": "Ссылки на блоки и гиперссылки блоков",
"configGroupOCREngine": "Движок распознавания",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index ce2ad449df..9a2dad859f 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Načítané ${shown}/${total}",
+ "mapSkippedCount": "Vynechané ${count}",
"databaseMapView": "Mapové zobrazenie databázy",
"exportBlockRefMode": "Odkazy na bloky a prepojenia blokov",
"configGroupOCREngine": "Mechanizmus rozpoznávania",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index e71113394c..b8d60d1cd2 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Учитано ${shown}/${total}",
+ "mapSkippedCount": "Прескочено ${count}",
"databaseMapView": "Приказ базе података на мапи",
"exportBlockRefMode": "Reference blokova i veze blokova",
"configGroupOCREngine": "Mehanizam prepoznavanja",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index b13d06c60e..6bea0c6152 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "โหลดแล้ว ${shown}/${total}",
+ "mapSkippedCount": "ข้าม ${count}",
"databaseMapView": "มุมมองแผนที่ฐานข้อมูล",
"exportBlockRefMode": "การอ้างอิงบล็อกและลิงก์บล็อก",
"configGroupOCREngine": "กลไกการรู้จำ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index bedb6cd327..9c7d929a8d 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Yüklendi ${shown}/${total}",
+ "mapSkippedCount": "Atlandı ${count}",
"databaseMapView": "Veritabanı harita görünümü",
"exportBlockRefMode": "Blok başvuruları ve blok bağlantıları",
"configGroupOCREngine": "Tanıma motoru",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 67b79fba55..89c883315c 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "Завантажено ${shown}/${total}",
+ "mapSkippedCount": "Пропущено ${count}",
"databaseMapView": "Подання бази даних на мапі",
"exportBlockRefMode": "Посилання на блоки та гіперпосилання блоків",
"configGroupOCREngine": "Рушій розпізнавання",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index da921a6b8b..720c3dd116 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "已加载 ${shown}/${total}",
+ "mapSkippedCount": "已跳过 ${count}",
"databaseMapView": "数据库 地图视图",
"exportBlockRefMode": "块引用与块超链接",
"configGroupOCREngine": "识别引擎",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index c90b5256ef..c50ae5af4c 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "mapLoadedCount": "已載入 ${shown}/${total}",
+ "mapSkippedCount": "已略過 ${count}",
"databaseMapView": "資料庫 地圖視圖",
"exportBlockRefMode": "區塊引用與區塊超鏈接",
"configGroupOCREngine": "辨識引擎",
diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.js
index 2748e0ba0f..0423a1dde1 100644
--- a/app/electron/mapHostManager.js
+++ b/app/electron/mapHostManager.js
@@ -299,7 +299,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
if (host.loaded) {
host.view.webContents.send("siyuan-map-viewport", {logicalSize: geometry.logicalSize, crop: geometry.crop});
}
- if (!host.ready || !host.win.isFocused() || !host.win.isVisible() || host.win.isMinimized()) {
+ if (!host.ready || !host.win.isVisible() || host.win.isMinimized()) {
setVisible(host, false);
return;
}
@@ -389,7 +389,8 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
for (const name of ["resize", "hide", "minimize", "enter-full-screen", "leave-full-screen"]) {
listen(host, owner.win, name, () => hide(host));
}
- listen(host, owner.win, "blur", () => setVisible(host, false));
+ // 失焦只撤销外链手势;仍可见的窗口继续绘制地图,遮挡由窗口系统和主文档分别处理。
+ listen(host, owner.win, "blur", () => { host.attributionGestureUntil = 0; });
for (const name of ["focus", "show", "restore"]) listen(host, owner.win, name, () => applyGeometry(host));
listen(host, event.sender, "zoom-changed", () => hide(host));
const nonce = randomID();
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.js
index 7f8bc95e1e..6f49fb13e4 100644
--- a/app/electron/mapHostManager.test.js
+++ b/app/electron/mapHostManager.test.js
@@ -188,9 +188,9 @@ const setup = (initialFault) => {
isDestroyed() { return this.destroyed; }, getZoomFactor() { return this.zoom; },
send(...args) { this.sent.push(structuredClone(args)); }});
const owner = contents(1);
- const win = Object.assign(new EventEmitter(), {webContents: owner, destroyed: false, focused: true, children: [],
+ const win = Object.assign(new EventEmitter(), {webContents: owner, destroyed: false, focused: true, visible: true, minimized: false, children: [],
isDestroyed() { return this.destroyed; }, isFocused() { return this.focused; },
- isVisible: () => true, isMinimized: () => false, getContentBounds: () => ({width: 1000, height: 800})});
+ isVisible() { return this.visible; }, isMinimized() { return this.minimized; }, getContentBounds: () => ({width: 1000, height: 800})});
win.contentView = {addChildView: view => { fault("attach"); win.children.push(view); },
removeChildView: view => { fault("detach"); win.children = win.children.filter(item => item !== view); }};
const target = {origin};
@@ -340,7 +340,14 @@ test("attribution links require one recent native input in a ready visible focus
contents.emit("before-input-event", {}, {type: "keyDown", key: "Enter", isAutoRepeat: false});
s.reply({type: "attributionClick", link: "openstreetmap"});
assert.equal(links().length, 2);
- click(); s.win.focused = false; s.win.emit("blur"); s.win.focused = true; s.win.emit("focus");
+ click(); s.win.focused = false; s.win.emit("blur");
+ assert.equal(s.views[0].visible, true, "switching applications keeps the visible map painted");
+ s.reply({type: "attributionClick", link: "maplibre"});
+ click(); s.reply({type: "attributionClick", link: "maplibre"});
+ contents.emit("before-input-event", {}, {type: "keyDown", key: "Enter", isAutoRepeat: false});
+ s.reply({type: "attributionClick", link: "maplibre"});
+ assert.equal(links().length, 2, "an unfocused visible map cannot authorize an attribution link");
+ s.win.focused = true; s.win.emit("focus");
s.reply({type: "attributionClick", link: "maplibre"});
assert.equal(links().length, 2, "blur invalidates an outstanding gesture even after focus returns");
click(); s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false});
@@ -352,7 +359,7 @@ test("attribution links require one recent native input in a ready visible focus
assert.equal(links().length, 2, "expired native input cannot open a link");
s.command({type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 400, height: 300}});
const sent = s.channels[0].port1.sent.filter(message => message.type === "visibility");
- assert.deepEqual(sent.map(message => message.visible), [true, false, true, false, true]);
+ assert.deepEqual(sent.map(message => message.visible), [true, false, true]);
assert.deepEqual(sent[0].viewport, {x: 0, y: 0, width: 400, height: 300});
s.manager.destroyAll();
assert.equal(contents.listenerCount("before-mouse-event"), 0);
@@ -540,17 +547,53 @@ test("Electron's default file-access switch permits the HTTP map host while file
s.manager.destroyAll();
});
-test("geometry updates cannot show a map in an unfocused window and focus restores fresh geometry", () => {
+test("switching applications keeps a visible map painted through blur, geometry updates and focus", () => {
const s = setup(); s.create(); s.load(); s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});
- s.win.focused = false; s.win.emit("blur");
- s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: true,
- bounds: {x: 10, y: 20, width: 200, height: 100}, logicalSize: {width: 200, height: 100}, crop: {x: 0, y: 0}});
- assert.equal(s.views[0].visible, false);
- s.win.focused = true; s.win.emit("focus");
+ const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},
+ logicalSize: {width: 200, height: 100}, crop: {x: 0, y: 0}};
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
assert.equal(s.views[0].visible, true);
+ for (let i = 0; i < 3; i++) {
+ s.win.focused = false; s.win.emit("blur");
+ assert.equal(s.views[0].visible, true);
+ geometry.bounds.x += 10;
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
+ assert.equal(s.views[0].visible, true);
+ assert.deepEqual(s.views[0].bounds, geometry.bounds);
+ s.win.focused = true; s.win.emit("focus");
+ assert.equal(s.views[0].visible, true);
+ }
+ const visibility = s.channels[0].port1.sent.filter(message => message.type === "visibility");
+ assert.deepEqual(visibility.map(message => message.visible), [true], "focus changes must not hide and restore the provider");
+ s.manager.destroyAll();
+});
+
+test("an unfocused window can finish showing a map but hiding, minimizing and owner overlays still suppress it", () => {
+ const s = setup(); s.create(); s.load();
+ const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},
+ logicalSize: {width: 200, height: 100}, crop: {x: 0, y: 0}};
s.win.focused = false; s.win.emit("blur");
- assert.equal(s.views[0].visible, false);
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
+ assert.equal(s.views[0].visible, false, "bootstrap must still complete before showing the map");
+ s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});
+ assert.equal(s.views[0].visible, true);
+ for (const [property, hiddenValue, event, restore] of [
+ ["visible", false, "hide", "show"], ["minimized", true, "minimize", "restore"],
+ ]) {
+ s.win[property] = hiddenValue;
+ s.win.emit(event);
+ assert.equal(s.views[0].visible, false);
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
+ s.win.emit("focus");
+ assert.equal(s.views[0].visible, false, "geometry and focus cannot show a hidden or minimized window");
+ s.win[property] = !hiddenValue;
+ s.win.emit(restore);
+ assert.equal(s.views[0].visible, true);
+ }
+ s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false});
s.win.focused = true; s.win.emit("focus");
+ assert.equal(s.views[0].visible, false, "window focus must not revive an owner-occluded map");
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
assert.equal(s.views[0].visible, true);
s.manager.destroyAll();
});
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index 242cb4b942..458450765e 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -18,6 +18,19 @@
overflow-wrap: anywhere;
}
+.av__map-summary {
+ display: flex;
+ flex-wrap: wrap;
+ align-self: flex-start;
+ max-width: 100%;
+ gap: 4px 12px;
+}
+
+.av__map-status:empty,
+.av__map-skipped:empty {
+ display: none;
+}
+
.av__map-canvas {
width: 100%;
height: clamp(240px, 50vh, 480px);
diff --git a/app/src/protyle/render/av/locationIntegration.test.ts b/app/src/protyle/render/av/locationIntegration.test.ts
index 2e1dcf56e9..47077f6f8c 100644
--- a/app/src/protyle/render/av/locationIntegration.test.ts
+++ b/app/src/protyle/render/av/locationIntegration.test.ts
@@ -41,7 +41,8 @@ test("location cells display longitude first in every layout, row attributes and
}};
for (const type of ["table", "list", "gallery", "kanban", "map"] as TAVView[]) {
const html = cell.renderCell(value, 0, false, type);
- assert.match(html, /&lt;Home&gt;; 180, 0 \[WGS84\]/);
+ assert.match(html, /&lt;Home&gt; 180, 0/);
+ assert.doesNotMatch(html, /\[WGS84\]/);
assert.doesNotMatch(html, /<Home>/);
const data = /data-cell-value="([^"]+)"/.exec(html)?.[1];
assert.deepEqual(JSON.parse(decodeURIComponent(data)), value);
@@ -49,10 +50,10 @@ test("location cells display longitude first in every layout, row attributes and
}
const attr = loadModule<typeof import("./attributeValue")>("attributeValue");
const html = attr.genAVValueHTML(value);
- assert.match(html, /&lt;Home>; 180, 0 \[WGS84\]/);
+ assert.match(html, /&lt;Home> 180, 0/);
assert.match(html, /data-cell-value=/);
const rollupHTML = cell.renderCell({type: "rollup", rollup: {contents: [value]}}, 0, false, "table");
- assert.match(rollupHTML, /180, 0 \[WGS84\]/);
+ assert.match(rollupHTML, /180, 0/);
});
test("location copies preserve canonical text for cells, nested leaves and templates", () => {
@@ -74,8 +75,8 @@ test("location copies preserve canonical text for cells, nested leaves and templ
assert.equal(cell.getCellText(firstLeaf as unknown as HTMLElement), "20, 30 [WGS84]");
assert.equal(cell.getCellText(wrapper([firstLeaf])), "20, 30 [WGS84]");
assert.equal(cell.getCellText(wrapper([firstLeaf, makeLeaf(), secondLeaf])), "20, 30 [WGS84], Ordinary text, Other; 40, 50 [WGS84]");
- assert.equal(cell.getCellText(firstLeaf as unknown as HTMLElement, "display"), "30, 20 [WGS84]");
- assert.equal(cell.getCellText(wrapper([firstLeaf, makeLeaf(), secondLeaf]), "display"), "30, 20 [WGS84], Ordinary text, Other; 50, 40 [WGS84]");
+ assert.equal(cell.getCellText(firstLeaf as unknown as HTMLElement, "display"), "30, 20");
+ assert.equal(cell.getCellText(wrapper([firstLeaf, makeLeaf(), secondLeaf]), "display"), "30, 20, Ordinary text, Other 50, 40");
assert.equal(cell.getCellText(makeLeaf(first, true) as unknown as HTMLElement), "Custom display");
assert.equal(cell.getCellText(wrapper([makeLeaf(first, true)])), "Custom display");
assert.equal(cell.getCellText(wrapper([makeLeaf(first, true)]), "display"), "Custom display");
@@ -217,7 +218,8 @@ test("template and automation value buttons preserve the structured location unt
const column = {type: "location"} as IAVColumn;
const html = editor.getValueInputHTML(column, {mode: "static", value: {type: "location", location}});
assert.match(html, /data-value-type="location"/);
- assert.match(html, /-180, -90 \[WGS84\]/);
+ assert.match(html, /-180, -90/);
+ assert.doesNotMatch(html, /\[WGS84\]/);
const input = {dataset: {location: encodeURIComponent(JSON.stringify(location))}} as unknown as HTMLElement;
assert.deepEqual(JSON.parse(JSON.stringify(editor.genFieldValue(column, input))), {
type: "location", location: locationValue.createAVLocationReplacement(location),
diff --git a/app/src/protyle/render/av/locationValue.test.ts b/app/src/protyle/render/av/locationValue.test.ts
index fe9c76b483..80fda2d169 100644
--- a/app/src/protyle/render/av/locationValue.test.ts
+++ b/app/src/protyle/render/av/locationValue.test.ts
@@ -117,11 +117,13 @@ describe("database location values", () => {
const location = {name: "Office", latitude: 20, longitude: 30, originalInput: "20,30"};
const before = {...location};
const label = "WGS84";
- assert.equal(getAVLocationDisplayText(location), `Office; 30, 20 [${label}]`);
+ assert.equal(getAVLocationDisplayText(location), "Office 30, 20");
assert.equal(getAVLocationText(location), `Office; 20, 30 [${label}]`);
assert.deepEqual(location, before);
assert.equal(parseAVLocationCoordinates(getAVLocationText(location), "longitudeLatitude"), undefined);
- assert.equal(getAVLocationDisplayText({latitude: 1e-7, longitude: -1e-8}), "-0.00000001, 0.0000001 [WGS84]");
+ assert.equal(getAVLocationDisplayText({latitude: 1e-7, longitude: -1e-8}), "-0.00000001, 0.0000001");
+ assert.equal(getAVLocationDisplayText({name: " 昆明 ", latitude: 25.04, longitude: 102.71}), "昆明 102.71, 25.04");
+ assert.equal(getAVLocationDisplayText({latitude: 0, longitude: 0}), "0, 0");
});
it("excludes provenance from emptiness, display, and semantic equality", () => {
diff --git a/app/src/protyle/render/av/locationValue.ts b/app/src/protyle/render/av/locationValue.ts
index baba8fdbef..80086b2bfb 100644
--- a/app/src/protyle/render/av/locationValue.ts
+++ b/app/src/protyle/render/av/locationValue.ts
@@ -56,7 +56,8 @@ const formatAVLocationText = (location?: IAVCellLocationValue, longitudeFirst =
return name;
}
const coordinates = longitudeFirst ? [location.longitude, location.latitude] : [location.latitude, location.longitude];
- return `${name ? name + "; " : ""}${coordinates.map(formatAVLocationCoordinate).join(", ")} [WGS84]`;
+ const text = coordinates.map(formatAVLocationCoordinate).join(", ");
+ return longitudeFirst ? `${name ? name + " " : ""}${text}` : `${name ? name + "; " : ""}${text} [WGS84]`;
};
// 复制、类型转换和内核导出保持既有的纬度、经度文本契约。
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index a33ba92789..395852e09c 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -461,7 +461,7 @@ describe("desktop map transport", () => {
assert.equal(lastGeometry().visible, true);
assert.equal(f.domListeners.has("blur"), false, "focusing the native map must not hide it");
f.domListeners.get("focus")();
- assert.equal(lastGeometry().visible, false);
+ assert.equal(lastGeometry().visible, true);
f.advance();
assert.equal(lastGeometry().visible, true);
f.domListeners.get("scroll")();
@@ -495,6 +495,60 @@ describe("desktop map transport", () => {
globalThis.ResizeObserver = oldResize;
}
});
+ it("keeps the map visible when focus returns from attribution while rechecking real occlusion", async () => {
+ const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;
+ class Observer { observe() {} disconnect() {} }
+ globalThis.MutationObserver = Observer as any;
+ globalThis.ResizeObserver = Observer as any;
+ const f = fixture();
+ const geometryCalls = () => f.calls.filter(([name]) => name === "siyuan-map-geometry");
+ const lastGeometry = () => geometryCalls().at(-1)[1];
+ try {
+ await f.created();
+ f.reply({type: "ready"});
+ f.advance();
+ const count = geometryCalls().length;
+ assert.equal(f.domListeners.has("blur"), false, "the map receives focus without hiding its native view");
+ for (let i = 0; i < 3; i++) {
+ f.domListeners.get("focus")();
+ assert.equal(lastGeometry().visible, true, "clicking outside attribution must not blank the map");
+ f.advance(30);
+ }
+ assert.equal(geometryCalls().length, count, "unchanged focus returns must not send hidden geometry");
+ const menu = {contains: () => false, getClientRects: () => [f.rect],
+ getBoundingClientRect: () => ({...f.rect, width: 5, height: 5})};
+ f.doc.querySelectorAll = () => [menu];
+ f.domListeners.get("focus")();
+ assert.equal(lastGeometry().visible, false, "an overlapping app menu must hide the map immediately on focus");
+ f.doc.querySelectorAll = (): HTMLElement[] => [];
+ f.domListeners.get("focus")();
+ f.advance(119);
+ assert.equal(lastGeometry().visible, false);
+ f.advance(1);
+ assert.equal(lastGeometry().visible, true);
+ f.rect.x += 10;
+ f.domListeners.get("focus")();
+ assert.equal(lastGeometry().visible, false, "changed geometry still waits for layout to settle");
+ f.advance();
+ assert.equal(lastGeometry().bounds.x, f.rect.x);
+ f.doc.hidden = true;
+ f.domListeners.get("focus")();
+ assert.equal(lastGeometry().visible, false, "a genuinely hidden document remains hidden");
+ f.doc.hidden = false;
+ f.doc.elementFromPoint = () => ({});
+ f.domListeners.get("focus")();
+ assert.equal(lastGeometry().visible, false, "unknown owner overlays retain the hit-test safeguard");
+ f.doc.elementFromPoint = () => f.container;
+ f.domListeners.get("focus")();
+ f.advance();
+ assert.equal(lastGeometry().visible, true);
+ assert.deepEqual(f.errors, []);
+ } finally {
+ f.host.destroy();
+ globalThis.MutationObserver = oldMutation;
+ globalThis.ResizeObserver = oldResize;
+ }
+ });
it("clips beneath its own fixed database tabs while retaining menu and unknown occlusion checks", async () => {
const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;
const callbacks: Array<() => void> = [];
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index fe7217cb65..8986fb2b18 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -240,6 +240,12 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
geometry(checkGeometry());
}
};
+ const onFocus = () => {
+ if (!destroyed) {
+ // 从原生地图回到编辑器只复核布局;实际几何或遮挡变化仍会立即隐藏地图。
+ checkGeometry();
+ }
+ };
const tick = () => {
if (destroyed) {
return;
@@ -265,7 +271,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
scope?.removeEventListener("pagehide", destroy);
scope?.removeEventListener("scroll", onScroll, true);
scope?.removeEventListener("resize", invalidate);
- scope?.removeEventListener("focus", invalidate);
+ scope?.removeEventListener("focus", onFocus);
container.ownerDocument.removeEventListener("visibilitychange", invalidate);
observer?.disconnect();
resizeObserver?.disconnect();
@@ -383,8 +389,8 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
created = true;
scope.addEventListener("scroll", onScroll, true);
scope.addEventListener("resize", invalidate);
- // BrowserWindow focus is enforced in main. DOM blur also fires when the map view gains focus.
- scope.addEventListener("focus", invalidate);
+ // DOM 焦点会在编辑器与原生地图间切换,窗口是否隐藏由主进程与文档可见性共同判断。
+ scope.addEventListener("focus", onFocus);
container.ownerDocument.addEventListener("visibilitychange", invalidate);
observer = new MutationObserver(() => {
// 悬停提示和块标也会改变 DOM;仅地图几何或遮挡变化需要隐藏原生视图。
diff --git a/app/src/protyle/render/av/map/providers.test.ts b/app/src/protyle/render/av/map/providers.test.ts
index 98016cdb53..0d608c873a 100644
--- a/app/src/protyle/render/av/map/providers.test.ts
+++ b/app/src/protyle/render/av/map/providers.test.ts
@@ -12,19 +12,23 @@ const fixture = () => {
const classes = new Set<string>();
let now = 0, nextFrame = 0;
const rect = {left: 0, top: 0, right: 300, bottom: 24, width: 300, height: 24};
- const attribution: any = {open: true, textContent: "MapLibre OpenFreeMap OpenStreetMap OpenMapTiles",
- classList: {toggle: (name: string, on: boolean) => on ? classes.add(name) : classes.delete(name)},
+ const attributionText = {textContent: "MapLibre OpenFreeMap OpenStreetMap OpenMapTiles", getClientRects: () => [rect],
+ getBoundingClientRect: () => ({left: rect.left + 8, right: rect.right - 28, top: rect.top + 2,
+ bottom: rect.bottom - 2, width: rect.width - 36, height: rect.height - 4})};
+ const attribution: any = {tagName: "DETAILS", open: true, querySelector: () => attributionText,
+ classList: {toggle: (name: string, on: boolean) => on ? classes.add(name) : classes.delete(name),
+ contains: (name: string) => classes.has(name)},
addEventListener: (name: string, callback: (event: any) => void) => events.set(name, callback),
removeEventListener: (name: string) => events.delete(name),
getClientRects: () => [rect], getBoundingClientRect: () => rect,
- contains: (target: unknown) => target === attribution || target === anchor || target === summary};
+ contains: (target: unknown) => [attribution, attributionText, anchor, summary].includes(target)};
const anchor = {href: "", getAttribute: () => anchor.href, closest: (selector: string): any => selector === "a" ? anchor : null};
const summary = {closest: (selector: string): any => selector === "summary" ? summary : null};
const scope = {innerWidth: 800, innerHeight: 600, navigator: {userActivation: {isActive: true}},
requestAnimationFrame: (callback: (now: number) => void) => { frames.set(++nextFrame, callback); return nextFrame; },
cancelAnimationFrame: (id: number) => frames.delete(id)};
const doc = {documentElement: {dataset: {}}, defaultView: scope, hidden: false,
- elementFromPoint: (): unknown => attribution,
+ elementFromPoint: (() => attribution) as (x: number, y: number) => unknown,
addEventListener: (name: string, callback: () => void) => documentEvents.set(name, callback),
removeEventListener: (name: string) => documentEvents.delete(name)};
class SDKObject {
@@ -166,6 +170,49 @@ test("trusted attribution interaction cancels auto-collapse and only exact offic
assert.equal(clicked.length, 4);
});
+test("rounded attribution corners do not prevent its visible text from completing the display clock", () => {
+ const f = fixture();
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
+ f.doc.elementFromPoint = (x: number, y: number) =>
+ (x < 8 || x > 292) && (y < 2 || y > 22) ? f.container : f.attribution;
+ f.load(); adapter.setVisible(true, visibleViewport); f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true);
+ assert.equal(f.attribution.classList.contains("maplibregl-compact-show"), true);
+ f.advance(1);
+ assert.equal(f.attribution.open, false);
+ assert.equal(f.attribution.classList.contains("maplibregl-compact-show"), false);
+ adapter.destroy();
+});
+
+test("trusted local disclosure clicks survive host visibility transitions without permitting external navigation", () => {
+ const f = fixture();
+ const clicked: string[] = [];
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {
+ onMarkerClick() {}, onError() {}, onAttributionClick: link => clicked.push(link),
+ });
+ f.load(); adapter.setVisible(true, visibleViewport); f.advance(0);
+ f.scope.navigator.userActivation.isActive = false;
+ adapter.setVisible(false);
+ assert.equal((f.click() as any).prevented, true);
+ assert.equal(f.attribution.open, false);
+ assert.equal(f.attribution.classList.contains("maplibregl-compact-show"), false);
+ f.click("https://maplibre.org/");
+ assert.deepEqual(clicked, []);
+ f.click(undefined, {isTrusted: false});
+ assert.equal(f.attribution.open, false);
+ adapter.setVisible(true, visibleViewport);
+ f.click();
+ assert.equal(f.attribution.open, true);
+ f.advance(10000);
+ assert.equal(f.attribution.open, true, "the user's disclosure choice cancels automatic collapse");
+ f.click("https://maplibre.org/");
+ assert.deepEqual(clicked, []);
+ f.scope.navigator.userActivation.isActive = true;
+ f.click("https://maplibre.org/");
+ assert.deepEqual(clicked, ["maplibre"]);
+ adapter.destroy();
+});
+
test("attribution display time respects parent clipping and translated native viewport coordinates", () => {
const f = fixture();
const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
diff --git a/app/src/protyle/render/av/map/providers.ts b/app/src/protyle/render/av/map/providers.ts
index 98be094ed4..2e2cdc45c3 100644
--- a/app/src/protyle/render/av/map/providers.ts
+++ b/app/src/protyle/render/av/map/providers.ts
@@ -44,6 +44,7 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
map.addControl(new sdk.AttributionControl({compact: true,
customAttribution: `<a href="${maplibre.href}" target="_blank">${maplibre.label}</a>`}));
const attribution = container.querySelector<HTMLDetailsElement>(".maplibregl-ctrl-attrib");
+ const attributionText = attribution.querySelector<HTMLElement>(".maplibregl-ctrl-attrib-inner");
let loaded = false, visible = false, expanded = true, automatic = true;
let viewport: AVMapViewport;
let frame = 0, visibleSince: number;
@@ -58,13 +59,16 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
visibleSince = undefined;
};
const attributionVisible = () => {
- if (!viewport || doc.hidden || !attribution.getClientRects().length || !attribution.textContent?.trim()) return false;
+ if (!viewport || doc.hidden || !attributionText.getClientRects().length || !attributionText.textContent?.trim()) return false;
const rect = attribution.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0 || rect.left < 0 || rect.top < 0 ||
rect.right > scope.innerWidth || rect.bottom > scope.innerHeight ||
rect.left < viewport.x || rect.top < viewport.y || rect.right > viewport.x + viewport.width ||
rect.bottom > viewport.y + viewport.height) return false;
- return [rect.left + 1, rect.right - 1].every(x => [rect.top + 1, rect.bottom - 1].every(y =>
+ // 紧凑控件的圆角属于透明区域,遮挡检查应命中实际展示的版权文字。
+ const textRect = attributionText.getBoundingClientRect();
+ if (textRect.width <= 0 || textRect.height <= 0) return false;
+ return [textRect.left + 1, textRect.right - 1].every(x => [textRect.top + 1, textRect.bottom - 1].every(y =>
attribution.contains(doc.elementFromPoint(x, y))));
};
const tickAttribution = (now: number) => {
@@ -90,8 +94,7 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
}
};
const onAttributionInteraction = (event: Event) => {
- if (!event.isTrusted ||
- !(scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) return;
+ if (!event.isTrusted) return;
automatic = false;
stopCollapse();
};
@@ -103,13 +106,15 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
// 不向供应商文档授予导航或弹窗权限。
event.preventDefault();
event.stopImmediatePropagation();
- if (destroyed || !visible || !event.isTrusted || event.button !== 0 ||
- !(scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) return;
- onAttributionInteraction(event);
+ if (destroyed || !event.isTrusted || event.button !== 0) return;
if (summary) {
+ // 本地展开不依赖跨宿主可见性消息或外链所需的瞬时激活状态。
+ onAttributionInteraction(event);
expanded = !expanded;
syncAttribution();
- } else if (attribution.contains(anchor)) {
+ } else if (visible && attribution.contains(anchor) &&
+ (scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) {
+ onAttributionInteraction(event);
const link = AV_MAP_ATTRIBUTION_LINKS[provider].find(item => item.href === anchor.getAttribute("href"));
if (link) callbacks.onAttributionClick?.(link.id);
}
diff --git a/app/src/protyle/render/av/map/providersLoader.test.ts b/app/src/protyle/render/av/map/providersLoader.test.ts
index 91f883fceb..581a2db6a3 100644
--- a/app/src/protyle/render/av/map/providersLoader.test.ts
+++ b/app/src/protyle/render/av/map/providersLoader.test.ts
@@ -41,6 +41,7 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
scope.document = document;
const container = {ownerDocument: document, replaceChildren() {}, querySelector: () => ({
classList: {toggle() {}}, addEventListener() {}, removeEventListener() {},
+ querySelector: () => ({}),
})} as unknown as HTMLElement;
return {scope, requested, container, destroyed: () => destroyed};
};
diff --git a/app/src/protyle/render/av/map/render.test.ts b/app/src/protyle/render/av/map/render.test.ts
index d5cd4b6767..3f03ad6e8c 100644
--- a/app/src/protyle/render/av/map/render.test.ts
+++ b/app/src/protyle/render/av/map/render.test.ts
@@ -18,10 +18,11 @@ class ElementStub {
readonly children = new Map<string, ElementStub>();
readonly events = new Map<string, () => void>();
readonly classes = new Set<string>();
+ readonly attributes = new Map<string, string>();
readonly classList = {add: (...names: string[]) => names.forEach(name => this.classes.add(name)),
remove: (...names: string[]) => names.forEach(name => this.classes.delete(name)),
toggle: (name: string, enabled: boolean) => enabled ? this.classes.add(name) : this.classes.delete(name)};
- setAttribute() {}
+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }
remove() { this.isConnected = false; }
addEventListener(type: string, callback: () => void) { this.events.set(type, callback); }
querySelector(selector: string) {
@@ -39,8 +40,10 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
const block = {dataset: {avId: "database", nodeId: "carrier"}, removeAttribute() {}, querySelector: (selector: string) =>
selector.endsWith(".av__map") ? root : records};
Object.assign(records, {before: (element: ElementStub) => { root = element; roots.push(root); }});
- const languages = new Proxy<Record<string, string>>({mapPageScope: "${shown}/${total}",
- mapSkippedLocations: "${empty}/${invalid}/${unknown}/${mismatch}"}, {get: (target, key: string) => target[key] || key});
+ const languages = new Proxy<Record<string, string>>({mapPageScope: "Map covers ${shown} loaded records of ${total} filtered records",
+ mapLoadedCount: "Loaded ${shown}/${total}", mapSkippedCount: "Skipped ${count}",
+ mapSkippedLocations: "Skipped locations: ${empty} missing, ${invalid} invalid, ${projection} unsupported projection"},
+ {get: (target, key: string) => target[key] || key});
const events = new Map<string, () => void>();
const observers: Array<{disconnected: boolean}> = [];
class Observer {
@@ -146,6 +149,49 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
status: () => root.querySelector(".av__map-status").textContent};
};
+test("map summary keeps loaded scope in one compact line and omits zero skipped locations", async () => {
+ const scenario = setup();
+ await scenario.render();
+ assert.match(scenario.roots[0].innerHTML, /<span>Loaded 1\/12<\/span><span class="av__map-skipped"><\/span>/);
+ assert.match(scenario.roots[0].innerHTML, /b3-tooltips b3-tooltips__ne" aria-label="Map covers 1 loaded records of 12 filtered records" tabindex="0"/);
+ assert.equal(scenario.control(".av__map-skipped").textContent, "");
+ assert.doesNotMatch(scenario.roots[0].innerHTML, /<div class="av__map-skipped|Skipped 0/);
+});
+
+test("map summary counts all skipped locations and keeps their reasons in its tooltip", async () => {
+ const scenario = setup();
+ const view = scenario.data.view as IAVTable;
+ const row = view.rows[0];
+ const withLocation = (id: string, location?: IAVCellLocationValue) => ({...row, id, cells: [{
+ ...row.cells[0], value: {...row.cells[0].value, location},
+ }]});
+ view.rows.push(withLocation("empty"), withLocation("invalid", {latitude: 100, longitude: 0}),
+ withLocation("projection", {latitude: 90, longitude: 0}));
+ await scenario.render();
+ assert.match(scenario.roots[0].innerHTML, /<span>Loaded 4\/12<\/span>/);
+ assert.equal(scenario.control(".av__map-skipped").textContent, "Skipped 3");
+ assert.equal(scenario.control(".av__map-summary").attributes.get("aria-label"),
+ "Map covers 4 loaded records of 12 filtered records\nSkipped locations: 1 missing, 1 invalid, 1 unsupported projection");
+ assert.equal(scenario.hosts[0].points.length, 1);
+ view.rows = [row];
+ await scenario.render();
+ assert.match(scenario.roots[1].innerHTML, /<span>Loaded 1\/12<\/span>/);
+ assert.equal(scenario.control(".av__map-skipped").textContent, "");
+ assert.doesNotMatch(scenario.roots[1].innerHTML, /Skipped locations/);
+});
+
+test("map summary retains skipped counts when every loaded row lacks a compatible location", async () => {
+ const scenario = setup();
+ const view = scenario.data.view as IAVTable;
+ view.rows[0].cells[0].value.location.latitude = 90;
+ await scenario.render();
+ assert.equal(scenario.status(), "mapNoMarkers");
+ assert.equal(scenario.control(".av__map-skipped").textContent, "Skipped 1");
+ assert.equal(scenario.control(".av__map-summary").attributes.get("aria-label"),
+ "Map covers 1 loaded records of 12 filtered records\nSkipped locations: 0 missing, 0 invalid, 1 unsupported projection");
+ assert.deepEqual(scenario.calls, []);
+});
+
test("map attribution stays inside the control and parent opens only fixed current destinations", async () => {
const scenario = setup();
await scenario.render();
diff --git a/app/src/protyle/render/av/map/render.ts b/app/src/protyle/render/av/map/render.ts
index 40bd518c3a..0c19c8faa2 100644
--- a/app/src/protyle/render/av/map/render.ts
+++ b/app/src/protyle/render/av/map/render.ts
@@ -100,8 +100,11 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
root.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-summary ft__smaller ft__on-surface">${escapeHtml(pageText)}</div>
-<div class="av__map-skipped ft__smaller ft__on-surface"></div>
+ const loadedText = window.siyuan.languages.mapLoadedCount.replace("${shown}", view.rows.length.toString())
+ .replace("${total}", view.rowCount.toString());
+ root.innerHTML = `<div class="av__map-summary ft__smaller ft__on-surface b3-tooltips b3-tooltips__ne" aria-label="${escapeAttr(pageText)}" tabindex="0">
+ <span>${escapeHtml(loadedText)}</span><span class="av__map-skipped"></span>
+</div>
<div class="av__map-status ft__on-surface" role="status"></div>
<div class="av__map-canvas fn__none"></div>
`;
@@ -145,8 +148,14 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
return;
}
const {points, skipped} = getMapPoints(view);
- root.querySelector(".av__map-skipped").textContent = Object.entries(skipped).reduce((text, [key, value]) =>
- text.replace("${" + key + "}", value.toString()), window.siyuan.languages.mapSkippedLocations);
+ const skippedCount = skipped.empty + skipped.invalid + skipped.projection;
+ if (skippedCount) {
+ const skippedElement = root.querySelector(".av__map-skipped");
+ skippedElement.textContent = window.siyuan.languages.mapSkippedCount.replace("${count}", skippedCount.toString());
+ const skippedText = Object.entries(skipped).reduce((text, [key, value]) =>
+ text.replace("${" + key + "}", value.toString()), window.siyuan.languages.mapSkippedLocations);
+ root.querySelector(".av__map-summary").setAttribute("aria-label", `${pageText}\n${skippedText}`);
+ }
if (!canLoadMapHost({published: false, history: false, protocol: window.location.protocol})) {
fallback(window.siyuan.languages.mapUnsupportedClient);
return;
diff --git a/app/tests/mapAttribution.test.js b/app/tests/mapAttribution.test.js
new file mode 100644
index 0000000000..19f9d121ba
--- /dev/null
+++ b/app/tests/mapAttribution.test.js
@@ -0,0 +1,183 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const install = (sources, css, controlledClock) => {
+ document.head.innerHTML = "";
+ document.body.innerHTML = '<div id="map" class="maplibregl-map"></div>';
+ const style = document.createElement("style");
+ style.textContent = css + "body{margin:0} #map{width:100vw;height:100vh;position:relative;background:lightblue}";
+ document.head.append(style);
+ const modules = {};
+ for (const [name, source] of Object.entries(sources)) {
+ const exports = {};
+ new Function("require", "exports", source)(name => modules[name.slice(2)], exports);
+ modules[name] = exports;
+ }
+ const container = document.getElementById("map");
+ class FakeMap {
+ callbacks = new Map();
+ style = {stylesheet: {}, tileManagers: {source: {used: true, getSource: () => ({attribution:
+ '<a href="https://openfreemap.org" target="_blank">OpenFreeMap</a> ' +
+ '<a href="https://www.openmaptiles.org/" target="_blank">&copy; OpenMapTiles</a> ' +
+ 'Data from <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>'})}}};
+ on(name, callback) {
+ if (!this.callbacks.has(name)) this.callbacks.set(name, []);
+ this.callbacks.get(name).push(callback);
+ }
+ off(name, callback) {
+ this.callbacks.set(name, this.callbacks.get(name)?.filter(item => item !== callback) || []);
+ }
+ remove() {}
+ getCanvasContainer() { return container; }
+ _getUIString() { return "Toggle attribution"; }
+ addControl(control) {
+ const wrapper = document.createElement("div");
+ wrapper.className = "maplibregl-ctrl-bottom-right";
+ container.append(wrapper);
+ wrapper.append(control.onAdd(this));
+ }
+ emit(name) { this.callbacks.get(name)?.forEach(callback => callback()); }
+ constructor() { window.mapFixture = this; }
+ }
+ if (controlledClock) {
+ let now = 0, nextFrame = 0;
+ const frames = new Map();
+ window.requestAnimationFrame = callback => { frames.set(++nextFrame, callback); return nextFrame; };
+ window.cancelAnimationFrame = frame => frames.delete(frame);
+ window.advanceAttribution = elapsed => {
+ now += elapsed;
+ const pending = [...frames.values()];
+ frames.clear();
+ pending.forEach(callback => callback(now));
+ };
+ }
+ window.attributionLinks = [];
+ window.attributionAdapter = modules.providers.createAVMapAdapter("openfreemap", {
+ Map: FakeMap, AttributionControl: window.maplibregl.AttributionControl,
+ }, container, {onMarkerClick() {}, onError() {}, onAttributionClick: link => window.attributionLinks.push(link)});
+ window.showAttribution = visible => window.attributionAdapter.setVisible(visible,
+ visible ? {x: 0, y: 0, width: window.innerWidth, height: window.innerHeight} : undefined);
+ window.showAttribution(true);
+ window.mapFixture.emit("load");
+};
+
+const inspect = () => {
+ const attribution = document.querySelector(".maplibregl-ctrl-attrib");
+ const text = attribution.querySelector(".maplibregl-ctrl-attrib-inner");
+ const rect = attribution.getBoundingClientRect();
+ return {tag: attribution.tagName, buttonTag: attribution.firstElementChild.tagName, open: attribution.open,
+ expandedClass: attribution.classList.contains("maplibregl-compact-show"),
+ textVisible: text.checkVisibility(), hidden: document.hidden,
+ radius: getComputedStyle(attribution).borderTopLeftRadius,
+ corners: [rect.left + 1, rect.right - 1].flatMap(x => [rect.top + 1, rect.bottom - 1]
+ .map(y => attribution.contains(document.elementFromPoint(x, y))))};
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.whenReady().then(async () => {
+ const win = new BrowserWindow({width: 800, height: 600, useContentSize: true, show: true,
+ webPreferences: {sandbox: true, nodeIntegration: false, contextIsolation: true, backgroundThrottling: false}});
+ let code = 0;
+ try {
+ const ts = require("typescript");
+ const compile = name => ts.transpileModule(fs.readFileSync(
+ path.join(__dirname, "../src/protyle/render/av/map", name + ".ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ const sources = {protocol: compile("protocol"), providers: compile("providers")};
+ const css = fs.readFileSync(require.resolve("maplibre-gl/dist/maplibre-gl.css"), "utf8");
+ const sdk = fs.readFileSync(require.resolve("maplibre-gl/dist/maplibre-gl-csp.js"), "utf8");
+ const evaluate = source => win.webContents.executeJavaScript(source);
+ const state = () => evaluate(`(${inspect.toString()})()`);
+ const setup = async controlled => {
+ await win.loadURL("data:text/html,<html><head></head><body></body></html>");
+ await evaluate(sdk);
+ await evaluate(`(${install.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(css)}, ${controlled})`);
+ };
+ await setup(false);
+ const initial = await state();
+ assert.equal(initial.tag, "DETAILS");
+ assert.equal(initial.buttonTag, "SUMMARY");
+ assert.equal(initial.hidden, false);
+ assert.equal(initial.radius, "12px");
+ assert.ok(initial.corners.some(hit => !hit), "rounded transparent corners do not hit attribution");
+ assert.equal(initial.textVisible, true);
+ const deadline = Date.now() + 10000;
+ while ((await state()).open && Date.now() < deadline) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ assert.equal((await state()).open, false, "actual visible time automatically collapses after five seconds");
+ assert.equal((await state()).textVisible, false);
+ await evaluate("window.attributionAdapter.destroy()");
+
+ await setup(true);
+ win.webContents.debugger.attach("1.3");
+ await win.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {enabled: true});
+ const click = async selector => {
+ const point = await evaluate(`(() => {const rect = document.querySelector(${JSON.stringify(selector)})
+ .getBoundingClientRect(); return {x: rect.x + rect.width / 2, y: rect.y + rect.height / 2};})()`);
+ for (const type of ["mousePressed", "mouseReleased"]) {
+ await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
+ type, ...point, button: "left", clickCount: 1,
+ });
+ }
+ };
+ await evaluate("advanceAttribution(0); advanceAttribution(4999)");
+ assert.equal((await state()).open, true);
+ await evaluate("showAttribution(false); advanceAttribution(10000); showAttribution(true); advanceAttribution(0); advanceAttribution(4999)");
+ assert.equal((await state()).open, true, "hidden time is not charged");
+ await evaluate("advanceAttribution(1)");
+ assert.equal((await state()).open, false);
+ assert.equal((await state()).expandedClass, false);
+ await click("summary");
+ assert.equal((await state()).open, true, "trusted click expands once without a duplicate native toggle");
+ assert.equal((await state()).textVisible, true);
+ await evaluate("showAttribution(false)");
+ await click("summary");
+ assert.equal((await state()).open, false, "local disclosure survives delayed host visibility messages");
+ await click("summary");
+ assert.equal((await state()).open, true);
+ await click('a[href="https://maplibre.org/"]');
+ assert.deepEqual(await evaluate("window.attributionLinks"), [], "hidden host cannot open an official link");
+ await evaluate("showAttribution(true)");
+ for (const href of ["https://maplibre.org/", "https://openfreemap.org", "https://www.openmaptiles.org/",
+ "https://www.openstreetmap.org/copyright"]) {
+ await click(`a[href="${href}"]`);
+ }
+ assert.deepEqual(await evaluate("window.attributionLinks"), ["maplibre", "openfreemap", "openmaptiles", "openstreetmap"]);
+ await evaluate("document.querySelector('summary').click(); advanceAttribution(10000); mapFixture.emit('drag')");
+ assert.equal((await state()).open, true, "synthetic input, elapsed time and drag preserve the user's choice");
+ await click("summary");
+ assert.equal((await state()).open, false);
+ await evaluate("window.attributionAdapter.destroy()");
+ } catch (error) {
+ console.error(error);
+ code = 1;
+ } finally {
+ win.destroy();
+ app.exit(code);
+ }
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("MapLibre attribution uses its real rounded DOM and supports trusted disclosure and visible display time", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY
+ ? "Real Electron DOM verification requires DISPLAY or WAYLAND_DISPLAY" : false,
+ }, async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-map-attribution-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 30000});
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}