Skip to content

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

:art: Align map inbox with calendar menu styles https://github.com/siyuan-note/siyuan/issues/20129

Daniele79d631bf227
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.js
index 42d2c04bf1..ee4f8699d4 100644
--- a/app/electron/mapHostManager.test.js
+++ b/app/electron/mapHostManager.test.js
@@ -233,6 +233,7 @@ const setup = (initialFault) => {
views.push(this);
}
setVisible(value) { this.visible = value; (this.visibility ||= []).push(value); }
+ setBackgroundColor(value) { this.background = value; }
setBounds(value) { fault("bounds"); this.bounds = value; }
},
MessageChannelMain: class {
diff --git a/app/electron/mapUnplaced/manager.js b/app/electron/mapUnplaced/manager.js
index 3d68010a5d..ebad1f7439 100644
--- a/app/electron/mapUnplaced/manager.js
+++ b/app/electron/mapUnplaced/manager.js
@@ -98,7 +98,7 @@ const createManager = ({ipcMain, session, WebContentsView, owner, win, ownerURL,
if (!host) return false;
if (!currentOwner()) { close("owner-unavailable"); return false; }
const zoom = owner.getZoomFactor();
- const bounds = place(host.anchor, zoom, win.getContentBounds());
+ const bounds = place(host.anchor, zoom, win.getContentBounds(), host.preferredHeight);
if (!permitted() || !win.isVisible() || win.isMinimized?.() || !bounds) { close("unavailable"); return false; }
const key = JSON.stringify({bounds, zoom});
if (host.geometryKey !== key) {
@@ -131,6 +131,7 @@ const createManager = ({ipcMain, session, WebContentsView, owner, win, ownerURL,
pending: state.loading, query: state.query, page: state.page, requestID: 0};
const active = host;
const contents = view.webContents;
+ view.setBackgroundColor("#00000000");
contents.setWindowOpenHandler(() => ({action: "deny"}));
for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {
listen(contents, name, event => event.preventDefault(), host.listeners);
@@ -204,6 +205,11 @@ const createManager = ({ipcMain, session, WebContentsView, owner, win, ownerURL,
return;
}
if (!host.ready || action.revision !== host.state.revision) return;
+ if (action.type === "resize") {
+ host.preferredHeight = action.height;
+ geometry();
+ return;
+ }
if (action.type === "close") { close(action.reason, true); return; }
if (action.type === "editing") {
host.ids.clear();
diff --git a/app/electron/mapUnplaced/menu.css b/app/electron/mapUnplaced/menu.css
index 575c15a0ab..289bd2410a 100644
--- a/app/electron/mapUnplaced/menu.css
+++ b/app/electron/mapUnplaced/menu.css
@@ -1,40 +1,8 @@
-:root {
- --b3-menu-background: #ffffff;
- --b3-theme-background: #ffffff;
- --b3-theme-surface: #f6f6f6;
- --b3-theme-surface-lighter: #dddddd;
- --b3-theme-on-background: #222222;
- --b3-theme-on-surface: #666666;
- --b3-theme-primary: #3576d5;
- --b3-theme-primary-light: #6d9fe7;
- --b3-theme-primary-lighter: #bed4f3;
- --b3-border-color: #cccccc;
- --b3-list-hover: #eeeeee;
- --b3-scroll-color: #aaaaaa;
- --b3-border-radius: 4px;
- --b3-border-radius-b: 6px;
- --b3-dialog-shadow: none;
- --b3-font-size: 16px;
- --b3-font-family: system-ui, sans-serif;
- --b3-body-background: var(--b3-theme-background);
- --b3-empty-color: var(--b3-theme-on-surface);
- color-scheme: light;
-}
-:root[data-theme="dark"] {
- --b3-menu-background: #292929;
- --b3-theme-background: #292929;
- --b3-theme-surface: #222222;
- --b3-theme-surface-lighter: #444444;
- --b3-theme-on-background: #eeeeee;
- --b3-theme-on-surface: #bbbbbb;
- --b3-border-color: #666666;
- --b3-list-hover: #444444;
- color-scheme: dark;
-}
:root[data-font-size="12"] { --b3-font-size: 12px; }
:root[data-font-size="13"] { --b3-font-size: 13px; }
:root[data-font-size="14"] { --b3-font-size: 14px; }
:root[data-font-size="15"] { --b3-font-size: 15px; }
+:root[data-font-size="16"] { --b3-font-size: 16px; }
:root[data-font-size="17"] { --b3-font-size: 17px; }
:root[data-font-size="18"] { --b3-font-size: 18px; }
:root[data-font-size="19"] { --b3-font-size: 19px; }
@@ -51,13 +19,11 @@
:root[data-font-size="30"] { --b3-font-size: 30px; }
:root[data-font-size="31"] { --b3-font-size: 31px; }
:root[data-font-size="32"] { --b3-font-size: 32px; }
-html, body { height: 100%; margin: 0; overflow: hidden; }
-body { color: var(--b3-theme-on-background); font-family: system-ui, sans-serif; }
-.map-unplaced-menu { inset: 0; display: flex; flex-direction: column; overflow: auto; }
-.map-unplaced-menu header, .map-unplaced-search, #status { padding: 6px 12px; }
-.map-unplaced-search input { width: 100%; }
-.map-unplaced-menu #rows { flex: 1 0 56px; min-height: 56px; overflow: auto; }
-.map-unplaced-menu footer { display: flex; flex-wrap: wrap; }
-.map-unplaced-menu footer .b3-menu__item { flex: 1 1 auto; width: auto; max-width: 100%; white-space: normal; overflow-wrap: anywhere; }
-.map-unplaced-menu #rows .b3-menu__item { width: calc(100% - 8px); }
-.map-unplaced-menu [hidden] { display: none; }
+html, body { height: 100%; margin: 0; overflow: hidden; background: transparent; }
+.map-unplaced-menu { inset: 24px 24px auto; display: flex; flex-direction: column; max-height: calc(100vh - 48px); overflow: auto; }
+.map-unplaced-menu--measure { max-height: none; }
+.av-records-panel-head, .av-records-panel-search, .map-unplaced-menu footer { flex-shrink: 0; }
+.av-records-panel-item { gap: 4px; }
+.map-unplaced-menu footer { display: flex; flex-wrap: wrap; padding: 4px 8px 0; }
+.map-unplaced-menu footer .b3-button { flex: 1 1 auto; white-space: normal; overflow-wrap: anywhere; }
+.map-unplaced-menu [hidden], body > [hidden] { display: none; }
diff --git a/app/electron/mapUnplaced/menu.html b/app/electron/mapUnplaced/menu.html
index d2bee3d36f..6d2fb7f441 100644
--- a/app/electron/mapUnplaced/menu.html
+++ b/app/electron/mapUnplaced/menu.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html lang="zh-CN" data-theme="light" data-font-size="16">
+<html lang="zh-CN" data-theme="light" data-theme-mode="light" data-font-size="14">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -9,12 +9,20 @@
<title></title>
</head>
<body>
- <section class="b3-menu map-unplaced-menu" role="dialog" aria-labelledby="title">
- <header><span id="title"></span> <span id="count"></span></header>
- <div class="map-unplaced-search"><input id="search" class="b3-text-field" type="search" maxlength="256"></div>
- <div id="rows" class="b3-menu__items" role="group"></div>
- <div id="status" role="status" aria-live="polite"></div>
- <footer><button id="previous" class="b3-menu__item" type="button"></button><button id="more" class="b3-menu__item" type="button"></button><button id="close" class="b3-menu__item" type="button"></button></footer>
+ <svg hidden aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
+ <symbol id="iconOpen" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6"/><path d="m21 3-9 9"/><path d="M15 3h6v6"/>
+ </symbol>
+ <symbol id="iconFile" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/>
+ </symbol>
+ </svg>
+ <section id="menu" class="b3-menu av-records-panel map-unplaced-menu" role="dialog" aria-labelledby="title">
+ <header class="av-records-panel-head"><span id="title" class="b3-menu__label"></span><span id="count" class="counter counter--bg"></span></header>
+ <div class="av-records-panel-search"><input id="search" class="b3-text-field" type="search" maxlength="256"></div>
+ <div id="rows" class="b3-menu__items av-records-panel-list" role="group"></div>
+ <div id="status" class="av-records-panel-empty" role="status" aria-live="polite" hidden></div>
+ <footer><button id="previous" class="b3-button b3-button--cancel" type="button" hidden></button><button id="more" class="b3-button b3-button--cancel" type="button" hidden></button><button id="close" class="b3-button b3-button--cancel" type="button"></button></footer>
</section>
</body>
</html>
diff --git a/app/electron/mapUnplaced/menu.js b/app/electron/mapUnplaced/menu.js
index bac8687302..165be4d5d0 100644
--- a/app/electron/mapUnplaced/menu.js
+++ b/app/electron/mapUnplaced/menu.js
@@ -1,11 +1,36 @@
(() => {
const bridge = window.unplacedMenu;
+ const menu = document.getElementById("menu");
const input = document.getElementById("search");
const rows = document.getElementById("rows");
const status = document.getElementById("status");
const more = document.getElementById("more");
const previous = document.getElementById("previous");
let composing = false, timer, first = true, lastQuery = "", state, pending = false, awaitingSearch = false, searchSent = false;
+ let reportedHeight = 0, reportedRevision = -1;
+ const resize = () => {
+ if (!state) return;
+ // 临时解除当前原生窗口的高度限制,测量后立即恢复,避免逐次缩小。
+ menu.classList.add("map-unplaced-menu--measure");
+ const height = Math.max(50, Math.min(4096, Math.ceil(menu.getBoundingClientRect().height + 48)));
+ menu.classList.remove("map-unplaced-menu--measure");
+ if (height !== reportedHeight || state.revision !== reportedRevision) {
+ reportedHeight = height;
+ reportedRevision = state.revision;
+ bridge.resize(height);
+ }
+ };
+ const observer = new ResizeObserver(resize);
+ observer.observe(menu);
+ const icon = (name, className) => {
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ svg.setAttribute("class", className);
+ svg.setAttribute("aria-hidden", "true");
+ const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
+ use.setAttribute("href", "#" + name);
+ svg.append(use);
+ return svg;
+ };
const disableRows = () => { for (const row of rows.children) row.disabled = true; };
const search = () => {
clearTimeout(timer);
@@ -52,6 +77,9 @@
bridge.previous();
});
document.getElementById("close").addEventListener("click", () => bridge.close("button"));
+ document.addEventListener("pointerdown", event => {
+ if (!menu.contains(event.target)) bridge.close("button");
+ });
// 共享 reset 去掉原生 outline;键盘焦点复用菜单已有的 current 状态反馈。
document.addEventListener("focusin", event => {
if (event.target.classList?.contains("b3-menu__item")) event.target.classList.add("b3-menu__item--current");
@@ -70,10 +98,12 @@
event.preventDefault();
buttons[next].focus();
});
- window.addEventListener("pagehide", () => { clearTimeout(timer); state = undefined; });
+ window.addEventListener("pagehide", () => { clearTimeout(timer); observer.disconnect(); state = undefined; });
const applyTheme = theme => {
document.documentElement.dataset.theme = theme.mode;
+ document.documentElement.dataset.themeMode = theme.mode;
document.documentElement.dataset.fontSize = String(theme.fontSize);
+ resize();
};
bridge.subscribe(value => {
applyTheme(value.theme);
@@ -84,6 +114,7 @@
document.title = value.labels.title;
document.getElementById("title").textContent = value.labels.title;
document.getElementById("count").textContent = value.loading ? "" : String(value.total);
+ document.getElementById("count").hidden = value.loading;
input.placeholder = value.labels.search;
input.setAttribute("aria-label", value.labels.search);
if (first) { input.value = value.query; lastQuery = value.query; }
@@ -92,18 +123,25 @@
for (const row of value.rows) {
const button = document.createElement("button");
button.type = "button";
- button.className = "b3-menu__item";
+ button.className = "b3-menu__item av-records-panel-item";
button.dataset.rowId = row.id;
button.disabled = value.loading || value.error;
const label = document.createElement("span");
label.className = "b3-menu__label";
label.textContent = row.title;
+ button.append(icon("iconFile", "b3-menu__icon"));
button.append(label);
+ const open = document.createElement("span");
+ open.className = "block__icon block__icon--show";
+ open.setAttribute("aria-hidden", "true");
+ open.append(icon("iconOpen", ""));
+ button.append(open);
button.addEventListener("click", () => { if (!pending && !button.disabled) bridge.select(row.id); });
rows.append(button);
if (focusedID === row.id) button.focus();
}
status.textContent = value.loading ? value.labels.loading : value.error ? value.labels.retry : value.rows.length ? "" : value.labels.empty;
+ status.hidden = !status.textContent;
more.textContent = value.error ? value.labels.retry : value.labels.more;
more.hidden = !value.error && value.page * 50 >= value.total;
more.disabled = value.loading;
@@ -112,5 +150,6 @@
previous.disabled = value.loading;
document.getElementById("close").textContent = value.labels.close;
if (first) { first = false; input.focus(); }
+ resize();
}, applyTheme);
})();
diff --git a/app/electron/mapUnplaced/policy.js b/app/electron/mapUnplaced/policy.js
index 60b070409c..32a2ca82c4 100644
--- a/app/electron/mapUnplaced/policy.js
+++ b/app/electron/mapUnplaced/policy.js
@@ -43,6 +43,7 @@ const parseAction = value => {
if (["ready", "editing", "more", "previous", "retry"].includes(value.type) && keys(value, base)) return {...value};
if (value.type === "search" && keys(value, [...base, "query"]) && text(value.query, 256)) return {...value};
if (value.type === "select" && keys(value, [...base, "id"]) && text(value.id, 128) && value.id) return {...value};
+ if (value.type === "resize" && keys(value, [...base, "height"]) && integer(value.height, 4096) && value.height >= 50) return {...value};
if (value.type === "close" && keys(value, [...base, "reason"]) &&
["escape", "button"].includes(value.reason)) return {...value};
};
@@ -53,15 +54,17 @@ const parseAnchor = value => {
return {...value};
};
// 缩放取主进程的真实 WebContents 值,锚点以 owner 的 CSS 像素表示。
-const place = (anchor, zoom, bounds) => {
+const place = (anchor, zoom, bounds, preferredHeight = 408) => {
if (!parseAnchor(anchor) || !Number.isFinite(zoom) || zoom < 0.25 || zoom > 5 ||
- bounds.width < 240 || bounds.height < 160) return;
+ !integer(preferredHeight, 4096) || preferredHeight < 50 || bounds.width < 240 || bounds.height < 160) return;
const a = {x: anchor.x * zoom, y: anchor.y * zoom, width: anchor.width * zoom, height: anchor.height * zoom};
if (a.x < 0 || a.y < 0 || a.x + a.width > bounds.width || a.y + a.height > bounds.height) return;
- const width = Math.min(Math.round(320 * zoom), bounds.width);
- const height = Math.min(Math.round(360 * zoom), bounds.height);
- return {x: Math.max(0, Math.min(Math.round(a.x + a.width - width), bounds.width - width)),
- y: Math.max(0, Math.min(Math.round(a.y + a.height), bounds.height - height)), width, height};
+ const padding = Math.round(24 * zoom);
+ const width = Math.min(Math.round(368 * zoom), bounds.width);
+ const height = Math.min(Math.round(preferredHeight * zoom), Math.round(568 * zoom),
+ Math.floor(bounds.height * 0.65) + 2 * padding, bounds.height);
+ return {x: Math.max(0, Math.min(Math.round(a.x + a.width - width + padding), bounds.width - width)),
+ y: Math.max(0, Math.min(Math.round(a.y + a.height - padding), bounds.height - height)), width, height};
};
const resource = (url, method) => {
if (!["GET", "HEAD"].includes(method) || typeof url !== "string") return;
diff --git a/app/electron/mapUnplaced/preload.js b/app/electron/mapUnplaced/preload.js
index 3cec74b5f2..c6b036bc1a 100644
--- a/app/electron/mapUnplaced/preload.js
+++ b/app/electron/mapUnplaced/preload.js
@@ -28,6 +28,7 @@ contextBridge.exposeInMainWorld("unplacedMenu", Object.freeze({
more() { send("more"); },
previous() { send("previous"); },
retry() { send("retry"); },
+ resize(height) { if (Number.isSafeInteger(height) && height >= 50 && height <= 4096) send("resize", {height}); },
select(id) { if (typeof id === "string" && id.length <= 128) send("select", {id}); },
close(reason) { if (["escape", "button"].includes(reason)) send("close", {reason}); },
}));
diff --git a/app/src/assets/scss/business/_av-calendar.scss b/app/src/assets/scss/business/_av-calendar.scss
index 0ec9c47ec1..1a5b534e21 100644
--- a/app/src/assets/scss/business/_av-calendar.scss
+++ b/app/src/assets/scss/business/_av-calendar.scss
@@ -1,4 +1,5 @@
@use "../util/tokens";
+@use "../component/record-inbox";
.av[data-av-type="calendar"] {
width: 100%;
@@ -28,64 +29,7 @@
max-height: min(65vh, 520px);
}
- .av__calendar-undated-head {
- display: flex;
- align-items: center;
- padding: 0 16px 8px;
-
- .b3-menu__label {
- min-width: 0;
- margin-right: auto;
- }
- }
-
- .av__calendar-undated-search {
- box-sizing: border-box;
- display: flex;
- min-width: 0;
- margin-bottom: 8px;
- padding: 0 16px;
-
- .b3-text-field {
- flex: 1;
- min-width: 0;
- }
- }
-
- .av__calendar-undated-hint {
- padding: 0 16px;
- font-size: 12px;
- line-height: 16px;
- }
-
- .av__calendar-undated-list {
- min-height: 36px;
- max-height: min(45vh, 360px);
- overflow-y: auto;
- }
-
- .av__calendar-undated-item {
- min-width: 0;
-
- .b3-menu__label {
- min-width: 0;
- flex: 1;
- }
-
- &--selected {
- background-color: var(--b3-theme-primary-lightest);
- }
- }
-
- .av__calendar-undated-empty {
- padding: 8px;
- }
-
- .av__calendar-undated-more,
- .av__calendar-undated-retry {
- align-self: stretch;
- margin: 4px 8px 0;
- }
+ @include record-inbox.content("av__calendar-undated");
}
.av[data-av-type="calendar"] {
diff --git a/app/src/assets/scss/component/_counter.scss b/app/src/assets/scss/component/_counter.scss
new file mode 100644
index 0000000000..b8bd65c044
--- /dev/null
+++ b/app/src/assets/scss/component/_counter.scss
@@ -0,0 +1,19 @@
+.counter {
+ margin-left: 4px;
+ line-height: 22px;
+ padding: 0 8px;
+ color: var(--b3-theme-on-surface-light);
+ border-radius: var(--b3-border-radius);
+ font-size: 12px;
+ user-select: none;
+ height: 22px;
+
+ &--right {
+ width: 32px;
+ text-align: right;
+ }
+
+ &--bg {
+ background-color: var(--b3-theme-surface);
+ }
+}
diff --git a/app/src/assets/scss/component/_record-inbox.scss b/app/src/assets/scss/component/_record-inbox.scss
new file mode 100644
index 0000000000..ded24ab5fc
--- /dev/null
+++ b/app/src/assets/scss/component/_record-inbox.scss
@@ -0,0 +1,61 @@
+// 日历无日期列表和可信地图菜单共享同一组内容布局。
+@mixin content($prefix, $list-max-height: min(45vh, 360px)) {
+ .#{$prefix}-head {
+ display: flex;
+ align-items: center;
+ padding: 0 16px 8px;
+
+ .b3-menu__label {
+ min-width: 0;
+ margin-right: auto;
+ }
+ }
+
+ .#{$prefix}-search {
+ box-sizing: border-box;
+ display: flex;
+ min-width: 0;
+ margin-bottom: 8px;
+ padding: 0 16px;
+
+ .b3-text-field {
+ flex: 1;
+ min-width: 0;
+ }
+ }
+
+ .#{$prefix}-hint {
+ padding: 0 16px;
+ font-size: 12px;
+ line-height: 16px;
+ }
+
+ .#{$prefix}-list {
+ min-height: 36px;
+ max-height: $list-max-height;
+ overflow-y: auto;
+ }
+
+ .#{$prefix}-item {
+ min-width: 0;
+
+ .b3-menu__label {
+ min-width: 0;
+ flex: 1;
+ }
+
+ &--selected {
+ background-color: var(--b3-theme-primary-lightest);
+ }
+ }
+
+ .#{$prefix}-empty {
+ padding: 8px;
+ }
+
+ .#{$prefix}-more,
+ .#{$prefix}-retry {
+ align-self: stretch;
+ margin: 4px 8px 0;
+ }
+}
diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scss
index 587aa97a3f..837b7bc36b 100644
--- a/app/src/assets/scss/main/_main.scss
+++ b/app/src/assets/scss/main/_main.scss
@@ -1,3 +1,5 @@
+@use "../component/counter";
+
/*
.status: 2
@@ -435,26 +437,6 @@ html[data-frontend="browser-desktop"] {
font-size: 16px;
}
-.counter {
- margin-left: 4px;
- line-height: 22px;
- padding: 0 8px;
- color: var(--b3-theme-on-surface-light);
- border-radius: var(--b3-border-radius);
- font-size: 12px;
- user-select: none;
- height: 22px;
-
- &--right {
- width: 32px;
- text-align: right;
- }
-
- &--bg {
- background-color: var(--b3-theme-surface);
- }
-}
-
.reveal {
font-family: var(--b3-font-family);
}
diff --git a/app/src/protyle/render/av/map/desktopUnplaced.ts b/app/src/protyle/render/av/map/desktopUnplaced.ts
index 47fc5cd2c8..b0d5340952 100644
--- a/app/src/protyle/render/av/map/desktopUnplaced.ts
+++ b/app/src/protyle/render/av/map/desktopUnplaced.ts
@@ -72,7 +72,8 @@ export const openDesktopMapUnplaced = (canvas: HTMLElement, anchor: HTMLElement,
const active = () => !closed && hosts.get(canvas) === host && host.available() && available() &&
canvas.isConnected && anchor.isConnected && !anchor.ownerDocument.hidden;
const theme = () => ({mode: host.theme(),
- fontSize: Math.max(12, Math.min(32, Math.round(window.siyuan.config?.editor?.fontSize || 16)))});
+ fontSize: Math.max(12, Math.min(32, Math.round(Number.parseFloat(
+ scope.getComputedStyle(anchor.ownerDocument.documentElement).getPropertyValue("--b3-font-size")) || 14)))});
const wireState = () => ({...state, revision, theme: theme(),
rows: state.rows.map(row => ({id: row.id, title: row.title})), labels: {...state.labels}});
const position = () => {
diff --git a/app/src/protyle/render/av/map/unplaced.test.ts b/app/src/protyle/render/av/map/unplaced.test.ts
index 9ecf2da925..db0841a352 100644
--- a/app/src/protyle/render/av/map/unplaced.test.ts
+++ b/app/src/protyle/render/av/map/unplaced.test.ts
@@ -112,7 +112,8 @@ const setup = (mobile = false, nativeReady = false) => {
const scopeEvents = new Map<string, (event?: any) => void>();
const documentEvents = new Map<string, (event?: any) => void>();
const scope = {innerWidth: 1000, innerHeight: 800,
- getComputedStyle: () => ({display: "block", visibility: "visible", overflowX: "visible", overflowY: "visible"}),
+ getComputedStyle: () => ({display: "block", visibility: "visible", overflowX: "visible", overflowY: "visible",
+ getPropertyValue: (name: string) => name === "--b3-font-size" ? "14px" : ""}),
addEventListener: (type: string, callback: () => void) => scopeEvents.set(type, callback),
removeEventListener: (type: string) => scopeEvents.delete(type),
requestAnimationFrame: (callback: () => void) => { nativeFrames.set(++nextTimer, callback); return nextTimer; },
@@ -401,6 +402,8 @@ test("ready desktop host uses the real unplaced API and sends only the current p
scenario.click();
assert.equal(scenario.menus.length, 0, "native menus must not create a DOM menu over the map");
assert.equal(scenario.nativeOpens.length, 1);
+ assert.equal(scenario.nativeOpens[0].value.state.theme.fontSize, 14, "menu uses shared UI font size");
+ assert.equal(scenario.nativeOpens[0].value.state.labels.search, "searchPlaceholder");
assert.equal(JSON.stringify(scenario.requests[1].payload), JSON.stringify({id: "database", blockID: "carrier",
viewID: "map-view", query: "main query", search: "", page: 1, pageSize: 50}));
await scenario.nativeOpen();
diff --git a/app/src/protyle/render/av/map/unplaced.ts b/app/src/protyle/render/av/map/unplaced.ts
index 066bc12b3f..d63d884975 100644
--- a/app/src/protyle/render/av/map/unplaced.ts
+++ b/app/src/protyle/render/av/map/unplaced.ts
@@ -169,7 +169,7 @@ export const bindMapUnplaced = (options: {
const labels = window.siyuan.languages;
let members = new Map<string, IAVRow>();
let state: DesktopMapUnplacedState = {requestID: 0, query: "", rows: [], total: 0, page: 1,
- loading: true, error: false, labels: {title: labels.mapUnplaced, search: labels.search,
+ loading: true, error: false, labels: {title: labels.mapUnplaced, search: labels.searchPlaceholder,
empty: labels.empty, loading: labels.loading, more: labels.next, previous: labels.previous,
retry: labels.retry, close: labels.close}};
const loadPage = async (requestID: number, query: string, nextPage: number) => {
diff --git a/app/tests/mapUnplacedAssets.test.js b/app/tests/mapUnplacedAssets.test.js
index 94c239ea58..2a7ddc88ae 100644
--- a/app/tests/mapUnplacedAssets.test.js
+++ b/app/tests/mapUnplacedAssets.test.js
@@ -3,8 +3,10 @@ const path = require("node:path");
const {readFileSync} = require("node:fs");
const {test} = require("node:test");
const config = require("../webpack.map");
+const sass = require("sass");
+const postcss = require("postcss");
-test("map asset plugin emits shared menu controls and watches their Sass dependencies", () => {
+const emitAssets = () => {
const assets = new Map();
const compilation = {
fileDependencies: new Set(),
@@ -14,20 +16,80 @@ test("map asset plugin emits shared menu controls and watches their Sass depende
const compiler = {hooks: {thisCompilation: {tap(_name, callback) { callback(compilation); }}}};
const options = config({}, {mode: "production"});
options.plugins.forEach(plugin => plugin.apply(compiler));
+ return {assets, compilation, options};
+};
+
+test("map asset plugin emits shared menu controls and watches their Sass and built-in theme dependencies", () => {
+ const {assets, compilation, options} = emitAssets();
const controls = assets.get("unplaced-controls.css");
assert.equal(typeof controls, "string");
assert.match(controls, /\.b3-menu__item/);
assert.match(controls, /\.b3-text-field/);
assert.match(controls, /button,\s*input,\s*select,\s*textarea\s*\{[^}]*font-size: 100%/);
assert.doesNotMatch(controls, /@import|https?:\/\//);
- for (const name of ["_menu.scss", "_text-field.scss"]) {
+ for (const name of ["_menu.scss", "_text-field.scss", "_button.scss", "_counter.scss", "_record-inbox.scss"]) {
assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../src/assets/scss/component", name)), name);
}
assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../src/assets/scss/util/_reset.scss")));
+ for (const name of ["daylight", "midnight"]) {
+ assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../appearance/themes", name, "theme.css")), name);
+ }
+ assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../electron/mapUnplaced/menu.css")));
assert.equal(options.output.path, path.resolve(__dirname, "../stage/build/map"));
assert.ok(assets.has("maplibre-gl.js"));
});
+test("trusted menu shares calendar content geometry and built-in theme values without remote resource styles", () => {
+ const {assets} = emitAssets();
+ const controls = postcss.parse(assets.get("unplaced-controls.css"));
+ const calendar = postcss.parse(sass.compile(path.resolve(__dirname, "../src/assets/scss/business/_av-calendar.scss"),
+ {logger: sass.Logger.silent}).css);
+ const declarations = (root, selector) => {
+ const result = {};
+ root.walkRules(rule => {
+ if (rule.selectors.includes(selector)) rule.walkDecls(declaration => { result[declaration.prop] = declaration.value; });
+ });
+ return result;
+ };
+ for (const suffix of ["-head", "-head .b3-menu__label", "-search", "-search .b3-text-field", "-empty", "-more"]) {
+ const expected = declarations(calendar, "#commonMenu .av__calendar-undated" + suffix);
+ assert.ok(Object.keys(expected).length, suffix);
+ assert.deepEqual(declarations(controls, ".av-records-panel" + suffix), expected, suffix);
+ }
+ assert.equal(declarations(controls, ".av-records-panel-list")["min-height"], "36px");
+ assert.equal(declarations(controls, ".av-records-panel-list")["max-height"], "360px");
+ assert.equal(declarations(controls, ".b3-menu__item")["line-height"], "28px");
+ assert.equal(declarations(controls, ".counter")["height"], "22px");
+ assert.equal(declarations(controls, ".counter--bg")["background-color"], "var(--b3-theme-surface)");
+ assert.equal(declarations(controls, ".av-records-panel-item .b3-menu__label")["text-overflow"], "ellipsis");
+ for (const [mode, theme] of [["light", "daylight"], ["dark", "midnight"]]) {
+ const source = postcss.parse(readFileSync(path.resolve(__dirname, "../appearance/themes", theme, "theme.css"), "utf8"));
+ const expected = declarations(source, ":root");
+ const actual = declarations(controls, ':root[data-theme="' + mode + '"]');
+ for (const name of ["--b3-font-size", "--b3-font-family", "--b3-menu-background", "--b3-menu-icon-color",
+ "--b3-theme-background", "--b3-theme-surface-lighter", "--b3-border-radius", "--b3-border-radius-b", "--b3-dialog-shadow"]) {
+ assert.equal(actual[name], expected[name], mode + " " + name);
+ }
+ for (const value of Object.values(actual)) {
+ for (const reference of value.matchAll(/var\((--[\w-]+)/g)) assert.ok(actual[reference[1]], reference[1]);
+ }
+ }
+ assert.doesNotMatch(assets.get("unplaced-controls.css"), /url\s*\(|@import|https?:\/\//i);
+ assert.doesNotMatch(readFileSync(path.resolve(__dirname, "../electron/mapUnplaced/menu.css"), "utf8"),
+ /--b3-(?:theme-|menu-|border-|dialog-)|font-family\s*:/);
+});
+
+test("trusted menu embeds only the fixed repository file and open symbols", () => {
+ const template = readFileSync(path.resolve(__dirname, "../electron/mapUnplaced/menu.html"), "utf8");
+ const source = readFileSync(path.resolve(__dirname, "../appearance/icons/litheness/icon.js"), "utf8");
+ for (const name of ["iconFile", "iconOpen"]) {
+ const symbol = new RegExp('<symbol id="' + name + '"[^>]*>[\\s\\S]*?<\\/symbol>');
+ assert.equal(template.match(symbol)?.[0].replace(/\s+/g, " "), source.match(symbol)?.[0].replace(/\s+/g, " "), name);
+ }
+ assert.equal((template.match(/<symbol /g) || []).length, 2);
+ assert.doesNotMatch(template, /<svg[^>]*(?:on\w+=)|<(?:iframe|image)|href="(?:https?:)?\/\//i);
+});
+
test("all desktop packages include local trusted menu resources and generated controls", () => {
for (const name of ["electron-builder.yml", "electron-builder-arm64.yml", "electron-builder-linux.yml",
"electron-builder-linux-arm64.yml", "electron-builder-darwin.yml", "electron-builder-darwin-arm64.yml"]) {
diff --git a/app/tests/mapUnplacedOverlay.test.js b/app/tests/mapUnplacedOverlay.test.js
index 4ff6ba1f3b..9a7402b4f6 100644
--- a/app/tests/mapUnplacedOverlay.test.js
+++ b/app/tests/mapUnplacedOverlay.test.js
@@ -55,6 +55,7 @@ const setup = (fail = "") => {
const webContents = createContents("");
if (fail === "load") webContents.loadURL = () => Promise.reject(new Error("load"));
const view = {options, webContents, bounds: [], visibility: [],
+ setBackgroundColor(value) { this.background = value; },
setBounds(value) { if (fail === "bounds") throw new Error("bounds"); this.bounds.push(value); },
setVisible(value) { this.visibility.push(value); }};
views.push(view);
@@ -382,7 +383,7 @@ test("actual preload exposes only fixed operations, binds session/revision and n
contextBridge: {exposeInMainWorld(name, value) { assert.equal(name, "unplacedMenu"); bridge = value; }}}; },
process: {argv: ["--unplaced-session=" + "a".repeat(48)]},
});
- assert.deepEqual(Object.keys(bridge).sort(), ["close", "editing", "more", "previous", "retry", "search", "select", "subscribe"]);
+ assert.deepEqual(Object.keys(bridge).sort(), ["close", "editing", "more", "previous", "resize", "retry", "search", "select", "subscribe"]);
const updates = [], themes = [];
bridge.subscribe((...args) => updates.push(args), (...args) => themes.push(args));
assert.equal(sent[0].value.type, "ready");
@@ -402,7 +403,12 @@ test("actual preload exposes only fixed operations, binds session/revision and n
assert.equal(sent.at(-1).value.sessionID, "a".repeat(48));
const count = sent.length;
bridge.close("url"); bridge.search("x".repeat(257));
+ for (const height of [0, 49, 4097, 50.5, NaN, Infinity, "200"]) bridge.resize(height);
assert.equal(sent.length, count);
+ bridge.resize(220);
+ assert.equal(sent.at(-1).value.type, "resize");
+ assert.equal(sent.at(-1).value.height, 220);
+ assert.equal(sent.at(-1).value.revision, 3);
});
test("actual menu script uses text nodes, preserves pending edits against late states and suppresses composing search (simulated DOM)", () => {
@@ -411,14 +417,22 @@ test("actual menu script uses text nodes, preserves pending edits against late s
document.body.innerHTML = fs.readFileSync(path.join(resourceDirectory, "menu.html"), "utf8");
document.getElementById = id => document.body.querySelector('[id="' + id + '"]');
document.addEventListener = (...args) => document.documentElement.addEventListener(...args);
+ document.createElementNS = (_namespace, name) => document.createElement(name);
+ const menu = document.getElementById("menu");
+ let preferredHeight = 180, observed, disconnected = false;
+ menu.getBoundingClientRect = () => ({height: menu.classList.contains("map-unplaced-menu--measure") ? preferredHeight : 120});
const rows = document.getElementById("rows");
rows.replaceChildren = () => { Array.from(rows.children).forEach(child => child.remove()); };
const actions = [], timers = new Map();
let update, themeUpdate, nextTimer = 0;
const bridge = {subscribe(fn, onTheme) { update = fn; themeUpdate = onTheme; }};
+ const sizes = [], windowEvents = new Map();
for (const name of ["search", "editing", "more", "previous", "retry", "select", "close"]) bridge[name] = value => actions.push([name, value]);
- const window = {unplacedMenu: bridge, addEventListener() {}};
+ bridge.resize = value => sizes.push(value);
+ const window = {unplacedMenu: bridge, addEventListener(name, callback) { windowEvents.set(name, callback); }};
vm.runInNewContext(fs.readFileSync(path.join(resourceDirectory, "menu.js"), "utf8"), {window, document,
+ ResizeObserver: function (callback) { observed = callback; this.observe = target => assert.equal(target, menu);
+ this.disconnect = () => { disconnected = true; }; },
setTimeout(fn) { timers.set(++nextTimer, fn); return nextTimer; }, clearTimeout(id) { timers.delete(id); }});
const flush = () => { const callbacks = [...timers.values()]; timers.clear(); callbacks.forEach(fn => fn()); };
const fire = (element, type, event = {}) => (element.events.get(type) || []).forEach(fn => fn({preventDefault() {}, ...event}));
@@ -426,6 +440,20 @@ test("actual menu script uses text nodes, preserves pending edits against late s
assert.equal(rows.children.length, 1);
assert.equal(rows.querySelectorAll("img").length, 0);
assert.equal(rows.children[0].textContent, "Private <img src=x>");
+ assert.deepEqual(rows.querySelectorAll("use").map(icon => icon.getAttribute("href")), ["#iconFile", "#iconOpen"]);
+ assert.ok(rows.children[0].classList.contains("av-records-panel-item"));
+ assert.ok(document.getElementById("count").classList.contains("counter--bg"));
+ assert.equal(document.getElementById("count").textContent, "123");
+ assert.equal(document.getElementById("status").hidden, true);
+ assert.deepEqual(sizes, [228]);
+ assert.equal(menu.classList.contains("map-unplaced-menu--measure"), false);
+ observed();
+ assert.deepEqual(sizes, [228], "viewport resize must not create a shrinking feedback loop");
+ update(state({revision: 2}));
+ assert.deepEqual(sizes, [228, 228], "a new state revision retries the same height after a stale resize");
+ preferredHeight = 240;
+ observed();
+ assert.equal(sizes.at(-1), 288);
const input = document.getElementById("search");
fire(document.getElementById("more"), "click");
assert.equal(rows.children[0].disabled, true);
@@ -462,6 +490,15 @@ test("actual menu script uses text nodes, preserves pending edits against late s
assert.equal(document.documentElement.dataset.fontSize, "24");
fire(document.documentElement, "keydown", {key: "Escape"});
assert.deepEqual(actions.at(-1), ["close", "escape"]);
+ const actionCount = actions.length;
+ fire(document.documentElement, "pointerdown", {target: input});
+ assert.equal(actions.length, actionCount);
+ fire(document.documentElement, "pointerdown", {target: document.body});
+ assert.deepEqual(actions.at(-1), ["close", "button"]);
+ fire(document.getElementById("close"), "click");
+ assert.deepEqual(actions.at(-1), ["close", "button"]);
+ windowEvents.get("pagehide")();
+ assert.equal(disconnected, true);
});
test("actual owner script keeps toggle/outside separate and cancels stale same-query work (simulated DOM)", async () => {
@@ -525,3 +562,34 @@ test("actual owner script keeps toggle/outside separate and cancels stale same-q
reply({type: "closed", sessionID, reason: "outside", restore: false});
assert.equal(timers.size, 0);
});
+
+test("trusted menu content sizing stays bounded and rejects stale or foreign renderer requests", () => {
+ const f = setup();
+ try {
+ f.open(); f.action("ready");
+ const view = f.views[0];
+ assert.equal(view.background, "#00000000");
+ f.action("resize", {height: 220});
+ assert.equal(view.bounds.at(-1).height, 220);
+ const count = view.bounds.length;
+ f.action("resize", {height: 220});
+ assert.equal(view.bounds.length, count, "same content size never moves or flashes the view");
+ for (const height of [0, 49, 4097, 100.5, NaN, Infinity]) {
+ f.action("resize", {height});
+ assert.equal(view.bounds.length, count);
+ }
+ f.action("resize", {height: 250, revision: 0});
+ f.action("resize", {height: 250, sessionID: "f".repeat(48)});
+ f.action("resize", {height: 250}, {sender: f.owner, senderFrame: f.owner.mainFrame});
+ assert.equal(view.bounds.length, count);
+ f.action("resize", {height: 4096});
+ const bounds = view.bounds.at(-1);
+ assert.ok(bounds.height <= Math.floor(f.win.bounds.height * 0.65) + 48);
+ assert.ok(bounds.x >= 0 && bounds.y >= 0 && bounds.x + bounds.width <= f.win.bounds.width &&
+ bounds.y + bounds.height <= f.win.bounds.height);
+ assert.deepEqual(view.visibility, [false, true], "resizing content never hides the map/menu");
+ assert.equal(f.actions.length, 0, "content size does not become an owner data action");
+ f.manager.revoke();
+ assert.equal(f.manager.inspect(), undefined);
+ } finally { f.manager.destroy(); }
+});
diff --git a/app/webpack.map.js b/app/webpack.map.js
index 98900d0982..5899919e9a 100644
--- a/app/webpack.map.js
+++ b/app/webpack.map.js
@@ -3,6 +3,29 @@ const path = require("path");
const {fileURLToPath} = require("url");
const webpack = require("webpack");
const {EsbuildPlugin} = require("esbuild-loader");
+const postcss = require("postcss");
+
+// 只打包共享控件引用的内置主题变量,不加载用户 CSS、远程资源或可执行内容。
+const menuTheme = (mode, controls, compilation) => {
+ const themePath = path.resolve(__dirname, "appearance/themes", mode === "dark" ? "midnight" : "daylight", "theme.css");
+ compilation.fileDependencies.add(themePath);
+ const variables = new Map();
+ postcss.parse(fs.readFileSync(themePath, "utf8")).walkRules(":root", rule => {
+ rule.walkDecls(declaration => variables.set(declaration.prop, declaration.value));
+ });
+ const names = new Set(Array.from(controls.matchAll(/var\((--[\w-]+)/g), match => match[1]));
+ const declarations = [];
+ for (const name of names) {
+ const value = variables.get(name);
+ if (!value) continue;
+ if (!/^[\w\s#.,%()"'/-]+$/.test(value) || /(?:url|expression|image|paint)\s*\(/i.test(value)) {
+ throw new Error("Unsafe built-in menu theme variable: " + name);
+ }
+ for (const dependency of value.matchAll(/var\((--[\w-]+)/g)) names.add(dependency[1]);
+ declarations.push(name + ": " + value + ";");
+ }
+ return ':root[data-theme="' + mode + '"] {\n' + declarations.join("\n") + "\n}\n";
+};
// 地图代码独立使用 web 目标,不共享 electron-renderer 的运行时或依赖包。
class MapLibreAssetsPlugin {
@@ -23,14 +46,21 @@ class MapLibreAssetsPlugin {
}
// 可信菜单复用共享控件,运行时不加载 Sass 或远程样式。
const sass = require("sass");
- const controls = sass.compileString('@use "../util/reset"; @use "menu"; @use "text-field";', {
+ const controls = sass.compileString('@use "../util/reset"; @use "../util/mixin"; @use "../business/block"; ' +
+ '@use "menu"; @use "text-field"; @use "button"; @use "counter"; @use "record-inbox"; ' +
+ '@include record-inbox.content("av-records-panel", 360px); ' +
+ ".av-records-panel-item .b3-menu__label { @include mixin.text-clamp(1); display: block; }", {
loadPaths: [path.resolve(__dirname, "src/assets/scss/component")],
logger: sass.Logger.silent,
});
for (const url of controls.loadedUrls) {
if (url.protocol === "file:") compilation.fileDependencies.add(fileURLToPath(url));
}
- compilation.emitAsset("unplaced-controls.css", new webpack.sources.RawSource(controls.css));
+ const menuCSSPath = path.resolve(__dirname, "electron/mapUnplaced/menu.css");
+ compilation.fileDependencies.add(menuCSSPath);
+ const references = controls.css + fs.readFileSync(menuCSSPath, "utf8");
+ const themes = ["light", "dark"].map(mode => menuTheme(mode, references, compilation)).join("");
+ compilation.emitAsset("unplaced-controls.css", new webpack.sources.RawSource(themes + controls.css));
});
});
}