Skip to content

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

:bug: Improve map defaults and compact attribution https://github.com/siyuan-note/siyuan/issues/20129

Danieleb787246b5aa
diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.js
index 294e65eafa..2748e0ba0f 100644
--- a/app/electron/mapHostManager.js
+++ b/app/electron/mapHostManager.js
@@ -224,9 +224,23 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
try { host.owner.send("siyuan-map-reply", reply); } catch (_error) { destroy(host); }
}
};
+ const setVisible = (host, visible) => {
+ if (!host.view.webContents.isDestroyed()) host.view.setVisible(visible);
+ if (!visible) host.attributionGestureUntil = 0;
+ host.visible = visible;
+ // 原生视口已裁剪并平移 #map,此处不能再次叠加 crop。
+ const visibility = visible ? {visible: true, viewport: {x: 0, y: 0,
+ width: host.geometry.bounds.width / host.geometry.zoom, height: host.geometry.bounds.height / host.geometry.zoom}} :
+ {visible: false};
+ const key = JSON.stringify(visibility);
+ if (host.ready && key !== host.lastVisibility) {
+ host.lastVisibility = key;
+ post(host, {version: 1, instanceID: host.init.instanceID, type: "visibility", ...visibility});
+ }
+ };
const hide = host => {
host.geometry = undefined;
- if (!host.view.webContents.isDestroyed()) host.view.setVisible(false);
+ setVisible(host, false);
};
const destroy = host => {
if (!host || host.destroyed) return;
@@ -286,10 +300,10 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
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()) {
- host.view.setVisible(false);
+ setVisible(host, false);
return;
}
- host.view.setVisible(true);
+ setVisible(host, true);
post(host, {version: 1, instanceID: host.init.instanceID, type: "resize"});
};
ipcMain.handle("siyuan-map-capability", event => {
@@ -328,10 +342,22 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
spellcheck: false, backgroundThrottling: false, preload: path.join(__dirname, "mapHostPreload.js")}});
const contents = view.webContents;
host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin, diagnostics: new Set(), report,
- view, router, listeners: [], ids: new Set(), revision: -1, loaded: false, ready: false, bootstrapped: false, destroyed: false};
+ view, router, listeners: [], ids: new Set(), revision: -1, loaded: false, ready: false, bootstrapped: false, destroyed: false,
+ visible: false, attributionGestureUntil: 0};
hosts.set(key, host);
// 全局 web-contents-created 会安装外部打开链接处理器,必须在加载前替换为拒绝。
contents.setWindowOpenHandler(() => ({action: "deny"}));
+ const armAttributionClick = () => {
+ if (host.ready && host.visible && host.win.isFocused() && host.win.isVisible() && !host.win.isMinimized()) {
+ host.attributionGestureUntil = Date.now() + 1000;
+ }
+ };
+ listen(host, contents, "before-mouse-event", (_event, input) => {
+ if (input.type === "mouseUp" && input.button === "left") armAttributionClick();
+ });
+ listen(host, contents, "before-input-event", (_event, input) => {
+ if (input.type === "keyDown" && input.key === "Enter" && !input.isAutoRepeat) armAttributionClick();
+ });
mapContents.add(contents.id);
const denyNavigation = event => event.preventDefault();
for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {
@@ -363,7 +389,7 @@ 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", () => view.setVisible(false));
+ listen(host, owner.win, "blur", () => setVisible(host, false));
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();
@@ -403,6 +429,11 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
sendOwner(host, reply);
} else if (reply.type === "markerClick" && host.ready && reply.revision === host.revision && host.ids.has(reply.id)) {
sendOwner(host, reply);
+ } else if (reply.type === "attributionClick" && host.ready && host.visible &&
+ host.win.isFocused() && host.win.isVisible() && !host.win.isMinimized() &&
+ host.attributionGestureUntil > Date.now()) {
+ host.attributionGestureUntil = 0;
+ sendOwner(host, reply);
} else if (reply.type === "error") {
fail(host, reply.code === "hostUnavailable" ?
host.bootstrapped ? "hostOperationFailed" : "hostBootstrapFailed" : reply.code);
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.js
index 95acff0b9b..7f8bc95e1e 100644
--- a/app/electron/mapHostManager.test.js
+++ b/app/electron/mapHostManager.test.js
@@ -314,6 +314,51 @@ test("points and clicks are bounded by current revision and membership; ready is
s.manager.destroyAll();
});
+test("attribution links require one recent native input in a ready visible focused map", (t) => {
+ let now = 100000;
+ t.mock.method(Date, "now", () => now);
+ const s = setup(); s.create(); s.load();
+ const contents = s.views[0].webContents;
+ const click = () => contents.emit("before-mouse-event", {}, {type: "mouseUp", button: "left"});
+ const links = () => s.owner.sent.filter(entry => entry[1].type === "attributionClick").map(entry => entry[1]);
+ const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 400, height: 300},
+ logicalSize: {width: 400, height: 300}, crop: {x: 0, y: 0}};
+ click(); s.reply({type: "attributionClick", link: "maplibre"});
+ s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});
+ click(); s.reply({type: "attributionClick", link: "maplibre"});
+ assert.deepEqual(links(), []);
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
+ s.reply({type: "attributionClick", link: "maplibre"});
+ assert.deepEqual(links(), [], "a provider message alone is insufficient");
+ click();
+ s.reply({type: "attributionClick", link: "maplibre", instanceID: "b".repeat(48)});
+ s.reply({type: "attributionClick", link: "https://evil.invalid/"});
+ assert.deepEqual(links(), []);
+ s.reply({type: "attributionClick", link: "maplibre", href: "https://evil.invalid/"});
+ s.reply({type: "attributionClick", link: "openstreetmap"});
+ assert.deepEqual(links(), [{...envelope, type: "attributionClick", link: "maplibre"}]);
+ 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");
+ 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});
+ s.reply({type: "attributionClick", link: "maplibre"});
+ s.handlers["siyuan-map-geometry"](s.event(), geometry);
+ s.reply({type: "attributionClick", link: "maplibre"});
+ assert.equal(links().length, 2, "hidden geometry invalidates an outstanding gesture");
+ click(); now += 1001; s.reply({type: "attributionClick", link: "maplibre"});
+ 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[0].viewport, {x: 0, y: 0, width: 400, height: 300});
+ s.manager.destroyAll();
+ assert.equal(contents.listenerCount("before-mouse-event"), 0);
+ assert.equal(contents.listenerCount("before-input-event"), 0);
+});
+
test("geometry is invisible before ready, uses owner zoom, and hides on invalid geometry or window transitions", () => {
const s = setup(); s.create(); s.load(); s.owner.zoom = 1.25;
const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},
@@ -325,6 +370,8 @@ test("geometry is invisible before ready, uses owner zoom, and hides on invalid
assert.equal(s.views[0].visible, true);
assert.deepEqual(s.views[0].bounds, {x: 13, y: 25, width: 249, height: 125});
assert.equal(s.views[0].webContents.zoom, 1.25);
+ assert.deepEqual(s.channels[0].port1.sent.find(message => message.type === "visibility" && message.visible).viewport,
+ {x: 0, y: 0, width: 199.2, height: 100}, "native viewport uses cropped DIP bounds divided by zoom without adding crop");
s.win.emit("resize"); assert.equal(s.views[0].visible, false);
s.handlers["siyuan-map-geometry"](s.event(), geometry); assert.equal(s.views[0].visible, true);
s.handlers["siyuan-map-geometry"](s.event(), {...geometry, bounds: {...geometry.bounds, width: 10000}});
diff --git a/app/electron/mapHostPolicy.js b/app/electron/mapHostPolicy.js
index e2a494c4da..2a83918b80 100644
--- a/app/electron/mapHostPolicy.js
+++ b/app/electron/mapHostPolicy.js
@@ -75,6 +75,9 @@ const parseMapReply = (value, instanceID) => {
if (value.type === "markerClick" && isMapIdentifier(value.id) && isMapRevision(value.revision)) {
return {...base, type: value.type, id: value.id, revision: value.revision};
}
+ if (value.type === "attributionClick" && ["openfreemap", "openmaptiles", "openstreetmap", "maplibre"].includes(value.link)) {
+ return {...base, type: value.type, link: value.link};
+ }
if (value.type === "error" && ["unsupportedEnvironment", "invalidConfiguration",
"hostUnavailable", "sdkUnavailable", "mapUnavailable", "sdkScriptLoadFailed",
"sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout", "hostLimitReached", "hostSetupFailed",
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index bc46fc86c2..a33ba92789 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -66,14 +66,15 @@ const fixture = (warnings: unknown[][] = []) => {
doc.defaultView = scope;
const container: any = {ownerDocument: doc, isConnected: true, parentElement: null, closest: (): HTMLElement | null => null,
getClientRects: () => [rect], getBoundingClientRect: () => rect, contains: (target: unknown) => target === container};
- const errors: string[] = [], clicks: unknown[] = [];
+ const errors: string[] = [], clicks: unknown[] = [], attributionClicks: string[] = [];
let ready = 0;
const api = load(ipc, false, warnings);
const host = api.createDesktopAVMapHost(container, {provider: "openfreemap", theme: "light",
onError: (value: string) => errors.push(value),
+ onAttributionClick: (link: string) => attributionClicks.push(link),
onMarkerClick: (...args: unknown[]) => clicks.push(args), onReady: () => ready++});
const instanceID = calls[0][1].instanceID;
- return {host, calls, listeners, domListeners, frames, timers, errors, clicks, doc, container, rect,
+ return {host, calls, listeners, domListeners, frames, timers, errors, clicks, attributionClicks, doc, container, rect,
ready: () => ready,
reply: (value: object) => listeners.get("siyuan-map-reply")?.({}, {version: 1, instanceID, ...value}),
rejected: async () => {
@@ -93,6 +94,29 @@ const fixture = (warnings: unknown[][] = []) => {
};
describe("desktop map transport", () => {
+ it("forwards only ready current fixed attribution replies already verified by main", async () => {
+ class Observer { observe() {} disconnect() {} }
+ const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;
+ globalThis.MutationObserver = Observer as any;
+ globalThis.ResizeObserver = Observer as any;
+ const f = fixture();
+ try {
+ f.reply({type: "attributionClick", link: "maplibre"});
+ assert.deepEqual(f.attributionClicks, []);
+ await f.created(); f.reply({type: "ready"});
+ f.reply({type: "attributionClick", link: "maplibre", instanceID: "old"});
+ f.reply({type: "attributionClick", link: "https://evil.invalid/"});
+ f.reply({type: "attributionClick", link: "maplibre", url: "https://evil.invalid/"});
+ assert.deepEqual(f.attributionClicks, ["maplibre"]);
+ f.host.destroy();
+ f.reply({type: "attributionClick", link: "maplibre"});
+ assert.deepEqual(f.attributionClicks, ["maplibre"]);
+ } finally {
+ f.host.destroy();
+ globalThis.MutationObserver = oldMutation;
+ globalThis.ResizeObserver = oldResize;
+ }
+ });
it("preserves fixed creation failures and never logs rejected IPC details", async () => {
for (const code of ["hostLimitReached", "hostSetupFailed", "hostAttachFailed"] as const) {
const warnings: unknown[][] = [];
@@ -317,7 +341,7 @@ describe("desktop map transport", () => {
assert.equal(geometry.bounds.width, widthRect.width);
assert.equal(parseMapGeometry(geometry, 1.25, {width: 4000, height: 3000})?.visible, true);
});
- it("reports only fixed visibility transitions and distinguishes clipped bottom hit tests", async () => {
+ it("keeps all visibility and hit-test checks without logging normal geometry transitions", async () => {
const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;
class Observer { observe() {} disconnect() {} }
globalThis.MutationObserver = Observer as any;
@@ -325,23 +349,20 @@ describe("desktop map transport", () => {
const warnings: unknown[][] = [];
const f = fixture(warnings);
const getStyle = f.doc.defaultView.getComputedStyle;
- const visibility = () => warnings.filter(([prefix]) => prefix === "Database map visibility:");
const lastGeometry = () => f.calls.filter(([name]) => name === "siyuan-map-geometry").at(-1)[1];
f.container.id = "private-block-id";
f.container.textContent = "private-document-content";
try {
await f.created();
- assert.deepEqual(visibility(), [["Database map visibility:", "openfreemap", "stabilizing"]]);
+ assert.equal(lastGeometry().visible, false);
f.advance();
- assert.deepEqual(visibility().at(-1), ["Database map visibility:", "openfreemap", "visible"]);
+ assert.equal(lastGeometry().visible, true);
const scroll = f.domListeners.get("scroll");
const expectHidden = (reason: string) => {
scroll();
- assert.equal(lastGeometry().visible, false);
- assert.deepEqual(visibility().at(-1), ["Database map visibility:", "openfreemap", reason]);
- const count = warnings.length;
+ assert.equal(lastGeometry().visible, false, reason);
for (let i = 0; i < 10; i++) f.advance(30);
- assert.equal(warnings.length, count, "unchanged reasons must not log on every animation frame");
+ assert.equal(warnings.length, 0, "normal geometry changes must not log warnings");
};
f.doc.hidden = true;
expectHidden("documentHidden");
@@ -385,24 +406,16 @@ describe("desktop map transport", () => {
f.doc.elementFromPoint = () => f.container;
scroll();
assert.equal(lastGeometry().visible, true);
- assert.deepEqual(visibility().at(-1), ["Database map visibility:", "openfreemap", "visible"]);
- const fixedReasons = new Set(["stabilizing", "visible", "documentHidden", "disconnected", "noClientRects",
- "hiddenStyle", "zeroRect", "invalidGeometry", "outsideViewport", "clipped", "overlay", "hitTestTop",
- "hitTestMiddle", "hitTestBottom"]);
- assert.ok(warnings.every(values => values.length === 3 && values[0] === "Database map visibility:" &&
- values[1] === "openfreemap" && fixedReasons.has(values[2] as string)));
- assert.doesNotMatch(JSON.stringify(warnings), /private|do-not-send|https:|instanceID/);
for (let i = 0; i < 100; i++) {
f.doc.hidden = i % 2 === 0;
scroll();
- assert.equal(lastGeometry().visible, !f.doc.hidden, "the log limit must not interrupt geometry updates");
+ assert.equal(lastGeometry().visible, !f.doc.hidden, "repeated changes must not interrupt geometry updates");
}
- assert.equal(visibility().length, 64);
- const count = warnings.length;
+ assert.equal(warnings.length, 0);
f.host.destroy();
scroll();
f.advance();
- assert.equal(warnings.length, count);
+ assert.equal(warnings.length, 0);
} finally {
f.host.destroy();
globalThis.MutationObserver = oldMutation;
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index edb04d41c9..fe7217cb65 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -11,23 +11,17 @@ interface MapRect { x: number; y: number; width: number; height: number; }
type MapGeometry = {visible: false} | {
visible: true; bounds: MapRect; logicalSize: {width: number; height: number}; crop: {x: number; y: number};
};
-type MapVisibilityReason = "visible" | "stabilizing" | "ownerUnavailable" | "documentHidden" | "disconnected" |
- "noClientRects" | "hiddenStyle" | "invalidGeometry" | "zeroRect" | "outsideViewport" | "clipped" | "overlay" |
- "hitTestTop" | "hitTestMiddle" | "hitTestBottom";
const intersects = (a: MapRect, b: MapRect) => a.x < b.x + b.width && b.x < a.x + a.width &&
a.y < b.y + b.height && b.y < a.y + a.height;
// All coordinates stay in owner CSS pixels. Only the main process applies the owner zoom factor.
-export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occluders: MapRect[] = [],
- report?: (reason: MapVisibilityReason) => void): MapGeometry => {
+export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occluders: MapRect[] = []): MapGeometry => {
if (![rect, ...clips, ...occluders].every((item) => [item.x, item.y, item.width, item.height].every(Number.isFinite) &&
item.width >= 0 && item.height >= 0)) {
- report?.("invalidGeometry");
return {visible: false};
}
if (rect.width < 1 || rect.height < 1) {
- report?.("zeroRect");
return {visible: false};
}
let left = rect.x, top = rect.y, right = rect.x + rect.width, bottom = rect.y + rect.height;
@@ -45,14 +39,11 @@ export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occ
// 裁剪差值的浮点舍入不能使可见尺寸超过原始尺寸。
const bounds = {x: left, y: top, width: Math.min(rect.width, right - left), height: Math.min(rect.height, bottom - top)};
if (left < 0 || top < 0 || bounds.width < 1 || bounds.height < 1) {
- report?.("clipped");
return {visible: false};
}
if (occluders.some((item) => item.width > 0 && item.height > 0 && intersects(bounds, item))) {
- report?.("overlay");
return {visible: false};
}
- report?.("visible");
return {visible: true, bounds, logicalSize: {width: rect.width, height: rect.height},
crop: {x: left - rect.x, y: top - rect.y}};
};
@@ -117,24 +108,20 @@ export const isDesktopAVMapHostSupported = async (): Promise<boolean> => {
return false;
};
-const readGeometry = (container: HTMLElement, report: (reason: MapVisibilityReason) => void): MapGeometry => {
+const readGeometry = (container: HTMLElement): MapGeometry => {
const doc = container.ownerDocument;
const scope = doc.defaultView;
- const hidden = (reason: MapVisibilityReason): MapGeometry => {
- report(reason);
- return {visible: false};
- };
if (!scope) {
- return hidden("ownerUnavailable");
+ return {visible: false};
}
if (doc.hidden) {
- return hidden("documentHidden");
+ return {visible: false};
}
if (!container.isConnected) {
- return hidden("disconnected");
+ return {visible: false};
}
if (!container.getClientRects().length) {
- return hidden("noClientRects");
+ return {visible: false};
}
const rect = container.getBoundingClientRect();
const clips: MapRect[] = [{x: 0, y: 0, width: scope.innerWidth, height: scope.innerHeight}];
@@ -142,7 +129,7 @@ const readGeometry = (container: HTMLElement, report: (reason: MapVisibilityReas
const style = scope.getComputedStyle(element);
if (style.display === "none" || style.visibility !== "visible" || Number(style.opacity) === 0 ||
style.getPropertyValue("content-visibility") === "hidden") {
- return hidden("hiddenStyle");
+ return {visible: false};
}
if (element !== container && /hidden|clip|scroll|auto/.test(style.overflowX + style.overflowY)) {
const bounds = element.getBoundingClientRect();
@@ -180,19 +167,15 @@ const readGeometry = (container: HTMLElement, report: (reason: MapVisibilityReas
occluders.push(element.getBoundingClientRect());
}
});
- const geometry = computeDesktopAVMapGeometry(rect, clips, occluders, reason => {
- report(reason === "clipped" && !intersects(rect, clips[0]) ? "outsideViewport" : reason);
- });
+ const geometry = computeDesktopAVMapGeometry(rect, clips, occluders);
if (geometry.visible) {
const bounds = geometry.bounds;
// Hit-test the owner's DOM (native child views are not in this tree), including sticky toolbars.
for (const x of [bounds.x + 0.5, bounds.x + bounds.width / 2, bounds.x + bounds.width - 0.5]) {
- const samples: Array<[number, MapVisibilityReason]> = [[bounds.y + 0.5, "hitTestTop"],
- [bounds.y + bounds.height / 2, "hitTestMiddle"], [bounds.y + bounds.height - 0.5, "hitTestBottom"]];
- for (const [y, reason] of samples) {
+ for (const y of [bounds.y + 0.5, bounds.y + bounds.height / 2, bounds.y + bounds.height - 0.5]) {
const top = doc.elementFromPoint(x, y);
if (!top || !container.contains(top)) {
- return hidden(reason);
+ return {visible: false};
}
}
}
@@ -209,10 +192,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
let ids = new Set<string>();
let frame = 0, timeout = 0, stableAfter = 0, scrollingUntil = 0;
let lastGeometry = "", sentGeometry = "";
- let visibilityReason: MapVisibilityReason = "stabilizing", lastVisibilityReason: MapVisibilityReason;
- let visibilityDiagnosticsRemaining = 64;
const diagnostics = new Set<string>();
- const provider = isAVMapProvider(options.provider) ? options.provider : undefined;
let observer: MutationObserver;
let resizeObserver: ResizeObserver;
const envelope = () => ({version: AV_MAP_PROTOCOL_VERSION, instanceID} as const);
@@ -221,16 +201,8 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
ipc.send("siyuan-map-command", command);
}
};
- const geometry = (value: MapGeometry, reason = visibilityReason) => {
+ const geometry = (value: MapGeometry) => {
const key = JSON.stringify(value);
- if (created && provider && reason !== lastVisibilityReason) {
- // 仅记录可见状态切换和固定原因,不输出 DOM、尺寸、位置或实例标识。
- if (visibilityDiagnosticsRemaining > 0) {
- console.warn("Database map visibility:", provider, reason);
- visibilityDiagnosticsRemaining--;
- }
- lastVisibilityReason = reason;
- }
if (created && key !== sentGeometry) {
ipc.send("siyuan-map-geometry", {...envelope(), ...value});
sentGeometry = key;
@@ -239,11 +211,11 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
const invalidate = () => {
if (!destroyed && scope) {
stableAfter = scope.performance.now() + 120;
- geometry({visible: false}, "stabilizing");
+ geometry({visible: false});
}
};
const checkGeometry = () => {
- const next = readGeometry(container, reason => { visibilityReason = reason; });
+ const next = readGeometry(container);
const key = JSON.stringify(next);
if (key !== lastGeometry) {
lastGeometry = key;
@@ -252,7 +224,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
geometry(next);
} else {
stableAfter = scope.performance.now() + 120;
- geometry({visible: false}, next.visible ? "stabilizing" : visibilityReason);
+ geometry({visible: false});
}
}
if (!next.visible) {
@@ -340,6 +312,9 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
options.onReady?.();
} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {
options.onMarkerClick(reply.id, reply.revision);
+ } else if (reply?.type === "attributionClick" && ready) {
+ // 主进程已校验原生视图可见性,并消费一次可信用户输入。
+ options.onAttributionClick?.(reply.link);
} else if (reply?.type === "error") {
fail(reply.code);
}
diff --git a/app/src/protyle/render/av/map/host.test.ts b/app/src/protyle/render/av/map/host.test.ts
index bf4110097e..e8b101ba66 100644
--- a/app/src/protyle/render/av/map/host.test.ts
+++ b/app/src/protyle/render/av/map/host.test.ts
@@ -1,7 +1,7 @@
import * as assert from "node:assert/strict";
import {webcrypto} from "node:crypto";
import {afterEach, describe, it} from "node:test";
-import {createAVMapHost, isAVMapHostEnvironmentSupported} from "./host";
+import {createAVMapHost, getAVMapVisibility, isAVMapHostEnvironmentSupported} from "./host";
import {isAVMapRuntimeIsolated} from "./hostRuntime";
describe("map host boundary", () => {
@@ -60,7 +60,11 @@ describe("map host boundary", () => {
addEventListener() {}, remove() { iframe.removed = true; },
};
const scope = {
- location: {protocol: "https:", origin: "https://fixture.invalid"}, navigator: {userAgent: "Chromium"}, crypto: webcrypto,
+ location: {protocol: "https:", origin: "https://fixture.invalid"},
+ navigator: {userAgent: "Chromium", userActivation: {isActive: true}}, crypto: webcrypto,
+ innerWidth: 1000, innerHeight: 800,
+ getComputedStyle: () => ({display: "block", visibility: "visible", opacity: "1", getPropertyValue: () => ""}),
+ requestAnimationFrame: () => 1, cancelAnimationFrame() {},
HTMLIFrameElement: {prototype: {credentialless: false}},
clearTimeout(id: number) { timers.delete(id); },
setTimeout(callback: () => void, delay: number) {
@@ -70,12 +74,19 @@ describe("map host boundary", () => {
addEventListener: (name: string, listener: (event?: unknown) => void) => listeners.set(name, listener),
removeEventListener: (name: string) => listeners.delete(name),
};
- const container = {ownerDocument: {defaultView: scope, createElement: () => iframe}, appendChild() {}};
+ const rect = {left: 0, top: 0, right: 400, bottom: 300, width: 400, height: 300};
+ const doc = {defaultView: scope, createElement: () => iframe, hidden: false,
+ elementFromPoint: () => iframe, querySelectorAll: (): HTMLElement[] => [], addEventListener() {}, removeEventListener() {}};
+ const container = {ownerDocument: doc, appendChild() {}, isConnected: true, clientWidth: 400, clientHeight: 300,
+ getClientRects: () => [rect],
+ getBoundingClientRect: () => rect, contains: (element: unknown) => element === iframe};
let ready = 0;
const clicked: any[] = [];
+ const links: string[] = [];
const host = createAVMapHost(container as unknown as HTMLElement, {
provider: "openfreemap", theme: "light",
onReady: () => ready++, onMarkerClick: (...args) => clicked.push(args), onError: () => assert.fail("unexpected error"),
+ onAttributionClick: link => links.push(link),
});
cleanups.push(host.destroy);
await new Promise<void>((resolve) => setImmediate(resolve));
@@ -111,12 +122,24 @@ describe("map host boundary", () => {
assert.deepEqual(port.messages[0], {version: 1, instanceID, type: "init", provider: "openfreemap",
theme: "light"});
const reply = (data: Record<string, unknown>) => port.onmessage({data: {version: 1, instanceID, ...data}});
+ reply({type: "attributionClick", link: "maplibre"});
+ assert.equal(links.length, 0);
reply({type: "ready", instanceID: "old"});
assert.equal(ready, 0);
reply({type: "ready"});
reply({type: "ready"});
assert.equal(timers.size, 0, "ready clears the SDK deadline");
assert.equal(ready, 1);
+ reply({type: "attributionClick", link: "maplibre", instanceID: "old"});
+ reply({type: "attributionClick", link: "https://evil.invalid/"});
+ scope.navigator.userActivation.isActive = false;
+ reply({type: "attributionClick", link: "maplibre"});
+ scope.navigator.userActivation.isActive = true;
+ doc.hidden = true; reply({type: "attributionClick", link: "maplibre"}); doc.hidden = false;
+ assert.equal(links.length, 0);
+ rect.top = -100;
+ reply({type: "attributionClick", link: "maplibre"});
+ assert.deepEqual(links, ["maplibre"], "visible attribution remains clickable when the map top is cropped");
assert.deepEqual(port.messages.find((message) => message.type === "setPoints").points, [point]);
assert.equal(port.messages.filter((message) => message.type === "fit").length, 1);
reply({type: "markerClick", id: "row-1", revision: 0});
@@ -132,6 +155,8 @@ describe("map host boundary", () => {
assert.equal(iframe.removed, true);
assert.equal(port.closed, true);
lateReply({data: {version: 1, instanceID, type: "markerClick", id: "row-1", revision: 2}});
+ lateReply({data: {version: 1, instanceID, type: "attributionClick", link: "maplibre"}});
+ assert.equal(links.length, 1);
assert.equal(clicked.length, 1);
});
it("does not create a frame after destruction while an asynchronous native report is pending", async () => {
@@ -139,7 +164,7 @@ describe("map host boundary", () => {
const scope = {location: {protocol: "http:"}, navigator: {userAgent: "SiYuanAndroid"}, JSAndroid: {},
HTMLIFrameElement: {prototype: {}}, setTimeout, clearTimeout, removeEventListener() {},
getAVMapNativeBoundary: () => new Promise((resolve) => { finish = resolve; })};
- const container = {ownerDocument: {defaultView: scope,
+ const container = {ownerDocument: {defaultView: {...scope, cancelAnimationFrame() {}}, removeEventListener() {},
createElement: () => assert.fail("late native response must not create an iframe")}};
const host = createAVMapHost(container as unknown as HTMLElement, {provider: "openfreemap", theme: "light",
onMarkerClick() {}, onError: () => assert.fail("destroyed host must not emit errors")});
@@ -148,4 +173,33 @@ describe("map host boundary", () => {
finish({version: 1, enabled: true});
await new Promise<void>((resolve) => setImmediate(resolve));
});
+ it("distinguishes partial visibility from safe attribution display time and checks clipping", () => {
+ const rect = {left: 10, top: -10, right: 410, bottom: 290, width: 400, height: 300};
+ const style = {display: "block", visibility: "visible", opacity: "1", overflowX: "visible", overflowY: "visible",
+ getPropertyValue: () => ""};
+ const doc: any = {hidden: false, defaultView: {innerWidth: 800, innerHeight: 600, getComputedStyle: () => style},
+ elementFromPoint: () => container, querySelectorAll: (): HTMLElement[] => []};
+ const container: any = {ownerDocument: doc, isConnected: true, clientWidth: 400, clientHeight: 300, getClientRects: () => [rect],
+ getBoundingClientRect: () => rect, contains: (element: unknown) => element === container};
+ assert.deepEqual(getAVMapVisibility(container), {visible: true, viewport: {x: 0, y: 10, width: 400, height: 290}});
+ rect.top = 10;
+ rect.bottom = 310;
+ assert.equal(getAVMapVisibility(container).visible, true);
+ doc.hidden = true; assert.equal(getAVMapVisibility(container).visible, false); doc.hidden = false;
+ style.opacity = "0"; assert.equal(getAVMapVisibility(container).visible, false); style.opacity = "1";
+ doc.elementFromPoint = () => ({}); assert.equal(getAVMapVisibility(container).visible, false);
+ doc.elementFromPoint = () => container;
+ rect.width = 800; rect.right = 810; rect.height = 600; rect.bottom = 610;
+ assert.deepEqual(getAVMapVisibility(container), {visible: true, viewport: {x: 0, y: 0, width: 395, height: 295}},
+ "parent CSS scaling is removed before forwarding iframe viewport coordinates");
+ container.parentElement = {parentElement: null, clientLeft: 0, clientTop: 0, clientWidth: 350, clientHeight: 500,
+ offsetWidth: 350, offsetHeight: 500, getBoundingClientRect: () => ({left: 20, top: 30, width: 350, height: 500})};
+ style.overflowX = "hidden"; style.overflowY = "scroll";
+ assert.deepEqual(getAVMapVisibility(container), {visible: true, viewport: {x: 5, y: 10, width: 175, height: 250}},
+ "ancestor scroll clipping is converted in the same coordinate system");
+ doc.querySelectorAll = () => [{contains: () => false, getClientRects: () => [{}],
+ getBoundingClientRect: () => ({left: 100, right: 120, top: 250, bottom: 270, width: 20, height: 20})}];
+ assert.deepEqual(getAVMapVisibility(container), {visible: true},
+ "a small parent overlay blocks counting even when it misses every sampled point");
+ });
});
diff --git a/app/src/protyle/render/av/map/host.ts b/app/src/protyle/render/av/map/host.ts
index c59e700e0c..530744bc2f 100644
--- a/app/src/protyle/render/av/map/host.ts
+++ b/app/src/protyle/render/av/map/host.ts
@@ -1,5 +1,5 @@
import {
- AV_MAP_PROTOCOL_VERSION, AVMapCommand, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme,
+ AV_MAP_PROTOCOL_VERSION, AVMapAttributionLink, AVMapCommand, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapVisibility,
isAVMapProvider, isAVMapRevision, isAVMapTheme, parseAVMapReply,
sanitizeAVMapPoints,
} from "./protocol";
@@ -12,6 +12,7 @@ export interface AVMapHostOptions {
onReady?: () => void;
onMarkerClick: (id: string, revision: number) => void;
onError: (code: AVMapErrorCode) => void;
+ onAttributionClick?: (link: AVMapAttributionLink) => void;
}
export interface AVMapHost {
@@ -31,6 +32,55 @@ const randomID = (scope: Window): string => {
return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
};
+// 将父页面裁剪区域换算为隔离 iframe 视口的 CSS 像素。
+export const getAVMapVisibility = (container: HTMLElement): AVMapVisibility => {
+ const doc = container.ownerDocument;
+ const scope = doc.defaultView;
+ const hidden = {visible: false};
+ if (!scope || doc.hidden || !container.isConnected || !container.getClientRects().length) return hidden;
+ const rect = container.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0 || container.clientWidth <= 0 || container.clientHeight <= 0) return hidden;
+ let left = Math.max(0, rect.left), top = Math.max(0, rect.top);
+ let right = Math.min(scope.innerWidth, rect.right), bottom = Math.min(scope.innerHeight, rect.bottom);
+ for (let element = container; element; element = element.parentElement) {
+ const style = scope.getComputedStyle(element);
+ if (style.display === "none" || style.visibility !== "visible" || Number(style.opacity) === 0 ||
+ style.getPropertyValue("content-visibility") === "hidden") return hidden;
+ if (element !== container) {
+ const clip = element.getBoundingClientRect();
+ const scaleX = element.offsetWidth ? clip.width / element.offsetWidth : 1;
+ const scaleY = element.offsetHeight ? clip.height / element.offsetHeight : 1;
+ if (/hidden|clip|scroll|auto/.test(style.overflowX)) {
+ const x = clip.left + element.clientLeft * scaleX;
+ left = Math.max(left, x); right = Math.min(right, x + element.clientWidth * scaleX);
+ }
+ if (/hidden|clip|scroll|auto/.test(style.overflowY)) {
+ const y = clip.top + element.clientTop * scaleY;
+ top = Math.max(top, y); bottom = Math.min(bottom, y + element.clientHeight * scaleY);
+ }
+ }
+ }
+ if (right - left < 2 || bottom - top < 2) return hidden;
+ const hits = [left + 0.5, (left + right) / 2, right - 0.5].flatMap(x =>
+ [top + 0.5, (top + bottom) / 2, bottom - 0.5].map(y => container.contains(doc.elementFromPoint(x, y))));
+ if (!hits.some(Boolean)) return hidden;
+ if (!hits.every(Boolean)) return {visible: true};
+ // 内层无法命中检测父页面浮层;小浮层也可能遮住署名而避开上面的采样点。
+ const overlays = doc.querySelectorAll<HTMLElement>(
+ ".b3-menu, .b3-dialog, .av__panel, .protyle-util, .protyle-toolbar, .block__popover, [popover]");
+ for (const overlay of Array.from(overlays)) {
+ if (overlay.contains(container) || !overlay.getClientRects().length) continue;
+ const style = scope.getComputedStyle(overlay);
+ const bounds = overlay.getBoundingClientRect();
+ if (style.display !== "none" && style.visibility === "visible" && Number(style.opacity) !== 0 &&
+ bounds.width > 0 && bounds.height > 0 && bounds.left < right && bounds.right > left &&
+ bounds.top < bottom && bounds.bottom > top) return {visible: true};
+ }
+ const scaleX = rect.width / container.clientWidth, scaleY = rect.height / container.clientHeight;
+ return {visible: true, viewport: {x: (left - rect.left) / scaleX, y: (top - rect.top) / scaleY,
+ width: (right - left) / scaleX, height: (bottom - top) / scaleY}};
+};
+
export const createAVMapHost = (container: HTMLElement, options: AVMapHostOptions): AVMapHost => {
const scope = container.ownerDocument.defaultView;
let destroyed = false;
@@ -48,6 +98,7 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
let nonce = "";
let nativeBoundary = false;
let preparing = false;
+ let frame = 0, visible = false, lastVisibility = "";
const send = (command: AVMapCommand) => {
if (!destroyed && port) {
@@ -55,6 +106,20 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
}
};
const envelope = () => ({version: AV_MAP_PROTOCOL_VERSION, instanceID} as const);
+ const updateVisibility = () => {
+ const next = ready ? getAVMapVisibility(container) : {visible: false};
+ const key = JSON.stringify(next);
+ if (key !== lastVisibility) {
+ visible = next.visible;
+ lastVisibility = key;
+ send({...envelope(), type: "visibility", ...next});
+ }
+ };
+ const tickVisibility = () => {
+ if (destroyed) return;
+ updateVisibility();
+ frame = scope.requestAnimationFrame(tickVisibility);
+ };
const destroy = () => {
if (destroyed) {
return;
@@ -63,8 +128,10 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
destroyed = true;
ready = false;
scope?.clearTimeout(timeout);
+ scope?.cancelAnimationFrame(frame);
scope?.removeEventListener("message", onMessage);
scope?.removeEventListener("pagehide", destroy);
+ container.ownerDocument.removeEventListener("visibilitychange", updateVisibility);
observer?.disconnect();
if (port) {
port.onmessage = null;
@@ -124,8 +191,13 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
pendingFit = false;
}
options.onReady?.();
+ tickVisibility();
} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {
options.onMarkerClick(reply.id, reply.revision);
+ } else if (reply?.type === "attributionClick" && ready && visible &&
+ getAVMapVisibility(container).visible &&
+ (scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) {
+ options.onAttributionClick?.(reply.link);
} else if (reply?.type === "error") {
fail(reply.code);
}
@@ -203,6 +275,7 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
iframe.addEventListener("error", () => fail("hostDocumentLoadFailed"), {once: true});
scope.addEventListener("message", onMessage);
scope.addEventListener("pagehide", destroy, {once: true});
+ container.ownerDocument.addEventListener("visibilitychange", updateVisibility);
timeout = scope.setTimeout(() => fail("hostBootstrapTimeout"), 30000);
container.appendChild(iframe);
if (typeof ResizeObserver !== "undefined") {
diff --git a/app/src/protyle/render/av/map/hostRuntime.test.ts b/app/src/protyle/render/av/map/hostRuntime.test.ts
index 7014f29ec5..f38da8260b 100644
--- a/app/src/protyle/render/av/map/hostRuntime.test.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.test.ts
@@ -14,6 +14,7 @@ const fixture = () => {
setPoints: (...args) => { calls.push(["setPoints", ...args]); },
fit: () => { calls.push(["fit"]); }, resize: () => { calls.push(["resize"]); },
setTheme: (...args) => { calls.push(["theme", ...args]); }, destroy: () => { calls.push(["destroy"]); },
+ setVisible: (...args) => { calls.push(["visibility", ...args]); },
};
const send = (data: Record<string, unknown>) => port.onmessage?.({data: {version: 1, instanceID: "one", ...data}});
return {replies, calls, port, adapter, send};
@@ -75,6 +76,29 @@ describe("isolated map runtime lifecycle", () => {
assert.equal(replies.length, 0);
assert.equal(calls.filter((call) => call[0] === "destroy").length, 1);
});
+ it("passes only fixed attribution identifiers and visibility booleans through the runtime", async () => {
+ const {port, adapter, replies, calls, send} = fixture();
+ let callbacks: AVMapAdapterCallbacks;
+ const stop = startAVMapRuntime(port as unknown as MessagePort, "one", "openfreemap", {} as HTMLElement,
+ async (_init, _container, value) => {
+ callbacks = value;
+ value.onAttributionClick("maplibre");
+ return adapter;
+ });
+ await send({type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 800, height: 600}});
+ await send({type: "init", provider: "openfreemap", theme: "light"});
+ assert.deepEqual(replies.map(reply => reply.type), ["ready"]);
+ await send({type: "visibility", visible: "true"});
+ const viewport = {x: 0, y: 50, width: 800, height: 550};
+ await send({type: "visibility", visible: true, viewport});
+ await send({type: "visibility", visible: false});
+ assert.deepEqual(calls.filter(call => call[0] === "visibility"), [["visibility", true, viewport], ["visibility", false, undefined]]);
+ callbacks.onAttributionClick("maplibre");
+ callbacks.onAttributionClick("https://evil.invalid/" as any);
+ assert.deepEqual(replies[1], {version: 1, instanceID: "one", type: "attributionClick", link: "maplibre"});
+ stop(); callbacks.onAttributionClick("maplibre");
+ assert.equal(replies.length, 2);
+ });
it("never initializes a removed provider", async () => {
for (const provider of ["amap", "tencent", "baidu"]) {
const {port, replies, send} = fixture();
diff --git a/app/src/protyle/render/av/map/hostRuntime.ts b/app/src/protyle/render/av/map/hostRuntime.ts
index 7229b65c41..76319d0778 100644
--- a/app/src/protyle/render/av/map/hostRuntime.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.ts
@@ -1,5 +1,5 @@
import {
- AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, getAVMapLoadErrorCode, isAVMapHandshake, isAVMapProvider,
+ AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, getAVMapLoadErrorCode, isAVMapAttributionLink, isAVMapHandshake, isAVMapProvider,
parseAVMapCommand,
} from "./protocol";
import {AVMapAdapter, AVMapAdapterCallbacks} from "./providers";
@@ -81,6 +81,11 @@ export const startAVMapRuntime = (port: MessagePort, instanceID: string, provide
}
},
onError: fail,
+ onAttributionClick: link => {
+ if (adapter && isAVMapAttributionLink(link)) {
+ send({...envelope, type: "attributionClick", link});
+ }
+ },
}, abort.signal);
if (destroyed) {
next.destroy();
@@ -103,6 +108,8 @@ export const startAVMapRuntime = (port: MessagePort, instanceID: string, provide
adapter.fit();
} else if (adapter && command.type === "resize") {
adapter.resize();
+ } else if (adapter && command.type === "visibility") {
+ adapter.setVisible(command.visible, command.viewport);
}
} catch (error) {
fail(getAVMapLoadErrorCode(error) || (adapter ? "mapUnavailable" : "sdkUnavailable"));
diff --git a/app/src/protyle/render/av/map/protocol.test.ts b/app/src/protyle/render/av/map/protocol.test.ts
index 605232cf7d..fc2779e272 100644
--- a/app/src/protyle/render/av/map/protocol.test.ts
+++ b/app/src/protyle/render/av/map/protocol.test.ts
@@ -10,7 +10,7 @@ describe("isolated map protocol", () => {
const point = {id: "row-1", longitude: 0, latitude: 0};
it("keeps attribution destinations in a fixed official allowlist", () => {
assert.deepEqual(AV_MAP_ATTRIBUTION_LINKS.openfreemap.map((link) => link.href), [
- "https://openfreemap.org", "https://www.openmaptiles.org/", "https://www.openstreetmap.org/copyright",
+ "https://openfreemap.org", "https://www.openmaptiles.org/", "https://www.openstreetmap.org/copyright", "https://maplibre.org/",
]);
assert.deepEqual(Object.keys(AV_MAP_ATTRIBUTION_LINKS), ["openfreemap"]);
Object.values(AV_MAP_ATTRIBUTION_LINKS).flat().forEach((link) => {
@@ -18,6 +18,30 @@ describe("isolated map protocol", () => {
assert.equal(/[<>]/.test(link.label), false);
});
});
+ it("accepts only fixed attribution identifiers across both protocol boundaries", () => {
+ const {parseMapReply, parseMapCommand} = require("../../../../../electron/mapHostPolicy");
+ for (const {id: link} of AV_MAP_ATTRIBUTION_LINKS.openfreemap) {
+ const reply = {version: 1, instanceID: "one", type: "attributionClick", link};
+ assert.deepEqual(parseAVMapReply({...reply, href: "https://evil.invalid/", url: "private"}, "one"), reply);
+ assert.deepEqual(parseMapReply({...reply, href: "https://evil.invalid/", url: "private"}, "one"), reply);
+ assert.equal(parseAVMapReply(reply, "old"), undefined);
+ }
+ for (const link of ["https://maplibre.org/", "https://evil.invalid/", "maplibre?secret", "", {}, null]) {
+ const reply = {version: 1, instanceID: "one", type: "attributionClick", link};
+ assert.equal(parseAVMapReply(reply, "one"), undefined);
+ assert.equal(parseMapReply(reply, "one"), undefined);
+ }
+ const visibility = {version: 1, instanceID: "one", type: "visibility", visible: true,
+ viewport: {x: 0, y: 50, width: 800, height: 550}};
+ assert.deepEqual(parseAVMapCommand(visibility, "one"), visibility);
+ assert.equal(parseAVMapCommand({...visibility, viewport: {x: 0, y: 0, width: -1, height: 500}}, "one"), undefined);
+ for (const value of [NaN, Infinity, "0", -1, 32769]) {
+ assert.equal(parseAVMapCommand({...visibility, viewport: {...visibility.viewport, x: value}}, "one"), undefined);
+ }
+ assert.deepEqual(parseAVMapCommand({...visibility, viewport: {...visibility.viewport, url: "secret"}}, "one"), visibility);
+ assert.equal(parseAVMapCommand({...visibility, visible: "true"}, "one"), undefined);
+ assert.equal(parseMapCommand(visibility, "one"), undefined, "the owner cannot override native visibility");
+ });
it("copies only identifiers and WGS84 coordinates", () => {
const input = {...point, name: "Private place", title: "Private record", document: "secret", token: "secret",
originalInput: "sensitive source"};
diff --git a/app/src/protyle/render/av/map/protocol.ts b/app/src/protyle/render/av/map/protocol.ts
index 61bc2ad26c..d1269d1e0a 100644
--- a/app/src/protyle/render/av/map/protocol.ts
+++ b/app/src/protyle/render/av/map/protocol.ts
@@ -4,6 +4,10 @@ export const AV_MAP_MERCATOR_MAX_LATITUDE = 85.0511287798066;
export type AVMapProvider = "openfreemap";
export type AVMapTheme = "light" | "dark";
+export type AVMapAttributionLink = "openfreemap" | "openmaptiles" | "openstreetmap" | "maplibre";
+// 可见矩形使用隔离文档视口的 CSS 像素,原生裁剪的平移已包含在 DOM 坐标中。
+export interface AVMapViewport { x: number; y: number; width: number; height: number; }
+export interface AVMapVisibility { visible: boolean; viewport?: AVMapViewport; }
export type AVMapLoadErrorCode = "sdkScriptLoadFailed" | "sdkGlobalMissing" |
"mapCreationFailed" | "mapReadyTimeout";
export type AVMapHostErrorCode = "hostLimitReached" | "hostSetupFailed" | "hostAttachFailed" |
@@ -39,15 +43,20 @@ export class AVMapLoadError extends Error {
export const getAVMapLoadErrorCode = (error: unknown): AVMapLoadErrorCode | undefined =>
error instanceof AVMapLoadError && isAVMapLoadErrorCode(error.code) ? error.code : undefined;
-// 父页面仅展示固定官方署名链接,不接受隔离框架返回的 URL 或 HTML。
-export const AV_MAP_ATTRIBUTION_LINKS: Readonly<Record<AVMapProvider, ReadonlyArray<{label: string; href: string}>>> = {
+// 父页面仅从固定标识解析官方署名链接,不接受隔离框架返回的 URL 或 HTML。
+export const AV_MAP_ATTRIBUTION_LINKS: Readonly<Record<AVMapProvider,
+ ReadonlyArray<{id: AVMapAttributionLink; label: string; href: string}>>> = {
openfreemap: [
- {label: "OpenFreeMap", href: "https://openfreemap.org"},
- {label: "© OpenMapTiles", href: "https://www.openmaptiles.org/"},
- {label: "© OpenStreetMap", href: "https://www.openstreetmap.org/copyright"},
+ {id: "openfreemap", label: "OpenFreeMap", href: "https://openfreemap.org"},
+ {id: "openmaptiles", label: "© OpenMapTiles", href: "https://www.openmaptiles.org/"},
+ {id: "openstreetmap", label: "© OpenStreetMap", href: "https://www.openstreetmap.org/copyright"},
+ {id: "maplibre", label: "MapLibre", href: "https://maplibre.org/"},
],
};
+export const isAVMapAttributionLink = (value: unknown): value is AVMapAttributionLink =>
+ AV_MAP_ATTRIBUTION_LINKS.openfreemap.some(link => link.id === value);
+
export interface AVMapPoint {
id: string;
longitude: number;
@@ -68,9 +77,11 @@ export interface AVMapInit extends AVMapEnvelope {
export type AVMapCommand = AVMapInit |
(AVMapEnvelope & {type: "setPoints"; revision: number; points: AVMapPoint[]}) |
(AVMapEnvelope & {type: "theme"; theme: AVMapTheme}) |
+ (AVMapEnvelope & {type: "visibility"} & AVMapVisibility) |
(AVMapEnvelope & {type: "fit" | "resize" | "destroy"});
export type AVMapReply = (AVMapEnvelope & {type: "ready"}) |
+ (AVMapEnvelope & {type: "attributionClick"; link: AVMapAttributionLink}) |
(AVMapEnvelope & {type: "markerClick"; id: string; revision: number}) |
(AVMapEnvelope & {type: "error"; code: AVMapErrorCode});
@@ -113,6 +124,14 @@ export const sanitizeAVMapPoints = (input: unknown): AVMapPoint[] => {
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
+const parseAVMapViewport = (value: unknown): AVMapViewport | undefined => {
+ const rect = asRecord(value);
+ if (!rect || ![rect.x, rect.y, rect.width, rect.height].every(number =>
+ typeof number === "number" && Number.isFinite(number) && number >= 0 && number <= 32768) ||
+ (rect.width as number) <= 0 || (rect.height as number) <= 0) return;
+ return {x: rect.x as number, y: rect.y as number, width: rect.width as number, height: rect.height as number};
+};
+
export const parseAVMapCommand = (value: unknown, instanceID: string, provider?: AVMapProvider): AVMapCommand | undefined => {
const input = asRecord(value);
if (!input || input.version !== AV_MAP_PROTOCOL_VERSION || input.instanceID !== instanceID) {
@@ -133,6 +152,13 @@ export const parseAVMapCommand = (value: unknown, instanceID: string, provider?:
points: sanitizeAVMapPoints(input.points)};
case "theme":
return isAVMapTheme(input.theme) ? {...envelope, type: "theme", theme: input.theme} : undefined;
+ case "visibility": {
+ if (typeof input.visible !== "boolean") return;
+ if (!input.visible) return {...envelope, type: "visibility", visible: false};
+ if (input.viewport === undefined) return {...envelope, type: "visibility", visible: true};
+ const viewport = parseAVMapViewport(input.viewport);
+ return viewport ? {...envelope, type: "visibility", visible: true, viewport} : undefined;
+ }
case "fit":
case "resize":
case "destroy":
@@ -152,6 +178,9 @@ export const parseAVMapReply = (value: unknown, instanceID: string): AVMapReply
if (input.type === "markerClick" && isAVMapIdentifier(input.id) && isAVMapRevision(input.revision)) {
return {...envelope, type: "markerClick", id: input.id, revision: input.revision};
}
+ if (input.type === "attributionClick" && isAVMapAttributionLink(input.link)) {
+ return {...envelope, type: "attributionClick", link: input.link};
+ }
if (input.type === "error" && (["unsupportedEnvironment", "invalidConfiguration",
"hostUnavailable", "sdkUnavailable", "mapUnavailable"].includes(input.code as string) ||
isAVMapLoadErrorCode(input.code) || isAVMapHostErrorCode(input.code))) {
diff --git a/app/src/protyle/render/av/map/providers.test.ts b/app/src/protyle/render/av/map/providers.test.ts
index df44c11a7a..98016cdb53 100644
--- a/app/src/protyle/render/av/map/providers.test.ts
+++ b/app/src/protyle/render/av/map/providers.test.ts
@@ -1,10 +1,32 @@
import * as assert from "node:assert/strict";
import {test} from "node:test";
import {AV_MAP_OPENFREEMAP_STYLE, createAVMapAdapter} from "./providers";
+import {AV_MAP_ATTRIBUTION_LINKS} from "./protocol";
const fixture = () => {
const instances: any[] = [];
const calls: Array<[string, ...any[]]> = [];
+ const frames = new Map<number, (now: number) => void>();
+ const events = new Map<string, (event: any) => void>();
+ const documentEvents = new Map<string, () => void>();
+ 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)},
+ 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};
+ 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,
+ addEventListener: (name: string, callback: () => void) => documentEvents.set(name, callback),
+ removeEventListener: (name: string) => documentEvents.delete(name)};
class SDKObject {
callbacks = new Map<string, (...args: any[]) => void>();
constructor(...args: any[]) { calls.push([new.target.name, ...args]); instances.push(this); }
@@ -19,13 +41,30 @@ const fixture = () => {
fitBounds(...args: any[]) { calls.push(["fitBounds", ...args]); }
resize() { calls.push(["resize"]); }
extend(...args: any[]) { calls.push(["extend", ...args]); }
+ addControl(control: unknown) { calls.push(["addControl", control]); }
}
const sdk = {Map: class Map extends SDKObject {}, Marker: class Marker extends SDKObject {},
- LngLatBounds: class LngLatBounds extends SDKObject {}};
- const container = {ownerDocument: {documentElement: {dataset: {}}}, replaceChildren() { calls.push(["clear"]); }};
- return {sdk, calls, instances, container: container as unknown as HTMLElement};
+ LngLatBounds: class LngLatBounds extends SDKObject {}, AttributionControl: class AttributionControl extends SDKObject {}};
+ const container = {ownerDocument: doc, querySelector: () => attribution,
+ replaceChildren() { calls.push(["clear"]); }};
+ return {sdk, calls, instances, container: container as unknown as HTMLElement, attribution, frames, events, doc, scope, rect,
+ load: () => instances[0].callbacks.get("load")(),
+ advance: (milliseconds: number) => {
+ now += milliseconds;
+ const pending = [...frames.values()]; frames.clear(); pending.forEach(callback => callback(now));
+ },
+ visibility: (hidden: boolean) => { doc.hidden = hidden; documentEvents.get("visibilitychange")?.(); },
+ click: (href?: string, values: Record<string, unknown> = {}) => {
+ anchor.href = href;
+ const event = {target: href === undefined ? summary : anchor, isTrusted: true, button: 0,
+ preventDefault() { this.prevented = true; }, stopImmediatePropagation() {}, ...values};
+ events.get("click")?.(event);
+ return event;
+ }};
};
+const visibleViewport = {x: 0, y: 0, width: 800, height: 600};
+
test("OpenFreeMap preserves longitude/latitude, attribution and cleans stale callbacks", () => {
const {sdk, calls, instances, container} = fixture();
const clicked: Array<[string, number]> = [];
@@ -39,7 +78,9 @@ test("OpenFreeMap preserves longitude/latitude, attribution and cleans stale cal
oldClick();
assert.deepEqual(clicked, [["row-1", 1]]);
assert.equal(calls.find(call => call[0] === "Map")[1].style, AV_MAP_OPENFREEMAP_STYLE);
- assert.equal(calls.find(call => call[0] === "Map")[1].attributionControl, true);
+ assert.equal(calls.find(call => call[0] === "Map")[1].attributionControl, false);
+ assert.equal(calls.find(call => call[0] === "AttributionControl")[1].compact, true);
+ assert.match(calls.find(call => call[0] === "AttributionControl")[1].customAttribution, /https:\/\/maplibre.org\//);
assert.deepEqual(calls.filter(call => call[0] === "setLngLat"), [["setLngLat", [121, 31]]]);
adapter.fit();
adapter.resize();
@@ -63,6 +104,95 @@ test("OpenFreeMap preserves longitude/latitude, attribution and cleans stale cal
assert.equal(calls.filter(call => call[0] === "clear").length, 1);
});
+test("attribution waits for five continuously visible seconds after load and stays expandable", () => {
+ const f = fixture();
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
+ f.advance(10000);
+ assert.equal(f.attribution.open, true);
+ adapter.setVisible(true, visibleViewport);
+ f.advance(10000);
+ assert.equal(f.attribution.open, true, "no clock before the map loads");
+ f.load(); f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true);
+ adapter.setVisible(false); f.advance(10000); adapter.setVisible(true, visibleViewport); f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true, "hidden native views cannot consume the initial display");
+ f.visibility(true); f.advance(10000); f.visibility(false); f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true, "background tabs restart the display clock");
+ f.rect.bottom = 700; f.advance(1); f.rect.bottom = 24; f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true, "cropped attribution cannot consume display time");
+ f.advance(1);
+ assert.equal(f.attribution.open, false);
+ assert.equal(f.frames.size, 0);
+ f.click(undefined, {isTrusted: false});
+ assert.equal(f.attribution.open, false);
+ f.click();
+ assert.equal(f.attribution.open, true);
+ f.advance(20000);
+ f.attribution.open = false;
+ f.instances[0].callbacks.get("drag")();
+ assert.equal(f.attribution.open, true, "map interaction preserves the user's expanded choice");
+ adapter.destroy();
+ assert.equal(f.events.size, 0);
+ assert.equal(f.frames.size, 0);
+});
+
+test("trusted attribution interaction cancels auto-collapse and only exact official links leave the frame", () => {
+ 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.advance(2000);
+ f.events.get("keydown")({isTrusted: true});
+ f.advance(10000);
+ assert.equal(f.attribution.open, true);
+ for (const link of AV_MAP_ATTRIBUTION_LINKS.openfreemap) {
+ assert.equal((f.click(link.href) as any).prevented, true);
+ }
+ assert.deepEqual(clicked, AV_MAP_ATTRIBUTION_LINKS.openfreemap.map(link => link.id));
+ for (const href of ["https://maplibre.org/?secret=x", "https://maplibre.org/#secret", "https://maplibre.org:443/",
+ "http://maplibre.org/", "javascript:alert(1)", "https://evil.invalid/", "https://maplibre.org.evil.invalid/"]) {
+ f.click(href);
+ }
+ f.click("https://maplibre.org/", {isTrusted: false});
+ f.click("https://maplibre.org/", {button: 1});
+ f.scope.navigator.userActivation.isActive = false;
+ f.click("https://maplibre.org/");
+ f.scope.navigator.userActivation.isActive = true;
+ adapter.setVisible(false); f.click("https://maplibre.org/");
+ assert.equal(clicked.length, 4);
+ adapter.destroy();
+ f.click("https://maplibre.org/");
+ assert.equal(clicked.length, 4);
+});
+
+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() {}});
+ f.load();
+ Object.assign(f.rect, {left: 480, right: 780, top: 560, bottom: 584});
+ adapter.setVisible(true, {x: 0, y: 0, width: 800, height: 500});
+ f.advance(0); f.advance(10000);
+ assert.equal(f.attribution.open, true, "a clipped bottom edge cannot consume display time");
+ adapter.setVisible(true, {x: 0, y: 100, width: 800, height: 500});
+ f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true);
+ f.advance(1);
+ assert.equal(f.attribution.open, false, "a hidden top edge still permits five seconds of visible attribution");
+ adapter.destroy();
+
+ const native = fixture();
+ const nativeAdapter = createAVMapAdapter("openfreemap", native.sdk, native.container, {onMarkerClick() {}, onError() {}});
+ native.load();
+ // DOM 矩形已经包含原生 preload 的 translate(-crop),此处不再传入或减去 crop。
+ Object.assign(native.rect, {left: 280, right: 580, top: 160, bottom: 184});
+ native.scope.innerWidth = 600; native.scope.innerHeight = 200;
+ nativeAdapter.setVisible(true, {x: 0, y: 0, width: 600, height: 200});
+ native.advance(0); native.advance(5000);
+ assert.equal(native.attribution.open, false);
+ nativeAdapter.destroy();
+});
+
test("removed providers cannot create a map", () => {
for (const provider of ["amap", "tencent", "baidu"]) {
const {sdk, calls, container} = fixture();
diff --git a/app/src/protyle/render/av/map/providers.ts b/app/src/protyle/render/av/map/providers.ts
index 87feb2cc59..98be094ed4 100644
--- a/app/src/protyle/render/av/map/providers.ts
+++ b/app/src/protyle/render/av/map/providers.ts
@@ -1,4 +1,7 @@
-import {AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, sanitizeAVMapPoints} from "./protocol";
+import {
+ AV_MAP_ATTRIBUTION_LINKS, AVMapAttributionLink, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapViewport,
+ sanitizeAVMapPoints,
+} from "./protocol";
export const AV_MAP_OPENFREEMAP_STYLE = "https://tiles.openfreemap.org/styles/liberty";
@@ -7,6 +10,7 @@ export interface AVMapAdapter {
fit: () => void;
resize: () => void;
setTheme: (theme: AVMapTheme) => void;
+ setVisible: (visible: boolean, viewport?: AVMapViewport) => void;
destroy: () => void;
}
@@ -14,6 +18,7 @@ export interface AVMapAdapterCallbacks {
onMarkerClick: (id: string, revision: number) => void;
onError: (code: AVMapErrorCode) => void;
onReady?: () => void;
+ onAttributionClick?: (link: AVMapAttributionLink) => void;
}
// The SDK is loaded only in the isolated web entry, never in the main interface.
@@ -31,10 +36,100 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
const error = () => {
if (!destroyed) callbacks.onError("mapUnavailable");
};
+ const doc = container.ownerDocument;
+ const scope = doc.defaultView;
const map = new sdk.Map({container, style: AV_MAP_OPENFREEMAP_STYLE, center: [0, 0], zoom: 1,
- attributionControl: true, trackResize: false});
+ attributionControl: false, trackResize: false});
+ const maplibre = AV_MAP_ATTRIBUTION_LINKS[provider].find(link => link.id === "maplibre");
+ 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");
+ let loaded = false, visible = false, expanded = true, automatic = true;
+ let viewport: AVMapViewport;
+ let frame = 0, visibleSince: number;
+ const syncAttribution = () => {
+ // MapLibre 的紧凑控件同时使用 details 状态和此 CSS 类。
+ attribution.open = expanded;
+ attribution.classList.toggle("maplibregl-compact-show", expanded);
+ };
+ const stopCollapse = () => {
+ scope.cancelAnimationFrame(frame);
+ frame = 0;
+ visibleSince = undefined;
+ };
+ const attributionVisible = () => {
+ if (!viewport || doc.hidden || !attribution.getClientRects().length || !attribution.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 =>
+ attribution.contains(doc.elementFromPoint(x, y))));
+ };
+ const tickAttribution = (now: number) => {
+ frame = 0;
+ if (destroyed || !automatic || !loaded || !visible || doc.hidden) return;
+ if (attributionVisible()) {
+ if (visibleSince === undefined) visibleSince = now;
+ if (now - visibleSince >= 5000) {
+ automatic = false;
+ expanded = false;
+ syncAttribution();
+ return;
+ }
+ } else {
+ visibleSince = undefined;
+ }
+ frame = scope.requestAnimationFrame(tickAttribution);
+ };
+ const updateVisibility = () => {
+ stopCollapse();
+ if (!destroyed && automatic && loaded && visible && !doc.hidden) {
+ frame = scope.requestAnimationFrame(tickAttribution);
+ }
+ };
+ const onAttributionInteraction = (event: Event) => {
+ if (!event.isTrusted ||
+ !(scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) return;
+ automatic = false;
+ stopCollapse();
+ };
+ const onAttributionClick = (event: MouseEvent) => {
+ const target = event.target as Element;
+ const anchor = target.closest<HTMLAnchorElement>("a");
+ const summary = target.closest("summary");
+ if (!anchor && !summary) return;
+ // 不向供应商文档授予导航或弹窗权限。
+ 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 (summary) {
+ expanded = !expanded;
+ syncAttribution();
+ } else if (attribution.contains(anchor)) {
+ const link = AV_MAP_ATTRIBUTION_LINKS[provider].find(item => item.href === anchor.getAttribute("href"));
+ if (link) callbacks.onAttributionClick?.(link.id);
+ }
+ };
+ attribution.addEventListener("click", onAttributionClick, true);
+ attribution.addEventListener("auxclick", onAttributionClick, true);
+ attribution.addEventListener("pointerdown", onAttributionInteraction, true);
+ attribution.addEventListener("keydown", onAttributionInteraction, true);
+ doc.addEventListener("visibilitychange", updateVisibility);
+ // MapLibre 拖动时会收起署名,保留首次展示时间及用户主动选择的展开状态。
+ map.on("drag", syncAttribution);
+ map.on("resize", syncAttribution);
+ syncAttribution();
const onReady = () => {
- if (!destroyed) callbacks.onReady?.();
+ if (!destroyed) {
+ loaded = true;
+ syncAttribution();
+ updateVisibility();
+ callbacks.onReady?.();
+ }
};
map.on("error", error);
map.on("load", onReady);
@@ -72,9 +167,24 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
setTheme: theme => {
if (!destroyed) container.ownerDocument.documentElement.dataset.theme = theme;
},
+ setVisible: (nextVisible, nextViewport) => {
+ if (!destroyed && (visible !== nextVisible || JSON.stringify(viewport) !== JSON.stringify(nextViewport))) {
+ visible = nextVisible;
+ viewport = nextViewport;
+ updateVisibility();
+ }
+ },
destroy: () => {
if (destroyed) return;
destroyed = true;
+ stopCollapse();
+ attribution.removeEventListener("click", onAttributionClick, true);
+ attribution.removeEventListener("auxclick", onAttributionClick, true);
+ attribution.removeEventListener("pointerdown", onAttributionInteraction, true);
+ attribution.removeEventListener("keydown", onAttributionInteraction, true);
+ doc.removeEventListener("visibilitychange", updateVisibility);
+ map.off("drag", syncAttribution);
+ map.off("resize", syncAttribution);
map.off("load", onReady);
cleanMarkers();
points = [];
diff --git a/app/src/protyle/render/av/map/providersLoader.test.ts b/app/src/protyle/render/av/map/providersLoader.test.ts
index 7671b34739..91f883fceb 100644
--- a/app/src/protyle/render/av/map/providersLoader.test.ts
+++ b/app/src/protyle/render/av/map/providersLoader.test.ts
@@ -16,11 +16,13 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
if (options.ready !== false && type === "load") queueMicrotask(callback);
}
off() {}
+ addControl() {}
remove() { destroyed++; }
}
const scope: any = {
- setTimeout, clearTimeout,
- maplibregl: options.missingSDK ? undefined : {Map: FakeMap, setWorkerUrl: (url: string) => requested.push({worker: url})},
+ setTimeout, clearTimeout, cancelAnimationFrame() {},
+ maplibregl: options.missingSDK ? undefined : {Map: FakeMap, AttributionControl: class {},
+ setWorkerUrl: (url: string) => requested.push({worker: url})},
fetch: async (url: string, options: unknown) => {
requested.push({url, options});
return {ok: true, text: async () => "/* fixture worker */"};
@@ -28,6 +30,7 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
};
const document: any = {
defaultView: scope, documentElement: {dataset: {}},
+ addEventListener() {}, removeEventListener() {},
createElement: (tag: string) => ({tag, remove() {}}),
head: {appendChild: (element: any) => {
requested.push({tag: element.tag, src: element.src, href: element.href, referrerPolicy: element.referrerPolicy,
@@ -36,7 +39,9 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
}},
};
scope.document = document;
- const container = {ownerDocument: document, replaceChildren() {}} as unknown as HTMLElement;
+ const container = {ownerDocument: document, replaceChildren() {}, querySelector: () => ({
+ classList: {toggle() {}}, addEventListener() {}, removeEventListener() {},
+ })} as unknown as HTMLElement;
return {scope, requested, container, destroyed: () => destroyed};
};
const init: AVMapInit = {version: 1, instanceID: "fixture", type: "init", provider: "openfreemap", theme: "light"};
diff --git a/app/src/protyle/render/av/map/render.test.ts b/app/src/protyle/render/av/map/render.test.ts
index def6d0288f..d5cd4b6767 100644
--- a/app/src/protyle/render/av/map/render.test.ts
+++ b/app/src/protyle/render/av/map/render.test.ts
@@ -52,6 +52,7 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
const hosts: Array<{options: AVMapHostOptions; points: protocol.AVMapPoint[]; revision: number;
destroyed: boolean; fitted: boolean}> = [];
const opened: unknown[] = [];
+ const openedLinks: unknown[] = [];
const calls: string[] = [];
const transactions: Array<{perform: IOperation[]; undo: IOperation[]; callback: () => void}> = [];
let settleTransaction: () => void;
@@ -125,12 +126,13 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
}).outputText, {exports: methods, require: (id: string) => modules[id] || {},
window: {...context, location: {protocol: "https:"},
+ open: (...args: unknown[]) => openedLinks.push(args),
addEventListener: (type: string, callback: () => void) => events.set(type, callback),
removeEventListener: (type: string) => events.delete(type)},
navigator: {userAgent: "Mozilla/5.0", onLine: options.online !== false},
document: {createElement: () => new ElementStub(), documentElement: {getAttribute: () => "light"}},
MutationObserver: Observer, ResizeObserver: Observer, Lute: {NewNodeID: () => "new-location"}});
- return {data, protyle, calls, hosts, roots, records, opened, events, observers, destroyMap, transactions, context,
+ return {data, protyle, calls, hosts, roots, records, opened, openedLinks, events, observers, destroyMap, transactions, context,
refreshes: () => refreshes,
completeTransaction: async (success = true) => {
if (success) transactions[transactions.length - 1].callback();
@@ -144,6 +146,19 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
status: () => root.querySelector(".av__map-status").textContent};
};
+test("map attribution stays inside the control and parent opens only fixed current destinations", async () => {
+ const scenario = setup();
+ await scenario.render();
+ const {options} = scenario.hosts[0];
+ assert.doesNotMatch(scenario.roots[0].innerHTML, /data-map-attribution/);
+ options.onAttributionClick("maplibre");
+ options.onAttributionClick("https://evil.invalid/" as any);
+ assert.deepEqual(scenario.openedLinks, [["https://maplibre.org/", "_blank", "noopener,noreferrer"]]);
+ scenario.destroyMap();
+ options.onAttributionClick("openstreetmap");
+ assert.equal(scenario.openedLinks.length, 1);
+});
+
test("published maps render a status without inline settings, runtime admission, or SDK calls", async () => {
const scenario = setup({published: true});
await scenario.render();
@@ -156,7 +171,7 @@ test("published maps render a status without inline settings, runtime admission,
test("missing field, unavailable host, offline and unsupported projection maps never request runtime admission", async () => {
for (const option of [{hostSupported: false}, {online: false}, {}]) {
const scenario = setup(option);
- if (!Object.keys(option).length) (scenario.data.view as IAVTable).map.locationKeyID = "";
+ if (!Object.keys(option).length) (scenario.data.view as IAVTable).columns = [];
await scenario.render();
assert.deepEqual(scenario.calls, []);
assert.equal(scenario.hosts.length, 0);
@@ -168,8 +183,8 @@ test("missing field, unavailable host, offline and unsupported projection maps n
assert.equal(incompatible.status(), "mapNoMarkers");
});
-test("unconfigured, deleted and changed-type map fields show a repairable location setup", async () => {
- for (const locationKeyID of ["", "deleted", "text"]) {
+test("deleted and changed-type map fields show a repairable location setup", async () => {
+ for (const locationKeyID of ["deleted", "text"]) {
const scenario = setup();
(scenario.data.view as IAVTable).map.locationKeyID = locationKeyID;
await scenario.render();
@@ -185,9 +200,27 @@ test("unconfigured, deleted and changed-type map fields show a repairable locati
assert.deepEqual(scenario.calls, []);
}
const empty = setup();
+ (empty.data.view as IAVTable).map.locationKeyID = "";
(empty.data.view as IAVTable).columns = [];
await empty.render();
assert.match(empty.setupHTML(), /data-map-create-field/);
+ assert.match(empty.setupHTML(), /mapSelectLocationField/);
+});
+
+test("unconfigured maps render existing location fields without submitting settings transactions", async () => {
+ for (const mode of ["editable", "readonly", "published", "history"]) {
+ const scenario = setup({published: mode === "published"});
+ const view = scenario.data.view as IAVTable;
+ view.map.locationKeyID = "";
+ scenario.protyle.disabled = mode === "readonly";
+ if (mode === "history") scenario.protyle.options.history = {created: "version"};
+ const before = JSON.stringify(view);
+ await scenario.render();
+ assert.equal(JSON.stringify(view), before);
+ assert.equal(scenario.transactions.length, 0);
+ assert.equal(scenario.hosts.length, mode === "editable" || mode === "readonly" ? 1 : 0);
+ assert.doesNotMatch(scenario.setupHTML(), /data-map-create-field/);
+ }
});
test("selecting an existing location field submits one undoable transaction and refreshes after success", async () => {
@@ -224,6 +257,7 @@ test("selecting an existing location field submits one undoable transaction and
test("adding a location field atomically creates, selects and hides it with an undo restoring the previous field", async () => {
const scenario = setup();
(scenario.data.view as IAVTable).map.locationKeyID = "";
+ (scenario.data.view as IAVTable).columns = [];
await scenario.render();
const create = scenario.control("[data-map-create-field]");
create.events.get("click")();
@@ -250,7 +284,7 @@ test("map setup hides write controls for readonly, published and history modes",
const scenario = setup({published: mode === "published"});
scenario.protyle.disabled = mode === "disabled";
if (["created", "snapshot"].includes(mode)) scenario.protyle.options.history = {[mode]: "version"};
- (scenario.data.view as IAVTable).map.locationKeyID = "";
+ (scenario.data.view as IAVTable).map.locationKeyID = "deleted";
await scenario.render();
assert.doesNotMatch(scenario.setupHTML(), /data-map-location-field|data-map-create-field/);
if (mode === "disabled") assert.match(scenario.setupHTML(), /av__map-empty/);
@@ -261,7 +295,7 @@ test("map setup hides write controls for readonly, published and history modes",
test("stale setup controls and permissions changed after render cannot submit a transaction", async () => {
for (const mode of ["disabled", "published", "created", "snapshot", "destroyed", "removed", "rerendered"]) {
const scenario = setup();
- (scenario.data.view as IAVTable).map.locationKeyID = "";
+ (scenario.data.view as IAVTable).map.locationKeyID = "deleted";
await scenario.render();
const select = scenario.control("[data-map-location-field]");
const create = scenario.control("[data-map-create-field]");
@@ -281,6 +315,7 @@ test("stale setup controls and permissions changed after render cannot submit a
test("failed setup transactions reenable controls, while late completion cannot refresh a destroyed map", async () => {
const scenario = setup();
(scenario.data.view as IAVTable).map.locationKeyID = "";
+ (scenario.data.view as IAVTable).columns = [];
await scenario.render();
const create = scenario.control("[data-map-create-field]");
create.events.get("click")();
@@ -298,7 +333,7 @@ test("failed setup transactions reenable controls, while late completion cannot
test("late setup transaction completions cannot refresh a removed or superseded view", async () => {
for (const mode of ["removed", "rerendered"]) {
const scenario = setup();
- (scenario.data.view as IAVTable).map.locationKeyID = "";
+ (scenario.data.view as IAVTable).map.locationKeyID = "deleted";
await scenario.render();
scenario.control("[data-map-create-field]").events.get("click")();
if (mode === "removed") scenario.roots[0].remove();
diff --git a/app/src/protyle/render/av/map/render.ts b/app/src/protyle/render/av/map/render.ts
index c74de7a810..40bd518c3a 100644
--- a/app/src/protyle/render/av/map/render.ts
+++ b/app/src/protyle/render/av/map/render.ts
@@ -17,7 +17,7 @@ const getTheme = () => document.documentElement.getAttribute("data-theme-mode")
const renderMapSetup = (root: HTMLElement, blockElement: HTMLElement, protyle: IProtyle,
data: IAV, current: () => boolean) => {
const view = data.view as IAVTable;
- const previous = getMapSettings(view);
+ const previous = {locationKeyID: view.map?.locationKeyID || ""};
const editable = canEditMapSettings(protyle);
const message = previous.locationKeyID ? window.siyuan.languages.mapMissingLocationField :
window.siyuan.languages.mapSelectLocationField;
@@ -104,13 +104,11 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
<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>
-<div class="ft__smaller fn__none" data-map-attribution></div>
`;
records.before(root);
["click", "keydown", "pointerdown"].forEach(type => root.addEventListener(type, event => event.stopPropagation()));
const status = root.querySelector<HTMLElement>(".av__map-status");
const canvas = root.querySelector<HTMLElement>(".av__map-canvas");
- const attribution = root.querySelector<HTMLElement>("[data-map-attribution]");
let host: AVMapHost;
let themeObserver: MutationObserver;
let resizeObserver: ResizeObserver;
@@ -130,7 +128,6 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
revision++;
host?.destroy();
host = undefined;
- attribution.classList.add("fn__none");
status.textContent = message;
canvas.classList.add("fn__none");
};
@@ -188,9 +185,6 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
const rowByID = new Map(view.rows.map(row => [row.id, row]));
const pointIDs = new Set(points.map(point => point.id));
const activeRevision = ++revision;
- // 固定官方署名链接留在父页,避免为第三方 SDK 放宽沙箱弹窗权限。
- attribution.innerHTML = AV_MAP_ATTRIBUTION_LINKS.openfreemap.map(link =>
- `<a href="${escapeAttr(link.href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(link.label)}</a>`).join(" · ");
canvas.classList.remove("fn__none");
host = (desktopHost ? createDesktopAVMapHost : createAVMapHost)(canvas, {
provider: "openfreemap",
@@ -201,7 +195,12 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
return;
}
status.textContent = "";
- attribution.classList.remove("fn__none");
+ },
+ onAttributionClick: id => {
+ if (!current() || revision !== activeRevision) return;
+ // 仅可信父页面解析固定官方链接,供应商 URL 不跨越隔离边界。
+ const link = AV_MAP_ATTRIBUTION_LINKS.openfreemap.find(item => item.id === id);
+ if (link) window.open(link.href, "_blank", "noopener,noreferrer");
},
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.ts
index d0be7aef9d..096add68eb 100644
--- a/app/src/protyle/render/av/map/settings.test.ts
+++ b/app/src/protyle/render/av/map/settings.test.ts
@@ -77,6 +77,46 @@ test("map field selection uses an undoable transaction without changing cells",
assert.equal(JSON.stringify(operations[0].undo[0].data), JSON.stringify({locationKeyID: "missing-field"}));
});
+test("the default field is displayed without writes and can be explicitly pinned with a raw-state undo", () => {
+ const {methods, operations, menus} = setup();
+ const database = data();
+ const view = database.view as IAVTable;
+ view.map.locationKeyID = "";
+ const before = JSON.stringify(view);
+ assert.match(methods.getMapSettingsHTML(view), /&lt;Location>/);
+ const field = control();
+ methods.bindMapSettings({data: database, protyle: {options: {}} as IProtyle,
+ blockElement: {getAttribute: () => "carrier"} as unknown as Element,
+ menuElement: {querySelectorAll: () => [field]} as unknown as Element});
+ field.handlers.click({preventDefault() {}, stopPropagation() {}});
+ assert.equal(operations.length, 0);
+ assert.equal(JSON.stringify(view), before);
+ assert.equal(menus[0].length, 1);
+ assert.equal(menus[0][0].checked, true);
+ menus[0][0].click();
+ assert.equal(JSON.stringify(operations[0].perform[0].data), JSON.stringify({locationKeyID: "location"}));
+ assert.equal(JSON.stringify(operations[0].undo[0].data), JSON.stringify({locationKeyID: ""}));
+ assert.equal(view.map.locationKeyID, "location");
+});
+
+test("choosing another field from an automatic default keeps the empty binding in undo", () => {
+ const {methods, operations, menus} = setup();
+ const database = data();
+ const view = database.view as IAVTable;
+ view.map.locationKeyID = "";
+ view.columns.push({id: "second", type: "location", name: "Second"});
+ const field = control();
+ methods.bindMapSettings({data: database, protyle: {options: {}} as IProtyle,
+ blockElement: {getAttribute: () => "carrier"} as unknown as Element,
+ menuElement: {querySelectorAll: () => [field]} as unknown as Element});
+ field.handlers.click({preventDefault() {}, stopPropagation() {}});
+ menus[0].find(item => item.label === "Second").click();
+ assert.equal(view.map.locationKeyID, "second");
+ assert.equal(JSON.stringify(operations[0].undo[0].data), JSON.stringify({locationKeyID: ""}));
+ view.map = {locationKeyID: (operations[0].undo[0].data as IAVMapSettings).locationKeyID};
+ assert.equal(state.getMapSettings(view).locationKeyID, "location");
+});
+
test("readonly, history, and published maps cannot change settings", () => {
for (const mode of ["disabled", "history", "published"]) {
const {methods, operations, context} = setup();
diff --git a/app/src/protyle/render/av/map/settings.ts b/app/src/protyle/render/av/map/settings.ts
index af97bbd61d..08f99fca86 100644
--- a/app/src/protyle/render/av/map/settings.ts
+++ b/app/src/protyle/render/av/map/settings.ts
@@ -8,8 +8,10 @@ export const canEditMapSettings = (protyle: IProtyle) => !protyle.disabled && !w
!protyle.options.history?.created && !protyle.options.history?.snapshot;
const getChoices = (view: IAVTable) => {
- const choices = [{value: "", label: window.siyuan.languages.mapSelectLocationField},
- ...view.columns.filter(column => column.type === "location").map(column => ({value: column.id, label: column.name}))];
+ const choices = view.columns.filter(column => column.type === "location").map(column => ({value: column.id, label: column.name}));
+ if (choices.length === 0) {
+ choices.push({value: "", label: window.siyuan.languages.mapSelectLocationField});
+ }
const saved = getMapSettings(view).locationKeyID;
if (saved && !choices.some(choice => choice.value === saved)) {
choices.push({value: saved, label: window.siyuan.languages.mapMissingLocationField});
@@ -42,7 +44,7 @@ export const bindMapSettings = (options: {
}
const update = (locationKeyID: string) => {
if (!canEditMapSettings(options.protyle)) return;
- const previous = getMapSettings(view);
+ const previous = {locationKeyID: view.map?.locationKeyID || ""};
if (previous.locationKeyID === locationKeyID) return;
const next = {locationKeyID};
const operation = {action: "setAttrViewMap" as const, avID: options.data.id,
diff --git a/app/src/protyle/render/av/map/state.test.ts b/app/src/protyle/render/av/map/state.test.ts
index 30c777e4ac..8d12fbb9a8 100644
--- a/app/src/protyle/render/av/map/state.test.ts
+++ b/app/src/protyle/render/av/map/state.test.ts
@@ -52,6 +52,25 @@ test("missing or changed location fields retain their saved identifiers and do n
assert.deepEqual(getMapSettings({} as IAVTable), {locationKeyID: ""});
});
+test("unconfigured maps derive the first location in view order without persisting it", () => {
+ const view = table([{latitude: 0, longitude: 0}]);
+ view.map.locationKeyID = "";
+ const before = JSON.stringify(view);
+ assert.equal(getMapSettings(view).locationKeyID, "location");
+ assert.deepEqual(getMapPoints(view).points, [{id: "row-0", longitude: 0, latitude: 0}]);
+ assert.equal(JSON.stringify(view), before);
+ view.columns.unshift({id: "other", type: "location", hidden: true});
+ assert.equal(getMapSettings(view).locationKeyID, "other");
+ view.map.locationKeyID = "location";
+ assert.equal(getMapSettings(view).locationKeyID, "location");
+ delete view.map;
+ assert.equal(getMapSettings(view).locationKeyID, "other");
+ view.columns = [];
+ assert.equal(getMapSettings(view).locationKeyID, "");
+ view.columns.push({id: "added", type: "location"});
+ assert.equal(getMapSettings(view).locationKeyID, "added");
+});
+
test("map does not silently truncate the loaded page before the explicit rendering limit", () => {
const view = table(Array.from({length: AV_MAP_MAX_POINTS + 1}, () => ({
latitude: 0, longitude: 0,
diff --git a/app/src/protyle/render/av/map/state.ts b/app/src/protyle/render/av/map/state.ts
index 3c56ce22f7..1c408d9e2b 100644
--- a/app/src/protyle/render/av/map/state.ts
+++ b/app/src/protyle/render/av/map/state.ts
@@ -2,8 +2,9 @@ import {hasAVLocationCoordinates, validateAVLocation} from "../locationValue";
import type {AVMapPoint} from "./protocol";
import {isAVMapIdentifier, isAVMapProjectionSupported} from "./protocol";
+// 未配置时按视图顺序派生默认值;读取不写入配置,失效的显式绑定仍由用户修复。
export const getMapSettings = (view: IAVTable): IAVMapSettings => ({
- locationKeyID: view.map?.locationKeyID || "",
+ locationKeyID: view.map?.locationKeyID || view.columns?.find(column => column.type === "location")?.id || "",
});
// 只使用选定字段的已加载行,WGS84 坐标不会被裁切或改写。