Skip to content

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

:bug: Keep map visible beside its unplaced menu https://github.com/siyuan-note/siyuan/issues/20129

Daniel7c655c325531
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index 36ab9b1cad..12465b2867 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -29,6 +29,7 @@
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
+ line-height: 16px;
min-width: 0;
max-width: 100%;
gap: 4px 12px;
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index 395852e09c..4d9bf896f7 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -4,6 +4,7 @@ import {webcrypto} from "node:crypto";
import {describe, it} from "node:test";
import * as ts from "typescript";
import * as protocol from "./protocol";
+import * as unplacedMenu from "./unplacedMenu";
const source = readFileSync(__dirname + "/desktopTransport.ts", "utf8");
const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {
@@ -18,6 +19,7 @@ const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {
const result: any = {};
const requireModule = (name: string) => {
if (name === "./protocol") { return protocol; }
+ if (name === "./unplacedMenu") { return unplacedMenu; }
assert.equal(name, "electron");
assert.equal(browser, false, "browser must not import Electron");
return {ipcRenderer: ipc};
@@ -62,6 +64,7 @@ const fixture = (warnings: unknown[][] = []) => {
addEventListener: (name: string, fn: () => void) => domListeners.set(name, fn),
removeEventListener: (name: string) => domListeners.delete(name),
getComputedStyle: () => ({display: "block", visibility: "visible", opacity: "1", overflowX: "visible", overflowY: "visible",
+ transform: "none", filter: "none", boxShadow: "none", outlineStyle: "none",
getPropertyValue: () => ""})};
doc.defaultView = scope;
const container: any = {ownerDocument: doc, isConnected: true, parentElement: null, closest: (): HTMLElement | null => null,
@@ -299,6 +302,174 @@ describe("desktop map transport", () => {
assert.equal(await load({invoke: async () => ({version: 2, supported: true})}).isDesktopAVMapHostSupported(), false);
assert.equal(await load({invoke: async () => { throw new Error("old main"); }}).isDesktopAVMapHostSupported(), false);
});
+ it("selects the largest safe rectangle around one owned menu and retains the full logical map", () => {
+ const compute = load({}).computeDesktopAVMapGeometry;
+ const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");
+ const rect = {x: 10, y: 20, width: 400, height: 300};
+ const cases = [
+ {menu: {...rect, width: 100}, bounds: {x: 111, y: 20, width: 299, height: 300}},
+ {menu: {...rect, x: 310, width: 100}, bounds: {x: 10, y: 20, width: 299, height: 300}},
+ {menu: {...rect, height: 100}, bounds: {x: 10, y: 121, width: 400, height: 199}},
+ {menu: {...rect, y: 220, height: 100}, bounds: {x: 10, y: 20, width: 400, height: 199}},
+ {menu: {x: 160, y: 120, width: 100, height: 100}, bounds: {x: 10, y: 20, width: 149, height: 300}},
+ ];
+ for (const {menu, bounds} of cases) {
+ const geometry = compute(rect, [], [], [menu]);
+ assert.equal(geometry.visible, true);
+ assert.deepEqual(geometry.bounds, bounds);
+ assert.deepEqual(geometry.logicalSize, {width: rect.width, height: rect.height});
+ assert.deepEqual(geometry.crop, {x: bounds.x - rect.x, y: bounds.y - rect.y});
+ for (const zoom of [0.8, 0.9, 1, 1.25, 1.5, 2]) {
+ const native = parseMapGeometry(geometry, zoom, {width: 4000, height: 3000});
+ assert.equal(native?.visible, true);
+ assert.ok(native.bounds.x >= rect.x * zoom && native.bounds.y >= rect.y * zoom);
+ assert.ok(native.bounds.x + native.bounds.width <= (rect.x + rect.width) * zoom);
+ assert.ok(native.bounds.y + native.bounds.height <= (rect.y + rect.height) * zoom);
+ assert.ok(native.bounds.x + native.bounds.width <= menu.x * zoom ||
+ native.bounds.x >= (menu.x + menu.width) * zoom ||
+ native.bounds.y + native.bounds.height <= menu.y * zoom ||
+ native.bounds.y >= (menu.y + menu.height) * zoom);
+ }
+ }
+ const menu = {...rect, width: 100};
+ assert.deepEqual(compute(rect, [], [menu]), {visible: false}, "ordinary menus never opt into cropping");
+ assert.deepEqual(compute(rect, [], [{...rect, width: 2}], [menu]), {visible: false},
+ "a second overlay hides the map even when it would lie outside the chosen crop");
+ assert.deepEqual(compute(rect, [], [], [menu, {...menu, x: 300}]), {visible: false});
+ assert.deepEqual(compute(rect, [], [], [rect]), {visible: false});
+ assert.deepEqual(compute(rect, [], [], [{...rect, width: 380}]), {visible: false});
+ assert.deepEqual(compute({...rect, height: 100}, [], [], [{...rect, width: 360}]), {visible: false});
+ assert.deepEqual(compute(rect, [], [], [{...menu, x: NaN}]), {visible: false});
+ const fractional = {x: 10.25, y: 20.75, width: 400.5, height: 300.5};
+ const geometry = compute(fractional, [{x: 30.5, y: 50.25, width: 340, height: 220}], [],
+ [{x: 290.5, y: 30, width: 100, height: 290}]);
+ assert.deepEqual(geometry.bounds, {x: 32, y: 52, width: 257, height: 217});
+ assert.deepEqual(geometry.crop, {x: 21.75, y: 31.25});
+ assert.deepEqual(geometry.logicalSize, {width: 400.5, height: 300.5});
+ });
+ it("clips only its own live unplaced menu including shadows and restores without refitting or recreating", async () => {
+ const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;
+ const callbacks: Array<() => void> = [];
+ class Observer {
+ constructor(callback: () => void) { callbacks.push(callback); }
+ observe() {}
+ disconnect() {}
+ }
+ globalThis.MutationObserver = Observer as any;
+ globalThis.ResizeObserver = Observer as any;
+ const f = fixture();
+ const rect = {x: 310, y: 30, width: 100, height: 260};
+ const submenu = {getClientRects: () => [rect]};
+ let submenus: unknown[] = [];
+ const menu: any = {contains: () => false, getClientRects: () => [rect], getBoundingClientRect: () => rect,
+ querySelectorAll: () => submenus};
+ const getStyle = f.doc.defaultView.getComputedStyle;
+ let shadow = "rgba(0, 0, 0, 0.2) 0px 8px 24px 0px";
+ let extraStyle = {};
+ f.doc.defaultView.getComputedStyle = (element: unknown) => ({...getStyle(),
+ ...(element === menu ? {boxShadow: shadow, ...extraStyle} : {})});
+ const lastGeometry = () => f.calls.filter(([name]) => name === "siyuan-map-geometry").at(-1)[1];
+ let release = unplacedMenu.registerMapUnplacedMenu(menu, f.container);
+ try {
+ await f.created();
+ f.reply({type: "ready"});
+ f.advance();
+ const commands = f.calls.filter(([name]) => name === "siyuan-map-command").length;
+ f.doc.querySelectorAll = () => [menu];
+ callbacks[0]();
+ f.advance();
+ assert.deepEqual(lastGeometry().bounds, {x: 10, y: 20, width: 251, height: 300});
+ assert.deepEqual(lastGeometry().logicalSize, {width: 400, height: 300});
+ const scroll = f.domListeners.get("scroll");
+ rect.height = 40;
+ scroll();
+ assert.deepEqual(lastGeometry().bounds, {x: 10, y: 127, width: 400, height: 193},
+ "a shorter result list can leave a larger rectangle below the menu");
+ rect.height = 260;
+ rect.x = 270;
+ scroll();
+ assert.equal(lastGeometry().bounds.width, 211, "moving or growing the menu refreshes its crop");
+ shadow = "rgba(0, 0, 0, 0.8) -8px -4px 3px 2px, rgb(255, 255, 255) 0px 0px 0px 2px";
+ scroll();
+ assert.equal(lastGeometry().bounds.width, 243, "every shadow and negative offset must be covered");
+ shadow = "rgb(0 0 0 / 0.5) 0px 0px 100px 0px inset";
+ scroll();
+ assert.equal(lastGeometry().bounds.width, 259, "inset shadows do not extend the menu");
+ extraStyle = {outlineStyle: "solid", outlineWidth: "4px", outlineOffset: "2px"};
+ scroll();
+ assert.equal(lastGeometry().bounds.width, 253, "outline pixels also remain outside the map");
+ extraStyle = {};
+ for (const unsupported of ["color(display-p3 1 0 0) 0px 0px 10px 0px", "rgb(0, 0, 0) 0px 0px invalid",
+ "rgb(0, 0, 0) 0px 0px -1px 0px"]) {
+ shadow = unsupported;
+ scroll();
+ assert.equal(lastGeometry().visible, false, "unsupported effects fail closed");
+ }
+ shadow = "none";
+ for (const style of [{transform: "matrix(1, 0, 0, 1, 1, 1)"}, {filter: "blur(2px)"},
+ {scale: "1.1"}, {getPropertyValue: () => "1.5"},
+ {outlineStyle: "solid", outlineWidth: "invalid", outlineOffset: "0px"}]) {
+ extraStyle = style;
+ scroll();
+ assert.equal(lastGeometry().visible, false);
+ }
+ extraStyle = {};
+ const parent = {};
+ menu.parentElement = parent;
+ f.doc.defaultView.getComputedStyle = (element: unknown) => ({...getStyle(),
+ ...(element === parent ? {getPropertyValue: () => "1.5"} : {})});
+ scroll();
+ assert.equal(lastGeometry().visible, false, "ancestor CSS zoom cannot leave underestimated shadow bounds");
+ menu.parentElement = null;
+ f.doc.defaultView.getComputedStyle = getStyle;
+ submenus = [submenu];
+ scroll();
+ assert.equal(lastGeometry().visible, false, "a visible submenu is not covered by the root rectangle");
+ submenus = [];
+ const otherMenu = {contains: () => false, getClientRects: () => [rect], getBoundingClientRect: () => rect};
+ f.doc.querySelectorAll = () => [menu, otherMenu];
+ scroll();
+ assert.equal(lastGeometry().visible, false, "a second overlapping menu retains full hiding");
+ f.doc.querySelectorAll = () => [menu];
+ f.doc.elementFromPoint = () => ({});
+ scroll();
+ assert.equal(lastGeometry().visible, false, "unknown overlays still fail the final hit test");
+ f.doc.elementFromPoint = () => f.container;
+ release();
+ scroll();
+ assert.equal(lastGeometry().visible, false, "a reused common menu loses the crop exception on close");
+ release = unplacedMenu.registerMapUnplacedMenu(menu, {} as HTMLElement);
+ scroll();
+ assert.equal(lastGeometry().visible, false, "another split view cannot claim this map's menu");
+ release();
+ release = unplacedMenu.registerMapUnplacedMenu(menu, f.container);
+ scroll();
+ assert.equal(lastGeometry().visible, true);
+ f.doc.querySelectorAll = (): HTMLElement[] => [];
+ callbacks[0]();
+ f.advance();
+ assert.deepEqual(lastGeometry().bounds, f.rect);
+ assert.deepEqual(lastGeometry().crop, {x: 0, y: 0});
+ assert.equal(f.calls.filter(([name]) => name === "siyuan-map-create").length, 1);
+ assert.equal(f.calls.filter(([name]) => name === "siyuan-map-command").length, commands,
+ "menu geometry changes must not send fit or recreate map state");
+ } finally {
+ release();
+ f.host.destroy();
+ globalThis.MutationObserver = oldMutation;
+ globalThis.ResizeObserver = oldResize;
+ }
+ });
+ it("keeps replacement menu ownership when an older registration is released", () => {
+ const menu = {} as HTMLElement, first = {} as HTMLElement, second = {} as HTMLElement;
+ const releaseFirst = unplacedMenu.registerMapUnplacedMenu(menu, first);
+ const releaseSecond = unplacedMenu.registerMapUnplacedMenu(menu, second);
+ releaseFirst();
+ assert.equal(unplacedMenu.isMapUnplacedMenu(menu, first), false);
+ assert.equal(unplacedMenu.isMapUnplacedMenu(menu, second), true);
+ releaseSecond();
+ assert.equal(unplacedMenu.isMapUnplacedMenu(menu, second), false);
+ });
it("preserves fractional geometry through native validation at every clipped edge and zoom", () => {
const compute = load({}).computeDesktopAVMapGeometry;
const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index 8986fb2b18..c81692dce1 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -2,6 +2,7 @@
import {ipcRenderer} from "electron";
/// #endif
import type {AVMapHost, AVMapHostOptions} from "./host";
+import {isMapUnplacedMenu} from "./unplacedMenu";
import {
AV_MAP_PROTOCOL_VERSION, AVMapCommand, AVMapErrorCode, AVMapPoint, isAVMapHostErrorCode, isAVMapProvider, isAVMapRevision,
isAVMapTheme, parseAVMapReply, sanitizeAVMapPoints,
@@ -15,9 +16,14 @@ type MapGeometry = {visible: false} | {
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;
+// 菜单打开时不展示难以操作的狭窄残片。
+const MIN_MENU_MAP_EDGE = 32;
+const MIN_MENU_MAP_AREA = 4096;
+
// 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[] = []): MapGeometry => {
- if (![rect, ...clips, ...occluders].every((item) => [item.x, item.y, item.width, item.height].every(Number.isFinite) &&
+export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occluders: MapRect[] = [],
+ menus: MapRect[] = []): MapGeometry => {
+ if (![rect, ...clips, ...occluders, ...menus].every((item) => [item.x, item.y, item.width, item.height].every(Number.isFinite) &&
item.width >= 0 && item.height >= 0)) {
return {visible: false};
}
@@ -37,15 +43,71 @@ export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occ
if (right < rect.x + rect.width) right -= 1;
if (bottom < rect.y + rect.height) bottom -= 1;
// 裁剪差值的浮点舍入不能使可见尺寸超过原始尺寸。
- const bounds = {x: left, y: top, width: Math.min(rect.width, right - left), height: Math.min(rect.height, bottom - top)};
+ let 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) {
return {visible: false};
}
if (occluders.some((item) => item.width > 0 && item.height > 0 && intersects(bounds, item))) {
return {visible: false};
}
+ const overlapping = menus.filter(item => item.width > 0 && item.height > 0 && intersects(bounds, item));
+ if (overlapping.length > 1) return {visible: false};
+ if (overlapping.length) {
+ const menu = overlapping[0];
+ const rightEdge = bounds.x + bounds.width, bottomEdge = bounds.y + bounds.height;
+ // 只处理当前地图唯一的未定位菜单,在四个连续矩形中选择面积最大的安全区域。
+ const candidates = [
+ [bounds.x, bounds.y, Math.min(rightEdge, menu.x - 1), bottomEdge],
+ [Math.max(bounds.x, menu.x + menu.width + 1), bounds.y, rightEdge, bottomEdge],
+ [bounds.x, bounds.y, rightEdge, Math.min(bottomEdge, menu.y - 1)],
+ [bounds.x, Math.max(bounds.y, menu.y + menu.height + 1), rightEdge, bottomEdge],
+ ].map(([x, y, right, bottom]) => ({x: Math.ceil(x), y: Math.ceil(y),
+ width: Math.floor(right) - Math.ceil(x), height: Math.floor(bottom) - Math.ceil(y)}))
+ .filter(item => item.width >= MIN_MENU_MAP_EDGE && item.height >= MIN_MENU_MAP_EDGE &&
+ item.width * item.height >= MIN_MENU_MAP_AREA);
+ if (!candidates.length) return {visible: false};
+ bounds = candidates.reduce((largest, item) => item.width * item.height > largest.width * largest.height ? item : largest);
+ }
return {visible: true, bounds, logicalSize: {width: rect.width, height: rect.height},
- crop: {x: left - rect.x, y: top - rect.y}};
+ crop: {x: bounds.x - rect.x, y: bounds.y - rect.y}};
+};
+
+const readMenuRect = (element: HTMLElement, style: CSSStyleDeclaration, scope: Window): MapRect | undefined => {
+ // 无法用单个矩形可靠界定的主题效果仍走全隐藏路径。
+ const measurable = (value: CSSStyleDeclaration) => value.transform === "none" && value.filter === "none" &&
+ ["", "normal", "1"].includes(value.getPropertyValue("zoom")) &&
+ [value.translate, value.rotate, value.scale].every(item => !item || item === "none");
+ if (!measurable(style)) return;
+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {
+ if (!measurable(scope.getComputedStyle(parent))) return;
+ }
+ const rect = element.getBoundingClientRect();
+ let left = 0, right = 0, top = 0, bottom = 0;
+ const shadows = style.boxShadow === "none" ? [] : style.boxShadow.split(/,(?![^()]*\))/);
+ for (const shadow of shadows) {
+ const parts = shadow.replace(/(?:rgba?|hsla?)\([\d\s.,%/+\-]+\)/, "").trim().split(/\s+/);
+ const inset = parts[0] === "inset" || parts[parts.length - 1] === "inset";
+ if (inset) parts.splice(parts[0] === "inset" ? 0 : parts.length - 1, 1);
+ if (parts.length < 2 || parts.length > 4 || parts.some(value => !/^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;
+ const [x, y, blur = 0, spread = 0] = parts.map(parseFloat);
+ if (blur < 0) return;
+ if (inset) continue;
+ // 模糊阴影按两倍半径保守外扩,包含多层阴影、负偏移和边框外侧的描边。
+ const extent = Math.max(0, blur * 2 + spread);
+ left = Math.max(left, extent - x);
+ right = Math.max(right, extent + x);
+ top = Math.max(top, extent - y);
+ bottom = Math.max(bottom, extent + y);
+ }
+ if (style.outlineStyle !== "none") {
+ if (![style.outlineWidth, style.outlineOffset].every(value => /^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;
+ const outline = Math.max(0, parseFloat(style.outlineWidth) + parseFloat(style.outlineOffset));
+ left = Math.max(left, outline);
+ right = Math.max(right, outline);
+ top = Math.max(top, outline);
+ bottom = Math.max(bottom, outline);
+ }
+ return {x: rect.x - left, y: rect.y - top, width: rect.width + left + right, height: rect.height + top + bottom};
};
const getIPC = () => {
@@ -156,6 +218,8 @@ const readGeometry = (container: HTMLElement): MapGeometry => {
}
}
const occluders: MapRect[] = [];
+ const menus: MapRect[] = [];
+ let unsupportedMenu = false;
// These are actual application overlay roots, not guesses based on arbitrary z-index values.
doc.querySelectorAll<HTMLElement>(".b3-menu, .b3-dialog, .av__panel, .protyle-util, .protyle-toolbar, .block__popover, [popover]")
.forEach((element) => {
@@ -164,10 +228,23 @@ const readGeometry = (container: HTMLElement): MapGeometry => {
}
const style = scope.getComputedStyle(element);
if (style.display !== "none" && style.visibility === "visible" && Number(style.opacity) !== 0) {
- occluders.push(element.getBoundingClientRect());
+ if (isMapUnplacedMenu(element, container)) {
+ const bounds = readMenuRect(element, style, scope);
+ const hasSubmenu = Array.from(element.querySelectorAll<HTMLElement>(".b3-menu__submenu"))
+ .some(submenu => {
+ const submenuStyle = scope.getComputedStyle(submenu);
+ return submenu.getClientRects().length && submenuStyle.display !== "none" &&
+ submenuStyle.visibility === "visible" && Number(submenuStyle.opacity) !== 0;
+ });
+ if (!bounds || hasSubmenu) unsupportedMenu = true;
+ else menus.push(bounds);
+ } else {
+ occluders.push(element.getBoundingClientRect());
+ }
}
});
- const geometry = computeDesktopAVMapGeometry(rect, clips, occluders);
+ if (unsupportedMenu) return {visible: false};
+ const geometry = computeDesktopAVMapGeometry(rect, clips, occluders, menus);
if (geometry.visible) {
const bounds = geometry.bounds;
// Hit-test the owner's DOM (native child views are not in this tree), including sticky toolbars.
diff --git a/app/src/protyle/render/av/map/render.test.ts b/app/src/protyle/render/av/map/render.test.ts
index 082eef08d1..d97060e669 100644
--- a/app/src/protyle/render/av/map/render.test.ts
+++ b/app/src/protyle/render/av/map/render.test.ts
@@ -169,7 +169,7 @@ test("map toolbar places the unplaced inbox after the summary and disposes its r
await scenario.render();
const html = scenario.roots[0].innerHTML;
assert.match(html, /av__map-toolbar/);
- assert.match(html, /data-map-unplaced-toggle.*aria-expanded="false".*#iconInbox/s);
+ assert.match(html, /data-map-unplaced-toggle data-position="4north".*aria-expanded="false".*#iconInbox/s);
assert.ok(html.indexOf("av__map-summary") < html.indexOf("data-map-unplaced-toggle"));
assert.equal(scenario.unplaced.length, 1);
assert.equal(scenario.unplaced[0].options.data, scenario.data);
diff --git a/app/src/protyle/render/av/map/render.ts b/app/src/protyle/render/av/map/render.ts
index edd54c01ae..7e6a484953 100644
--- a/app/src/protyle/render/av/map/render.ts
+++ b/app/src/protyle/render/av/map/render.ts
@@ -108,7 +108,7 @@ export const renderMap = async (blockElement: HTMLElement, protyle: IProtyle, da
<div class="av__map-summary ft__smaller ft__on-surface b3-tooltips b3-tooltips__nw" aria-label="${escapeAttr(pageText)}" tabindex="0">
<span>${escapeHtml(loadedText)}</span><span class="av__map-skipped"></span>
</div>
-${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class="block__icon block__icon--show ariaLabel fn__none" data-map-unplaced-toggle data-position="8south" aria-label="${escapeAttr(window.siyuan.languages.mapUnplaced)}" aria-expanded="false"><svg><use xlink:href="#iconInbox"></use></svg></button>` : ""}
+${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class="block__icon block__icon--show ariaLabel fn__none" data-map-unplaced-toggle data-position="4north" aria-label="${escapeAttr(window.siyuan.languages.mapUnplaced)}" aria-expanded="false"><svg><use xlink:href="#iconInbox"></use></svg></button>` : ""}
</div>
<div class="av__map-status ft__on-surface" role="status"></div>
<div class="av__map-canvas fn__none"></div>
diff --git a/app/src/protyle/render/av/map/unplaced.test.ts b/app/src/protyle/render/av/map/unplaced.test.ts
index f1a2ed68fc..2dab931ff9 100644
--- a/app/src/protyle/render/av/map/unplaced.test.ts
+++ b/app/src/protyle/render/av/map/unplaced.test.ts
@@ -7,6 +7,7 @@ import type {AVTableRow} from "../../../../types/api";
import * as escape from "../../../../util/escape";
import * as locationValue from "../locationValue";
import {getMapSettings} from "./state";
+import * as unplacedMenu from "./unplacedMenu";
class ElementStub {
isConnected = true;
@@ -46,7 +47,8 @@ const setup = (mobile = false) => {
const count = new ElementStub();
const search = {textContent: " main query "};
const input = new ElementStub();
- const root = {querySelector: () => toggle};
+ const canvas = new ElementStub();
+ const root = {querySelector: (selector: string) => selector === ".av__map-canvas" ? canvas : toggle};
const block = {dataset: {nodeId: "carrier", avId: "database"}, querySelector: () => search};
const protyle = {options: {}} as IProtyle;
const data = {id: "database", viewID: "map-view", view: {
@@ -104,6 +106,7 @@ const setup = (mobile = false) => {
}},
"../locationValue": locationValue,
"./state": {getMapSettings},
+ "./unplacedMenu": unplacedMenu,
"./settings": {canEditMapSettings: () => !protyle.disabled && !context.siyuan.isPublish &&
!protyle.options.history?.created && !protyle.options.history?.snapshot},
"./openRecord": {openMapRecord: (_protyle: IProtyle, _block: HTMLElement, row: IAVRow, keyID: string) =>
@@ -111,7 +114,7 @@ const setup = (mobile = false) => {
})[id] || {}});
const destroy = methods.bindMapUnplaced({root: root as unknown as HTMLElement, blockElement: block as unknown as HTMLElement,
protyle, data, current: () => current});
- return {methods, requests, menus, toggle, count, input, data, protyle, context, opens, destroy,
+ return {methods, requests, menus, toggle, count, input, canvas, data, protyle, context, opens, destroy,
positions: () => positions,
stale: () => { current = false; },
click: () => toggle.events.get("click")({preventDefault() {}}),
@@ -242,10 +245,14 @@ test("closing or destroying unplaced menus aborts pending work and rejects late
for (const close of ["toggle", "menu", "destroy"]) {
const scenario = setup();
scenario.click();
+ assert.equal(unplacedMenu.isMapUnplacedMenu(scenario.menus[0].element as unknown as HTMLElement,
+ scenario.canvas as unknown as HTMLElement), true);
if (close === "toggle") scenario.click();
if (close === "menu") scenario.menus[0].close();
if (close === "destroy") scenario.destroy();
assert.equal(scenario.requests[1].signal.aborted, true, close);
+ assert.equal(unplacedMenu.isMapUnplacedMenu(scenario.menus[0].element as unknown as HTMLElement,
+ scenario.canvas as unknown as HTMLElement), false);
assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false");
const before = scenario.positions();
await scenario.respond(1, [row("late")]);
@@ -315,6 +322,8 @@ test("mobile unplaced menu uses shared menu placement without forcing a software
await scenario.respond(1, [row("mobile")]);
assert.equal(scenario.menus[0].position.target, scenario.toggle);
assert.equal(scenario.input.focused, false);
+ assert.equal(unplacedMenu.isMapUnplacedMenu(scenario.menus[0].element as unknown as HTMLElement,
+ scenario.canvas as unknown as HTMLElement), false);
scenario.menus[0].click("&lt;Title mobile>");
assert.equal(scenario.opens[0].row.id, "mobile");
scenario.destroy();
diff --git a/app/src/protyle/render/av/map/unplaced.ts b/app/src/protyle/render/av/map/unplaced.ts
index 538adec0d8..397b8172e3 100644
--- a/app/src/protyle/render/av/map/unplaced.ts
+++ b/app/src/protyle/render/av/map/unplaced.ts
@@ -8,6 +8,7 @@ import {validateAVLocation} from "../locationValue";
import {openMapRecord} from "./openRecord";
import {canEditMapSettings} from "./settings";
import {getMapSettings} from "./state";
+import {registerMapUnplacedMenu} from "./unplacedMenu";
const PAGE_SIZE = 50;
@@ -53,6 +54,7 @@ export const bindMapUnplaced = (options: {
let loading = false;
let elements: HTMLElement[] = [];
let count: HTMLElement;
+ let releaseMenu: () => void;
const updateCount = (value: number) => {
toggle.classList.toggle("fn__none", value === 0);
@@ -163,9 +165,13 @@ export const bindMapUnplaced = (options: {
menu = new Menu(undefined, () => {
clearTimeout(searchTimer);
request?.abort();
+ releaseMenu?.();
+ releaseMenu = undefined;
menu = undefined;
toggle.setAttribute("aria-expanded", "false");
});
+ const canvas = root.querySelector<HTMLElement>(".av__map-canvas");
+ if (!isMobile() && canvas) releaseMenu = registerMapUnplacedMenu(menu.element, canvas);
rows = [];
page = 0;
total = 0;
diff --git a/app/src/protyle/render/av/map/unplacedMenu.ts b/app/src/protyle/render/av/map/unplacedMenu.ts
new file mode 100644
index 0000000000..8420762b63
--- /dev/null
+++ b/app/src/protyle/render/av/map/unplacedMenu.ts
@@ -0,0 +1,13 @@
+const owners = new WeakMap<HTMLElement, {container: HTMLElement}>();
+
+export const registerMapUnplacedMenu = (menu: HTMLElement, container: HTMLElement) => {
+ const owner = {container};
+ owners.set(menu, owner);
+ return () => {
+ // 共用菜单被新实例接管后,旧实例的清理不能移除新归属。
+ if (owners.get(menu) === owner) owners.delete(menu);
+ };
+};
+
+export const isMapUnplacedMenu = (menu: HTMLElement, container: HTMLElement) =>
+ owners.get(menu)?.container === container;