An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Unify shared menu toggling by trigger https://github.com/siyuan-note/siyuan/issues/20418
Daniel1f60485a361c
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.ymlindex 7a602f91ef..80de4c5561 100644--- a/.github/workflows/cd.yml+++ b/.github/workflows/cd.yml@@ -257,6 +257,9 @@ jobs:- name: Install frontend dependenciesrun: pnpm install --frozen-lockfileworking-directory: app+ - name: Check shared menu ownership+ run: pnpm run menu:check+ working-directory: app- name: Test frontend, Electron and packaging scriptsid: test_frontend_electron_and_packaging_scripts# 测试失败只记录结果,不阻塞后续发布构建。diff --git a/app/package.json b/app/package.jsonindex 32a8aa1b19..ebbd9c49e2 100644--- a/app/package.json+++ b/app/package.json@@ -7,7 +7,8 @@"main": "./electron/main.js","packageManager": "[email protected]","scripts": {- "lint": "pnpm run typecheck && eslint . --fix --cache && pnpm run css:check",+ "lint": "pnpm run typecheck && eslint . --fix --cache && pnpm run css:check && pnpm run menu:check",+ "menu:check": "node ../scripts/check-menu-owner.mjs","css:check": "node scripts/css-contracts.mjs","css:unused": "node scripts/css-contracts.mjs --report-unused","typecheck": "tsc -p tsconfig.typecheck.json && tsc -p tsconfig.api.json",diff --git a/app/src/ai/actions.ts b/app/src/ai/actions.tsindex d7fa41c02f..57739ad842 100644--- a/app/src/ai/actions.ts+++ b/app/src/ai/actions.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {fetchPost} from "../util/fetch";import {focusByRange} from "../protyle/util/selectionOffsets";import {Dialog} from "../dialog";@@ -283,24 +284,34 @@ const openAIActions = (actions: IAIEditorAction[], elements: HTMLElement[], protlet aiActionsRequestID = 0;-export const AIActions = (elements: Element[], protyle: IProtyle, range?: Range) => {+export const AIActions = (elements: Element[], protyle: IProtyle, range?: Range, target?: Element) => {if (isDisabledFeature("ai")) {return;}- window.siyuan.menus.menu.remove();- const sourceElements = elements.filter((item): item is HTMLElement => item instanceof HTMLElement);- const sourceRange = range?.cloneRange();- if (sourceRange) {- protyle.toolbar.range = sourceRange;- }- const requestID = ++aiActionsRequestID;- fetchPost("/api/ai/editor/lsActions", {}, (response) => {- if (requestID !== aiActionsRequestID ||- (sourceElements.length > 0 && !sourceElements[sourceElements.length - 1].isConnected) ||- (sourceRange && (!protyle.wysiwyg.element.contains(sourceRange.startContainer) ||- !protyle.wysiwyg.element.contains(sourceRange.endContainer)))) {- return;- }- openAIActions(Array.isArray(response.data) ? response.data : [], sourceElements, protyle, sourceRange);+ toggleMenu({+ target: target,+ build: (_menu, session) => {++ const sourceElements = elements.filter((item): item is HTMLElement => item instanceof HTMLElement);+ const sourceRange = range?.cloneRange();+ if (sourceRange) {+ protyle.toolbar.range = sourceRange;+ }+ const requestID = ++aiActionsRequestID;+ fetchPost("/api/ai/editor/lsActions", {}, (response) => {+ if (!session.isCurrent()) {+ return;+ }++ if (requestID !== aiActionsRequestID ||+ (sourceElements.length > 0 && !sourceElements[sourceElements.length - 1].isConnected) ||+ (sourceRange && (!protyle.wysiwyg.element.contains(sourceRange.startContainer) ||+ !protyle.wysiwyg.element.contains(sourceRange.endContainer)))) {+ return;+ }+ session.show(() => openAIActions(Array.isArray(response.data) ? response.data : [], sourceElements, protyle, sourceRange));+ });++ },});};diff --git a/app/src/assets/scss/component/_typography.scss b/app/src/assets/scss/component/_typography.scssindex e60fd60716..c7db47bcb1 100644--- a/app/src/assets/scss/component/_typography.scss+++ b/app/src/assets/scss/component/_typography.scss@@ -88,7 +88,7 @@span[data-type~="inline-math"] {direction: ltr;- user-select: text;+ user-select: all;display: inline;// https://github.com/siyuan-note/siyuan/issues/17211&:after {diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.tsindex 9711d3644a..f5f50840dd 100644--- a/app/src/boot/globalEvent/command/global.ts+++ b/app/src/boot/globalEvent/command/global.ts@@ -160,7 +160,8 @@ export const globalCommand = (command: string, app: App, range?: Range, openOnlyreturn true;case "mainMenu":if (!isWindow()) {- workspaceMenu(app, document.querySelector("#barWorkspace").getBoundingClientRect(), openOnly);+ const target = document.querySelector("#barWorkspace");+ workspaceMenu(app, target.getBoundingClientRect(), openOnly, target);}return true;case "recentDocs":diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.tsindex c39a24b4b6..6b5352dba4 100644--- a/app/src/boot/globalEvent/keydown.ts+++ b/app/src/boot/globalEvent/keydown.ts@@ -1732,7 +1732,8 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {}if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.mainMenu, event)) {- workspaceMenu(app, document.querySelector("#barWorkspace").getBoundingClientRect(), true);+ const target = document.querySelector("#barWorkspace");+ workspaceMenu(app, target.getBoundingClientRect(), true, target);event.preventDefault();return;}diff --git a/app/src/card/openCard.test.ts b/app/src/card/openCard.test.tsindex 171bccc4ca..0cdde2cbee 100644--- a/app/src/card/openCard.test.ts+++ b/app/src/card/openCard.test.ts@@ -4,6 +4,7 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";import * as flashcardMode from "./flashcardMode";+const {loadMenuToggle} = require("../../tests/menu-toggle-fixture.cjs");const classList = () => {const values = new Set<string>();@@ -24,6 +25,9 @@ const createReview = async () => {querySelectorAll: () => actions, querySelector: (selector: string) => selector === '[data-type="filter"]' ? {getAttribute: (name: string) => name === "data-id" ? "" : "all"} : {innerHTML: ""}};const protyle = {element, block: {id: "block"}, wysiwyg: {element: {querySelector: (): null => null}, renderCustom: () => {}}};const constants = {LOCAL_FLASHCARD: "card", CB_GET_ALL: "all", SIZE_GET_MAX: 100, DIALOG_OPENCARD: "card", QUICK_DECK_ID: "deck"};+ const menuToggle = loadMenuToggle({window: {siyuan: {menus: {menu: {+ element: {classList: {contains: () => true}}, remove() {},+ }}}}});const dependencies = new Proxy({Constants: constants, Protyle: class {protyle = protyle;},fetchPost: (url: string, payload: Record<string, unknown>, callback: (response: unknown) => void) => new Promise<void>(resolve => { requests.push({url, payload, callback, resolve}); }),Menu: class {addItem(item: IMenu) {menuItems.set(item.id, item);} addSeparator() {} fullscreen() {} open() {}},@@ -36,6 +40,7 @@ const createReview = async () => {runInNewContext(transpileModule(readFileSync(__dirname + "/openCard.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText, {exports, require: (specifier: string) => {+ if (specifier.endsWith("menuToggle")) return menuToggle;if (specifier === "./flashcardMode") return {...flashcardMode, hasFlashcardAnswer: () => true};if (specifier === "dayjs") return () => ({format: () => "date", add: () => ({isValid: () => true, year: () => 2026, format: () => "20261015000000"})});return dependencies;@@ -46,7 +51,8 @@ const createReview = async () => {cardsData: {cards: [card]} as unknown as ICardData, cardType: "all"});const press = (detail: string) => click({detail, target: {}, preventDefault: () => {}, stopPropagation: () => {}});return {requests, actions, press, menuItems,- more: () => click({detail: 0, target: {type: "more", getBoundingClientRect: () => ({})}, preventDefault: () => {}, stopPropagation: () => {}}),+ more: () => click({detail: 0, target: {type: "more", closest: (): null => null, setAttribute() {},+ getBoundingClientRect: () => ({})}, preventDefault: () => {}, stopPropagation: () => {}}),confirmDue: () => confirmDue("7", {element: {querySelector: () => ({})}}),complete: () => {requests[0].callback({data: {ial: {}}});diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.tsindex 118034160b..9ec4cfd11e 100644--- a/app/src/card/openCard.ts+++ b/app/src/card/openCard.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {Dialog} from "../dialog";import {openInputDialog} from "../dialog/inputDialog";import {fetchPost} from "../util/fetch";@@ -396,252 +397,266 @@ export const bindCardEvent = async (options: {}const moreElement = hasClosestByAttribute(target, "data-type", "more");if (moreElement && currentCard) {- event.stopPropagation();- event.preventDefault();- if (filterElement.getAttribute("data-cardtype") === "all" && filterElement.getAttribute("data-id")) {- showMessage(window.siyuan.languages.noSupportTip);- return;- }- const menu = new Menu();- menu.addItem({- id: "setDueTime",- icon: "iconClock",- label: window.siyuan.languages.setDueTime,- click() {- openInputDialog({- title: window.siyuan.languages.setDueTime,- label: window.siyuan.languages.showCardDay,- value: "1",- type: "number",- min: "1",- step: "1",- onConfirm: (value, timedialog) => {- const inputElement = timedialog.element.querySelector("input") as HTMLInputElement;- const days = Number(value);- if (!Number.isInteger(days) || days < 1) {- showMessage(window.siyuan.languages.invalid, 3000, "error");- inputElement.focus();- inputElement.select();- return;- }- const due = dayjs().add(days, "day");- if (!due.isValid() || due.year() > 9999) {- showMessage(window.siyuan.languages.invalid, 3000, "error");- inputElement.focus();- inputElement.select();- return;- }- fetchPost("/api/riff/batchSetRiffCardsDueTime", {- cardDues: [{- id: currentCard.cardID,- due: due.format("YYYYMMDDHHmmss")- }]- }, () => {- actionElements[0].classList.add("fn__none");- actionElements[1].classList.remove("fn__none");- if (currentCard.state === 0) {- options.cardsData.unreviewedNewCardCount--;- } else {- options.cardsData.unreviewedOldCardCount--;- }- options.element.firstElementChild.dispatchEvent(new CustomEvent("click", {detail: "0"}));- options.cardsData.cards.splice(index, 1);- index--;- timedialog.destroy();- });- },- });- }- });- if (currentCard.state !== 0) {- menu.addItem({- id: "reset",- icon: "iconRefresh",- label: window.siyuan.languages.reset,- click() {- resetPending = true;- let refreshing: Promise<void>;- fetchPost("/api/riff/resetRiffCards", {- type: filterElement.getAttribute("data-cardtype"),- id: docId,- deckID: Constants.QUICK_DECK_ID,- blockIDs: [currentCard.blockID],- }, () => {- resetRefresh = {card: currentCard, onRefreshed: () => {- const minLang = window.siyuan.languages._time["1m"].replace("%s", "");- currentCard.lapses = 0;- currentCard.lastReview = -62135596800000;- currentCard.reps = 0;- currentCard.state = 0;- currentCard.nextDues = {- 1: minLang,- 2: minLang.replace("1", "5"),- 3: minLang.replace("1", "10"),- 4: window.siyuan.languages._time["1d"].replace("%s", "").replace("1", "6")- };- actionElements[1].querySelectorAll("button.b3-button").forEach((element, btnIndex) => {- if (btnIndex < 2) {+ toggleMenu({+ target: moreElement,+ build: (_menu, session) => {+ event.stopPropagation();+ event.preventDefault();+ if (filterElement.getAttribute("data-cardtype") === "all" && filterElement.getAttribute("data-id")) {+ showMessage(window.siyuan.languages.noSupportTip);+ return;+ }+ const menu = new Menu();+ menu.addItem({+ id: "setDueTime",+ icon: "iconClock",+ label: window.siyuan.languages.setDueTime,+ click() {+ openInputDialog({+ title: window.siyuan.languages.setDueTime,+ label: window.siyuan.languages.showCardDay,+ value: "1",+ type: "number",+ min: "1",+ step: "1",+ onConfirm: (value, timedialog) => {+ const inputElement = timedialog.element.querySelector("input") as HTMLInputElement;+ const days = Number(value);+ if (!Number.isInteger(days) || days < 1) {+ showMessage(window.siyuan.languages.invalid, 3000, "error");+ inputElement.focus();+ inputElement.select();+ return;+ }+ const due = dayjs().add(days, "day");+ if (!due.isValid() || due.year() > 9999) {+ showMessage(window.siyuan.languages.invalid, 3000, "error");+ inputElement.focus();+ inputElement.select();return;}- element.previousElementSibling.textContent = currentCard.nextDues[btnIndex - 1];+ fetchPost("/api/riff/batchSetRiffCardsDueTime", {+ cardDues: [{+ id: currentCard.cardID,+ due: due.format("YYYYMMDDHHmmss")+ }]+ }, () => {+ actionElements[0].classList.add("fn__none");+ actionElements[1].classList.remove("fn__none");+ if (currentCard.state === 0) {+ options.cardsData.unreviewedNewCardCount--;+ } else {+ options.cardsData.unreviewedOldCardCount--;+ }+ options.element.firstElementChild.dispatchEvent(new CustomEvent("click", {detail: "0"}));+ options.cardsData.cards.splice(index, 1);+ index--;+ timedialog.destroy();+ });+ },+ });+ }+ });+ if (currentCard.state !== 0) {+ menu.addItem({+ id: "reset",+ icon: "iconRefresh",+ label: window.siyuan.languages.reset,+ click() {+ resetPending = true;+ let refreshing: Promise<void>;+ fetchPost("/api/riff/resetRiffCards", {+ type: filterElement.getAttribute("data-cardtype"),+ id: docId,+ deckID: Constants.QUICK_DECK_ID,+ blockIDs: [currentCard.blockID],+ }, () => {+ resetRefresh = {+ card: currentCard, onRefreshed: () => {+ const minLang = window.siyuan.languages._time["1m"].replace("%s", "");+ currentCard.lapses = 0;+ currentCard.lastReview = -62135596800000;+ currentCard.reps = 0;+ currentCard.state = 0;+ currentCard.nextDues = {+ 1: minLang,+ 2: minLang.replace("1", "5"),+ 3: minLang.replace("1", "10"),+ 4: window.siyuan.languages._time["1d"].replace("%s", "").replace("1", "6")+ };+ actionElements[1].querySelectorAll("button.b3-button").forEach((element, btnIndex) => {+ if (btnIndex < 2) {+ return;+ }+ element.previousElementSibling.textContent = currentCard.nextDues[btnIndex - 1];+ });+ options.cardsData.unreviewedOldCardCount--;+ options.cardsData.unreviewedNewCardCount++;+ countElement.innerHTML = genCardCount(options.cardsData, index);+ }+ };+ refreshing = refreshResetCard();+ }).finally(async () => {+ await refreshing;+ resetPending = false;});- options.cardsData.unreviewedOldCardCount--;- options.cardsData.unreviewedNewCardCount++;- countElement.innerHTML = genCardCount(options.cardsData, index);- }};- refreshing = refreshResetCard();- }).finally(async () => {- await refreshing;- resetPending = false;+ }});}- });- }- menu.addItem({- id: "removeRiffCard",- icon: "iconTrashcan",- label: `${window.siyuan.languages.remove} <b>${window.siyuan.languages.riffCard}</b>`,- click() {- actionElements[0].classList.add("fn__none");- actionElements[1].classList.remove("fn__none");- if (currentCard.state === 0) {- options.cardsData.unreviewedNewCardCount--;- } else {- options.cardsData.unreviewedOldCardCount--;- }- options.element.firstElementChild.dispatchEvent(new CustomEvent("click", {detail: "0"}));- transaction(undefined, [{- action: "removeFlashcards",- deckID: Constants.QUICK_DECK_ID,- blockIDs: [currentCard.blockID]- }]);- options.cardsData.cards.splice(index, 1);- index--;- }- });- menu.addSeparator();- menu.addItem({- id: "forgetCountAndRevisionCountAndCardStatusAndLastReviewTime",- iconHTML: "",- type: "readonly",- label: `<div class="fn__flex">- <div class="fn__flex-1 ft__breakword">${window.siyuan.languages.forgetCount}</div>- <div class="fn__space"></div>- <div>${currentCard.lapses}</div>-</div><div class="fn__flex">- <div class="fn__flex-1 ft__breakword">${window.siyuan.languages.revisionCount}</div>- <div class="fn__space"></div>- <div>${currentCard.reps}</div>-</div><div class="fn__flex">- <div class="fn__flex-1 ft__breakword">${window.siyuan.languages.cardStatus}</div>- <div class="fn__space"></div>- <div class="${currentCard.state === 0 ? "ft__primary" : "ft__success"}">${currentCard.state === 0 ? window.siyuan.languages.flashcardNewCard : window.siyuan.languages.flashcardReviewCard}</div>-</div><div class="fn__flex${currentCard.lastReview > 0 ? "" : " fn__none"}">- <div class="fn__flex-1 ft__breakword" style="width: 170px;">${window.siyuan.languages.lastReviewTime}</div>- <div class="fn__space"></div>- <div>${dayjs(currentCard.lastReview).format("YYYY-MM-DD")}</div>-</div>`,- });- /// #if MOBILE- menu.fullscreen();- /// #else- const rect = moreElement.getBoundingClientRect();- menu.open({- x: rect.left,- y: rect.bottom,- h: rect.height+ menu.addItem({+ id: "removeRiffCard",+ icon: "iconTrashcan",+ label: `${window.siyuan.languages.remove} <b>${window.siyuan.languages.riffCard}</b>`,+ click() {+ actionElements[0].classList.add("fn__none");+ actionElements[1].classList.remove("fn__none");+ if (currentCard.state === 0) {+ options.cardsData.unreviewedNewCardCount--;+ } else {+ options.cardsData.unreviewedOldCardCount--;+ }+ options.element.firstElementChild.dispatchEvent(new CustomEvent("click", {detail: "0"}));+ transaction(undefined, [{+ action: "removeFlashcards",+ deckID: Constants.QUICK_DECK_ID,+ blockIDs: [currentCard.blockID]+ }]);+ options.cardsData.cards.splice(index, 1);+ index--;+ }+ });+ menu.addSeparator();+ menu.addItem({+ id: "forgetCountAndRevisionCountAndCardStatusAndLastReviewTime",+ iconHTML: "",+ type: "readonly",+ label: `<div class="fn__flex">+ <div class="fn__flex-1 ft__breakword">${window.siyuan.languages.forgetCount}</div>+ <div class="fn__space"></div>+ <div>${currentCard.lapses}</div>+ </div><div class="fn__flex">+ <div class="fn__flex-1 ft__breakword">${window.siyuan.languages.revisionCount}</div>+ <div class="fn__space"></div>+ <div>${currentCard.reps}</div>+ </div><div class="fn__flex">+ <div class="fn__flex-1 ft__breakword">${window.siyuan.languages.cardStatus}</div>+ <div class="fn__space"></div>+ <div class="${currentCard.state === 0 ? "ft__primary" : "ft__success"}">${currentCard.state === 0 ? window.siyuan.languages.flashcardNewCard : window.siyuan.languages.flashcardReviewCard}</div>+ </div><div class="fn__flex${currentCard.lastReview > 0 ? "" : " fn__none"}">+ <div class="fn__flex-1 ft__breakword" style="width: 170px;">${window.siyuan.languages.lastReviewTime}</div>+ <div class="fn__space"></div>+ <div>${dayjs(currentCard.lastReview).format("YYYY-MM-DD")}</div>+ </div>`,+ });+ /// #if MOBILE+ session.show(() => menu.fullscreen());+ /// #else+ const rect = moreElement.getBoundingClientRect();+ session.show(() => menu.open({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));+ /// #endif++ },});- /// #endif- return;+ return;}/// #if !MOBILEconst sticktabElement = hasClosestByAttribute(target, "data-type", "sticktab");if (sticktabElement) {- const stickMenu = new Menu();- stickMenu.addItem({- id: "openInNewTab",- icon: "iconOpen",- label: window.siyuan.languages.openInNewTab,- click() {- openFile({- app: options.app,- custom: {- icon: "iconRiffCard",- title: window.siyuan.languages.spaceRepetition,- data: {- cardsData: options.cardsData,- index,- cardType: filterElement.getAttribute("data-cardtype") as TCardType,- id: docId,- title: options.title- },- id: "siyuan-card"- },+ toggleMenu({+ target: sticktabElement,+ build: (_menu, session) => {+ const stickMenu = new Menu();+ stickMenu.addItem({+ id: "openInNewTab",+ icon: "iconOpen",+ label: window.siyuan.languages.openInNewTab,+ click() {+ openFile({+ app: options.app,+ custom: {+ icon: "iconRiffCard",+ title: window.siyuan.languages.spaceRepetition,+ data: {+ cardsData: options.cardsData,+ index,+ cardType: filterElement.getAttribute("data-cardtype") as TCardType,+ id: docId,+ title: options.title+ },+ id: "siyuan-card"+ },+ });+ options.dialog.destroy();+ }});- options.dialog.destroy();- }- });- stickMenu.addItem({- id: "insertRight",- icon: "iconLayoutRight",- label: window.siyuan.languages.insertRight,- click() {- openFile({- app: options.app,- position: "right",- custom: {- icon: "iconRiffCard",- title: window.siyuan.languages.spaceRepetition,- data: {- cardsData: options.cardsData,- index,- cardType: filterElement.getAttribute("data-cardtype") as TCardType,- id: docId,- title: options.title- },- id: "siyuan-card"- },+ stickMenu.addItem({+ id: "insertRight",+ icon: "iconLayoutRight",+ label: window.siyuan.languages.insertRight,+ click() {+ openFile({+ app: options.app,+ position: "right",+ custom: {+ icon: "iconRiffCard",+ title: window.siyuan.languages.spaceRepetition,+ data: {+ cardsData: options.cardsData,+ index,+ cardType: filterElement.getAttribute("data-cardtype") as TCardType,+ id: docId,+ title: options.title+ },+ id: "siyuan-card"+ },+ });+ options.dialog.destroy();+ }});- options.dialog.destroy();- }- });- /// #if !BROWSER- stickMenu.addItem({- id: "openByNewWindow",- icon: "iconOpenWindow",- label: window.siyuan.languages.openByNewWindow,- click() {- const json = [{- "title": window.siyuan.languages.spaceRepetition,- "icon": "iconRiffCard",- "instance": "Tab",- "children": {- "instance": "Custom",- "customModelType": "siyuan-card",- "customModelData": {- "cardsData": options.cardsData,- "index": index,- "cardType": filterElement.getAttribute("data-cardtype"),- "id": docId,- "title": options.title- }+ /// #if !BROWSER+ stickMenu.addItem({+ id: "openByNewWindow",+ icon: "iconOpenWindow",+ label: window.siyuan.languages.openByNewWindow,+ click() {+ const json = [{+ "title": window.siyuan.languages.spaceRepetition,+ "icon": "iconRiffCard",+ "instance": "Tab",+ "children": {+ "instance": "Custom",+ "customModelType": "siyuan-card",+ "customModelData": {+ "cardsData": options.cardsData,+ "index": index,+ "cardType": filterElement.getAttribute("data-cardtype"),+ "id": docId,+ "title": options.title+ }+ }+ }];+ const url = new URL("/stage/build/app/window.html", window.location.origin);+ url.searchParams.set("v", Constants.SIYUAN_VERSION);+ url.searchParams.set("json", JSON.stringify(json));+ ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: appendRemoteQuery(url).href});+ options.dialog.destroy();}- }];- const url = new URL("/stage/build/app/window.html", window.location.origin);- url.searchParams.set("v", Constants.SIYUAN_VERSION);- url.searchParams.set("json", JSON.stringify(json));- ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: appendRemoteQuery(url).href});- options.dialog.destroy();- }- });- /// #endif- const rect = sticktabElement.getBoundingClientRect();- stickMenu.open({- x: rect.left,- y: rect.bottom,- h: rect.height+ });+ /// #endif+ const rect = sticktabElement.getBoundingClientRect();+ session.show(() => stickMenu.open({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));++ },});- event.stopPropagation();+ event.stopPropagation();event.preventDefault();return;}@@ -657,66 +672,76 @@ export const bindCardEvent = async (options: {}const filterTempElement = hasClosestByAttribute(target, "data-type", "filter");if (filterTempElement) {- fetchPost("/api/riff/getRiffDecks", {}, (response) => {- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- id: "all",- iconHTML: "",- label: window.siyuan.languages.all,- click() {- filterElement.setAttribute("data-id", "");- filterElement.setAttribute("data-cardtype", "all");- fetchNewRound();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "fileTree",- iconHTML: "",- label: window.siyuan.languages.fileTree,- click() {- movePathTo({- cb: (toPath, toNotebook) => {- filterElement.setAttribute("data-id", toPath[0] === "/" ? toNotebook[0] : getDisplayName(toPath[0], true, true));- filterElement.setAttribute("data-cardtype", toPath[0] === "/" ? "notebook" : "doc");+ toggleMenu({+ target: filterTempElement,+ build: (_menu, session) => {+ fetchPost("/api/riff/getRiffDecks", {}, (response) => {+ if (!session.isCurrent()) {+ return;+ }++ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.append(new MenuItem({+ id: "all",+ iconHTML: "",+ label: window.siyuan.languages.all,+ click() {+ filterElement.setAttribute("data-id", "");+ filterElement.setAttribute("data-cardtype", "all");fetchNewRound();},- title: window.siyuan.languages.specifyPath,- flashcard: true+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "fileTree",+ iconHTML: "",+ label: window.siyuan.languages.fileTree,+ click() {+ movePathTo({+ cb: (toPath, toNotebook) => {+ filterElement.setAttribute("data-id", toPath[0] === "/" ? toNotebook[0] : getDisplayName(toPath[0], true, true));+ filterElement.setAttribute("data-cardtype", toPath[0] === "/" ? "notebook" : "doc");+ fetchNewRound();+ },+ title: window.siyuan.languages.specifyPath,+ flashcard: true+ });+ }+ }).element);+ if (options.title || response.data.length > 0) {+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);+ }+ if (options.title) {+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: escapeHtml(options.title),+ click() {+ filterElement.setAttribute("data-id", options.id);+ filterElement.setAttribute("data-cardtype", options.cardType);+ fetchNewRound();+ },+ }).element);+ if (response.data.length > 0) {+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);+ }+ }+ response.data.forEach((deck: {id: string, name: string}) => {+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: escapeHtml(deck.name),+ click() {+ filterElement.setAttribute("data-id", deck.id);+ filterElement.setAttribute("data-cardtype", "all");+ fetchNewRound();+ },+ }).element);});- }- }).element);- if (options.title || response.data.length > 0) {- window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);- }- if (options.title) {- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: escapeHtml(options.title),- click() {- filterElement.setAttribute("data-id", options.id);- filterElement.setAttribute("data-cardtype", options.cardType);- fetchNewRound();- },- }).element);- if (response.data.length > 0) {- window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);- }- }- response.data.forEach((deck: { id: string, name: string }) => {- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: escapeHtml(deck.name),- click() {- filterElement.setAttribute("data-id", deck.id);- filterElement.setAttribute("data-cardtype", "all");- fetchNewRound();- },- }).element);- });- const filterRect = filterTempElement.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: filterRect.left, y: filterRect.bottom, h: filterRect.height});+ const filterRect = filterTempElement.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: filterRect.left, y: filterRect.bottom, h: filterRect.height}));+ });++ },});- event.stopPropagation();+ event.stopPropagation();event.preventDefault();return;}diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.tsindex 46830a8898..708e634d5d 100644--- a/app/src/config/tabs/ai/aiProviderUi.ts+++ b/app/src/config/tabs/ai/aiProviderUi.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../../menus/menuToggle";import {escapeHtmlTextAndAttr} from "../../../util/escape";import type {AIModelTestData} from "../../../types/api";import {bindPasswordIconaToggle, genConfigItemMainHtml} from "../../render/fragments";@@ -280,82 +281,90 @@ const renderDraftModels = (container: HTMLElement, models: Config.IModel[], avai</div>`).join("");};-const openAvailableModelMenu = (modelInput: HTMLInputElement, models: string[], displayNames: Record<string, string> = {}) => {- const menu = new Menu();- menu.addItem({- iconHTML: "",- type: "empty",- label: `<div class="fn__flex-column b3-menu__filter">- <input spellcheck="false" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.searchPlaceholder}">- <div class="fn__hr"></div>- <div class="b3-list fn__flex-1 b3-list--background">- ${models.map((model) => `<div class="b3-list-item b3-list-item--narrow" data-model="${escapeHTML(model)}">- <span class="b3-list-item__text">${escapeHTML(displayNames[model] || model)}</span>- ${model === modelInput.value ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}-</div>`).join("")}- <div class="b3-list--empty fn__none" data-type="empty">${window.siyuan.languages.emptyContent}</div>- </div>-</div>`,- bind(element) {- const listElement = element.querySelector<HTMLElement>(".b3-list");- const searchInput = element.querySelector<HTMLInputElement>("input");- const emptyElement = element.querySelector<HTMLElement>("[data-type='empty']");- const selectModel = (item: HTMLElement) => {- modelInput.value = item.dataset.model;- modelInput.dispatchEvent(new InputEvent("input", {bubbles: true}));- menu.close();- modelInput.focus();- };- const filterModels = () => {- const keyword = searchInput.value.toLowerCase().trim();- let firstVisibleItem: HTMLElement;- listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {- item.classList.remove("b3-list-item--focus");- const hidden = !item.dataset.model.toLowerCase().includes(keyword);- item.classList.toggle("fn__none", hidden);- if (!hidden && !firstVisibleItem) {- firstVisibleItem = item;- }- });- firstVisibleItem?.classList.add("b3-list-item--focus");- emptyElement.classList.toggle("fn__none", !!firstVisibleItem);- };- filterModels();- searchInput.addEventListener("keydown", (event: KeyboardEvent) => {- event.stopPropagation();- if (event.isComposing) {- return;- }- upDownHint(listElement, event);- if (event.key === "Enter") {- const item = listElement.querySelector<HTMLElement>(".b3-list-item--focus");- if (item) {- selectModel(item);- }- event.preventDefault();- } else if (event.key === "Escape") {- menu.close();- modelInput.focus();- event.preventDefault();- }- });- searchInput.addEventListener("input", (event: InputEvent) => {- if (!event.isComposing) {+const openAvailableModelMenu = (modelInput: HTMLInputElement, models: string[], displayNames: Record<string, string> = {},+ toggle = true) => {+ toggleMenu({+ target: modelInput,+ toggle,+ build: (_menu, session) => {+ const menu = new Menu();+ menu.addItem({+ iconHTML: "",+ type: "empty",+ label: `<div class="fn__flex-column b3-menu__filter">+ <input spellcheck="false" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.searchPlaceholder}">+ <div class="fn__hr"></div>+ <div class="b3-list fn__flex-1 b3-list--background">+ ${models.map((model) => `<div class="b3-list-item b3-list-item--narrow" data-model="${escapeHTML(model)}">+ <span class="b3-list-item__text">${escapeHTML(displayNames[model] || model)}</span>+ ${model === modelInput.value ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}+ </div>`).join("")}+ <div class="b3-list--empty fn__none" data-type="empty">${window.siyuan.languages.emptyContent}</div>+ </div>+ </div>`,+ bind(element) {+ const listElement = element.querySelector<HTMLElement>(".b3-list");+ const searchInput = element.querySelector<HTMLInputElement>("input");+ const emptyElement = element.querySelector<HTMLElement>("[data-type='empty']");+ const selectModel = (item: HTMLElement) => {+ modelInput.value = item.dataset.model;+ modelInput.dispatchEvent(new InputEvent("input", {bubbles: true}));+ menu.close();+ modelInput.focus();+ };+ const filterModels = () => {+ const keyword = searchInput.value.toLowerCase().trim();+ let firstVisibleItem: HTMLElement;+ listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {+ item.classList.remove("b3-list-item--focus");+ const hidden = !item.dataset.model.toLowerCase().includes(keyword);+ item.classList.toggle("fn__none", hidden);+ if (!hidden && !firstVisibleItem) {+ firstVisibleItem = item;+ }+ });+ firstVisibleItem?.classList.add("b3-list-item--focus");+ emptyElement.classList.toggle("fn__none", !!firstVisibleItem);+ };filterModels();- }- });- searchInput.addEventListener("compositionend", filterModels);- listElement.addEventListener("click", (event) => {- const item = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item");- if (item) {- selectModel(item);- }+ searchInput.addEventListener("keydown", (event: KeyboardEvent) => {+ event.stopPropagation();+ if (event.isComposing) {+ return;+ }+ upDownHint(listElement, event);+ if (event.key === "Enter") {+ const item = listElement.querySelector<HTMLElement>(".b3-list-item--focus");+ if (item) {+ selectModel(item);+ }+ event.preventDefault();+ } else if (event.key === "Escape") {+ menu.close();+ modelInput.focus();+ event.preventDefault();+ }+ });+ searchInput.addEventListener("input", (event: InputEvent) => {+ if (!event.isComposing) {+ filterModels();+ }+ });+ searchInput.addEventListener("compositionend", filterModels);+ listElement.addEventListener("click", (event) => {+ const item = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item");+ if (item) {+ selectModel(item);+ }+ });+ },});+ const rect = modelInput.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: modelInput}));+ menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");+},});- const rect = modelInput.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: modelInput});- menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");};const showTestResult = (data: AIModelTestData) => {@@ -658,7 +667,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr}modelInput.focus();if (availableModels.length > 0) {- openAvailableModelMenu(modelInput, availableModels, availableModelDisplayNames);+ openAvailableModelMenu(modelInput, availableModels, availableModelDisplayNames, false);}};@@ -862,7 +871,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrreturn;}event.preventDefault();- openAvailableModelMenu(target, availableModels, availableModelDisplayNames);+ openAvailableModelMenu(target, availableModels, availableModelDisplayNames, false);});view.addEventListener("click", (event) => {@@ -1065,60 +1074,66 @@ const openGroupedModelMenu = (options: IGroupedModelPickerOptions,update: () => void,) => {- if (element.disabled) {- return;- }- const modelGroups = getEnabledModelGroups(group);- const selectedModelId = options.getSelectedModelId ? options.getSelectedModelId() : getSelectedModelId(group);- const menu = new Menu(getGroupedModelMenuId(group, options));- if (menu.isOpen) {- return;- }- const selectModel = (modelId: string, label: string) => {- if (modelId === selectedModelId) {- return;- }- if (options.onSelect) {- options.onSelect(modelId);- update();- return;- }- element.dataset.modelId = modelId;- setGroupedModelPickerLabel(element, label);- aiConfigApi.patch(`${group}.modelId`, modelId, () => syncGroupedModelPickers(root));- };- const optional = group === "imageGeneration";- if (optional) {- menu.addItem({- iconHTML: "",- label: window.siyuan.languages.noModelConfigured,- current: selectedModelId === "",- click: () => selectModel("", window.siyuan.languages.noModelConfigured),- });- menu.addSeparator();- }- modelGroups.forEach(({provider, models}, index) => {- if (index > 0) {- menu.addSeparator();- }- menu.addItem({- iconHTML: "",- type: "readonly",- label: escapeHTML(getProviderTitle(provider)),- });- models.forEach((model) => {- const label = model.displayName || model.name;- menu.addItem({- iconHTML: "",- label: escapeHTML(label),- current: model.id === selectedModelId,- click: () => selectModel(model.id, label),+ toggleMenu({+ target: element,+ build: (_menu, session) => {+ if (element.disabled) {+ return;+ }+ const modelGroups = getEnabledModelGroups(group);+ const selectedModelId = options.getSelectedModelId ? options.getSelectedModelId() : getSelectedModelId(group);+ const menu = new Menu(getGroupedModelMenuId(group, options));+ if (menu.isOpen) {+ return;+ }+ const selectModel = (modelId: string, label: string) => {+ if (modelId === selectedModelId) {+ return;+ }+ if (options.onSelect) {+ options.onSelect(modelId);+ update();+ return;+ }+ element.dataset.modelId = modelId;+ setGroupedModelPickerLabel(element, label);+ aiConfigApi.patch(`${group}.modelId`, modelId, () => syncGroupedModelPickers(root));+ };+ const optional = group === "imageGeneration";+ if (optional) {+ menu.addItem({+ iconHTML: "",+ label: window.siyuan.languages.noModelConfigured,+ current: selectedModelId === "",+ click: () => selectModel("", window.siyuan.languages.noModelConfigured),+ });+ menu.addSeparator();+ }+ modelGroups.forEach(({provider, models}, index) => {+ if (index > 0) {+ menu.addSeparator();+ }+ menu.addItem({+ iconHTML: "",+ type: "readonly",+ label: escapeHTML(getProviderTitle(provider)),+ });+ models.forEach((model) => {+ const label = model.displayName || model.name;+ menu.addItem({+ iconHTML: "",+ label: escapeHTML(label),+ current: model.id === selectedModelId,+ click: () => selectModel(model.id, label),+ });+ });});- });+ const rect = element.getBoundingClientRect();+ menu.element.style.minWidth = `${rect.width}px`;+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: element}));++ },});- const rect = element.getBoundingClientRect();- menu.element.style.minWidth = `${rect.width}px`;- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: element});};const syncGroupedModelPickers = (root: HTMLElement) => {diff --git a/app/src/config/tabs/appearanceTab.test.ts b/app/src/config/tabs/appearanceTab.test.tsindex cee0887b68..b4ad2c7785 100644--- a/app/src/config/tabs/appearanceTab.test.ts+++ b/app/src/config/tabs/appearanceTab.test.ts@@ -4,6 +4,7 @@ import {resolve} from "node:path";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+const {loadMenuToggle} = require("../../../tests/menu-toggle-fixture.cjs");const {parse} = require("ifdef-loader/preprocessor");@@ -63,26 +64,30 @@ const createPendingFontMenu = (key: string) => {const listeners = new Map<string, () => Promise<void>>();const attributes = new Map<string, string>();const state = {opened: 0, focused: 0, items: 0};+ let visible = false;let resolveFonts: (fonts: unknown[]) => void;- const input = {style: {removeProperty() {}}, isConnected: true,+ const input = {style: {removeProperty() {}}, isConnected: true, closest: (): null => null, setAttribute() {},addEventListener: (name: string, callback: () => Promise<void>) => listeners.set(name, callback),getBoundingClientRect: () => ({left: 700, bottom: 200, height: 28})};const selected = {innerHTML: "", classList: {toggle() {}}, querySelectorAll: (): unknown[] => [], addEventListener() {}};const element = {+ classList: {contains: () => !visible},contains: (target: unknown) => target === element,getAttribute: (name: string) => attributes.get(name),setAttribute: (name: string, value: string) => attributes.set(name, value),querySelector: (selector: string) => selector === ".b3-menu__items" ? {setAttribute() {}} :{focus: () => state.focused++},};- const menu = {element, removeCB: undefined as (() => void),+ const menu = {element, data: undefined as Element, removeCB: undefined as (() => void),remove() {+ visible = false;+ this.data = undefined;const callback = this.removeCB;this.removeCB = undefined;callback?.();attributes.clear();},- addItem: () => state.items++, popup: () => state.opened++,+ addItem: () => state.items++, popup: () => { visible = true; state.opened++; },};const window = {siyuan: {menus: {menu}, languages: {default: "Default"},config: {appearance: {globalFontFamilies: [] as unknown[]},@@ -100,6 +105,7 @@ const createPendingFontMenu = (key: string) => {"../protyle/util/hasClosest": {hasClosestByAttribute: (target: unknown) => target === input},});const appearance = load("src/config/tabs/appearanceTab.ts", {+ "../../menus/menuToggle": loadMenuToggle({window}),"../../plugin/Menu": pluginMenu,"../../util/availableFont": {loadAvailableFonts: () => new Promise(resolve => {resolveFonts = fonts => resolve({customFontSupported: false, customFonts: [], fontItems: fonts});diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex 64e8b33a5b..9949e4de8b 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";/// #if !BROWSERimport * as path from "path";import {useShell} from "../../util/pathName";@@ -331,284 +332,303 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesConmountedFontConfigUpdaters.set(fontConfigElement, updateFontInput);updateFontInput(getFontConfig());fontFamiliesElement.addEventListener("click", async (event) => {- // 在异步加载前阻止冒泡,避免同一次点击关闭字体菜单。- event.stopPropagation();- let closed = false;- let cleanupFontPreview: () => void;- const fontMenu = new Menu(`appearanceFontFamily-${configKey}`, () => {- closed = true;- cleanupFontPreview?.();- refreshOpenMenu = undefined;- });- if (fontMenu.isOpen) {- return;- }- let availableFonts: Awaited<ReturnType<typeof loadAvailableFonts>>;- try {- availableFonts = await loadAvailableFonts();- } catch (error) {- console.warn("load font list failed", error);- if (!closed) {- fontMenu.close();- }- return;- }- if (closed) {- return;- }- if (!fontFamiliesElement.isConnected) {- fontMenu.close();- return;- }- const {customFontSupported, customFonts, fontItems} = availableFonts;- selectedFonts = getConfiguredFonts(getFontConfig(), configKey).map((selectedFont) =>- fontItems.find((font) => font.family === selectedFont.family && font.weight === selectedFont.weight) ||- selectedFont);- renderSelectedFonts();- const fontItemHtml = fontItems.map((item) =>- genFontListItemHtml(item, selectedFonts.some((font) =>- font.family === item.family && font.weight === item.weight))- ).join("");- const canManageCustomFonts = customFontSupported && !window.siyuan.config.readonly;- const canShowAllFonts = configKey === "codeFontFamilies" && fontItems.some((font) => !isCodeFont(font));- const customFontsByID = new Map(customFonts.map((font) => [font.id, font]));- fontMenu.addItem({- iconHTML: "",- type: "empty",- label: `<div class="fn__flex-column b3-menu__filter">- <div class="fn__flex">- <input spellcheck="false" class="b3-text-field fn__flex-1" data-type="font-search" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">- ${canShowAllFonts ? `<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center" data-type="show-all-fonts">${escapeHtml(window.siyuan.languages.showAll)}</button>` : ""}- ${canManageCustomFonts ? `<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center" data-type="import-font"><svg><use xlink:href="#iconDownload"></use></svg>${escapeHtml(window.siyuan.languages.importFont)}</button>` : ""}- </div>- ${customFontSupported ? `<div class="b3-label__text ft__on-surface" style="margin-top: 8px">${escapeHtml(window.siyuan.languages.fontFileTip)}</div>` : ""}- ${canManageCustomFonts ? '<input class="fn__none" data-type="font-file" type="file" accept=".ttf,.otf,font/ttf,font/otf">' : ""}- <div class="fn__hr"></div>- <div class="b3-list fn__flex-1 b3-list--background" data-type="available-fonts">${fontItemHtml}</div>-</div>`,- bind(element) {- const listElement = element.querySelector<HTMLElement>('[data-type="available-fonts"]');- const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-search"]');- let showAllFonts = configKey !== "codeFontFamilies";- const refreshFontMenu = () => {- listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {- const label = item.querySelector<HTMLElement>(".b3-menu__label");- const checked = selectedFonts.some((font) =>- font.family === label.dataset.family && font.weight === parseInt(label.dataset.weight, 10));- item.querySelector(".b3-menu__checked")?.remove();- if (checked) {- item.insertAdjacentHTML("beforeend", '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>');- }- });- };- refreshOpenMenu = () => {- refreshFontMenu();- filterFontList();- };- refreshFontMenu();- cleanupFontPreview = observeFontPreview(listElement, (label, item) => {- const customFont = item.dataset.id ? customFontsByID.get(item.dataset.id) : undefined;- if (customFont) {- registerCustomFont(customFont);- }- label.style.fontFamily = label.dataset.family;- label.style.fontWeight = label.dataset.weight;+ await toggleMenu({+ target: fontFamiliesElement,+ build: async (_menu, session) => {+ // 在异步加载前阻止冒泡,避免同一次点击关闭字体菜单。+ event.stopPropagation();+ let closed = false;+ let cleanupFontPreview: () => void;+ const fontMenu = new Menu(`appearanceFontFamily-${configKey}`, () => {+ closed = true;+ cleanupFontPreview?.();+ refreshOpenMenu = undefined;});- function filterFontList() {- const value = inputElement.value.toLowerCase().trim();- listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- listElement.querySelectorAll<HTMLElement>(".b3-list-item .b3-menu__label").forEach((item) => {- const name = item.dataset.name;- const selected = selectedFonts.some((font) =>- font.family === item.dataset.family && font.weight === parseInt(item.dataset.weight, 10));- const codeFontVisible = showAllFonts || selected || isCodeFont({spacing: item.dataset.spacing});- const searchVisible = !value || item.dataset.search.includes(value);- item.parentElement.classList.toggle("fn__none", !(codeFontVisible && searchVisible));- const idx = name.toLowerCase().indexOf(value);- item.replaceChildren(document.createTextNode(name));- if (idx !== -1 && value) {- const markElement = document.createElement("mark");- markElement.textContent = name.slice(idx, idx + value.length);- item.replaceChildren(- document.createTextNode(name.slice(0, idx)),- markElement,- document.createTextNode(name.slice(idx + value.length))- );- }- });- listElement.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");+ if (fontMenu.isOpen) {+ return;}- filterFontList();- element.querySelector<HTMLElement>('[data-type="show-all-fonts"]')?.addEventListener("click", (event) => {- showAllFonts = true;- (event.currentTarget as HTMLElement).remove();- filterFontList();- if (!isMobile()) {- inputElement.focus();- }- });- inputElement.addEventListener("keydown", (event: KeyboardEvent) => {- event.stopPropagation();- if (event.isComposing) {+ let availableFonts: Awaited<ReturnType<typeof loadAvailableFonts>>;+ try {+ availableFonts = await loadAvailableFonts();+ if (!session.isCurrent()) {return;}- upDownHint(listElement, event);- if (event.key === "Enter") {- const itemEl = listElement.querySelector<HTMLElement>(".b3-list-item--focus .b3-menu__label");- if (itemEl) {- toggleEditorFont(fontItemFromElement(itemEl));- }- } else if (event.key === "Escape") {- window.siyuan.menus.menu.remove();+ } catch (error) {+ console.warn("load font list failed", error);+ if (!closed) {+ fontMenu.close();}- });- inputElement.addEventListener("input", (event: InputEvent) => {- if (!event.isComposing) {+ return;+ }+ if (closed) {+ return;+ }+ if (!fontFamiliesElement.isConnected) {+ fontMenu.close();+ return;+ }+ const {customFontSupported, customFonts, fontItems} = availableFonts;+ selectedFonts = getConfiguredFonts(getFontConfig(), configKey).map((selectedFont) =>+ fontItems.find((font) => font.family === selectedFont.family && font.weight === selectedFont.weight) ||+ selectedFont);+ renderSelectedFonts();+ const fontItemHtml = fontItems.map((item) =>+ genFontListItemHtml(item, selectedFonts.some((font) =>+ font.family === item.family && font.weight === item.weight))+ ).join("");+ const canManageCustomFonts = customFontSupported && !window.siyuan.config.readonly;+ const canShowAllFonts = configKey === "codeFontFamilies" && fontItems.some((font) => !isCodeFont(font));+ const customFontsByID = new Map(customFonts.map((font) => [font.id, font]));+ fontMenu.addItem({+ iconHTML: "",+ type: "empty",+ label: `<div class="fn__flex-column b3-menu__filter">+ <div class="fn__flex">+ <input spellcheck="false" class="b3-text-field fn__flex-1" data-type="font-search" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">+ ${canShowAllFonts ? `<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center" data-type="show-all-fonts">${escapeHtml(window.siyuan.languages.showAll)}</button>` : ""}+ ${canManageCustomFonts ? `<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center" data-type="import-font"><svg><use xlink:href="#iconDownload"></use></svg>${escapeHtml(window.siyuan.languages.importFont)}</button>` : ""}+ </div>+ ${customFontSupported ? `<div class="b3-label__text ft__on-surface" style="margin-top: 8px">${escapeHtml(window.siyuan.languages.fontFileTip)}</div>` : ""}+ ${canManageCustomFonts ? '<input class="fn__none" data-type="font-file" type="file" accept=".ttf,.otf,font/ttf,font/otf">' : ""}+ <div class="fn__hr"></div>+ <div class="b3-list fn__flex-1 b3-list--background" data-type="available-fonts">${fontItemHtml}</div>+ </div>`,+ bind(element) {+ const listElement = element.querySelector<HTMLElement>('[data-type="available-fonts"]');+ const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-search"]');+ let showAllFonts = configKey !== "codeFontFamilies";+ const refreshFontMenu = () => {+ listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {+ const label = item.querySelector<HTMLElement>(".b3-menu__label");+ const checked = selectedFonts.some((font) =>+ font.family === label.dataset.family && font.weight === parseInt(label.dataset.weight, 10));+ item.querySelector(".b3-menu__checked")?.remove();+ if (checked) {+ item.insertAdjacentHTML("beforeend", '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>');+ }+ });+ };+ refreshOpenMenu = () => {+ refreshFontMenu();+ filterFontList();+ };+ refreshFontMenu();+ cleanupFontPreview = observeFontPreview(listElement, (label, item) => {+ const customFont = item.dataset.id ? customFontsByID.get(item.dataset.id) : undefined;+ if (customFont) {+ registerCustomFont(customFont);+ }+ label.style.fontFamily = label.dataset.family;+ label.style.fontWeight = label.dataset.weight;+ });+ function filterFontList() {+ const value = inputElement.value.toLowerCase().trim();+ listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");+ listElement.querySelectorAll<HTMLElement>(".b3-list-item .b3-menu__label").forEach((item) => {+ const name = item.dataset.name;+ const selected = selectedFonts.some((font) =>+ font.family === item.dataset.family && font.weight === parseInt(item.dataset.weight, 10));+ const codeFontVisible = showAllFonts || selected || isCodeFont({spacing: item.dataset.spacing});+ const searchVisible = !value || item.dataset.search.includes(value);+ item.parentElement.classList.toggle("fn__none", !(codeFontVisible && searchVisible));+ const idx = name.toLowerCase().indexOf(value);+ item.replaceChildren(document.createTextNode(name));+ if (idx !== -1 && value) {+ const markElement = document.createElement("mark");+ markElement.textContent = name.slice(idx, idx + value.length);+ item.replaceChildren(+ document.createTextNode(name.slice(0, idx)),+ markElement,+ document.createTextNode(name.slice(idx + value.length))+ );+ }+ });+ listElement.querySelector(".b3-list-item:not(.fn__none)")?.classList.add("b3-list-item--focus");+ }filterFontList();- }- });- inputElement.addEventListener("compositionend", filterFontList);- element.querySelector<HTMLElement>('[data-type="import-font"]')?.addEventListener("click", () => {- element.querySelector<HTMLInputElement>('[data-type="font-file"]').click();- });- element.querySelector<HTMLInputElement>('[data-type="font-file"]')?.addEventListener("change", (event) => {- const fileInput = event.currentTarget as HTMLInputElement;- const file = fileInput.files?.[0];- fileInput.value = "";- if (!file) {- return;- }- if (file.size > 64 * 1024 * 1024) {- showMessage(window.siyuan.languages.fontFileTip, 6000, "error");- return;- }- const formData = new ContractFormData({file});- fetchPost("/api/system/importCustomFont", formData, (response) => {- if (response.code !== 0) {- return;+ element.querySelector<HTMLElement>('[data-type="show-all-fonts"]')?.addEventListener("click", (event) => {+ showAllFonts = true;+ (event.currentTarget as HTMLElement).remove();+ filterFontList();+ if (!isMobile()) {+ inputElement.focus();+ }+ });+ inputElement.addEventListener("keydown", (event: KeyboardEvent) => {+ event.stopPropagation();+ if (event.isComposing) {+ return;+ }+ upDownHint(listElement, event);+ if (event.key === "Enter") {+ const itemEl = listElement.querySelector<HTMLElement>(".b3-list-item--focus .b3-menu__label");+ if (itemEl) {+ toggleEditorFont(fontItemFromElement(itemEl));+ }+ } else if (event.key === "Escape") {+ window.siyuan.menus.menu.remove();+ }+ });+ inputElement.addEventListener("input", (event: InputEvent) => {+ if (!event.isComposing) {+ filterFontList();+ }+ });+ inputElement.addEventListener("compositionend", filterFontList);+ element.querySelector<HTMLElement>('[data-type="import-font"]')?.addEventListener("click", () => {+ element.querySelector<HTMLInputElement>('[data-type="font-file"]').click();+ });+ element.querySelector<HTMLInputElement>('[data-type="font-file"]')?.addEventListener("change", (event) => {+ const fileInput = event.currentTarget as HTMLInputElement;+ const file = fileInput.files?.[0];+ fileInput.value = "";+ if (!file) {+ return;+ }+ if (file.size > 64 * 1024 * 1024) {+ showMessage(window.siyuan.languages.fontFileTip, 6000, "error");+ return;+ }+ const formData = new ContractFormData({file});+ fetchPost("/api/system/importCustomFont", formData, (response) => {+ if (response.code !== 0) {+ return;+ }+ const font = response.data;+ invalidateCustomFonts();+ registerCustomFont(font);+ persistFonts([...selectedFonts.filter((item) => item.family !== font.family), font]);+ showMessage(window.siyuan.languages.imported);+ });+ });+ listElement.addEventListener("click", (event) => {+ const target = event.target as HTMLElement;+ const itemElement = target.closest<HTMLElement>(".b3-list-item");+ const itemEl = itemElement?.querySelector<HTMLElement>(".b3-menu__label");+ if (!itemEl) {+ return;+ }+ if (target.closest('[data-type="delete-font"]')) {+ const id = itemElement.dataset.id;+ confirmDialog(+ window.siyuan.languages.deleteOpConfirm,+ window.siyuan.languages.deleteFontConfirm.replace(+ "${x}", `<b>${escapeHtml(itemEl.dataset.name)}</b>`),+ () => {+ fetchPost("/api/system/removeCustomFont", {id}, (response) => {+ if (response.code !== 0) {+ return;+ }+ unregisterCustomFont(id);+ invalidateCustomFonts();+ if (response.data.appearance) {+ appearanceConfigApi.apply(response.data.appearance);+ }+ if (response.data.editor) {+ editorConfigApi.apply(response.data.editor);+ }+ updateFontInput(getFontConfig());+ refreshMountedFontConfigs(getFontConfig(), fontConfigElement);+ fontMenu.close();+ });+ },+ undefined,+ true+ );+ return;+ }+ toggleEditorFont(fontItemFromElement(itemEl));+ });++ function toggleEditorFont(item: IFontItem) {+ const selected = selectedFonts.some((font) => font.family === item.family && font.weight === item.weight);+ const fonts = selected ? selectedFonts.filter((font) =>+ font.family !== item.family || font.weight !== item.weight) :+ [...selectedFonts.filter((font) => font.family !== item.family), item];+ persistFonts(fonts);}- const font = response.data;- invalidateCustomFonts();- registerCustomFont(font);- persistFonts([...selectedFonts.filter((item) => item.family !== font.family), font]);- showMessage(window.siyuan.languages.imported);- });- });- listElement.addEventListener("click", (event) => {- const target = event.target as HTMLElement;- const itemElement = target.closest<HTMLElement>(".b3-list-item");- const itemEl = itemElement?.querySelector<HTMLElement>(".b3-menu__label");- if (!itemEl) {- return;- }- if (target.closest('[data-type="delete-font"]')) {- const id = itemElement.dataset.id;- confirmDialog(- window.siyuan.languages.deleteOpConfirm,- window.siyuan.languages.deleteFontConfirm.replace(- "${x}", `<b>${escapeHtml(itemEl.dataset.name)}</b>`),- () => {- fetchPost("/api/system/removeCustomFont", {id}, (response) => {- if (response.code !== 0) {- return;- }- unregisterCustomFont(id);- invalidateCustomFonts();- if (response.data.appearance) {- appearanceConfigApi.apply(response.data.appearance);- }- if (response.data.editor) {- editorConfigApi.apply(response.data.editor);- }- updateFontInput(getFontConfig());- refreshMountedFontConfigs(getFontConfig(), fontConfigElement);- fontMenu.close();- });- },- undefined,- true- );- return;}- toggleEditorFont(fontItemFromElement(itemEl));});-- function toggleEditorFont(item: IFontItem) {- const selected = selectedFonts.some((font) => font.family === item.family && font.weight === item.weight);- const fonts = selected ? selectedFonts.filter((font) =>- font.family !== item.family || font.weight !== item.weight) :- [...selectedFonts.filter((font) => font.family !== item.family), item];- persistFonts(fonts);+ const rect = fontFamiliesElement.getBoundingClientRect();+ session.show(() => fontMenu.open({x: rect.left, y: rect.bottom, h: rect.height}));+ // 内部列表自行滚动,搜索框保持固定+ fontMenu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");+ if (!isMobile()) {+ fontMenu.element.querySelector<HTMLInputElement>('[data-type="font-search"]').focus();}- }++ },});- const rect = fontFamiliesElement.getBoundingClientRect();- fontMenu.open({x: rect.left, y: rect.bottom, h: rect.height});- // 内部列表自行滚动,搜索框保持固定- fontMenu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");- if (!isMobile()) {- fontMenu.element.querySelector<HTMLInputElement>('[data-type="font-search"]').focus();- }});async function openFontWeightMenu(chipElement: HTMLElement, index: number, event: MouseEvent) {- const selectedFont = selectedFonts[index];- if (!selectedFont || selectedFont.family !== chipElement.dataset.family) {- return;- }- let availableFonts: Awaited<ReturnType<typeof loadAvailableFonts>>;- try {- availableFonts = await loadAvailableFonts();- } catch (error) {- console.warn("load font list failed", error);- return;- }- const variantsByWeight = new Map<number, IFontItem>();- availableFonts.fontItems.forEach((font) => {- if (font.family === selectedFont.family) {- variantsByWeight.set(font.weight || 400, font);- }- });- if (!variantsByWeight.has(selectedFont.weight || 400)) {- variantsByWeight.set(selectedFont.weight || 400, selectedFont);- }- const variants = Array.from(variantsByWeight.values()).sort((fontA, fontB) =>- (fontA.weight || 400) - (fontB.weight || 400));- if (variants.length < 2) {- return;- }-- const customFontsByID = new Map(availableFonts.customFonts.map((font) => [font.id, font]));- const weightMenu = new Menu();- variants.forEach((font) => {- weightMenu.addItem({- iconHTML: "",- label: escapeHtml(font.displayName || font.family),- checked: (font.weight || 400) === (selectedFont.weight || 400),- bind(element) {- const labelElement = element.querySelector<HTMLElement>(".b3-menu__label");- const customFont = font.id ? customFontsByID.get(font.id) : undefined;- if (customFont) {- registerCustomFont(customFont);- }- if (labelElement) {- labelElement.style.fontFamily = font.family;- labelElement.style.fontWeight = String(font.weight || 400);- }- },- click() {- const currentFont = selectedFonts[index];- if (!currentFont || currentFont.family !== selectedFont.family ||- currentFont.weight === font.weight) {+ await toggleMenu({+ target: chipElement,+ toggle: false,+ build: async (_menu, session) => {+ const selectedFont = selectedFonts[index];+ if (!selectedFont || selectedFont.family !== chipElement.dataset.family) {+ return;+ }+ let availableFonts: Awaited<ReturnType<typeof loadAvailableFonts>>;+ try {+ availableFonts = await loadAvailableFonts();+ if (!session.isCurrent()) {return;}- const fonts = [...selectedFonts];- fonts[index] = font;- persistFonts(fonts);+ } catch (error) {+ console.warn("load font list failed", error);+ return;}- });+ const variantsByWeight = new Map<number, IFontItem>();+ availableFonts.fontItems.forEach((font) => {+ if (font.family === selectedFont.family) {+ variantsByWeight.set(font.weight || 400, font);+ }+ });+ if (!variantsByWeight.has(selectedFont.weight || 400)) {+ variantsByWeight.set(selectedFont.weight || 400, selectedFont);+ }+ const variants = Array.from(variantsByWeight.values()).sort((fontA, fontB) =>+ (fontA.weight || 400) - (fontB.weight || 400));+ if (variants.length < 2) {+ return;+ }++ const customFontsByID = new Map(availableFonts.customFonts.map((font) => [font.id, font]));+ const weightMenu = new Menu();+ variants.forEach((font) => {+ weightMenu.addItem({+ iconHTML: "",+ label: escapeHtml(font.displayName || font.family),+ checked: (font.weight || 400) === (selectedFont.weight || 400),+ bind(element) {+ const labelElement = element.querySelector<HTMLElement>(".b3-menu__label");+ const customFont = font.id ? customFontsByID.get(font.id) : undefined;+ if (customFont) {+ registerCustomFont(customFont);+ }+ if (labelElement) {+ labelElement.style.fontFamily = font.family;+ labelElement.style.fontWeight = String(font.weight || 400);+ }+ },+ click() {+ const currentFont = selectedFonts[index];+ if (!currentFont || currentFont.family !== selectedFont.family ||+ currentFont.weight === font.weight) {+ return;+ }+ const fonts = [...selectedFonts];+ fonts[index] = font;+ persistFonts(fonts);+ }+ });+ });+ session.show(() => weightMenu.open({x: event.clientX, y: event.clientY, target: chipElement}));++ },});- weightMenu.open({x: event.clientX, y: event.clientY, target: chipElement});}function updateFontInput(data: FontConfig) {diff --git a/app/src/editor/outlineMenu.test.ts b/app/src/editor/outlineMenu.test.tsindex a8e8f59167..dbd2950c9a 100644--- a/app/src/editor/outlineMenu.test.ts+++ b/app/src/editor/outlineMenu.test.ts@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";+const {loadMenuToggle, menuAnchor} = require("../../tests/menu-toggle-fixture.cjs");for (const path of ["src/layout/dock/Outline.ts", "src/mobile/dock/MobileOutline.ts"]) {test(`${path}: outline expand menu lists actions first without stale state`, () => {@@ -13,7 +14,7 @@ for (const path of ["src/layout/dock/Outline.ts", "src/mobile/dock/MobileOutline}).outputText;const items: IMenu[] = [];const locations: unknown[] = [];- const menu = {element: {setAttribute: () => {}}, remove: () => {}, append: (item: IMenu) => items.push(item),+ const menu = {element: {setAttribute: () => {}, classList: {contains: () => true}}, remove: () => {}, append: (item: IMenu) => items.push(item),popup: (position: unknown) => locations.push(position), fullscreen: (position: unknown) => locations.push(position)};const context = {window: {siyuan: {menus: {menu}, languages: new Proxy({}, {get: (_target, key) => String(key)}),@@ -21,12 +22,14 @@ for (const path of ["src/layout/dock/Outline.ts", "src/mobile/dock/MobileOutlineConstants: {MENU_OUTLINE_EXPAND_LEVEL: "outline-expand-level"},MenuItem: class {element: IMenu; constructor(item: IMenu) { this.element = item; }},};+ Object.assign(context, loadMenuToggle(context));const Harness = runInNewContext(`${compiled}\nHarness;`, context);const harness = new Harness();const actions: unknown[] = [];harness.setAllExpanded = (expanded: boolean) => actions.push(expanded);harness.expandToLevel = (level: number) => actions.push(level);- harness.showExpandLevelMenu({getBoundingClientRect: () => ({left: 10, bottom: 20, height: 30})});+ harness.element = {querySelector: () => menuAnchor()};+ harness.showExpandLevelMenu({...menuAnchor(), getBoundingClientRect: () => ({left: 10, bottom: 20, height: 30})});assert.deepEqual(items.map(item => item.id), ["expandAll", "foldAll", "separator_all", "heading1", "heading2", "heading3", "heading4", "heading5", "heading6"]);assert.ok(items.every(item => item.current === undefined));items.forEach(item => item.click?.(undefined, undefined));diff --git a/app/src/history/docReadonly.test.ts b/app/src/history/docReadonly.test.tsindex 49ecbe5314..fc8ac2e0b1 100644--- a/app/src/history/docReadonly.test.ts+++ b/app/src/history/docReadonly.test.ts@@ -7,6 +7,7 @@ import {ModuleKind, ScriptTarget, transpileModule} from "typescript";const {parse} = require("ifdef-loader/preprocessor");const noop = () => {};+const {loadMenuToggle} = require("../../tests/menu-toggle-fixture.cjs");const loadModule = (path: string, mobile: boolean, dependencies: Record<string, unknown>, globals: object) => {const source = parse(readFileSync(resolve("src", path), "utf8"), {MOBILE: mobile, BROWSER: true}, false, true, path);@@ -14,6 +15,7 @@ const loadModule = (path: string, mobile: boolean, dependencies: Record<string,const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;+ dependencies["../../menus/menuToggle"] = loadMenuToggle(globals);runInNewContext(code, {exports, require: (name: string) => name === "./documentMenu" ?loadModule("protyle/header/documentMenu.ts", mobile, dependencies, globals) : dependencies[name] || {}, ...globals});return exports;diff --git a/app/src/history/history.ts b/app/src/history/history.tsindex a056c0aece..7aae930d19 100644--- a/app/src/history/history.ts+++ b/app/src/history/history.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {showMessage} from "../dialog/message";import {Dialog} from "../dialog";import {openInputDialog} from "../dialog/inputDialog";@@ -523,7 +524,7 @@ export const openHistory = (app: App, tab: "doc" | "notebook" | "repo" = "doc",<button class="b3-button b3-button--outline" data-type="genRepo"><svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.createSnapshot}</button>- </div>+ </div></div><div class="fn__flex fn__flex-1 history__panel"><ul data-type="repoList" class="b3-list b3-list--background fn__flex-1" style="padding: 8px 0">@@ -747,27 +748,33 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {event.preventDefault();break;} else if (type === "more") {- const row = target.closest<HTMLElement>('li[data-type="repoitem"]');- const menu = window.siyuan.menus.menu;- menu.remove();- row.querySelectorAll<HTMLElement>(".history__snapshot-menu-action").forEach(action => {- menu.append(new MenuItem({- icon: action.querySelector("use").getAttribute("xlink:href").substring(1),- label: action.getAttribute("aria-label") || action.textContent.trim(),- click: () => {- menu.remove();- action.click();- },- }).element);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ const row = target.closest<HTMLElement>('li[data-type="repoitem"]');+ const menu = window.siyuan.menus.menu;++ row.querySelectorAll<HTMLElement>(".history__snapshot-menu-action").forEach(action => {+ menu.append(new MenuItem({+ icon: action.querySelector("use").getAttribute("xlink:href").substring(1),+ label: action.getAttribute("aria-label") || action.textContent.trim(),+ click: () => {+ menu.remove();+ action.click();+ },+ }).element);+ });+ menu.append(new MenuItem({+ icon: "iconInfo",+ label: window.siyuan.languages.info,+ click: () => row.querySelectorAll(".b3-list-item__meta").forEach(item => item.classList.toggle("fn__none")),+ }).element);+ const rect = target.getBoundingClientRect();+ session.show(() => menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));++ },});- menu.append(new MenuItem({- icon: "iconInfo",- label: window.siyuan.languages.info,- click: () => row.querySelectorAll(".b3-list-item__meta").forEach(item => item.classList.toggle("fn__none")),- }).element);- const rect = target.getBoundingClientRect();- menu.popup({x: rect.left, y: rect.bottom, h: rect.height});- event.stopPropagation();+ event.stopPropagation();event.preventDefault();break;} else if (type === "toggle") {diff --git a/app/src/history/repoPanel.ts b/app/src/history/repoPanel.tsindex a72fb887c2..8394584b1a 100644--- a/app/src/history/repoPanel.ts+++ b/app/src/history/repoPanel.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {confirmDialog} from "../dialog/confirmDialog";import {fetchSyncPost} from "../util/fetch";import {escapeHtml} from "../util/escape";@@ -231,21 +232,27 @@ export const initRepoPanel = (root: HTMLElement, render: (pane: Element, page: nconst expanded = root.classList.toggle("history__snapshots--filters");button.setAttribute("aria-expanded", String(expanded));} else if (action === "source-more") {- const pane = button.closest<HTMLElement>("[data-repo-source]");- const purge = pane.querySelector<HTMLButtonElement>('[data-action="purge"]');- const menu = window.siyuan.menus.menu;- menu.remove();- menu.append(new MenuItem({- icon: "iconTrashcan",- label: purge.textContent,- disabled: !canPurgeRepo(pane.dataset.repoSource as RepoSource, window.siyuan.config.sync.provider),- click: () => {- menu.remove();- purge.click();+ toggleMenu({+ target: button,+ build: (_menu, session) => {+ const pane = button.closest<HTMLElement>("[data-repo-source]");+ const purge = pane.querySelector<HTMLButtonElement>('[data-action="purge"]');+ const menu = window.siyuan.menus.menu;++ menu.append(new MenuItem({+ icon: "iconTrashcan",+ label: purge.textContent,+ disabled: !canPurgeRepo(pane.dataset.repoSource as RepoSource, window.siyuan.config.sync.provider),+ click: () => {+ menu.remove();+ purge.click();+ },+ }).element);+ const rect = button.getBoundingClientRect();+ session.show(() => menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));+},- }).element);- const rect = button.getBoundingClientRect();- menu.popup({x: rect.left, y: rect.bottom, h: rect.height});+ });} else if (action === "range-clear") {startDate.value = "";endDate.value = "";diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.tsindex 7cbb3feefb..6d0c7cdd30 100644--- a/app/src/layout/Wnd.ts+++ b/app/src/layout/Wnd.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {Layout} from "./index";import {genUUID} from "../util/genID";import {@@ -871,82 +872,85 @@ export class Wnd {if (!target || this.headersElement.children.length === 0) {return;}- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&+ if (focus && !window.siyuan.menus.menu.element.classList.contains("fn__none") &&window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TAB_LIST) {- if (!focus) {- window.siyuan.menus.menu.remove();- }return;}- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.classList.add("b3-menu--list");- Array.from(this.headersElement.children).forEach((item: HTMLElement) => {- const iconElement = item.querySelector(".item__icon");- const graphicElement = item.querySelector(".item__graphic");- let iconHTML = undefined;- if (iconElement) {- if (iconElement.firstElementChild?.tagName === "IMG") {- // 图标为图片的文档- iconHTML = `<img src="${iconElement.firstElementChild.getAttribute("src")}" class="b3-menu__icon">`;- } else {- // 有图标的文档- iconHTML = `<span class="b3-menu__icon">${iconElement.innerHTML}</span>`;- }- } else if (!graphicElement) {- // 没有图标的文档- iconHTML = getFileTreeIconHTML("", "file", "b3-menu__icon", true);- }- window.siyuan.menus.menu.append(new MenuItem({- label: escapeHtml(item.querySelector(".item__text").textContent),- action: "iconCloseRound",- iconHTML,- icon: graphicElement ? graphicElement.firstElementChild.getAttribute("xlink:href").substring(1) : "",- bind: (element) => {- element.addEventListener("click", (itemEvent) => {- if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {- this.removeTab(item.getAttribute("data-id"));- if (element.previousElementSibling || element.nextElementSibling) {- element.remove();- setPosition(window.siyuan.menus.menu.element, rect.left + rect.width - window.siyuan.menus.menu.element.clientWidth, rect.top + rect.height);- } else {- window.siyuan.menus.menu.remove();- }+ toggleMenu({+ target: target,+ toggle: !focus,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.classList.add("b3-menu--list");+ Array.from(this.headersElement.children).forEach((item: HTMLElement) => {+ const iconElement = item.querySelector(".item__icon");+ const graphicElement = item.querySelector(".item__graphic");+ let iconHTML = undefined;+ if (iconElement) {+ if (iconElement.firstElementChild?.tagName === "IMG") {+ // 图标为图片的文档+ iconHTML = `<img src="${iconElement.firstElementChild.getAttribute("src")}" class="b3-menu__icon">`;} else {- this.switchTab(item, true);- this.showHeading();- window.siyuan.menus.menu.remove();+ // 有图标的文档+ iconHTML = `<span class="b3-menu__icon">${iconElement.innerHTML}</span>`;}- itemEvent.preventDefault();- itemEvent.stopPropagation();- });- },- current: item.classList.contains("item--focus")- }).element);- });- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TAB_LIST);- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({- x: rect.left + rect.width,- y: rect.top + rect.height,- h: rect.height,- isLeft: true- });- if (focus) {- const menu = window.siyuan.menus.menu;- const activeElement = document.activeElement;- const currentElement = menu.element.querySelector<HTMLElement>(".b3-menu__item--selected") ||- menu.element.querySelector<HTMLElement>(".b3-menu__item");- currentElement?.classList.add("b3-menu__item--current");- currentElement?.focus({preventScroll: true});- currentElement?.scrollIntoView({block: "nearest"});- // 仅在焦点仍位于菜单内时恢复,避免页签切换后抢回原编辑器焦点。- menu.removeCB = () => {- if (activeElement instanceof HTMLElement && activeElement.isConnected &&- menu.element.contains(document.activeElement)) {- activeElement.focus({preventScroll: true});+ } else if (!graphicElement) {+ // 没有图标的文档+ iconHTML = getFileTreeIconHTML("", "file", "b3-menu__icon", true);+ }+ window.siyuan.menus.menu.append(new MenuItem({+ label: escapeHtml(item.querySelector(".item__text").textContent),+ action: "iconCloseRound",+ iconHTML,+ icon: graphicElement ? graphicElement.firstElementChild.getAttribute("xlink:href").substring(1) : "",+ bind: (element) => {+ element.addEventListener("click", (itemEvent) => {+ if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {+ this.removeTab(item.getAttribute("data-id"));+ if (element.previousElementSibling || element.nextElementSibling) {+ element.remove();+ setPosition(window.siyuan.menus.menu.element, rect.left + rect.width - window.siyuan.menus.menu.element.clientWidth, rect.top + rect.height);+ } else {+ window.siyuan.menus.menu.remove();+ }+ } else {+ this.switchTab(item, true);+ this.showHeading();+ window.siyuan.menus.menu.remove();+ }+ itemEvent.preventDefault();+ itemEvent.stopPropagation();+ });+ },+ current: item.classList.contains("item--focus")+ }).element);+ });+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TAB_LIST);+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({+ x: rect.left + rect.width,+ y: rect.top + rect.height,+ h: rect.height,+ isLeft: true+ }));+ if (focus) {+ const menu = window.siyuan.menus.menu;+ const activeElement = document.activeElement;+ const currentElement = menu.element.querySelector<HTMLElement>(".b3-menu__item--selected") ||+ menu.element.querySelector<HTMLElement>(".b3-menu__item");+ currentElement?.classList.add("b3-menu__item--current");+ currentElement?.focus({preventScroll: true});+ currentElement?.scrollIntoView({block: "nearest"});+ // 仅在焦点仍位于菜单内时恢复,避免页签切换后抢回原编辑器焦点。+ menu.removeCB = () => {+ if (activeElement instanceof HTMLElement && activeElement.isConnected &&+ menu.element.contains(document.activeElement)) {+ activeElement.focus({preventScroll: true});+ }+ };}- };- }++ },+ });}private removeOverCounter(isSaveLayout = false) {diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsindex 0cea32afc1..2cb45bf367 100644--- a/app/src/layout/dock/BacklinkContent.ts+++ b/app/src/layout/dock/BacklinkContent.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {GlobalBacklinkList} from "./GlobalBacklinkList";import {bindPanelSearch} from "./panelSearch";import type {Tab} from "../Tab";@@ -490,10 +491,16 @@ export class BacklinkContent extends Model {break;case "sort":case "mSort": {- this.showSortMenu(type, target.getAttribute("data-sort"));- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height});- event.stopPropagation();+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ this.showSortMenu(type, target.getAttribute("data-sort"));+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));++ },+ });+ event.stopPropagation();break;}case "sourceFilter":@@ -983,165 +990,171 @@ export class BacklinkContent extends Model {}private showSourceFilterMenu(target: HTMLElement) {- let foldedTypes = normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes"));- const foldItems = new Map<string, HTMLElement>();- let foldResetElement: HTMLElement;- let resetElement: HTMLElement;- const applyFoldTypes = (types: string[]) => {- this.viewState?.set("foldedBlockTypes", types);- this.updateSourceFilterButton();- BACKLINK_BLOCK_TYPES.forEach(([type]) => {- if (foldedTypes.includes(type) !== types.includes(type)) {- const field = `type-fold-generation:${type}`;- this.viewState?.set(field, (this.viewState.get<number>(field) || 0) + 1);- }- });- foldedTypes = types;- foldItems.forEach((element, type) => {- element.querySelector(".b3-menu__checked")?.remove();- if (foldedTypes.includes(type)) {- element.insertAdjacentHTML("beforeend", '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>');- }- });- if (foldedTypes.length === 0) {- foldResetElement?.setAttribute("disabled", "disabled");- } else {- foldResetElement?.removeAttribute("disabled");- }- if (!getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0) {- resetElement?.setAttribute("disabled", "disabled");- } else {- resetElement?.removeAttribute("disabled");- }- this.itemRecords[0].forEach(record => {- if (record.editor && this.viewState) {- configureBacklinkTypeFold(record.editor.protyle, types, this.viewState);- }- });- this.globalList?.updateFoldTypes();- };- const blockTypeFoldSubmenu: IMenu[] = [{- label: window.siyuan.languages.reset,- icon: "iconUndo",- disabled: foldedTypes.length === 0,- bind: element => { foldResetElement = element; },- click: () => {- applyFoldTypes([]);- return true;- },- }, {type: "separator"}, ...BACKLINK_BLOCK_TYPES.map(([type, label]) => ({- label: window.siyuan.languages[label] || label,- checked: foldedTypes.includes(type),- iconHTML: "",- bind: (element: HTMLElement) => { foldItems.set(type, element); },- click: () => {- applyFoldTypes(foldedTypes.includes(type) ?- foldedTypes.filter(item => item !== type) : [...foldedTypes, type]);- return true;- },- }))];- const dailyNoteSubmenu = ([- ["all", window.siyuan.languages.all],- ["only", window.siyuan.languages.dailyNote],- ["exclude", window.siyuan.languages.nonDailyNote],- ] as Array<[TBacklinkDailyNoteFilter, string]>).map(([value, label]) => ({- checked: this.sourceFilter.dailyNote === value,- iconHTML: "",- label,- click: () => {- this.applySourceFilter({...this.sourceFilter, dailyNote: value});- }- }));- const notebookSubmenu: IMenu[] = [{- checked: this.sourceFilter.excludedNotebookIDs.length === 0,- iconHTML: "",- label: window.siyuan.languages.allNotebooks,- click: () => {- this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: []});- }- }, {type: "separator"}];- (window.siyuan.notebooks || []).filter(item => !item.closed).forEach(item => {- notebookSubmenu.push({- checked: !this.sourceFilter.excludedNotebookIDs.includes(item.id),- iconHTML: "",- label: escapeHtml(item.name),- click: () => {- const excludedNotebookIDs = new Set(this.sourceFilter.excludedNotebookIDs);- if (excludedNotebookIDs.has(item.id)) {- excludedNotebookIDs.delete(item.id);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ let foldedTypes = normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes"));+ const foldItems = new Map<string, HTMLElement>();+ let foldResetElement: HTMLElement;+ let resetElement: HTMLElement;+ const applyFoldTypes = (types: string[]) => {+ this.viewState?.set("foldedBlockTypes", types);+ this.updateSourceFilterButton();+ BACKLINK_BLOCK_TYPES.forEach(([type]) => {+ if (foldedTypes.includes(type) !== types.includes(type)) {+ const field = `type-fold-generation:${type}`;+ this.viewState?.set(field, (this.viewState.get<number>(field) || 0) + 1);+ }+ });+ foldedTypes = types;+ foldItems.forEach((element, type) => {+ element.querySelector(".b3-menu__checked")?.remove();+ if (foldedTypes.includes(type)) {+ element.insertAdjacentHTML("beforeend", '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>');+ }+ });+ if (foldedTypes.length === 0) {+ foldResetElement?.setAttribute("disabled", "disabled");} else {- excludedNotebookIDs.add(item.id);+ foldResetElement?.removeAttribute("disabled");}- this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: Array.from(excludedNotebookIDs)});- }- });- });-- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconContract",- label: window.siyuan.languages.backlinkFoldByType,- type: "submenu",- disabled: !this.viewStateLoaded || !this.viewState,- submenu: blockTypeFoldSubmenu,- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconCalendar",- label: window.siyuan.languages.dailyNote,- type: "submenu",- submenu: dailyNoteSubmenu,- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconFiles",- label: window.siyuan.languages.agentCatNotebook,- type: "submenu",- submenu: notebookSubmenu,- }).element);- window.siyuan.menus.menu.append(new MenuItem({- checked: this.sourceFilter.excludeSelf,- iconHTML: "",- label: window.siyuan.languages.excludeSelfBacklink,- click: () => {- this.applySourceFilter({...this.sourceFilter, excludeSelf: !this.sourceFilter.excludeSelf});- }- }).element);- const refFilterGeneration = this.viewStateGeneration;- let refFilterMenuElement: HTMLElement;- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: `${window.siyuan.languages.backlinkExcludeRefDefs} (${this.sourceFilter.excludedRefDefIDs.length})`,- disabled: !this.blockId,- bind: element => { refFilterMenuElement = element; },- loadSubmenu: () => {- return loadBacklinkRefFilterMenu({- id: this.blockId,- notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",- keyword: this.inputsElement[0].value,- filter: this.sourceFilter,- getSelected: () => this.sourceFilter.excludedRefDefIDs,- isCurrent: () => !this.destroyed && refFilterGeneration === this.viewStateGeneration,- apply: ids => {- this.applySourceFilter({...this.sourceFilter, excludedRefDefIDs: ids});- refFilterMenuElement.querySelector(":scope > .b3-menu__label").textContent =- `${window.siyuan.languages.backlinkExcludeRefDefs} (${this.sourceFilter.excludedRefDefIDs.length})`;- resetElement?.toggleAttribute("disabled", !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0);+ if (!getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0) {+ resetElement?.setAttribute("disabled", "disabled");+ } else {+ resetElement?.removeAttribute("disabled");+ }+ this.itemRecords[0].forEach(record => {+ if (record.editor && this.viewState) {+ configureBacklinkTypeFold(record.editor.protyle, types, this.viewState);+ }+ });+ this.globalList?.updateFoldTypes();+ };+ const blockTypeFoldSubmenu: IMenu[] = [{+ label: window.siyuan.languages.reset,+ icon: "iconUndo",+ disabled: foldedTypes.length === 0,+ bind: element => {foldResetElement = element;},+ click: () => {+ applyFoldTypes([]);+ return true;},+ }, {type: "separator"}, ...BACKLINK_BLOCK_TYPES.map(([type, label]) => ({+ label: window.siyuan.languages[label] || label,+ checked: foldedTypes.includes(type),+ iconHTML: "",+ bind: (element: HTMLElement) => {foldItems.set(type, element);},+ click: () => {+ applyFoldTypes(foldedTypes.includes(type) ?+ foldedTypes.filter(item => item !== type) : [...foldedTypes, type]);+ return true;+ },+ }))];+ const dailyNoteSubmenu = ([+ ["all", window.siyuan.languages.all],+ ["only", window.siyuan.languages.dailyNote],+ ["exclude", window.siyuan.languages.nonDailyNote],+ ] as Array<[TBacklinkDailyNoteFilter, string]>).map(([value, label]) => ({+ checked: this.sourceFilter.dailyNote === value,+ iconHTML: "",+ label,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, dailyNote: value});+ }+ }));+ const notebookSubmenu: IMenu[] = [{+ checked: this.sourceFilter.excludedNotebookIDs.length === 0,+ iconHTML: "",+ label: window.siyuan.languages.allNotebooks,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: []});+ }+ }, {type: "separator"}];+ (window.siyuan.notebooks || []).filter(item => !item.closed).forEach(item => {+ notebookSubmenu.push({+ checked: !this.sourceFilter.excludedNotebookIDs.includes(item.id),+ iconHTML: "",+ label: escapeHtml(item.name),+ click: () => {+ const excludedNotebookIDs = new Set(this.sourceFilter.excludedNotebookIDs);+ if (excludedNotebookIDs.has(item.id)) {+ excludedNotebookIDs.delete(item.id);+ } else {+ excludedNotebookIDs.add(item.id);+ }+ this.applySourceFilter({...this.sourceFilter, excludedNotebookIDs: Array.from(excludedNotebookIDs)});+ }+ });});+++ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconContract",+ label: window.siyuan.languages.backlinkFoldByType,+ type: "submenu",+ disabled: !this.viewStateLoaded || !this.viewState,+ submenu: blockTypeFoldSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconCalendar",+ label: window.siyuan.languages.dailyNote,+ type: "submenu",+ submenu: dailyNoteSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconFiles",+ label: window.siyuan.languages.agentCatNotebook,+ type: "submenu",+ submenu: notebookSubmenu,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ checked: this.sourceFilter.excludeSelf,+ iconHTML: "",+ label: window.siyuan.languages.excludeSelfBacklink,+ click: () => {+ this.applySourceFilter({...this.sourceFilter, excludeSelf: !this.sourceFilter.excludeSelf});+ }+ }).element);+ const refFilterGeneration = this.viewStateGeneration;+ let refFilterMenuElement: HTMLElement;+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: `${window.siyuan.languages.backlinkExcludeRefDefs} (${this.sourceFilter.excludedRefDefIDs.length})`,+ disabled: !this.blockId,+ bind: element => {refFilterMenuElement = element;},+ loadSubmenu: () => {+ return loadBacklinkRefFilterMenu({+ id: this.blockId,+ notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",+ keyword: this.inputsElement[0].value,+ filter: this.sourceFilter,+ getSelected: () => this.sourceFilter.excludedRefDefIDs,+ isCurrent: () => !this.destroyed && refFilterGeneration === this.viewStateGeneration,+ apply: ids => {+ this.applySourceFilter({...this.sourceFilter, excludedRefDefIDs: ids});+ refFilterMenuElement.querySelector(":scope > .b3-menu__label").textContent =+ `${window.siyuan.languages.backlinkExcludeRefDefs} (${this.sourceFilter.excludedRefDefIDs.length})`;+ resetElement?.toggleAttribute("disabled", !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0);+ },+ });+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ disabled: !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0,+ bind: element => {resetElement = element;},+ icon: "iconUndo",+ label: window.siyuan.languages.reset,+ click: () => {+ this.applySourceFilter(createBacklinkSourceFilter());+ applyFoldTypes([]);+ }+ }).element);+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));+},- }).element);- window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- disabled: !getBacklinkSourceFilterParam(this.sourceFilter) && foldedTypes.length === 0,- bind: element => { resetElement = element; },- icon: "iconUndo",- label: window.siyuan.languages.reset,- click: () => {- this.applySourceFilter(createBacklinkSourceFilter());- applyFoldTypes([]);- }- }).element);- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height});+ });}private toggleItem(liElement: HTMLElement, isMention: boolean, persist = true) {diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 4b6f0c46da..8fd56b9eb6 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -7,7 +7,7 @@ import {Constants} from "../../constants";import {getDocDisplayName, isMoveTargetAllowed, pathPosix, setNoteBook} from "../../util/pathName";import {newFileInTree} from "../../util/newFile";import {initFileMenu, initNavigationMenu, sortMenu} from "../../menus/navigation";-import {toggleFileTreeMenu} from "../../menus/fileTreeMenu";+import {toggleMenu} from "../../menus/menuToggle";import {isDocTreeDragSelectionAllowed} from "../../menus/navigationSelection";import {MenuItem} from "../../menus/Menu";import {showMessage} from "../../dialog/message";@@ -112,7 +112,7 @@ export class Files extends Model {<div class="fn__space${window.siyuan.config.readonly ? " fn__none" : ""}"></div><div data-type="more" data-menu="true" class="ariaLabel block__icon${window.siyuan.config.readonly ? " fn__none" : ""}" data-position="north" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg>- </div>+ </div><span class="fn__space"></span><span data-type="min" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.min}${updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom)}"><svg><use xlink:href='#iconMin'></use></svg></span></div>@@ -220,9 +220,11 @@ export class Files extends Model {event.preventDefault();break;} else if (type === "more") {- toggleFileTreeMenu(target, () => {- const rect = target.getBoundingClientRect();- this.initMoreMenu().popup({x: rect.left, y: rect.bottom, h: rect.height});+ toggleMenu({+ target: target, build: () => {+ const rect = target.getBoundingClientRect();+ this.initMoreMenu().popup({x: rect.left, y: rect.bottom, h: rect.height});+ }});event.preventDefault();event.stopPropagation();@@ -352,24 +354,28 @@ export class Files extends Model {if (type === "new") {newFileInTree(options.app, notebookId, pathString);} else if (type === "more-root") {- toggleFileTreeMenu(target, () => {+ toggleMenu({+ target: target, build: () => {+ const rect = target.getBoundingClientRect();+ initNavigationMenu(options.app, target.parentElement).popup({+ x: rect.left,+ y: rect.bottom,+ h: rect.height,+ });+ }+ });+ }+ }+ if (type === "more-file") {+ toggleMenu({+ target: target, build: () => {const rect = target.getBoundingClientRect();- initNavigationMenu(options.app, target.parentElement).popup({+ initFileMenu(options.app, notebookId, pathString, target.parentElement).popup({x: rect.left,y: rect.bottom,h: rect.height,});- });- }- }- if (type === "more-file") {- toggleFileTreeMenu(target, () => {- const rect = target.getBoundingClientRect();- initFileMenu(options.app, notebookId, pathString, target.parentElement).popup({- x: rect.left,- y: rect.bottom,- h: rect.height,- });+ }});}event.preventDefault();@@ -2162,7 +2168,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 && item.subFileCount > 0 ? " file-tree__item--title-expand" : ""}`;const defaultIcon = item.subFileCount === 0 ? "file" : "folder";return `<li data-node-id="${item.id}" data-name="${escapeHtmlTextAndAttr(item.name)}" draggable="true" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}"-data-type="navigation-file"+data-type="navigation-file"style="--file-toggle-width:${paddingLeft + 18}px;--file-action-offset:${paddingLeft + 20}px"class="b3-list-item b3-list-item--hide-action${actionClasses}" data-path="${item.path}"${getFileTreeDefaultIconAttr(item.icon, defaultIcon)}><span style="padding-left: ${paddingLeft}px" class="b3-list-item__toggle b3-list-item__toggle--hl${item.subFileCount === 0 ? " fn__hidden" : ""}">diff --git a/app/src/layout/dock/Inbox.ts b/app/src/layout/dock/Inbox.tsindex 8ad6a4fc0e..c5600a2dfc 100644--- a/app/src/layout/dock/Inbox.ts+++ b/app/src/layout/dock/Inbox.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";/// #if !MOBILEimport {Tab} from "../Tab";import {setPanelFocus} from "../util";@@ -239,7 +240,7 @@ ${data.shorthandContent}private genItemHTML(item: IInbox) {return sanitizeKernelHTML(`<li style="padding-left: 0" data-id="${item.oId}" class="b3-list-item"><span data-type="select" class="b3-list-item__action">- <svg><use xlink:href="#icon${this.selectIds.includes(item.oId) ? "Check" : "Uncheck"}"></use></svg>+ <svg><use xlink:href="#icon${this.selectIds.includes(item.oId) ? "Check" : "Uncheck"}"></use></svg></span><span class="fn__space--small"></span><span class="b3-list-item__text" title="${item.shorthandTitle}${item.shorthandTitle === item.shorthandDesc ? "" : "\n" + item.shorthandDesc}">${item.shorthandTitle}</span>@@ -248,85 +249,92 @@ ${data.shorthandContent}}private more(event: MouseEvent, itemElement?: HTMLElement) {- const detailsElement = this.element.querySelector(".inboxDetails");- window.siyuan.menus.menu.remove();- /// #if !MOBILE- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.refresh,- icon: "iconRefresh",- click: () => {- this.refresh(itemElement);- }- }).element);- /// #endif- let ids: string[] = [];- if (itemElement) {- ids = [itemElement.dataset.id];- } else if (detailsElement.classList.contains("fn__none")) {- ids = this.selectIds;- } else {- ids = [detailsElement.getAttribute("data-id")];- }- if (ids.length > 0) {- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.move,- icon: "iconMove",- click: () => {- this.move(ids);- }- }).element);- let protyle: IProtyle;- /// #if MOBILE- protyle = window.siyuan.mobile.editor?.protyle;- /// #else- const tab = getActiveTab(false);- if (tab?.model instanceof Editor) {- protyle = tab.model.editor?.protyle;- }- /// #endif- if (protyle?.block.rootID && !protyle.disabled && !window.siyuan.config.readonly && !window.siyuan.isPublish) {+ toggleMenu({+ target: (event.target as Element).closest(".block__icon") || itemElement,+ toggle: event.type !== "contextmenu",+ build: (_menu, session) => {+ const detailsElement = this.element.querySelector(".inboxDetails");++ /// #if !MOBILEwindow.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.insertToCurrentDoc,- icon: "iconAdd",+ label: window.siyuan.languages.refresh,+ icon: "iconRefresh",click: () => {- void this.insertToCurrentDoc(ids, protyle.block.rootID);+ this.refresh(itemElement);}}).element);- }- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.remove,- icon: "iconTrashcan",- click: () => {- let removeTitle = "";- ids.forEach((id, index) => {- removeTitle += '<code class="fn__code">' + escapeHtml(this.data[id].shorthandTitle) + "</code>" + (index === ids.length - 1 ? "" : ", ");- });- confirmDialog(window.siyuan.languages.deleteOpConfirm, `${window.siyuan.languages.confirmDelete} ${removeTitle}?`, () => {- if (itemElement) {- this.remove([itemElement.dataset.id]);- } else if (detailsElement.classList.contains("fn__none")) {- this.remove();- } else {- this.remove([detailsElement.getAttribute("data-id")]);+ /// #endif+ let ids: string[] = [];+ if (itemElement) {+ ids = [itemElement.dataset.id];+ } else if (detailsElement.classList.contains("fn__none")) {+ ids = this.selectIds;+ } else {+ ids = [detailsElement.getAttribute("data-id")];+ }+ if (ids.length > 0) {+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.move,+ icon: "iconMove",+ click: () => {+ this.move(ids);+ }+ }).element);+ let protyle: IProtyle;+ /// #if MOBILE+ protyle = window.siyuan.mobile.editor?.protyle;+ /// #else+ const tab = getActiveTab(false);+ if (tab?.model instanceof Editor) {+ protyle = tab.model.editor?.protyle;+ }+ /// #endif+ if (protyle?.block.rootID && !protyle.disabled && !window.siyuan.config.readonly && !window.siyuan.isPublish) {+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.insertToCurrentDoc,+ icon: "iconAdd",+ click: () => {+ void this.insertToCurrentDoc(ids, protyle.block.rootID);+ }+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.remove,+ icon: "iconTrashcan",+ click: () => {+ let removeTitle = "";+ ids.forEach((id, index) => {+ removeTitle += '<code class="fn__code">' + escapeHtml(this.data[id].shorthandTitle) + "</code>" + (index === ids.length - 1 ? "" : ", ");+ });+ confirmDialog(window.siyuan.languages.deleteOpConfirm, `${window.siyuan.languages.confirmDelete} ${removeTitle}?`, () => {+ if (itemElement) {+ this.remove([itemElement.dataset.id]);+ } else if (detailsElement.classList.contains("fn__none")) {+ this.remove();+ } else {+ this.remove([detailsElement.getAttribute("data-id")]);+ }+ }, undefined, true);}- }, undefined, true);+ }).element);}- }).element);- }- emitOpenMenu({- type: "open-menu-inbox",- detail: {- ids,- element: itemElement || detailsElement,+ emitOpenMenu({+ type: "open-menu-inbox",+ detail: {+ ids,+ element: itemElement || detailsElement,+ },+ separatorPosition: "top",+ });+ const button = (event.target as Element).closest("[data-type='more']");+ const rect = (itemElement || button)?.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({+ x: !itemElement && rect ? rect.left : event.clientX,+ y: rect ? rect.bottom : event.clientY + 16,+ h: rect ? rect.height : 0,+ }));+},- separatorPosition: "top",- });- const button = (event.target as Element).closest("[data-type='more']");- const rect = (itemElement || button)?.getBoundingClientRect();- window.siyuan.menus.menu.popup({- x: !itemElement && rect ? rect.left : event.clientX,- y: rect ? rect.bottom : event.clientY + 16,- h: rect ? rect.height : 0,});}diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex 39e08ab3ea..f6156085fa 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {bindPanelSearch} from "./panelSearch";import type {BlockBreadcrumbRequestInput} from "../../types/api";import {Tab} from "../Tab";@@ -106,7 +107,6 @@ export class Outline extends Model {element: this.element,data: null,click: (element: HTMLElement, event?: MouseEvent) => {- window.siyuan.menus.menu.remove();if (event) {const actionElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item__action");if (actionElement) {@@ -114,6 +114,7 @@ export class Outline extends Model {return;}}+ window.siyuan.menus.menu.remove();const id = element.getAttribute("data-node-id");if (this.isPreview) {const headElement = document.getElementById(id);@@ -906,38 +907,42 @@ export class Outline extends Model {* 显示展开层级菜单*/private showExpandLevelMenu(target: HTMLElement) {- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_EXPAND_LEVEL);- window.siyuan.menus.menu.append(new MenuItem({- id: "expandAll",- icon: "iconExpand",- label: window.siyuan.languages.expandAll,- accelerator: window.siyuan.config.keymap.editor.general.expand.custom,- click: () => this.setAllExpanded(true)- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "foldAll",- icon: "iconContract",- label: window.siyuan.languages.foldAll,- accelerator: window.siyuan.config.keymap.editor.general.collapse.custom,- click: () => this.setAllExpanded(false)- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_all", type: "separator"}).element);- for (let i = 1; i <= 6; i++) {- window.siyuan.menus.menu.append(new MenuItem({- id: `heading${i}`,- icon: `iconH${i}`,- label: window.siyuan.languages[`heading${i}`],- click: () => this.expandToLevel(i)- }).element);- }- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({- x: rect.left,- y: rect.bottom,- h: rect.height+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_EXPAND_LEVEL);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandAll",+ icon: "iconExpand",+ label: window.siyuan.languages.expandAll,+ accelerator: window.siyuan.config.keymap.editor.general.expand.custom,+ click: () => this.setAllExpanded(true)+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldAll",+ icon: "iconContract",+ label: window.siyuan.languages.foldAll,+ accelerator: window.siyuan.config.keymap.editor.general.collapse.custom,+ click: () => this.setAllExpanded(false)+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_all", type: "separator"}).element);+ for (let i = 1; i <= 6; i++) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: `heading${i}`,+ icon: `iconH${i}`,+ label: window.siyuan.languages[`heading${i}`],+ click: () => this.expandToLevel(i)+ }).element);+ }+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));++ },});- return window.siyuan.menus.menu;}/**@@ -998,420 +1003,427 @@ export class Outline extends Model {* 显示右键菜单*/private showContextMenu(element: HTMLElement, event: MouseEvent) {- if (this.isPreview) {- return; // 预览模式下不显示右键菜单- }- const currentLevel = this.getHeadingLevel(element);- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_CONTEXT);- const id = element.getAttribute("data-node-id");- if (!window.siyuan.config.readonly) {- // 升级- if (currentLevel > 1) {- window.siyuan.menus.menu.append(new MenuItem({- id: "upgrade",- icon: "iconUp",- label: window.siyuan.languages.upgrade,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (data) {- turnsIntoTransaction({- protyle: data.protyle,- selectsElement: [data.blockElement],- type: "Blocks2Hs",- level: currentLevel - 1- });- }- }- }).element);- }+ toggleMenu({+ target: event.type === "contextmenu" ? element : (event.target as Element).closest(".b3-list-item__action") || element,+ toggle: event.type !== "contextmenu",+ build: (_menu, session) => {+ if (this.isPreview) {+ return; // 预览模式下不显示右键菜单+ }+ const currentLevel = this.getHeadingLevel(element);- // 降级- if (currentLevel < 6) {- window.siyuan.menus.menu.append(new MenuItem({- id: "downgrade",- icon: "iconDown",- label: window.siyuan.languages.downgrade,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (data) {- turnsIntoTransaction({- protyle: data.protyle,- selectsElement: [data.blockElement],- type: "Blocks2Hs",- level: currentLevel + 1- });- }+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_CONTEXT);+ const id = element.getAttribute("data-node-id");+ if (!window.siyuan.config.readonly) {+ // 升级+ if (currentLevel > 1) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "upgrade",+ icon: "iconUp",+ label: window.siyuan.languages.upgrade,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (data) {+ turnsIntoTransaction({+ protyle: data.protyle,+ selectsElement: [data.blockElement],+ type: "Blocks2Hs",+ level: currentLevel - 1+ });+ }+ }+ }).element);}- }).element);- }-- // 带子标题转换- checkFold(id, (zoomIn) => {- const action = isPhablet() ? Constants.CB_GET_HL : Constants.CB_GET_FOCUS;- openFileById({- app: this.app,- id,- scrollPosition: "start",- action: zoomIn ? [action, Constants.CB_GET_ALL, Constants.CB_GET_HTML, Constants.CB_GET_OUTLINE] : [action, Constants.CB_GET_OUTLINE, Constants.CB_GET_SETID, Constants.CB_GET_CONTEXT, Constants.CB_GET_HTML],- });- });- this.setCurrentById(id, false);- const headingSubMenu = [];- if (currentLevel !== 1) {- headingSubMenu.push(this.genHeadingTransform(id, 1));- }- if (currentLevel !== 2) {- headingSubMenu.push(this.genHeadingTransform(id, 2));- }- if (currentLevel !== 3) {- headingSubMenu.push(this.genHeadingTransform(id, 3));- }- if (currentLevel !== 4) {- headingSubMenu.push(this.genHeadingTransform(id, 4));- }- if (currentLevel !== 5) {- headingSubMenu.push(this.genHeadingTransform(id, 5));- }- if (currentLevel !== 6) {- headingSubMenu.push(this.genHeadingTransform(id, 6));- }- if (headingSubMenu.length > 0) {- window.siyuan.menus.menu.append(new MenuItem({- id: "tWithSubtitle",- type: "submenu",- icon: "iconRefresh",- label: window.siyuan.languages.tWithSubtitle,- submenu: headingSubMenu- }).element);- }+ // 降级+ if (currentLevel < 6) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "downgrade",+ icon: "iconDown",+ label: window.siyuan.languages.downgrade,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (data) {+ turnsIntoTransaction({+ protyle: data.protyle,+ selectsElement: [data.blockElement],+ type: "Blocks2Hs",+ level: currentLevel + 1+ });+ }+ }+ }).element);+ }- const rootID = this.blockId;- window.siyuan.menus.menu.append(new MenuItem({- id: "headingBatch",- icon: "iconHeadings",- label: window.siyuan.languages.headingBatch,- click: () => {- const protyle = getAllModels().editor.find(item =>- item.editor.protyle.block.rootID === rootID)?.editor.protyle;- if (canBatchConvertHeadings(protyle, rootID, this.isPreview)) {- void showHeadingBatchDialog(protyle, () => rootID === this.blockId &&- canBatchConvertHeadings(protyle, rootID, this.isPreview) && protyle.element.isConnected);+ // 带子标题转换+ checkFold(id, (zoomIn) => {+ const action = isPhablet() ? Constants.CB_GET_HL : Constants.CB_GET_FOCUS;+ openFileById({+ app: this.app,+ id,+ scrollPosition: "start",+ action: zoomIn ? [action, Constants.CB_GET_ALL, Constants.CB_GET_HTML, Constants.CB_GET_OUTLINE] : [action, Constants.CB_GET_OUTLINE, Constants.CB_GET_SETID, Constants.CB_GET_CONTEXT, Constants.CB_GET_HTML],+ });+ });+ this.setCurrentById(id, false);+ const headingSubMenu = [];+ if (currentLevel !== 1) {+ headingSubMenu.push(this.genHeadingTransform(id, 1));}- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);-- // 在前面插入同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "insertSameLevelHeadingBefore",- icon: "iconBefore",- label: window.siyuan.languages.insertSameLevelHeadingBefore,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (!data) {- return;+ if (currentLevel !== 2) {+ headingSubMenu.push(this.genHeadingTransform(id, 2));+ }+ if (currentLevel !== 3) {+ headingSubMenu.push(this.genHeadingTransform(id, 3));+ }+ if (currentLevel !== 4) {+ headingSubMenu.push(this.genHeadingTransform(id, 4));+ }+ if (currentLevel !== 5) {+ headingSubMenu.push(this.genHeadingTransform(id, 5));+ }+ if (currentLevel !== 6) {+ headingSubMenu.push(this.genHeadingTransform(id, 6));}- const newId = Lute.NewNodeID();- const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;- const previousID = data.blockElement.previousElementSibling?.getAttribute("data-node-id");- data.blockElement.insertAdjacentHTML("beforebegin", html);- const newElement = data.blockElement.previousElementSibling;- newElement.scrollIntoView();- focusByWbr(newElement, document.createRange());- transaction(data.protyle, [{- action: "insert",- data: html,- id: newId,- previousID,- parentID: data.blockElement.parentElement.getAttribute("data-node-id") || data.protyle.block.parentID,- }], [{- action: "delete",- id: newId- }]);- }- }).element);-- // 在后面插入同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "insertSameLevelHeadingAfter",- icon: "iconAfter",- label: window.siyuan.languages.insertSameLevelHeadingAfter,- click: () => {- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, (deleteResponse) => {- const data = this.getProtyleAndBlockElement(element);- if (!data || !deleteResponse.data?.doOperations?.length) {- return;- }- const previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;-- const newId = Lute.NewNodeID();- const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;- const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);- if (previousElement) {- previousElement.insertAdjacentHTML("afterend", html);- const newElement = previousElement.nextElementSibling;- newElement.scrollIntoView();- focusByWbr(newElement, document.createRange());- }- transaction(data.protyle, [{- action: "insert",- data: html,- id: newId,- previousID,- }], [{- action: "delete",- id: newId- }]);- });- }- }).element);- // 添加子标题- if (currentLevel < 6) { // 只有当前级别小于6时才能添加子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "addChildHeading",- icon: "iconAdd",- label: window.siyuan.languages.addChildHeading,- click: () => {- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, (deleteResponse) => {- if (!deleteResponse.data?.doOperations?.length || !deleteResponse.data?.undoOperations) {- return;- }- let previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;- deleteResponse.data.undoOperations.find((operationsItem, index: number) => {- if (typeof operationsItem.data !== "string") {- return false;- }- const startIndex = operationsItem.data.indexOf(' data-subtype="h');- if (index > 0 && startIndex > -1 && startIndex < 260 && parseInt(operationsItem.data.substring(startIndex + 16, startIndex + 17)) === currentLevel + 1) {- previousID = deleteResponse.data.undoOperations[index - 1].id;- return true;- }- });+ if (headingSubMenu.length > 0) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "tWithSubtitle",+ type: "submenu",+ icon: "iconRefresh",+ label: window.siyuan.languages.tWithSubtitle,+ submenu: headingSubMenu+ }).element);+ }+ const rootID = this.blockId;+ window.siyuan.menus.menu.append(new MenuItem({+ id: "headingBatch",+ icon: "iconHeadings",+ label: window.siyuan.languages.headingBatch,+ click: () => {+ const protyle = getAllModels().editor.find(item =>+ item.editor.protyle.block.rootID === rootID)?.editor.protyle;+ if (canBatchConvertHeadings(protyle, rootID, this.isPreview)) {+ void showHeadingBatchDialog(protyle, () => rootID === this.blockId &&+ canBatchConvertHeadings(protyle, rootID, this.isPreview) && protyle.element.isConnected);+ }+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);+ // 在前面插入同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "insertSameLevelHeadingBefore",+ icon: "iconBefore",+ label: window.siyuan.languages.insertSameLevelHeadingBefore,+ click: () => {const data = this.getProtyleAndBlockElement(element);if (!data) {return;}const newId = Lute.NewNodeID();- const html = `<div data-subtype="h${currentLevel + 1}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel + 1}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;- const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);- if (previousElement) {- previousElement.insertAdjacentHTML("afterend", html);- const newElement = previousElement.nextElementSibling;- newElement.scrollIntoView();- focusByWbr(newElement, document.createRange());- }+ const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;+ const previousID = data.blockElement.previousElementSibling?.getAttribute("data-node-id");+ data.blockElement.insertAdjacentHTML("beforebegin", html);+ const newElement = data.blockElement.previousElementSibling;+ newElement.scrollIntoView();+ focusByWbr(newElement, document.createRange());transaction(data.protyle, [{action: "insert",data: html,id: newId,previousID,+ parentID: data.blockElement.parentElement.getAttribute("data-node-id") || data.protyle.block.parentID,}], [{action: "delete",id: newId}]);- });- }- }).element);- }+ }+ }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);- }+ // 在后面插入同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "insertSameLevelHeadingAfter",+ icon: "iconAfter",+ label: window.siyuan.languages.insertSameLevelHeadingAfter,+ click: () => {+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, (deleteResponse) => {+ const data = this.getProtyleAndBlockElement(element);+ if (!data || !deleteResponse.data?.doOperations?.length) {+ return;+ }+ const previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;- // 复制带子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "copyHeadings1",- icon: "iconCopy",- label: `${window.siyuan.languages.copy} ${window.siyuan.languages.headings1}`,- click: () => {- const data = this.getProtyleAndBlockElement(element);- fetchPost("/api/block/getHeadingChildrenDOM", {- id,- removeFoldAttr: false- }, async (response) => {- await writeBlockDOMClipboard(data.protyle.lute, response.data);- });- }- }).element);-- if (!window.siyuan.config.readonly) {- // 剪切带子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "cutHeadings1",- icon: "iconCut",- label: `${window.siyuan.languages.cut} ${window.siyuan.languages.headings1}`,- click: () => {- const data = this.getProtyleAndBlockElement(element);- fetchPost("/api/block/getHeadingChildrenDOM", {- id,- removeFoldAttr: false- }, (response) => {- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, async (deleteResponse) => {- const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = deleteResponse.data;- const deletedIDs = headingTransaction.doOperations.map(- (operation: IOperation) => operation.id);- if (!await confirmBlockRef({- scope: "blocks",- ids: deletedIDs,- deletedIDs,- notebook: data.protyle.notebookId,- }, data.protyle)) {- return;- }- if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {- return;- }- if (!await writeBlockDOMClipboard(data.protyle.lute, response.data)) {- return;- }- if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {- return;- }- headingTransaction.doOperations.forEach((operation: IOperation) => {- data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {- itemElement.remove();- });- });- if (data.protyle.wysiwyg.element.childElementCount === 0) {- const newID = Lute.NewNodeID();- const emptyElement = genEmptyElement(false, false, newID);- data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);- headingTransaction.doOperations.push({+ const newId = Lute.NewNodeID();+ const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;+ const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);+ if (previousElement) {+ previousElement.insertAdjacentHTML("afterend", html);+ const newElement = previousElement.nextElementSibling;+ newElement.scrollIntoView();+ focusByWbr(newElement, document.createRange());+ }+ transaction(data.protyle, [{action: "insert",- data: emptyElement.outerHTML,- id: newID,- parentID: data.protyle.block.parentID- });- headingTransaction.undoOperations.push({+ data: html,+ id: newId,+ previousID,+ }], [{action: "delete",- id: newID,+ id: newId+ }]);+ });+ }+ }).element);++ // 添加子标题+ if (currentLevel < 6) { // 只有当前级别小于6时才能添加子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "addChildHeading",+ icon: "iconAdd",+ label: window.siyuan.languages.addChildHeading,+ click: () => {+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, (deleteResponse) => {+ if (!deleteResponse.data?.doOperations?.length || !deleteResponse.data?.undoOperations) {+ return;+ }+ let previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;+ deleteResponse.data.undoOperations.find((operationsItem, index: number) => {+ if (typeof operationsItem.data !== "string") {+ return false;+ }+ const startIndex = operationsItem.data.indexOf(' data-subtype="h');+ if (index > 0 && startIndex > -1 && startIndex < 260 && parseInt(operationsItem.data.substring(startIndex + 16, startIndex + 17)) === currentLevel + 1) {+ previousID = deleteResponse.data.undoOperations[index - 1].id;+ return true;+ }+ });+++ const data = this.getProtyleAndBlockElement(element);+ if (!data) {+ return;+ }+ const newId = Lute.NewNodeID();+ const html = `<div data-subtype="h${currentLevel + 1}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel + 1}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;+ const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);+ if (previousElement) {+ previousElement.insertAdjacentHTML("afterend", html);+ const newElement = previousElement.nextElementSibling;+ newElement.scrollIntoView();+ focusByWbr(newElement, document.createRange());+ }+ transaction(data.protyle, [{+ action: "insert",+ data: html,+ id: newId,+ previousID,+ }], [{+ action: "delete",+ id: newId+ }]);});- focusBlock(emptyElement);}- transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);- });- });+ }).element);+ }++ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);}- }).element);-- // 删除- window.siyuan.menus.menu.append(new MenuItem({- id: "deleteHeadings1",- icon: "iconTrashcan",- label: `${window.siyuan.languages.delete} ${window.siyuan.languages.headings1}`,- click: () => {- const data = this.getProtyleAndBlockElement(element);- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, async (response) => {- const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = response.data;- const deletedIDs = headingTransaction.doOperations.map((operation: IOperation) => operation.id);- if (!await confirmBlockRef({- scope: "blocks",- ids: deletedIDs,- deletedIDs,- notebook: data.protyle.notebookId,- }, data.protyle)) {- return;- }- if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {- return;- }- headingTransaction.doOperations.forEach((operation: IOperation) => {- data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {- itemElement.remove();- });++ // 复制带子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "copyHeadings1",+ icon: "iconCopy",+ label: `${window.siyuan.languages.copy} ${window.siyuan.languages.headings1}`,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ fetchPost("/api/block/getHeadingChildrenDOM", {+ id,+ removeFoldAttr: false+ }, async (response) => {+ await writeBlockDOMClipboard(data.protyle.lute, response.data);});- if (data.protyle.wysiwyg.element.childElementCount === 0) {- const newID = Lute.NewNodeID();- const emptyElement = genEmptyElement(false, false, newID);- data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);- headingTransaction.doOperations.push({- action: "insert",- data: emptyElement.outerHTML,- id: newID,- parentID: data.protyle.block.parentID+ }+ }).element);++ if (!window.siyuan.config.readonly) {+ // 剪切带子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "cutHeadings1",+ icon: "iconCut",+ label: `${window.siyuan.languages.cut} ${window.siyuan.languages.headings1}`,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ fetchPost("/api/block/getHeadingChildrenDOM", {+ id,+ removeFoldAttr: false+ }, (response) => {+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, async (deleteResponse) => {+ const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = deleteResponse.data;+ const deletedIDs = headingTransaction.doOperations.map(+ (operation: IOperation) => operation.id);+ if (!await confirmBlockRef({+ scope: "blocks",+ ids: deletedIDs,+ deletedIDs,+ notebook: data.protyle.notebookId,+ }, data.protyle)) {+ return;+ }+ if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ return;+ }+ if (!await writeBlockDOMClipboard(data.protyle.lute, response.data)) {+ return;+ }+ if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ return;+ }+ headingTransaction.doOperations.forEach((operation: IOperation) => {+ data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {+ itemElement.remove();+ });+ });+ if (data.protyle.wysiwyg.element.childElementCount === 0) {+ const newID = Lute.NewNodeID();+ const emptyElement = genEmptyElement(false, false, newID);+ data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);+ headingTransaction.doOperations.push({+ action: "insert",+ data: emptyElement.outerHTML,+ id: newID,+ parentID: data.protyle.block.parentID+ });+ headingTransaction.undoOperations.push({+ action: "delete",+ id: newID,+ });+ focusBlock(emptyElement);+ }+ transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);+ });});- headingTransaction.undoOperations.push({- action: "delete",- id: newID,+ }+ }).element);++ // 删除+ window.siyuan.menus.menu.append(new MenuItem({+ id: "deleteHeadings1",+ icon: "iconTrashcan",+ label: `${window.siyuan.languages.delete} ${window.siyuan.languages.headings1}`,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, async (response) => {+ const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = response.data;+ const deletedIDs = headingTransaction.doOperations.map((operation: IOperation) => operation.id);+ if (!await confirmBlockRef({+ scope: "blocks",+ ids: deletedIDs,+ deletedIDs,+ notebook: data.protyle.notebookId,+ }, data.protyle)) {+ return;+ }+ if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ return;+ }+ headingTransaction.doOperations.forEach((operation: IOperation) => {+ data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {+ itemElement.remove();+ });+ });+ if (data.protyle.wysiwyg.element.childElementCount === 0) {+ const newID = Lute.NewNodeID();+ const emptyElement = genEmptyElement(false, false, newID);+ data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);+ headingTransaction.doOperations.push({+ action: "insert",+ data: emptyElement.outerHTML,+ id: newID,+ parentID: data.protyle.block.parentID+ });+ headingTransaction.undoOperations.push({+ action: "delete",+ id: newID,+ });+ focusBlock(emptyElement);+ }+ transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);});- focusBlock(emptyElement);}- transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);- });+ }).element);}- }).element);- }- window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);-- // 展开子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "expandChildHeading",- icon: "iconExpand",- label: window.siyuan.languages.expandChildHeading,- accelerator: "⌘" + window.siyuan.languages.clickArrow,- click: () => this.collapseChildren(element, true)- }).element);-- // 折叠子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "foldChildHeading",- icon: "iconContract",- label: window.siyuan.languages.foldChildHeading,- accelerator: "⌘" + window.siyuan.languages.clickArrow,- click: () => this.collapseChildren(element, false)- }).element);-- // 展开同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "expandSameLevelHeading",- icon: "iconExpand",- label: window.siyuan.languages.expandSameLevelHeading,- accelerator: "⌥" + window.siyuan.languages.clickArrow,- click: () => this.collapseSameLevel(element, true)- }).element);-- // 折叠同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "foldSameLevelHeading",- icon: "iconContract",- label: window.siyuan.languages.foldSameLevelHeading,- accelerator: "⌥" + window.siyuan.languages.clickArrow,- click: () => this.collapseSameLevel(element, false)- }).element);-- // 全部展开- window.siyuan.menus.menu.append(new MenuItem({- id: "expandAll",- icon: "iconExpand",- label: window.siyuan.languages.expandAll,- click: () => this.setAllExpanded(true)- }).element);-- // 全部折叠- window.siyuan.menus.menu.append(new MenuItem({- id: "foldAll",- icon: "iconContract",- label: window.siyuan.languages.foldAll,- click: () => this.setAllExpanded(false)- }).element);-- const rect = element.getBoundingClientRect();- window.siyuan.menus.menu.popup({- x: event.clientX,- y: rect.bottom,- h: rect.height,+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);++ // 展开子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandChildHeading",+ icon: "iconExpand",+ label: window.siyuan.languages.expandChildHeading,+ accelerator: "⌘" + window.siyuan.languages.clickArrow,+ click: () => this.collapseChildren(element, true)+ }).element);++ // 折叠子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldChildHeading",+ icon: "iconContract",+ label: window.siyuan.languages.foldChildHeading,+ accelerator: "⌘" + window.siyuan.languages.clickArrow,+ click: () => this.collapseChildren(element, false)+ }).element);++ // 展开同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandSameLevelHeading",+ icon: "iconExpand",+ label: window.siyuan.languages.expandSameLevelHeading,+ accelerator: "⌥" + window.siyuan.languages.clickArrow,+ click: () => this.collapseSameLevel(element, true)+ }).element);++ // 折叠同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldSameLevelHeading",+ icon: "iconContract",+ label: window.siyuan.languages.foldSameLevelHeading,+ accelerator: "⌥" + window.siyuan.languages.clickArrow,+ click: () => this.collapseSameLevel(element, false)+ }).element);++ // 全部展开+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandAll",+ icon: "iconExpand",+ label: window.siyuan.languages.expandAll,+ click: () => this.setAllExpanded(true)+ }).element);++ // 全部折叠+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldAll",+ icon: "iconContract",+ label: window.siyuan.languages.foldAll,+ click: () => this.setAllExpanded(false)+ }).element);++ const rect = element.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({+ x: event.clientX,+ y: rect.bottom,+ h: rect.height,+ }));++ },});}diff --git a/app/src/layout/dock/PinnedDocs.test.ts b/app/src/layout/dock/PinnedDocs.test.tsindex bb6dff9db8..e6c4703f48 100644--- a/app/src/layout/dock/PinnedDocs.test.ts+++ b/app/src/layout/dock/PinnedDocs.test.ts@@ -64,10 +64,10 @@ const loadPanel = (fetchCode = 0) => {return {code: kind === "http" ? fetchCode : 0, data: args[0] === "/api/filetree/listDocsByPath" ? childData : docs};};const exports: {PinnedDocs?: {prototype: object}} = {};- const fileTreeMenu = {};- runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "../../menus/fileTreeMenu.ts"), "utf8"), {+ const menuToggle = {};+ runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "../../menus/menuToggle.ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},- }).outputText, {exports: fileTreeMenu, window: {siyuan: runtime}});+ }).outputText, {exports: menuToggle, window: {siyuan: runtime}});const source = ts.transpileModule(readFileSync(join(__dirname, "PinnedDocs.ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},}).outputText;@@ -84,7 +84,7 @@ const loadPanel = (fetchCode = 0) => {remove() { calls.push({kind: "removeGhost", args: [this]}); },})},require: (name: string) => {- if (name.endsWith("/fileTreeMenu")) { return fileTreeMenu; }+ if (name.endsWith("/menuToggle")) { return menuToggle; }if (name.endsWith("/menuClick")) { return {globalClickHideMenu: () => {}}; }if (name.endsWith("/dragTip")) { return {setDragTipGhost: record("dragTipGhost"),showDragTip: (...args: unknown[]) => tips.push(args), hideDragTip: () => tips.push([])}; }@@ -151,7 +151,8 @@ test("collapse clears descendant expansion and persists the closed section", asytest("pinned document more actions open the source document menu and toggle on repeated clicks", () => {const {panel, calls} = loadPanel();const row = {dataset: {nodeId: "document", notebook: "notebook", path: "/document.sy"}};- const button = {getBoundingClientRect: () => ({left: 180, bottom: 120, height: 24})};+ const button = {closest: (): null => null, setAttribute: () => {},+ getBoundingClientRect: () => ({left: 180, bottom: 120, height: 24})};const event = {stopPropagation: () => {}, clientX: 10, clientY: 20,target: {closest: (selector: string) => selector === "[data-pin-row]" ? row : selector === "[data-pin-more]" ? button : null},diff --git a/app/src/layout/dock/PinnedDocs.ts b/app/src/layout/dock/PinnedDocs.tsindex 0d5efaeddc..5f3dc18e0d 100644--- a/app/src/layout/dock/PinnedDocs.ts+++ b/app/src/layout/dock/PinnedDocs.ts@@ -7,7 +7,7 @@ import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";import {openEmojiPanel} from "../../emoji";import {escapeHtml} from "../../util/escape";import {initFileMenu} from "../../menus/navigation";-import {toggleFileTreeMenu} from "../../menus/fileTreeMenu";+import {toggleMenu} from "../../menus/menuToggle";import {globalClickHideMenu} from "../../menus/menuClick";import {parseDocumentTabDragData, parseDocumentTreeDragData} from "../../util/fileTreeMove";import {reorderSortedFileTree} from "../../util/fileTreeReorder";@@ -461,9 +461,11 @@ export class PinnedDocs {}const moreButton = target.closest("[data-pin-more]");if (moreButton) {- toggleFileTreeMenu(moreButton, () => {- const rect = moreButton.getBoundingClientRect();- this.menu(row, {x: rect.left, y: rect.bottom, h: rect.height});+ toggleMenu({+ target: moreButton, build: () => {+ const rect = moreButton.getBoundingClientRect();+ this.menu(row, {x: rect.left, y: rect.bottom, h: rect.height});+ }});} else if (target.closest("[data-pin-new]")) {newFileInTree(this.app, row.dataset.notebook, row.dataset.path);diff --git a/app/src/layout/dock/Tag.ts b/app/src/layout/dock/Tag.tsindex e06bd05585..a6cb7a4c22 100644--- a/app/src/layout/dock/Tag.ts+++ b/app/src/layout/dock/Tag.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {Tab} from "../Tab";import {bindPanelSearch} from "./panelSearch";import {Model} from "../Model";@@ -103,58 +104,63 @@ export class Tag extends Model {getDockByType("tag").toggleModel("tag", false, true);break;case "sort": {- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 0 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameASC,- click: () => {- window.siyuan.config.tag.sort = 0;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 1 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameDESC,- click: () => {- window.siyuan.config.tag.sort = 1;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 4 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameNatASC,- click: () => {- window.siyuan.config.tag.sort = 4;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 5 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameNatDESC,- click: () => {- window.siyuan.config.tag.sort = 5;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 7 ? "iconSelect" : undefined,- label: window.siyuan.languages.refCountASC,- click: () => {- window.siyuan.config.tag.sort = 7;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 8 ? "iconSelect" : undefined,- label: window.siyuan.languages.refCountDESC,- click: () => {- window.siyuan.config.tag.sort = 8;- this.update();+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 0 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameASC,+ click: () => {+ window.siyuan.config.tag.sort = 0;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 1 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameDESC,+ click: () => {+ window.siyuan.config.tag.sort = 1;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 4 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameNatASC,+ click: () => {+ window.siyuan.config.tag.sort = 4;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 5 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameNatDESC,+ click: () => {+ window.siyuan.config.tag.sort = 5;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 7 ? "iconSelect" : undefined,+ label: window.siyuan.languages.refCountASC,+ click: () => {+ window.siyuan.config.tag.sort = 7;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 8 ? "iconSelect" : undefined,+ label: window.siyuan.languages.refCountDESC,+ click: () => {+ window.siyuan.config.tag.sort = 8;+ this.update();+ },+ }).element);+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));+},- }).element);- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height});- event.preventDefault();+ });+ event.preventDefault();event.stopPropagation();break;}diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 5b1b5b503b..c7e7fb016d 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../../menus/menuToggle";import {fetchWithAppId} from "../../../util/fetchWithAppId";import {Model} from "../../Model";import type {App} from "../../../index";@@ -762,24 +763,30 @@ export class AgentChat extends Model {private initPermissionMenu() {this.applyPermissionMode(this.permissionMode);this.permissionButton.addEventListener("click", (event: MouseEvent) => {- event.stopPropagation();- const menu = new Menu("agent-chat-permission");- if (menu.isOpen) {- return;- }- (["confirm", "allowSession"] as AgentPermissionMode[]).forEach(mode => {- menu.addItem({- iconHTML: "",- label: escapeHtml(this.permissionLabel(mode)),- current: mode === this.permissionMode,- click: () => {- void this.changePermissionMode(mode);- },- });+ toggleMenu({+ target: this.permissionButton,+ build: (_menu, session) => {+ event.stopPropagation();+ const menu = new Menu("agent-chat-permission");+ if (menu.isOpen) {+ return;+ }+ (["confirm", "allowSession"] as AgentPermissionMode[]).forEach(mode => {+ menu.addItem({+ iconHTML: "",+ label: escapeHtml(this.permissionLabel(mode)),+ current: mode === this.permissionMode,+ click: () => {+ void this.changePermissionMode(mode);+ },+ });+ });+ const rect = this.permissionButton.getBoundingClientRect();+ menu.element.style.minWidth = `${rect.width}px`;+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.permissionButton}));++ },});- const rect = this.permissionButton.getBoundingClientRect();- menu.element.style.minWidth = `${rect.width}px`;- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.permissionButton});});}@@ -792,26 +799,32 @@ export class AgentChat extends Model {};updateLabel();this.reasoningEffortButton.addEventListener("click", (event: MouseEvent) => {- event.stopPropagation();- const menu = new Menu("agent-chat-reasoning-effort");- if (menu.isOpen) {- return;- }- options.forEach(option => {- menu.addItem({- iconHTML: "",- label: escapeHtml(option.label),- current: option.value === this.selectedReasoningEffort,- click: () => {- this.selectedReasoningEffort = option.value;- setAgentReasoningEffort(option.value);- updateLabel();- },- });+ toggleMenu({+ target: this.reasoningEffortButton,+ build: (_menu, session) => {+ event.stopPropagation();+ const menu = new Menu("agent-chat-reasoning-effort");+ if (menu.isOpen) {+ return;+ }+ options.forEach(option => {+ menu.addItem({+ iconHTML: "",+ label: escapeHtml(option.label),+ current: option.value === this.selectedReasoningEffort,+ click: () => {+ this.selectedReasoningEffort = option.value;+ setAgentReasoningEffort(option.value);+ updateLabel();+ },+ });+ });+ const rect = this.reasoningEffortButton.getBoundingClientRect();+ menu.element.style.minWidth = `${Math.max(rect.width, 120)}px`;+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.reasoningEffortButton}));++ },});- const rect = this.reasoningEffortButton.getBoundingClientRect();- menu.element.style.minWidth = `${Math.max(rect.width, 120)}px`;- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.reasoningEffortButton});});}diff --git a/app/src/layout/status.ts b/app/src/layout/status.tsindex 544a0d7304..2f9e504781 100644--- a/app/src/layout/status.ts+++ b/app/src/layout/status.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";/// #if !MOBILEimport {getDockByType} from "./tabUtil";import {applyStatusBarEntryVisibility} from "../config/entryVisibility/runtime";@@ -43,77 +44,77 @@ export const initStatus = (isWindow = false) => {event.stopPropagation();break;} else if (target.classList.contains("status__backgroundtask")) {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_STATUS_BACKGROUND_TASK) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_STATUS_BACKGROUND_TASK);- JSON.parse(target.getAttribute("data-tasks")).forEach((item: { action: string }) => {- window.siyuan.menus.menu.append(new MenuItem({- type: "readonly",- iconHTML: "",- label: item.action- }).element);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_STATUS_BACKGROUND_TASK);+ JSON.parse(target.getAttribute("data-tasks")).forEach((item: {action: string}) => {+ window.siyuan.menus.menu.append(new MenuItem({+ type: "readonly",+ iconHTML: "",+ label: item.action+ }).element);+ });+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },});- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ event.stopPropagation();break;} else if (target.id === "statusHelp") {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_STATUS_HELP) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_STATUS_HELP);- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.userGuide,- icon: "iconHelp",- ignore: window.siyuan.config.readonly,- click: () => {- mountHelp();- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.feedback,- icon: "iconFeedback",- click: () => {- if ("zh-CN" === window.siyuan.config.lang) {- openLink(window.siyuan.ws.app, "https://ld246.com/article/1649901726096");- } else {- openLink(window.siyuan.ws.app, "https://liuyun.io/article/1686530886208");- }- }- }).element);- /// #if !BROWSER- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.debug,- icon: "iconBug",- click: () => {- ipcRenderer.send(Constants.SIYUAN_CMD, "toggleDevTools");- }- }).element);- /// #endif- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages["_trayMenu"].officialWebsite,- icon: "iconSiYuan",- click: () => {- openLink(window.siyuan.ws.app, "https://b3log.org/siyuan");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages["_trayMenu"].openSource,- icon: "iconGithub",- click: () => {- openLink(window.siyuan.ws.app, "https://github.com/siyuan-note/siyuan");- }- }).element);- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_STATUS_HELP);+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.userGuide,+ icon: "iconHelp",+ ignore: window.siyuan.config.readonly,+ click: () => {+ mountHelp();+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.feedback,+ icon: "iconFeedback",+ click: () => {+ if ("zh-CN" === window.siyuan.config.lang) {+ openLink(window.siyuan.ws.app, "https://ld246.com/article/1649901726096");+ } else {+ openLink(window.siyuan.ws.app, "https://liuyun.io/article/1686530886208");+ }+ }+ }).element);+ /// #if !BROWSER+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.debug,+ icon: "iconBug",+ click: () => {+ ipcRenderer.send(Constants.SIYUAN_CMD, "toggleDevTools");+ }+ }).element);+ /// #endif+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages["_trayMenu"].officialWebsite,+ icon: "iconSiYuan",+ click: () => {+ openLink(window.siyuan.ws.app, "https://b3log.org/siyuan");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages["_trayMenu"].openSource,+ icon: "iconGithub",+ click: () => {+ openLink(window.siyuan.ws.app, "https://github.com/siyuan-note/siyuan");+ }+ }).element);+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },+ });+ event.stopPropagation();break;} else if (target.classList.contains("b3-menu__item")) {const type = target.getAttribute("data-type");diff --git a/app/src/layout/tabList.test.ts b/app/src/layout/tabList.test.tsindex 310f4aa2d5..4c4a31f845 100644--- a/app/src/layout/tabList.test.ts+++ b/app/src/layout/tabList.test.ts@@ -4,6 +4,7 @@ import {runInNewContext} from "node:vm";import {describe, it} from "node:test";import * as assert from "node:assert/strict";import * as ts from "typescript";+const {loadMenuToggle} = require("../../tests/menu-toggle-fixture.cjs");const source = ts.transpileModule(readFileSync(join(__dirname, "Wnd.ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},@@ -36,9 +37,11 @@ const fixture = () => {});menuElement.classes.add("fn__none");const menu = {+ data: undefined as Element,element: menuElement,removeCB: undefined as (() => void) | undefined,remove: () => {+ menu.data = undefined;menu.removeCB?.();menu.removeCB = undefined;items.length = 0;@@ -56,9 +59,11 @@ const fixture = () => {classList: {contains: () => active},});const headers = [header("first", false), header("second", true)];- const anchor = {getBoundingClientRect: () => ({left: 10, top: 20, width: 30, height: 40})};+ const anchor = {closest: (): null => null, setAttribute: () => {},+ getBoundingClientRect: () => ({left: 10, top: 20, width: 30, height: 40})};const exports: any = {};const dependencies: Record<string, object> = {+ "../menus/menuToggle": loadMenuToggle({window: {siyuan: {menus: {menu}}}}),"../constants": {Constants: {MENU_TAB_LIST: "tab-list"}},"../util/escape": {escapeHtml: (value: string) => value},"../emoji/fileTreeIcon": {getFileTreeIconHTML: () => ""},diff --git a/app/src/layout/topBar.ts b/app/src/layout/topBar.tsindex 2d21ceeb53..0bedff04c4 100644--- a/app/src/layout/topBar.ts+++ b/app/src/layout/topBar.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {isInMobileApp,setStorageVal,@@ -152,42 +153,42 @@ ${isInMobileApp() ? `<div id="barExit" data-topbar-entry="barExit" class="ft__erevent.stopPropagation();break;} else if (targetId === "barMore") {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BAR_MORE) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_MORE);- (target.getAttribute("data-hideids") || "").split(",").forEach((itemId) => {- // data-hideids 可能为空字符串,split(",") 会得到 [""],导致 querySelector("#") 抛出无效选择器异常- if (!itemId) {- return;- }- const hideElement = document.getElementById(itemId);- const useElement = hideElement.querySelector("use");- const menuOptions: IMenu = {- label: hideElement.getAttribute("aria-label"),- icon: itemId === "toolbarVIP" || itemId === "toolbarTitle" ? "iconAccount" :- (useElement ? useElement.getAttribute("xlink:href").substring(1) : undefined),- click: () => {- if (itemId.startsWith("plugin")) {- hideElement.dispatchEvent(new CustomEvent("click"));- } else {- toolbarElement.dispatchEvent(new CustomEvent("click", {detail: itemId}));+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_MORE);+ (target.getAttribute("data-hideids") || "").split(",").forEach((itemId) => {+ // data-hideids 可能为空字符串,split(",") 会得到 [""],导致 querySelector("#") 抛出无效选择器异常+ if (!itemId) {+ return;}- }- };- if (!useElement && hideElement.querySelector("svg")) {- const svgElement = hideElement.querySelector("svg").cloneNode(true) as HTMLElement;- svgElement.classList.add("b3-menu__icon");- menuOptions.iconHTML = svgElement.outerHTML;- }- window.siyuan.menus.menu.append(new MenuItem(menuOptions).element);+ const hideElement = document.getElementById(itemId);+ const useElement = hideElement.querySelector("use");+ const menuOptions: IMenu = {+ label: hideElement.getAttribute("aria-label"),+ icon: itemId === "toolbarVIP" || itemId === "toolbarTitle" ? "iconAccount" :+ (useElement ? useElement.getAttribute("xlink:href").substring(1) : undefined),+ click: () => {+ if (itemId.startsWith("plugin")) {+ hideElement.dispatchEvent(new CustomEvent("click"));+ } else {+ toolbarElement.dispatchEvent(new CustomEvent("click", {detail: itemId}));+ }+ }+ };+ if (!useElement && hideElement.querySelector("svg")) {+ const svgElement = hideElement.querySelector("svg").cloneNode(true) as HTMLElement;+ svgElement.classList.add("b3-menu__icon");+ menuOptions.iconHTML = svgElement.outerHTML;+ }+ window.siyuan.menus.menu.append(new MenuItem(menuOptions).element);+ });+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },});- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ event.stopPropagation();break;} else if (targetId === "barForward") {goForward(app);@@ -206,7 +207,7 @@ ${isInMobileApp() ? `<div id="barExit" data-topbar-entry="barExit" class="ft__erevent.stopPropagation();break;} else if (targetId === "barWorkspace") {- workspaceMenu(app, target.getBoundingClientRect());+ workspaceMenu(app, target.getBoundingClientRect(), false, target);event.stopPropagation();break;} else if (targetId === "barExit") {@@ -217,46 +218,46 @@ ${isInMobileApp() ? `<div id="barExit" data-topbar-entry="barExit" class="ft__er});break;} else if (targetId === "barMode") {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BAR_MODE) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_MODE);- window.siyuan.menus.menu.append(new MenuItem({- id: "themeLight",- label: window.siyuan.languages.themeLight,- icon: "iconLight",- current: window.siyuan.config.appearance.mode === 0 && !window.siyuan.config.appearance.modeOS,- click: () => {- setMode(0);- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "themeDark",- label: window.siyuan.languages.themeDark,- current: window.siyuan.config.appearance.mode === 1 && !window.siyuan.config.appearance.modeOS,- icon: "iconDark",- click: () => {- setMode(1);- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "themeOS",- label: window.siyuan.languages.themeOS,- current: window.siyuan.config.appearance.modeOS,- icon: "iconMode",- click: () => {- setMode(2);- }- }).element);- let rect = target.getBoundingClientRect();- if (rect.width === 0) {- rect = toolbarElement.querySelector("#barMore").getBoundingClientRect();- }- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_MODE);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "themeLight",+ label: window.siyuan.languages.themeLight,+ icon: "iconLight",+ current: window.siyuan.config.appearance.mode === 0 && !window.siyuan.config.appearance.modeOS,+ click: () => {+ setMode(0);+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "themeDark",+ label: window.siyuan.languages.themeDark,+ current: window.siyuan.config.appearance.mode === 1 && !window.siyuan.config.appearance.modeOS,+ icon: "iconDark",+ click: () => {+ setMode(1);+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "themeOS",+ label: window.siyuan.languages.themeOS,+ current: window.siyuan.config.appearance.modeOS,+ icon: "iconMode",+ click: () => {+ setMode(2);+ }+ }).element);+ let rect = target.getBoundingClientRect();+ if (rect.width === 0) {+ rect = toolbarElement.querySelector("#barMore").getBoundingClientRect();+ }+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },+ });+ event.stopPropagation();break;} else if (targetId === "toolbarVIP" || targetId === "toolbarTitle") {if (!window.siyuan.config.readonly) {@@ -276,47 +277,47 @@ ${isInMobileApp() ? `<div id="barExit" data-topbar-entry="barExit" class="ft__erevent.stopPropagation();break;} else if (targetId === "barCommand") {- commandPanel(app);+ toggleMenu({target, build: () => commandPanel(app)});event.stopPropagation();break;} else if (targetId === "barZoom") {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BAR_ZOOM) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_ZOOM);- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.zoomIn,- icon: "iconZoomIn",- accelerator: "⌘=",- click: () => {- setZoom("zoomIn");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.zoomOut,- accelerator: "⌘-",- icon: "iconZoomOut",- click: () => {- setZoom("zoomOut");- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- label: window.siyuan.languages.reset,- icon: "iconRefresh",- accelerator: "⌘0",- click: () => {- setZoom("restore");- }- }).element);- let rect = target.getBoundingClientRect();- if (rect.width === 0) {- rect = toolbarElement.querySelector("#barMore").getBoundingClientRect();- }- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_ZOOM);+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.zoomIn,+ icon: "iconZoomIn",+ accelerator: "⌘=",+ click: () => {+ setZoom("zoomIn");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.zoomOut,+ accelerator: "⌘-",+ icon: "iconZoomOut",+ click: () => {+ setZoom("zoomOut");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ label: window.siyuan.languages.reset,+ icon: "iconRefresh",+ accelerator: "⌘0",+ click: () => {+ setZoom("restore");+ }+ }).element);+ let rect = target.getBoundingClientRect();+ if (rect.width === 0) {+ rect = toolbarElement.querySelector("#barMore").getBoundingClientRect();+ }+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },+ });+ event.stopPropagation();break;}target = target.parentElement;diff --git a/app/src/menus/bookmark.ts b/app/src/menus/bookmark.tsindex b09ab65cc0..541548ac41 100644--- a/app/src/menus/bookmark.ts+++ b/app/src/menus/bookmark.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "./menuToggle";import {MenuItem} from "./Menu";import {openInputDialog} from "../dialog/inputDialog";import {fetchPost} from "../util/fetch";@@ -9,74 +10,75 @@ import {MobileBookmarks} from "../mobile/dock/MobileBookmarks";import {Constants} from "../constants";export const openBookmarkMenu = (element: HTMLElement, event: MouseEvent, bookmarkObj: Bookmark | MobileBookmarks) => {- if (event.type !== "contextmenu" && !window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BOOKMARK) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- const id = element.getAttribute("data-node-id");- if (!id && !window.siyuan.config.readonly) {- window.siyuan.menus.menu.append(new MenuItem({- id: "rename",- icon: "iconEdit",- label: window.siyuan.languages.rename,- click: () => {- const oldBookmark = element.querySelector(".b3-list-item__text").textContent;- const dialog = openInputDialog({- title: window.siyuan.languages.rename,- value: oldBookmark,- onConfirm: (value, dialog) => {- fetchPost("/api/bookmark/renameBookmark", {- oldBookmark,- newBookmark: value- }, () => {- dialog.destroy();+ toggleMenu({+ target: event.type === "contextmenu" ? element : (event.target as Element).closest(".b3-list-item__action") || element,+ toggle: event.type !== "contextmenu",+ build: (_menu, session) => {+ const id = element.getAttribute("data-node-id");+ if (!id && !window.siyuan.config.readonly) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "rename",+ icon: "iconEdit",+ label: window.siyuan.languages.rename,+ click: () => {+ const oldBookmark = element.querySelector(".b3-list-item__text").textContent;+ const dialog = openInputDialog({+ title: window.siyuan.languages.rename,+ value: oldBookmark,+ onConfirm: (value, dialog) => {+ fetchPost("/api/bookmark/renameBookmark", {+ oldBookmark,+ newBookmark: value+ }, () => {+ dialog.destroy();+ });+ },});- },- });- dialog.element.setAttribute("data-key", Constants.DIALOG_RENAMEBOOKMARK);+ dialog.element.setAttribute("data-key", Constants.DIALOG_RENAMEBOOKMARK);+ }+ }).element);+ }+ if (id) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "copy",+ label: window.siyuan.languages.copy,+ type: "submenu",+ icon: "iconCopy",+ submenu: copySubMenu([element.getAttribute("data-node-id")], false)+ }).element);}- }).element);- }- if (id) {- window.siyuan.menus.menu.append(new MenuItem({- id: "copy",- label: window.siyuan.languages.copy,- type: "submenu",- icon: "iconCopy",- submenu: copySubMenu([element.getAttribute("data-node-id")], false)- }).element);- }- if (!window.siyuan.config.readonly) {- window.siyuan.menus.menu.append(new MenuItem({- id: "remove",- icon: "iconTrashcan",- label: window.siyuan.languages.remove,- click: () => {- const bookmarkText = element.querySelector(".b3-list-item__text").textContent;- confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.removeBookmark.replace("${x}", `<b>${escapeHtml(bookmarkText)}</b>`), () => {- if (id) {- fetchPost("/api/attr/setBlockAttrs", {id, attrs: {bookmark: ""}}, () => {- bookmarkObj.update();- });- document.querySelectorAll(`.protyle-wysiwyg [data-node-id="${id}"]`).forEach((item) => {- item.setAttribute("bookmark", "");- const bookmarkElement = item.querySelector(".protyle-attr--bookmark");- if (bookmarkElement) {- bookmarkElement.remove();+ if (!window.siyuan.config.readonly) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "remove",+ icon: "iconTrashcan",+ label: window.siyuan.languages.remove,+ click: () => {+ const bookmarkText = element.querySelector(".b3-list-item__text").textContent;+ confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.removeBookmark.replace("${x}", `<b>${escapeHtml(bookmarkText)}</b>`), () => {+ if (id) {+ fetchPost("/api/attr/setBlockAttrs", {id, attrs: {bookmark: ""}}, () => {+ bookmarkObj.update();+ });+ document.querySelectorAll(`.protyle-wysiwyg [data-node-id="${id}"]`).forEach((item) => {+ item.setAttribute("bookmark", "");+ const bookmarkElement = item.querySelector(".protyle-attr--bookmark");+ if (bookmarkElement) {+ bookmarkElement.remove();+ }+ });+ } else {+ fetchPost("/api/bookmark/removeBookmark", {bookmark: bookmarkText});}- });- } else {- fetchPost("/api/bookmark/removeBookmark", {bookmark: bookmarkText});+ }, undefined, true);}- }, undefined, true);+ }).element);}- }).element);- }- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BOOKMARK);- const button = event.type === "contextmenu" ? null : (event.target as Element).closest(".b3-list-item__action");- const rect = (button || element).getBoundingClientRect();- window.siyuan.menus.menu.popup({x: button ? rect.left : event.clientX, y: rect.bottom, h: rect.height});+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BOOKMARK);+ const button = event.type === "contextmenu" ? null : (event.target as Element).closest(".b3-list-item__action");+ const rect = (button || element).getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: button ? rect.left : event.clientX, y: rect.bottom, h: rect.height}));++ },+ });};diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.tsindex 98b005ff4b..83cfd61e5f 100644--- a/app/src/menus/commonMenuItem.ts+++ b/app/src/menus/commonMenuItem.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "./menuToggle";import type {BlockQueryRequestInput} from "../types/api";import {confirmDialog} from "../dialog/confirmDialog";import {getSearch, isMobile, isValidCustomAttrName} from "../util/functions";@@ -393,32 +394,42 @@ export const openFileAttr = (attrs: Record<string, string>, focusName = "bookmarevent.preventDefault();break;} else if (type === "bookmark") {- fetchPost("/api/attr/getBookmarkLabels", {}, (response) => {- window.siyuan.menus.menu.remove();- if (response.data.length === 0) {- window.siyuan.menus.menu.append(new MenuItem({- id: "emptyContent",- iconHTML: "",- label: window.siyuan.languages.emptyContent,- type: "readonly",- }).element);- } else {- response.data.forEach((item: string) => {- window.siyuan.menus.menu.append(new MenuItem({- label: item,- click() {- const bookmarkInputElement = target.parentElement.parentElement.querySelector("input");- bookmarkInputElement.value = item;- bookmarkInputElement.dispatchEvent(new CustomEvent("change"));- }- }).element);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ fetchPost("/api/attr/getBookmarkLabels", {}, (response) => {+ if (!session.isCurrent()) {+ return;+ }++ window.siyuan.menus.menu.remove();+ if (response.data.length === 0) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "emptyContent",+ iconHTML: "",+ label: window.siyuan.languages.emptyContent,+ type: "readonly",+ }).element);+ } else {+ response.data.forEach((item: string) => {+ window.siyuan.menus.menu.append(new MenuItem({+ label: item,+ click() {+ const bookmarkInputElement = target.parentElement.parentElement.querySelector("input");+ bookmarkInputElement.value = item;+ bookmarkInputElement.dispatchEvent(new CustomEvent("change"));+ }+ }).element);+ });+ }+ window.siyuan.menus.menu.element.classList.add("b3-menu--list");+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width}));});- }- window.siyuan.menus.menu.element.classList.add("b3-menu--list");- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width});++ },});- event.stopPropagation();+ event.stopPropagation();event.preventDefault();break;} else if (type === "addCustom") {diff --git a/app/src/menus/fileTreeMenu.ts b/app/src/menus/fileTreeMenu.tsdeleted file mode 100644index 833b175442..0000000000--- a/app/src/menus/fileTreeMenu.ts+++ /dev/null@@ -1,10 +0,0 @@-export const toggleFileTreeMenu = (button: Element, openMenu: () => void) => {- const menu = window.siyuan.menus.menu;- if (!menu.element.classList.contains("fn__none") && menu.data === button) {- menu.remove();- return;- }- openMenu();- // 记录具体入口,使同一按钮关闭菜单,其他按钮切换操作对象。- menu.data = button;-};diff --git a/app/src/menus/menuToggle.test.ts b/app/src/menus/menuToggle.test.tsnew file mode 100644index 0000000000..5ff42dca4d--- /dev/null+++ b/app/src/menus/menuToggle.test.ts@@ -0,0 +1,148 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const {loadMenuToggle, menuAnchor} = require("../../tests/menu-toggle-fixture.cjs");++const fixture = () => {+ let visible = false;+ let sheet = false;+ const attributes = new Map<string, string>();+ let builds = 0;+ const shows: string[] = [];+ let restoreKeyboard: () => void;+ const menu = {+ data: undefined as Element,+ element: {classList: {contains: (name: string) => name === "fn__none" ? !visible : name === "b3-menu--sheet" && sheet},+ getAttribute: (key: string) => attributes.get(key),+ setAttribute: (key: string, value: string) => attributes.set(key, value)},+ remove() { visible = false; menu.data = undefined; attributes.clear(); },+ popup() { visible = true; sheet = false; shows.push("popup"); },+ closeSheet() { menu.remove(); restoreKeyboard?.(); },+ fullscreen(position = "all", restore?: () => void) {+ visible = true; sheet = true; shows.push(position); restoreKeyboard = restore;+ },+ addItem() { builds++; },+ };+ const globals = {window: {siyuan: {menus: {menu}}}};+ const helpers = loadMenuToggle(globals) as typeof import("./menuToggle");+ const exports = {} as typeof import("../plugin/Menu");+ runInNewContext(transpileModule(readFileSync("src/plugin/Menu.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText, {...globals, exports, require: () => helpers});+ const open = (target: Element, toggle?: boolean) => helpers.toggleMenu({+ target, toggle, build: () => { builds++; }, show: () => menu.popup(),+ });+ return {...helpers, Menu: exports.Menu, open, menu, shows, builds: () => builds, visible: () => visible,+ restoreKeyboard: () => restoreKeyboard};+};++test("the same trigger closes without rebuilding; another trigger opens immediately", () => {+ const f = fixture();+ const a = menuAnchor(), b = menuAnchor();+ f.open(a);+ f.open(a);+ assert.equal(f.visible(), false);+ assert.equal(f.builds(), 1);+ f.open(a);+ f.open(b);+ assert.equal(f.menu.data, b);+ assert.equal(f.visible(), true);+ assert.equal(f.builds(), 3);+});++test("SVG children normalize to the button, without treating a containing row as the same trigger", () => {+ const f = fixture();+ const button = menuAnchor(), row = menuAnchor();+ f.open(button);+ f.open({closest: () => button} as unknown as Element);+ assert.equal(f.visible(), false);+ f.open(row, false);+ f.open(button);+ assert.equal(f.menu.data, button);+ assert.equal(f.visible(), true);+ assert.equal(row.marked, false);+});++test("outside dismissal permits reopening and context menus reopen without marking their row", () => {+ const f = fixture();+ const anchor = menuAnchor();+ f.open(anchor);+ f.menu.remove();+ f.open(anchor);+ assert.equal(f.visible(), true);+ const row = menuAnchor();+ f.open(row, false);+ f.open(row, false);+ assert.equal(f.visible(), true);+ assert.equal(f.menu.data, row);+ assert.equal(row.marked, false);+});++test("pending menus can be cancelled, switched and dismissed before their response builds the menu", () => {+ const f = fixture();+ const a = menuAnchor(), b = menuAnchor();+ const replies: (() => void)[] = [];+ const request = (target: Element) => f.toggleMenu({target, build: (_menu, session) => {+ replies.push(() => {+ if (!session.isCurrent()) { return; }+ f.menu.remove();+ f.menu.addItem();+ session.show(() => f.menu.popup());+ });+ }});+ request(a);+ request(a);+ replies[0]();+ assert.equal(f.builds(), 0);+ request(a);+ request(b);+ replies[1]();+ assert.equal(f.builds(), 0);+ f.menu.remove();+ replies[2]();+ assert.equal(f.builds(), 0);+ request(a);+ replies[3]();+ assert.equal(f.visible(), true);+ assert.equal(f.menu.data, a);+});++test("mobile sheets retain their requested position and keyboard restoration callback", () => {+ const f = fixture();+ const anchor = menuAnchor();+ let restored = 0;+ const restore = () => { restored++; };+ f.toggleMenu({target: anchor, build: () => {}, show: menu => menu.fullscreen("bottom", restore)});+ assert.equal(f.restoreKeyboard(), restore);+ assert.deepEqual(f.shows, ["bottom"]);+ f.toggleMenu({target: anchor, build: () => {}, show: menu => menu.fullscreen("bottom")});+ assert.deepEqual(f.shows, ["bottom"]);+ assert.equal(restored, 1);+});++test("plugin toggle decides before constructing; legacy AV fixed-id construction still closes across targets", () => {+ const f = fixture();+ const a = menuAnchor(), b = menuAnchor();+ const open = (target: Element) => f.Menu.toggle({target, id: "shared", build: menu => menu.addItem({}),+ show: menu => menu.open({x: 1, y: 2})});+ open(a);+ open(b);+ assert.equal(f.menu.data, b);+ assert.equal(f.visible(), true);+ open(b);+ assert.equal(f.visible(), false);+ const first = new f.Menu("av-column");+ assert.equal(first.isOpen, false);+ first.addItem({});+ first.open({x: 1, y: 2});+ const second = new f.Menu("av-column");+ assert.equal(second.isOpen, true);+ second.addItem({});+ second.open({x: 3, y: 4});+ assert.equal(f.visible(), false);+ const third = new f.Menu("av-column");+ assert.equal(third.isOpen, false);+});diff --git a/app/src/menus/menuToggle.ts b/app/src/menus/menuToggle.tsnew file mode 100644index 0000000000..fe80f885ee--- /dev/null+++ b/app/src/menus/menuToggle.ts@@ -0,0 +1,72 @@+import type {Menu} from "./Menu";++export interface IMenuSession {+ isCurrent: () => boolean;+ show: (render: () => void) => void;+}++export interface IToggleMenuOptions {+ target?: Element;+ toggle?: boolean;+ build: (menu: Menu, session: IMenuSession) => void | Promise<void>;+ show?: (menu: Menu) => void;+}++const sessions = new WeakMap<Menu, object>();++// 在构建前判断具体按钮归属;异步构建必须在回调中检查会话,并通过 show 发布菜单。+export const toggleMenu = (options: IToggleMenuOptions) => {+ const menu = window.siyuan.menus.menu;+ const anchor = options.target?.closest("[data-menu=\"true\"]") ?? options.target;+ const toggle = options.toggle ?? Boolean(anchor);+ if (toggle && anchor && menu.data === anchor &&+ (!menu.element.classList.contains("fn__none") || sessions.has(menu))) {+ sessions.delete(menu);+ menu.data = undefined;+ if (!menu.element.classList.contains("fn__none") && menu.element.classList.contains("b3-menu--sheet")) {+ menu.closeSheet();+ } else {+ menu.remove();+ }+ return;+ }+ menu.remove();+ const token = {};+ sessions.set(menu, token);+ menu.data = anchor;+ if (toggle && anchor) {+ anchor.setAttribute("data-menu", "true");+ }+ let building = true;+ const session: IMenuSession = {+ isCurrent: () => sessions.get(menu) === token && (building || menu.data === anchor),+ show: render => {+ if (sessions.get(menu) !== token) {+ return;+ }+ menu.data = anchor;+ render();+ if (sessions.get(menu) === token) {+ menu.data = anchor;+ }+ },+ };+ let built: void | Promise<void>;+ try {+ built = options.build(menu, session);+ } catch (error) {+ if (sessions.get(menu) === token) {+ sessions.delete(menu);+ menu.remove();+ }+ throw error;+ }+ building = false;+ if (sessions.get(menu) === token) {+ menu.data = anchor;+ if (options.show) {+ session.show(() => options.show(menu));+ }+ }+ return built;+};diff --git a/app/src/menus/fileTreeMenu.test.ts b/app/src/menus/menuToggleIntegration.test.tssimilarity index 85%rename from app/src/menus/fileTreeMenu.test.tsrename to app/src/menus/menuToggleIntegration.test.tsindex 61a296d419..28b3d01711 100644--- a/app/src/menus/fileTreeMenu.test.ts+++ b/app/src/menus/menuToggleIntegration.test.ts@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+const {menuAnchor} = require("../../tests/menu-toggle-fixture.cjs");const fixture = () => {let visible = false;@@ -28,20 +29,20 @@ const fixture = () => {}).outputText, {...context, exports});return exports;};- const {toggleFileTreeMenu} = load<typeof import("./fileTreeMenu")>("/fileTreeMenu.ts");+ const {toggleMenu} = load<typeof import("./menuToggle")>("/menuToggle.ts");const {globalClickHideMenu} = load<typeof import("./menuClick")>("/menuClick.ts");- const click = (button: Element) => toggleFileTreeMenu(button, () => {+ const click = (button: Element) => toggleMenu({target: button, build: () => {menu.remove();opened.push(button);visible = true;- });+ }});return {click, opened, menu, dismiss: globalClickHideMenu, isVisible: () => visible,openContextMenu: () => { menu.remove(); visible = true; }};};test("repeated clicks on a file tree more button open, close and reopen its menu", () => {const f = fixture();- const button = {} as Element;+ const button = menuAnchor() as Element;f.click(button);assert.equal(f.isVisible(), true);f.click(button);@@ -54,7 +55,7 @@ test("repeated clicks on a file tree more button open, close and reopen its menutest("switching between panel, notebook, document and pinned more buttons opens the selected menu", () => {const f = fixture();- const buttons = Array.from({length: 4}, () => ({} as Element));+ const buttons = Array.from({length: 4}, () => menuAnchor() as Element);buttons.forEach(button => f.click(button));assert.equal(f.isVisible(), true);assert.deepEqual(f.opened, buttons);@@ -64,7 +65,7 @@ test("switching between panel, notebook, document and pinned more buttons openstest("outside dismissal permits reopening while trigger clicks retain toggle handling", () => {const f = fixture();- const button = {menuTrigger: true} as unknown as HTMLElement;+ const button = {...menuAnchor(), menuTrigger: true} as unknown as HTMLElement;f.click(button);f.dismiss(button);assert.equal(f.isVisible(), true);@@ -80,7 +81,7 @@ test("outside dismissal permits reopening while trigger clicks retain toggle hantest("a context menu replacing a more menu does not consume the next more-button click", () => {const f = fixture();- const button = {} as Element;+ const button = menuAnchor() as Element;f.click(button);f.openContextMenu();f.click(button);diff --git a/app/src/menus/panelMenus.test.ts b/app/src/menus/panelMenus.test.tsindex 1bbfff555d..0c006fa5ea 100644--- a/app/src/menus/panelMenus.test.ts+++ b/app/src/menus/panelMenus.test.ts@@ -4,18 +4,20 @@ import {readFileSync} from "node:fs";import {join} from "node:path";import {runInNewContext} from "node:vm";import * as ts from "typescript";+const {loadMenuToggle, menuAnchor} = require("../../tests/menu-toggle-fixture.cjs");const loadMenu = (name: "tag" | "bookmark") => {let visible = false;let menuName: string;const positions: {x: number, y: number, h: number}[] = [];const menu = {+ data: undefined as Element,element: {classList: {contains: () => !visible},getAttribute: () => menuName,setAttribute: (_key: string, value: string) => { menuName = value; },},- remove: () => { visible = false; },+ remove: () => { visible = false; menu.data = undefined; },append: () => {},popup: (position: {x: number, y: number, h: number}) => {visible = true;@@ -23,6 +25,7 @@ const loadMenu = (name: "tag" | "bookmark") => {},};const exports: Record<string, (...args: unknown[]) => void> = {};+ const menuToggle = loadMenuToggle({window: {siyuan: {menus: {menu}}}});const source = ts.transpileModule(readFileSync(join(__dirname, `${name}.ts`), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},}).outputText;@@ -30,6 +33,7 @@ const loadMenu = (name: "tag" | "bookmark") => {exports,window: {siyuan: {config: {readonly: false}, menus: {menu}, languages: {}}},require: (path: string) => {+ if (path === "./menuToggle") { return menuToggle; }if (path === "./Menu") { return {MenuItem: class { element = {}; }}; }if (path.endsWith("/constants")) {return {Constants: {MENU_TAG: "tag", MENU_BOOKMARK: "bookmark"}};@@ -44,7 +48,7 @@ const loadMenu = (name: "tag" | "bookmark") => {for (const name of ["tag", "bookmark"] as const) {test(`${name} right clicks reopen at the current row and pointer`, () => {const {open, positions, isVisible} = loadMenu(name);- const row = (bottom: number) => ({getAttribute: (): string | null => null,+ const row = (bottom: number) => ({...menuAnchor(), getAttribute: (): string | null => null,getBoundingClientRect: () => ({left: 0, bottom, height: 28})});const firstRow = row(120);const event = {type: "contextmenu", clientX: 80, clientY: 110};@@ -62,7 +66,7 @@ for (const name of ["tag", "bookmark"] as const) {test(`${name} more button anchors to the button and toggles on a second click`, () => {const {open, positions, isVisible} = loadMenu(name);const row = {getAttribute: (): string | null => null};- const button = {getBoundingClientRect: () => ({left: 240, bottom: 120, height: 20})};+ const button = {...menuAnchor(), getBoundingClientRect: () => ({left: 240, bottom: 120, height: 20})};const event = {type: "click", clientX: 250, clientY: 110, target: {closest: () => button}};open(row, event, "first");assert.equal(isVisible(), true);diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex dc28f803cd..c5d239ceb8 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -1,4 +1,5 @@import {createImageOCRMenu} from "./imageOCRMenu";+import {toggleMenu, IMenuSession} from "./menuToggle";import {escapeHtmlTextAndAttr} from "../util/escape";import type {FileTreeGetDocRequestInput} from "../types/api";import {@@ -98,12 +99,15 @@ import {stripSemanticMarkersFromRangeText,} from "../protyle/util/inlineElementMarker";-const renderAssetList = (element: Element, k: string, position: IPosition, exts: string[] = []) => {+const renderAssetList = (element: Element, k: string, position: IPosition, exts: string[] = [], session?: IMenuSession) => {fetchPost("/api/search/searchAsset", {k,exts,includeMetadata: true}, (response) => {+ if (session && !session.isCurrent()) {+ return;+ }let searchHTML = "";response.data.forEach((item: { path: string, hName: string }, index: number) => {searchHTML += `<div data-value="${item.path}" class="b3-list-item${index === 0 ? " b3-list-item--focus" : ""}"><div class="b3-list-item__text">${item.hName}</div></div>`;@@ -118,11 +122,18 @@ const renderAssetList = (element: Element, k: string, position: IPosition, exts:} else {previewElement.innerHTML = window.siyuan.languages.emptyContent;}- /// #if MOBILE- window.siyuan.menus.menu.fullscreen();- /// #else- window.siyuan.menus.menu.popup(position);- /// #endif+ const show = () => {+ /// #if MOBILE+ window.siyuan.menus.menu.fullscreen();+ /// #else+ window.siyuan.menus.menu.popup(position);+ /// #endif+ };+ if (session) {+ session.show(show);+ } else {+ show();+ }if (!k) {inputElement.select();}@@ -131,6 +142,18 @@ const renderAssetList = (element: Element, k: string, position: IPosition, exts:export const assetMenu = (protyle: IProtyle, position: IPosition, callback?: (url: string, name: string) => void,exts?: string[], independent = false) => {+ if (independent || !position.target) {+ buildAssetMenu(protyle, position, callback, exts, independent);+ return;+ }+ toggleMenu({+ target: position.target,+ build: (_menu, session) => buildAssetMenu(protyle, position, callback, exts, false, session),+ });+};++const buildAssetMenu = (protyle: IProtyle, position: IPosition, callback?: (url: string, name: string) => void,+ exts?: string[], independent = false, session?: IMenuSession) => {const menu = new Menu(Constants.MENU_BACKGROUND_ASSET, undefined, independent);if (menu.isOpen) {return;@@ -207,11 +230,11 @@ export const assetMenu = (protyle: IProtyle, position: IPosition, callback?: (urreturn;}event.stopPropagation();- renderAssetList(element, inputElement.value, position, exts);+ renderAssetList(element, inputElement.value, position, exts, session);});inputElement.addEventListener("compositionend", (event: InputEvent) => {event.stopPropagation();- renderAssetList(element, inputElement.value, position, exts);+ renderAssetList(element, inputElement.value, position, exts, session);});element.lastElementChild.addEventListener("click", (event) => {const target = event.target as HTMLElement;@@ -242,7 +265,7 @@ export const assetMenu = (protyle: IProtyle, position: IPosition, callback?: (ur}}});- renderAssetList(element, "", position, exts);+ renderAssetList(element, "", position, exts, session);}});};@@ -1274,19 +1297,19 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme<span class="fn__space"></span><span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}"><svg><use xlink:href="#iconCopy"></use></svg>- </span>+ </span></div><textarea spellcheck="false" style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" rows="1" class="b3-text-field">${src}</textarea><div class="fn__hr"></div><div class="fn__flex"><span class="fn__flex-center">${window.siyuan.languages.title}</span><span class="fn__space"></span><span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}"><svg><use xlink:href="#iconCopy"></use></svg>- </span>+ </span></div><textarea style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" rows="1" class="b3-text-field"></textarea><div class="fn__hr"></div><div class="fn__flex"><span class="fn__flex-center">${window.siyuan.languages.tooltipText}</span><span class="fn__space"></span><span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}"><svg><use xlink:href="#iconCopy"></use></svg>- </span>+ </span></div><textarea style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" rows="1" class="b3-text-field"></textarea>`,bind(element) {element.style.maxWidth = "none";@@ -1636,20 +1659,20 @@ export const linkMenu = (protyle: IProtyle, linkElement: HTMLElement, focusText<span class="fn__space"></span><span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}"><svg><use xlink:href="#iconCopy"></use></svg>- </span>-</div><textarea spellcheck="false" rows="1"+ </span>+</div><textarea spellcheck="false" rows="1"style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" class="b3-text-field"></textarea><div class="fn__hr"></div><div class="fn__flex"><span class="fn__flex-center">${window.siyuan.languages.anchor}</span><span class="fn__space"></span><span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}"><svg><use xlink:href="#iconCopy"></use></svg>- </span>+ </span></div><textarea style="width: ${isMobile() ? "100%" : "360px"};margin: 4px 0;" rows="1" class="b3-text-field"></textarea><div class="fn__hr"></div><div class="fn__flex"><span class="fn__flex-center">${window.siyuan.languages.title}</span><span class="fn__space"></span><span data-action="copy" class="block__icon block__icon--show b3-tooltips b3-tooltips__e fn__flex-center" aria-label="${window.siyuan.languages.copy}"><svg><use xlink:href="#iconCopy"></use></svg>- </span>+ </span></div><textarea style="width: ${isMobile() ? "100%" : "360px"};margin: 4px 0;" rows="1" class="b3-text-field"></textarea>`,bind(element) {element.style.maxWidth = "none";diff --git a/app/src/menus/tag.ts b/app/src/menus/tag.tsindex 42f60ea290..0babdd3356 100644--- a/app/src/menus/tag.ts+++ b/app/src/menus/tag.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "./menuToggle";import {MenuItem} from "./Menu";import {fetchPost} from "../util/fetch";import {confirmDialog} from "../dialog/confirmDialog";@@ -8,40 +9,43 @@ import {Tag} from "../layout/dock/Tag";import {Constants} from "../constants";export const openTagMenu = (element: HTMLElement, event: MouseEvent, labelName: string) => {- if (window.siyuan.config.readonly) {- return;- }- if (event.type !== "contextmenu" && !window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TAG) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconEdit",- label: window.siyuan.languages.rename,- click: () => {- renameTag(labelName);- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconTrashcan",- label: window.siyuan.languages.remove,- click: () => {- confirmDialog(window.siyuan.languages.deleteOpConfirm, `${window.siyuan.languages.confirmDelete} <b>${escapeHtml(labelName)}</b>?`, () => {- fetchPost("/api/tag/removeTag", {label: labelName}, () => {- /// #if MOBILE- window.siyuan.mobile.docks.tag.update();- /// #else- const dockTag = getDockByType("tag");- (dockTag.data.tag as Tag).update();- /// #endif- });- }, undefined, true);- }- }).element);- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TAG);- const button = event.type === "contextmenu" ? null : (event.target as Element).closest(".b3-list-item__action");- const rect = (button || element).getBoundingClientRect();- window.siyuan.menus.menu.popup({x: button ? rect.left : event.clientX, y: rect.bottom, h: rect.height});+ toggleMenu({+ target: event.type === "contextmenu" ? element : (event.target as Element).closest(".b3-list-item__action") || element,+ toggle: event.type !== "contextmenu",+ build: (_menu, session) => {+ if (window.siyuan.config.readonly) {+ return;+ }+++ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconEdit",+ label: window.siyuan.languages.rename,+ click: () => {+ renameTag(labelName);+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconTrashcan",+ label: window.siyuan.languages.remove,+ click: () => {+ confirmDialog(window.siyuan.languages.deleteOpConfirm, `${window.siyuan.languages.confirmDelete} <b>${escapeHtml(labelName)}</b>?`, () => {+ fetchPost("/api/tag/removeTag", {label: labelName}, () => {+ /// #if MOBILE+ window.siyuan.mobile.docks.tag.update();+ /// #else+ const dockTag = getDockByType("tag");+ (dockTag.data.tag as Tag).update();+ /// #endif+ });+ }, undefined, true);+ }+ }).element);+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TAG);+ const button = event.type === "contextmenu" ? null : (event.target as Element).closest(".b3-list-item__action");+ const rect = (button || element).getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: button ? rect.left : event.clientX, y: rect.bottom, h: rect.height}));++ },+ });};diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.tsindex 5a67c0ec67..da8c2778f8 100644--- a/app/src/menus/workspace.ts+++ b/app/src/menus/workspace.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "./menuToggle";import {getLayoutSubMenu} from "./layouts";import {hasClosestByClassName} from "../protyle/util/hasClosest";import {MenuItem} from "./Menu";@@ -135,409 +136,420 @@ const getZoomSubMenu = () => {return submenu;};-export const workspaceMenu = async (app: App, rect: DOMRect, openOnly = false) => {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&+export const workspaceMenu = async (app: App, rect: DOMRect, openOnly = false, target?: Element) => {+ if (openOnly && !window.siyuan.menus.menu.element.classList.contains("fn__none") &&window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BAR_WORKSPACE) {- if (!openOnly) {- window.siyuan.menus.menu.remove();- }return;}- let remoteConnections: string[] = [];- /// #if !BROWSER- remoteConnections = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "remoteConnections"});- const manageConnections = (origin?: string) => openRemoteConnection(origin);- /// #endif- const renderMenu = (workspaces: IWorkspace[]) => {- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_WORKSPACE);- if (!window.siyuan.config.readonly) {- window.siyuan.menus.menu.append(new MenuItem({- id: "config",- label: window.siyuan.languages.config,- icon: "iconSettings",- accelerator: window.siyuan.config.keymap.general.config.custom,- click: () => {- openSetting(app);+ await toggleMenu({+ target: target,+ toggle: !openOnly && Boolean(target),+ build: async (_menu, session) => {+ let remoteConnections: string[] = [];+ /// #if !BROWSER+ remoteConnections = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "remoteConnections"});+ if (!session.isCurrent()) {+ return;+ }+ const manageConnections = (origin?: string) => openRemoteConnection(origin);+ /// #endif+ const renderMenu = (workspaces: IWorkspace[]) => {+ if (!session.isCurrent()) {+ return;}- }).element);- }- const dockMenu: IMenu[] = [];- getAllDocks().forEach(item => {- dockMenu.push({- id: item.type,- icon: item.icon,- accelerator: getDockHotkey(item),- label: item.title,- click() {- getDockByType(item.type).toggleModel(item.type);++ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_WORKSPACE);+ if (!window.siyuan.config.readonly) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "config",+ label: window.siyuan.languages.config,+ icon: "iconSettings",+ accelerator: window.siyuan.config.keymap.general.config.custom,+ click: () => {+ openSetting(app);+ }+ }).element);}- });- });- if (!window.siyuan.config.readonly) {- dockMenu.push({id: "separator_1", type: "separator"});- dockMenu.push(togglePinDock("switchLeftDock", window.siyuan.layout.leftDock, "iconPanelLeft", "iconPanelLeftDashed"));- dockMenu.push(togglePinDock("switchRightDock", window.siyuan.layout.rightDock, "iconPanelRight", "iconPanelRightDashed"));- dockMenu.push(togglePinDock("switchBottomDock", window.siyuan.layout.bottomDock, "iconPanelBottom", "iconPanelBottomDashed"));- }- window.siyuan.menus.menu.append(new MenuItem({- id: "panels",- label: window.siyuan.languages.panels,- icon: "iconDock",- type: "submenu",- submenu: dockMenu- }).element);- if ((!window.siyuan.config.readonly && getHostCapabilities().workspaces) || !isBrowser()) {- let workspaceSubMenu: IMenu[];- /// #if !BROWSER- workspaceSubMenu = getHostCapabilities().workspaces ? [{- id: "newOrOpenBy",- label: getHostCapabilities().workspaces- ? `${window.siyuan.languages.new} / ${window.siyuan.languages.openBy}` : window.siyuan.languages.openBy,- iconHTML: "",- click: async () => {- const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, {- cmd: "showOpenDialog",- defaultPath: window.siyuan.config.system.homeDir,- properties: ["openDirectory", "createDirectory"],- });- if (localPath.filePaths.length === 0) {- return;- }- fetchPost("/api/system/checkWorkspaceDir", {path: localPath.filePaths[0]}, (response) => {- if (response.data.isWorkspace) {- openWorkspace(localPath.filePaths[0]);- } else {- confirmDialog("🏗️ " + window.siyuan.languages.createWorkspace, window.siyuan.languages.createWorkspaceTip + `<br><br><code class="fn__code">${escapeHtml(localPath.filePaths[0])}</code>`, () => {- openWorkspace(localPath.filePaths[0]);- });+ const dockMenu: IMenu[] = [];+ getAllDocks().forEach(item => {+ dockMenu.push({+ id: item.type,+ icon: item.icon,+ accelerator: getDockHotkey(item),+ label: item.title,+ click() {+ getDockByType(item.type).toggleModel(item.type);}});+ });+ if (!window.siyuan.config.readonly) {+ dockMenu.push({id: "separator_1", type: "separator"});+ dockMenu.push(togglePinDock("switchLeftDock", window.siyuan.layout.leftDock, "iconPanelLeft", "iconPanelLeftDashed"));+ dockMenu.push(togglePinDock("switchRightDock", window.siyuan.layout.rightDock, "iconPanelRight", "iconPanelRightDashed"));+ dockMenu.push(togglePinDock("switchBottomDock", window.siyuan.layout.bottomDock, "iconPanelBottom", "iconPanelBottomDashed"));}- }] : [];- workspaceSubMenu.push({- id: "connectRemoteKernel",- label: window.siyuan.languages.connectRemoteKernel,- icon: "iconCloud",- click: () => manageConnections(),- });- if (workspaces.length + remoteConnections.length > 0) {- workspaceSubMenu.push({id: "separator_1", type: "separator"});- }- workspaces.forEach((item: IWorkspace) => {- workspaceSubMenu.push(workspaceItem(item) as IMenu);- });- remoteConnections.forEach(origin => workspaceSubMenu.push({- label: escapeHtml(window.siyuan.languages.remoteConnection + " · " + origin),- icon: "iconCloud",- click: () => manageConnections(origin),- }));- /// #else- workspaceSubMenu = [{- id: "new",- label: window.siyuan.languages.new,- iconHTML: "",- click() {- const createWorkspaceDialog = openInputDialog({- title: window.siyuan.languages.new,- value: "",- onConfirm: (value, dialog) => {- fetchPost("/api/system/createWorkspaceDir", {- path: pathPosix().join(pathPosix().dirname(window.siyuan.config.system.workspaceDir), value)- }, () => {- dialog.destroy();+ window.siyuan.menus.menu.append(new MenuItem({+ id: "panels",+ label: window.siyuan.languages.panels,+ icon: "iconDock",+ type: "submenu",+ submenu: dockMenu+ }).element);+ if ((!window.siyuan.config.readonly && getHostCapabilities().workspaces) || !isBrowser()) {+ let workspaceSubMenu: IMenu[];+ /// #if !BROWSER+ workspaceSubMenu = getHostCapabilities().workspaces ? [{+ id: "newOrOpenBy",+ label: getHostCapabilities().workspaces+ ? `${window.siyuan.languages.new} / ${window.siyuan.languages.openBy}` : window.siyuan.languages.openBy,+ iconHTML: "",+ click: async () => {+ const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "showOpenDialog",+ defaultPath: window.siyuan.config.system.homeDir,+ properties: ["openDirectory", "createDirectory"],});- },- });- createWorkspaceDialog.element.setAttribute("data-key", Constants.DIALOG_CREATEWORKSPACE);- }- }, {- id: "openBy",- label: `${window.siyuan.languages.openBy}...`,- iconHTML: "",- click() {- fetchPost("/api/system/getMobileWorkspaces", {}, (response) => {- let selectHTML = "";- response.data.forEach((item: string, index: number) => {- selectHTML += `<option value="${escapeAttr(escapeHtml(item))}"${index === 0 ? ' selected="selected"' : ""}>${escapeHtml(pathPosix().basename(item))}</option>`;- });- const openWorkspaceDialog = new Dialog({- title: window.siyuan.languages.openBy,- content: `<div class="b3-dialog__content">- <select class="b3-text-field fn__block">${selectHTML}</select>-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,- width: "520px",- });- openWorkspaceDialog.element.setAttribute("data-key", Constants.DIALOG_OPENWORKSPACE);- const btnsElement = openWorkspaceDialog.element.querySelectorAll(".b3-button");- btnsElement[0].addEventListener("click", () => {- openWorkspaceDialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- const openPath = openWorkspaceDialog.element.querySelector("select").value;- if (openPath === window.siyuan.config.system.workspaceDir) {- openWorkspaceDialog.destroy();+ if (localPath.filePaths.length === 0) {return;}- confirmDialog(window.siyuan.languages.confirm, `${escapeHtml(pathPosix().basename(window.siyuan.config.system.workspaceDir))} -> ${escapeHtml(pathPosix().basename(openPath))}?`, () => {- fetchPost("/api/system/setWorkspaceDir", {- path: openPath- }, () => {- exitSiYuan(false);- });+ fetchPost("/api/system/checkWorkspaceDir", {path: localPath.filePaths[0]}, (response) => {+ if (response.data.isWorkspace) {+ openWorkspace(localPath.filePaths[0]);+ } else {+ confirmDialog("🏗️ " + window.siyuan.languages.createWorkspace, window.siyuan.languages.createWorkspaceTip + `<br><br><code class="fn__code">${escapeHtml(localPath.filePaths[0])}</code>`, () => {+ openWorkspace(localPath.filePaths[0]);+ });+ }});- });+ }+ }] : [];+ workspaceSubMenu.push({+ id: "connectRemoteKernel",+ label: window.siyuan.languages.connectRemoteKernel,+ icon: "iconCloud",+ click: () => manageConnections(),});- }- }];- workspaceSubMenu.push({id: "separator_1", type: "separator"});- workspaces.forEach((item: IWorkspace) => {- workspaceSubMenu.push({- iconHTML: "",- action: "iconCloseRound",- current: window.siyuan.config.system.workspaceDir === item.path,- label: pathPosix().basename(item.path),- bind(menuElement) {- menuElement.addEventListener("click", (event) => {- if (hasClosestByClassName(event.target as Element, "b3-menu__action")) {- event.preventDefault();- event.stopPropagation();- if (item.path === window.siyuan.config.system.workspaceDir) {- fetchPost("/api/system/removeWorkspaceDir", {path: item.path});- return;- }- confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.removeWorkspacePhysically.replace("${x}", () => escapeHtml(item.path)), () => {- fetchPost("/api/system/removeWorkspaceDirPhysically", {path: item.path});- }, () => {- fetchPost("/api/system/removeWorkspaceDir", {path: item.path});- }, true);- return;- }- confirmDialog(window.siyuan.languages.confirm, `${escapeHtml(pathPosix().basename(window.siyuan.config.system.workspaceDir))} -> ${escapeHtml(pathPosix().basename(item.path))}?`, () => {- fetchPost("/api/system/setWorkspaceDir", {- path: item.path- }, () => {- exitSiYuan(false);+ if (workspaces.length + remoteConnections.length > 0) {+ workspaceSubMenu.push({id: "separator_1", type: "separator"});+ }+ workspaces.forEach((item: IWorkspace) => {+ workspaceSubMenu.push(workspaceItem(item) as IMenu);+ });+ remoteConnections.forEach(origin => workspaceSubMenu.push({+ label: escapeHtml(window.siyuan.languages.remoteConnection + " · " + origin),+ icon: "iconCloud",+ click: () => manageConnections(origin),+ }));+ /// #else+ workspaceSubMenu = [{+ id: "new",+ label: window.siyuan.languages.new,+ iconHTML: "",+ click() {+ const createWorkspaceDialog = openInputDialog({+ title: window.siyuan.languages.new,+ value: "",+ onConfirm: (value, dialog) => {+ fetchPost("/api/system/createWorkspaceDir", {+ path: pathPosix().join(pathPosix().dirname(window.siyuan.config.system.workspaceDir), value)+ }, () => {+ dialog.destroy();+ });+ },+ });+ createWorkspaceDialog.element.setAttribute("data-key", Constants.DIALOG_CREATEWORKSPACE);+ }+ }, {+ id: "openBy",+ label: `${window.siyuan.languages.openBy}...`,+ iconHTML: "",+ click() {+ fetchPost("/api/system/getMobileWorkspaces", {}, (response) => {+ let selectHTML = "";+ response.data.forEach((item: string, index: number) => {+ selectHTML += `<option value="${escapeAttr(escapeHtml(item))}"${index === 0 ? ' selected="selected"' : ""}>${escapeHtml(pathPosix().basename(item))}</option>`;+ });+ const openWorkspaceDialog = new Dialog({+ title: window.siyuan.languages.openBy,+ content: `<div class="b3-dialog__content">+ <select class="b3-text-field fn__block">${selectHTML}</select>+ </div>+ <div class="b3-dialog__action">+ <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>+ <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>+ </div>`,+ width: "520px",+ });+ openWorkspaceDialog.element.setAttribute("data-key", Constants.DIALOG_OPENWORKSPACE);+ const btnsElement = openWorkspaceDialog.element.querySelectorAll(".b3-button");+ btnsElement[0].addEventListener("click", () => {+ openWorkspaceDialog.destroy();+ });+ btnsElement[1].addEventListener("click", () => {+ const openPath = openWorkspaceDialog.element.querySelector("select").value;+ if (openPath === window.siyuan.config.system.workspaceDir) {+ openWorkspaceDialog.destroy();+ return;+ }+ confirmDialog(window.siyuan.languages.confirm, `${escapeHtml(pathPosix().basename(window.siyuan.config.system.workspaceDir))} -> ${escapeHtml(pathPosix().basename(openPath))}?`, () => {+ fetchPost("/api/system/setWorkspaceDir", {+ path: openPath+ }, () => {+ exitSiYuan(false);+ });+ });});});+ }+ }];+ workspaceSubMenu.push({id: "separator_1", type: "separator"});+ workspaces.forEach((item: IWorkspace) => {+ workspaceSubMenu.push({+ iconHTML: "",+ action: "iconCloseRound",+ current: window.siyuan.config.system.workspaceDir === item.path,+ label: pathPosix().basename(item.path),+ bind(menuElement) {+ menuElement.addEventListener("click", (event) => {+ if (hasClosestByClassName(event.target as Element, "b3-menu__action")) {+ event.preventDefault();+ event.stopPropagation();+ if (item.path === window.siyuan.config.system.workspaceDir) {+ fetchPost("/api/system/removeWorkspaceDir", {path: item.path});+ return;+ }+ confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.removeWorkspacePhysically.replace("${x}", () => escapeHtml(item.path)), () => {+ fetchPost("/api/system/removeWorkspaceDirPhysically", {path: item.path});+ }, () => {+ fetchPost("/api/system/removeWorkspaceDir", {path: item.path});+ }, true);+ return;+ }+ confirmDialog(window.siyuan.languages.confirm, `${escapeHtml(pathPosix().basename(window.siyuan.config.system.workspaceDir))} -> ${escapeHtml(pathPosix().basename(item.path))}?`, () => {+ fetchPost("/api/system/setWorkspaceDir", {+ path: item.path+ }, () => {+ exitSiYuan(false);+ });+ });+ });+ }});+ });+ /// #endif+ if (!isBrowser() || isInMobileApp()) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "workspaceList",+ label: window.siyuan.languages.workspaceList,+ icon: "iconWorkspace",+ type: "submenu",+ submenu: workspaceSubMenu,+ }).element);}- });- });- /// #endif- if (!isBrowser() || isInMobileApp()) {+ }+ const layoutSubMenu = getLayoutSubMenu();+ if (!window.siyuan.config.readonly) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "layout",+ label: window.siyuan.languages.layout,+ icon: "iconLayout",+ type: "submenu",+ submenu: layoutSubMenu+ }).element);+ }window.siyuan.menus.menu.append(new MenuItem({- id: "workspaceList",- label: window.siyuan.languages.workspaceList,- icon: "iconWorkspace",+ id: "zoomControls",+ label: window.siyuan.languages.zoom,+ icon: "iconZoomIn",type: "submenu",- submenu: workspaceSubMenu,+ submenu: getZoomSubMenu(),}).element);- }- }- const layoutSubMenu = getLayoutSubMenu();- if (!window.siyuan.config.readonly) {- window.siyuan.menus.menu.append(new MenuItem({- id: "layout",- label: window.siyuan.languages.layout,- icon: "iconLayout",- type: "submenu",- submenu: layoutSubMenu- }).element);- }- window.siyuan.menus.menu.append(new MenuItem({- id: "zoomControls",- label: window.siyuan.languages.zoom,- icon: "iconZoomIn",- type: "submenu",- submenu: getZoomSubMenu(),- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);- if (!window.siyuan.config.readonly) {- if (getOpenNotebookCount() < 2) {- window.siyuan.menus.menu.append(new MenuItem({- id: "dailyNote",- label: window.siyuan.languages.dailyNote,- icon: "iconCalendar",- accelerator: window.siyuan.config.keymap.general.dailyNote.custom,- click: () => {- newDailyNote(app);- }- }).element);- } else {- const submenu: IMenu[] = [];- window.siyuan.notebooks.forEach(item => {- if (!item.closed) {- submenu.push({- label: escapeHtml(item.name),- iconHTML: getFileTreeIconHTML(item.icon, "notebook", "b3-menu__icon", true),- accelerator: window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] === item.id ? window.siyuan.config.keymap.general.dailyNote.custom : "",+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);+ if (!window.siyuan.config.readonly) {+ if (getOpenNotebookCount() < 2) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "dailyNote",+ label: window.siyuan.languages.dailyNote,+ icon: "iconCalendar",+ accelerator: window.siyuan.config.keymap.general.dailyNote.custom,click: () => {- fetchNewDailyNote(app, item.id);- window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] = item.id;- setStorageVal(Constants.LOCAL_DAILYNOTEID, window.siyuan.storage[Constants.LOCAL_DAILYNOTEID]);+ newDailyNote(app);+ }+ }).element);+ } else {+ const submenu: IMenu[] = [];+ window.siyuan.notebooks.forEach(item => {+ if (!item.closed) {+ submenu.push({+ label: escapeHtml(item.name),+ iconHTML: getFileTreeIconHTML(item.icon, "notebook", "b3-menu__icon", true),+ accelerator: window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] === item.id ? window.siyuan.config.keymap.general.dailyNote.custom : "",+ click: () => {+ fetchNewDailyNote(app, item.id);+ window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] = item.id;+ setStorageVal(Constants.LOCAL_DAILYNOTEID, window.siyuan.storage[Constants.LOCAL_DAILYNOTEID]);+ }+ });}});+ window.siyuan.menus.menu.append(new MenuItem({+ id: "dailyNote",+ label: window.siyuan.languages.dailyNote,+ icon: "iconCalendar",+ type: "submenu",+ submenu+ }).element);}- });- window.siyuan.menus.menu.append(new MenuItem({- id: "dailyNote",- label: window.siyuan.languages.dailyNote,- icon: "iconCalendar",- type: "submenu",- submenu- }).element);- }- if (!window.siyuan.config.readonly) {- window.siyuan.menus.menu.append(new MenuItem({- id: "riffCard",- label: window.siyuan.languages.riffCard,- type: "submenu",- icon: "iconRiffCard",- submenu: [{- id: "spaceRepetition",- iconHTML: "",- label: window.siyuan.languages.spaceRepetition,- accelerator: window.siyuan.config.keymap.general.riffCard.custom,+ if (!window.siyuan.config.readonly) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "riffCard",+ label: window.siyuan.languages.riffCard,+ type: "submenu",+ icon: "iconRiffCard",+ submenu: [{+ id: "spaceRepetition",+ iconHTML: "",+ label: window.siyuan.languages.spaceRepetition,+ accelerator: window.siyuan.config.keymap.general.riffCard.custom,+ click: () => {+ openCard(app);+ }+ }, {+ id: "manage",+ iconHTML: "",+ label: window.siyuan.languages.manage,+ click: () => {+ viewCards(app, "", window.siyuan.languages.all, "");+ }+ }],+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({+ id: "recentDocs",+ label: window.siyuan.languages.recentDocs,+ icon: "iconRecentDocs",+ accelerator: window.siyuan.config.keymap.general.recentDocs.custom,click: () => {- openCard(app);+ openRecentDocs();}- }, {- id: "manage",- iconHTML: "",- label: window.siyuan.languages.manage,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "dataHistory",+ label: window.siyuan.languages.dataHistory,+ icon: "iconHistory",+ accelerator: window.siyuan.config.keymap.general.dataHistory.custom,click: () => {- viewCards(app, "", window.siyuan.languages.all, "");+ openHistory(app);}- }],- }).element);- }- window.siyuan.menus.menu.append(new MenuItem({- id: "recentDocs",- label: window.siyuan.languages.recentDocs,- icon: "iconRecentDocs",- accelerator: window.siyuan.config.keymap.general.recentDocs.custom,- click: () => {- openRecentDocs();- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "dataHistory",- label: window.siyuan.languages.dataHistory,- icon: "iconHistory",- accelerator: window.siyuan.config.keymap.general.dataHistory.custom,- click: () => {- openHistory(app);+ }).element);+ if (!window.siyuan.config.readonly && getHostCapabilities().documentImportExport) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "dataMigration",+ label: window.siyuan.languages.dataMigration,+ icon: "iconDatabaseBackup",+ click: () => {+ openDataMigration();+ }+ }).element);+ }+ if (getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "templateManager",+ label: window.siyuan.languages.templateManager,+ icon: "iconMarkdown",+ click: () => {+ const editor = getAllModels().editor.find(item =>+ item.parent.headElement.classList.contains("item--focus"));+ openTemplateManager(editor?.editor.protyle.block.rootID || "");+ }+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({+ id: "lockScreen",+ label: window.siyuan.languages.lockScreen,+ icon: "iconLock",+ accelerator: window.siyuan.config.keymap.general.lockScreen.custom,+ click: () => {+ lockScreen();+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);}- }).element);- if (!window.siyuan.config.readonly && getHostCapabilities().documentImportExport) {window.siyuan.menus.menu.append(new MenuItem({- id: "dataMigration",- label: window.siyuan.languages.dataMigration,- icon: "iconDatabaseBackup",+ id: "userGuide",+ label: window.siyuan.languages.userGuide,+ icon: "iconHelp",+ ignore: window.siyuan.config.readonly,click: () => {- openDataMigration();+ mountHelp();}}).element);- }- if (getHostCapabilities().importExport) {window.siyuan.menus.menu.append(new MenuItem({- id: "templateManager",- label: window.siyuan.languages.templateManager,- icon: "iconMarkdown",+ id: "feedback",+ label: window.siyuan.languages.feedback,+ icon: "iconFeedback",click: () => {- const editor = getAllModels().editor.find(item =>- item.parent.headElement.classList.contains("item--focus"));- openTemplateManager(editor?.editor.protyle.block.rootID || "");+ if ("zh-CN" === window.siyuan.config.lang) {+ openLink(app, "https://ld246.com/article/1649901726096");+ } else {+ openLink(app, "https://liuyun.io/article/1686530886208");+ }}}).element);- }- window.siyuan.menus.menu.append(new MenuItem({- id: "lockScreen",- label: window.siyuan.languages.lockScreen,- icon: "iconLock",- accelerator: window.siyuan.config.keymap.general.lockScreen.custom,- click: () => {- lockScreen();- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);- }- window.siyuan.menus.menu.append(new MenuItem({- id: "userGuide",- label: window.siyuan.languages.userGuide,- icon: "iconHelp",- ignore: window.siyuan.config.readonly,- click: () => {- mountHelp();- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "feedback",- label: window.siyuan.languages.feedback,- icon: "iconFeedback",- click: () => {- if ("zh-CN" === window.siyuan.config.lang) {- openLink(app, "https://ld246.com/article/1649901726096");- } else {- openLink(app, "https://liuyun.io/article/1686530886208");- }- }- }).element);- /// #if !BROWSER- window.siyuan.menus.menu.append(new MenuItem({- id: "debug",- label: window.siyuan.languages.debug,- icon: "iconBug",- click: () => {- ipcRenderer.send(Constants.SIYUAN_CMD, "toggleDevTools");- }- }).element);- /// #endif- if (isIPad() || isInAndroid() || isInHarmony() || !isBrowser()) {- window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "safeQuit",- label: window.siyuan.languages.safeQuit,- icon: "iconQuit",- warning: true,- click: () => {- exportLayout({- errorExit: true,- cb: exitSiYuan,- });+ /// #if !BROWSER+ window.siyuan.menus.menu.append(new MenuItem({+ id: "debug",+ label: window.siyuan.languages.debug,+ icon: "iconBug",+ click: () => {+ ipcRenderer.send(Constants.SIYUAN_CMD, "toggleDevTools");+ }+ }).element);+ /// #endif+ if (isIPad() || isInAndroid() || isInHarmony() || !isBrowser()) {+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "safeQuit",+ label: window.siyuan.languages.safeQuit,+ icon: "iconQuit",+ warning: true,+ click: () => {+ exportLayout({+ errorExit: true,+ cb: exitSiYuan,+ });+ }+ }).element);}- }).element);- }- window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height});- if (openOnly) {- const menu = window.siyuan.menus.menu;- const activeElement = document.activeElement;- const currentElement = Array.from(menu.element.lastElementChild.children).find(item =>- item.classList.contains("b3-menu__item") &&- !item.classList.contains("b3-menu__item--readonly") &&- !item.hasAttribute("disabled") && item.getBoundingClientRect().height > 0) as HTMLElement;- currentElement?.classList.add("b3-menu__item--current");- currentElement?.focus({preventScroll: true});- currentElement?.scrollIntoView({block: "nearest"});- // 仅在焦点仍位于菜单内时恢复,避免菜单动作打开新界面后抢回原焦点。- menu.removeCB = () => {- if (activeElement instanceof HTMLElement && activeElement.isConnected &&- menu.element.contains(document.activeElement)) {- activeElement.focus({preventScroll: true});+ session.show(() => window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height}));+ if (openOnly) {+ const menu = window.siyuan.menus.menu;+ const activeElement = document.activeElement;+ const currentElement = Array.from(menu.element.lastElementChild.children).find(item =>+ item.classList.contains("b3-menu__item") &&+ !item.classList.contains("b3-menu__item--readonly") &&+ !item.hasAttribute("disabled") && item.getBoundingClientRect().height > 0) as HTMLElement;+ currentElement?.classList.add("b3-menu__item--current");+ currentElement?.focus({preventScroll: true});+ currentElement?.scrollIntoView({block: "nearest"});+ // 仅在焦点仍位于菜单内时恢复,避免菜单动作打开新界面后抢回原焦点。+ menu.removeCB = () => {+ if (activeElement instanceof HTMLElement && activeElement.isConnected &&+ menu.element.contains(document.activeElement)) {+ activeElement.focus({preventScroll: true});+ }+ };}};- }- };- if (getHostCapabilities().workspaces) {- fetchPost("/api/system/getWorkspaces", {}, (response) => renderMenu(response.data));- } else {- renderMenu([]);- }+ if (getHostCapabilities().workspaces) {+ fetchPost("/api/system/getWorkspaces", {}, (response) => renderMenu(response.data));+ } else {+ renderMenu([]);+ }++ },+ });};const openWorkspace = (workspace: string) => {diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex d21cd138e8..b6f6ae133b 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -5,7 +5,7 @@ import {Model} from "../../layout/Model";import {Constants} from "../../constants";import {getDocDisplayName, isMoveTargetAllowed, pathPosix, setNoteBook} from "../../util/pathName";import {initFileMenu, initNavigationMenu, sortMenu} from "../../menus/navigation";-import {toggleFileTreeMenu} from "../../menus/fileTreeMenu";+import {toggleMenu} from "../../menus/menuToggle";import {getPublishAccessLevel,getPublishAccessOptionByLevel,@@ -298,18 +298,22 @@ export class MobileFiles extends Model {if (type === "new") {newFileInTree(app, notebookId, pathString);} else if (type === "more-root") {- toggleFileTreeMenu(target, () => {- initNavigationMenu(app, target.parentElement);- this.insertMultiSelectMenu(target.parentElement);- window.siyuan.menus.menu.fullscreen("bottom");+ toggleMenu({+ target: target, build: () => {+ initNavigationMenu(app, target.parentElement);+ this.insertMultiSelectMenu(target.parentElement);+ window.siyuan.menus.menu.fullscreen("bottom");+ }});}}if (type === "more-file") {- toggleFileTreeMenu(target, () => {- initFileMenu(app, notebookId, pathString, target.parentElement);- this.insertMultiSelectMenu(target.parentElement);- window.siyuan.menus.menu.fullscreen("bottom");+ toggleMenu({+ target: target, build: () => {+ initFileMenu(app, notebookId, pathString, target.parentElement);+ this.insertMultiSelectMenu(target.parentElement);+ window.siyuan.menus.menu.fullscreen("bottom");+ }});}}@@ -839,35 +843,40 @@ export class MobileFiles extends Model {}private genSort() {- window.siyuan.menus.menu.remove();- const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {- if (sort === null) {- return;- }- fetchPost("/api/setting/setFiletree", {- ...window.siyuan.config.fileTree,- sort,- }, (response) => {- if (response.code !== 0) {- return;- }- window.siyuan.config.fileTree = {- ...response.data,- tabStartupMode: response.data.tabStartupMode === 1 ? 1 : response.data.tabStartupMode === 2 ? 2 : 0,- };- this.onDocSortModeChanged({- scope: "global",- box: "",- id: "",- path: "/",- sortMode: sort,+ toggleMenu({+ target: this.element.querySelector("[data-type=sort]"),+ build: (_menu, session) => {+ const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {+ if (sort === null) {+ return;+ }+ fetchPost("/api/setting/setFiletree", {+ ...window.siyuan.config.fileTree,+ sort,+ }, (response) => {+ if (response.code !== 0) {+ return;+ }+ window.siyuan.config.fileTree = {+ ...response.data,+ tabStartupMode: response.data.tabStartupMode === 1 ? 1 : response.data.tabStartupMode === 2 ? 2 : 0,+ };+ this.onDocSortModeChanged({+ scope: "global",+ box: "",+ id: "",+ path: "/",+ sortMode: sort,+ });+ });});- });- });- subMenu.forEach((item) => {- window.siyuan.menus.menu.append(new MenuItem(item).element);+ subMenu.forEach((item) => {+ window.siyuan.menus.menu.append(new MenuItem(item).element);+ });+ session.show(() => window.siyuan.menus.menu.fullscreen("bottom"));++ },});- window.siyuan.menus.menu.fullscreen("bottom");}private updateItemArrow(notebookId: string, filePath: string) {diff --git a/app/src/mobile/dock/MobileOutline.ts b/app/src/mobile/dock/MobileOutline.tsindex dfc4c1edd3..2dacfad1b2 100644--- a/app/src/mobile/dock/MobileOutline.ts+++ b/app/src/mobile/dock/MobileOutline.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {bindPanelSearch} from "../../layout/dock/panelSearch";import type {BlockBreadcrumbRequestInput} from "../../types/api";import {Tree} from "../../util/Tree";@@ -89,7 +90,7 @@ export class MobileOutline extends Model {if (event) {const actionElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item__action");if (actionElement) {- this.showContextMenu(element);+ this.showContextMenu(element, actionElement);return;}}@@ -780,31 +781,35 @@ export class MobileOutline extends Model {* 显示展开层级菜单*/private showExpandLevelMenu() {- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_EXPAND_LEVEL);- window.siyuan.menus.menu.append(new MenuItem({- id: "expandAll",- icon: "iconExpand",- label: window.siyuan.languages.expandAll,- click: () => this.setAllExpanded(true)- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "foldAll",- icon: "iconContract",- label: window.siyuan.languages.foldAll,- click: () => this.setAllExpanded(false)- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_all", type: "separator"}).element);- for (let i = 1; i <= 6; i++) {- window.siyuan.menus.menu.append(new MenuItem({- id: `heading${i}`,- icon: `iconH${i}`,- label: window.siyuan.languages[`heading${i}`],- click: () => this.expandToLevel(i)- }).element);- }- window.siyuan.menus.menu.fullscreen("bottom");- return window.siyuan.menus.menu;+ toggleMenu({+ target: this.element.querySelector("[data-type=expandLevel]"),+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_EXPAND_LEVEL);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandAll",+ icon: "iconExpand",+ label: window.siyuan.languages.expandAll,+ click: () => this.setAllExpanded(true)+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldAll",+ icon: "iconContract",+ label: window.siyuan.languages.foldAll,+ click: () => this.setAllExpanded(false)+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_all", type: "separator"}).element);+ for (let i = 1; i <= 6; i++) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: `heading${i}`,+ icon: `iconH${i}`,+ label: window.siyuan.languages[`heading${i}`],+ click: () => this.expandToLevel(i)+ }).element);+ }+ session.show(() => window.siyuan.menus.menu.fullscreen("bottom"));++ },+ });}/**@@ -887,414 +892,421 @@ export class MobileOutline extends Model {/*** 显示右键菜单*/- private showContextMenu(element: HTMLElement) {- if (this.isPreview) {- return; // 预览模式下不显示右键菜单- }- const currentLevel = this.getHeadingLevel(element);- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_CONTEXT);- const id = element.getAttribute("data-node-id");- if (!window.siyuan.config.readonly) {- // 升级- if (currentLevel > 1) {- window.siyuan.menus.menu.append(new MenuItem({- id: "upgrade",- icon: "iconUp",- label: window.siyuan.languages.upgrade,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (data) {- getSelection()?.removeAllRanges();- turnsIntoTransaction({- protyle: data.protyle,- selectsElement: [data.blockElement],- type: "Blocks2Hs",- level: currentLevel - 1,- unfocus: true,- });- }- }- }).element);- }+ private showContextMenu(element: HTMLElement, target?: Element) {+ toggleMenu({+ target: target || element,+ toggle: Boolean(target),+ build: (_menu, session) => {+ if (this.isPreview) {+ return; // 预览模式下不显示右键菜单+ }+ const currentLevel = this.getHeadingLevel(element);- // 降级- if (currentLevel < 6) {- window.siyuan.menus.menu.append(new MenuItem({- id: "downgrade",- icon: "iconDown",- label: window.siyuan.languages.downgrade,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (data) {- getSelection()?.removeAllRanges();- turnsIntoTransaction({- protyle: data.protyle,- selectsElement: [data.blockElement],- type: "Blocks2Hs",- level: currentLevel + 1,- unfocus: true,- });- }+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_OUTLINE_CONTEXT);+ const id = element.getAttribute("data-node-id");+ if (!window.siyuan.config.readonly) {+ // 升级+ if (currentLevel > 1) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "upgrade",+ icon: "iconUp",+ label: window.siyuan.languages.upgrade,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (data) {+ getSelection()?.removeAllRanges();+ turnsIntoTransaction({+ protyle: data.protyle,+ selectsElement: [data.blockElement],+ type: "Blocks2Hs",+ level: currentLevel - 1,+ unfocus: true,+ });+ }+ }+ }).element);}- }).element);- }- this.setCurrentById(id);- const headingSubMenu = [];- if (currentLevel !== 1) {- headingSubMenu.push(this.genHeadingTransform(id, 1));- }- if (currentLevel !== 2) {- headingSubMenu.push(this.genHeadingTransform(id, 2));- }- if (currentLevel !== 3) {- headingSubMenu.push(this.genHeadingTransform(id, 3));- }- if (currentLevel !== 4) {- headingSubMenu.push(this.genHeadingTransform(id, 4));- }- if (currentLevel !== 5) {- headingSubMenu.push(this.genHeadingTransform(id, 5));- }- if (currentLevel !== 6) {- headingSubMenu.push(this.genHeadingTransform(id, 6));- }-- if (headingSubMenu.length > 0) {- window.siyuan.menus.menu.append(new MenuItem({- id: "tWithSubtitle",- type: "submenu",- icon: "iconRefresh",- label: window.siyuan.languages.tWithSubtitle,- submenu: headingSubMenu- }).element);- }- const rootID = this.blockId;- window.siyuan.menus.menu.append(new MenuItem({- id: "headingBatch",- icon: "iconHeadings",- label: window.siyuan.languages.headingBatch,- click: () => {- const protyle = window.siyuan.mobile.editor?.protyle;- if (canBatchConvertHeadings(protyle, rootID, this.isPreview)) {- void showHeadingBatchDialog(protyle, () => rootID === this.blockId &&- window.siyuan.mobile.editor?.protyle === protyle &&- canBatchConvertHeadings(protyle, rootID, this.isPreview));+ // 降级+ if (currentLevel < 6) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "downgrade",+ icon: "iconDown",+ label: window.siyuan.languages.downgrade,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (data) {+ getSelection()?.removeAllRanges();+ turnsIntoTransaction({+ protyle: data.protyle,+ selectsElement: [data.blockElement],+ type: "Blocks2Hs",+ level: currentLevel + 1,+ unfocus: true,+ });+ }+ }+ }).element);}- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);-- // 在前面插入同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "insertSameLevelHeadingBefore",- icon: "iconBefore",- label: window.siyuan.languages.insertSameLevelHeadingBefore,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (!data) {- return;+ this.setCurrentById(id);+ const headingSubMenu = [];+ if (currentLevel !== 1) {+ headingSubMenu.push(this.genHeadingTransform(id, 1));}- const newId = Lute.NewNodeID();- const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;- const previousID = data.blockElement.previousElementSibling?.getAttribute("data-node-id");- data.blockElement.insertAdjacentHTML("beforebegin", html);- const newElement = data.blockElement.previousElementSibling;- this.focusInsertedHeading(newElement);- transaction(data.protyle, [{- action: "insert",- data: html,- id: newId,- previousID,- parentID: data.blockElement.parentElement.getAttribute("data-node-id") || data.protyle.block.parentID,- }], [{- action: "delete",- id: newId- }]);- }- }).element);-- // 在后面插入同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "insertSameLevelHeadingAfter",- icon: "iconAfter",- label: window.siyuan.languages.insertSameLevelHeadingAfter,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (!data) {- return;+ if (currentLevel !== 2) {+ headingSubMenu.push(this.genHeadingTransform(id, 2));+ }+ if (currentLevel !== 3) {+ headingSubMenu.push(this.genHeadingTransform(id, 3));+ }+ if (currentLevel !== 4) {+ headingSubMenu.push(this.genHeadingTransform(id, 4));+ }+ if (currentLevel !== 5) {+ headingSubMenu.push(this.genHeadingTransform(id, 5));+ }+ if (currentLevel !== 6) {+ headingSubMenu.push(this.genHeadingTransform(id, 6));}- const rootID = data.protyle.block.rootID;- focusBlock(data.blockElement);- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, (deleteResponse) => {- if (window.siyuan.mobile.editor?.protyle !== data.protyle || this.blockId !== rootID ||- !deleteResponse.data?.doOperations?.length) {- return;- }- const previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;-- const newId = Lute.NewNodeID();- const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;- const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);- if (previousElement) {- previousElement.insertAdjacentHTML("afterend", html);- const newElement = previousElement.nextElementSibling;- this.focusInsertedHeading(newElement);- }- transaction(data.protyle, [{- action: "insert",- data: html,- id: newId,- previousID,- }], [{- action: "delete",- id: newId- }]);- });- }- }).element);- // 添加子标题- if (currentLevel < 6) { // 只有当前级别小于6时才能添加子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "addChildHeading",- icon: "iconAdd",- label: window.siyuan.languages.addChildHeading,- click: () => {- const data = this.getProtyleAndBlockElement(element);- if (!data) {- return;+ if (headingSubMenu.length > 0) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "tWithSubtitle",+ type: "submenu",+ icon: "iconRefresh",+ label: window.siyuan.languages.tWithSubtitle,+ submenu: headingSubMenu+ }).element);+ }++ const rootID = this.blockId;+ window.siyuan.menus.menu.append(new MenuItem({+ id: "headingBatch",+ icon: "iconHeadings",+ label: window.siyuan.languages.headingBatch,+ click: () => {+ const protyle = window.siyuan.mobile.editor?.protyle;+ if (canBatchConvertHeadings(protyle, rootID, this.isPreview)) {+ void showHeadingBatchDialog(protyle, () => rootID === this.blockId &&+ window.siyuan.mobile.editor?.protyle === protyle &&+ canBatchConvertHeadings(protyle, rootID, this.isPreview));+ }}- const rootID = data.protyle.block.rootID;- focusBlock(data.blockElement);- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, (deleteResponse) => {- if (window.siyuan.mobile.editor?.protyle !== data.protyle || this.blockId !== rootID ||- !deleteResponse.data?.doOperations?.length || !deleteResponse.data?.undoOperations) {+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);++ // 在前面插入同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "insertSameLevelHeadingBefore",+ icon: "iconBefore",+ label: window.siyuan.languages.insertSameLevelHeadingBefore,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (!data) {return;}- let previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;- deleteResponse.data.undoOperations.find((operationsItem, index: number) => {- if (typeof operationsItem.data !== "string") {- return false;- }- const startIndex = operationsItem.data.indexOf(' data-subtype="h');- if (index > 0 && startIndex > -1 && startIndex < 260 && parseInt(operationsItem.data.substring(startIndex + 16, startIndex + 17)) === currentLevel + 1) {- previousID = deleteResponse.data.undoOperations[index - 1].id;- return true;- }- });const newId = Lute.NewNodeID();- const html = `<div data-subtype="h${currentLevel + 1}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel + 1}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;- const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);- if (previousElement) {- previousElement.insertAdjacentHTML("afterend", html);- const newElement = previousElement.nextElementSibling;- this.focusInsertedHeading(newElement);- }+ const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;+ const previousID = data.blockElement.previousElementSibling?.getAttribute("data-node-id");+ data.blockElement.insertAdjacentHTML("beforebegin", html);+ const newElement = data.blockElement.previousElementSibling;+ this.focusInsertedHeading(newElement);transaction(data.protyle, [{action: "insert",data: html,id: newId,previousID,+ parentID: data.blockElement.parentElement.getAttribute("data-node-id") || data.protyle.block.parentID,}], [{action: "delete",id: newId}]);- });- }- }).element);- }-- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);- }-- // 复制带子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "copyHeadings1",- icon: "iconCopy",- label: `${window.siyuan.languages.copy} ${window.siyuan.languages.headings1}`,- click: () => {- const data = this.getProtyleAndBlockElement(element);- fetchPost("/api/block/getHeadingChildrenDOM", {- id,- removeFoldAttr: false- }, async (response) => {- await writeBlockDOMClipboard(data.protyle.lute, response.data);- });- }- }).element);-- if (!window.siyuan.config.readonly) {- // 剪切带子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "cutHeadings1",- icon: "iconCut",- label: `${window.siyuan.languages.cut} ${window.siyuan.languages.headings1}`,- click: () => {- const data = this.getProtyleAndBlockElement(element);- fetchPost("/api/block/getHeadingChildrenDOM", {- id,- removeFoldAttr: false- }, (response) => {- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, async (deleteResponse) => {- const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = deleteResponse.data;- const deletedIDs = headingTransaction.doOperations.map(- (operation: IOperation) => operation.id);- if (!await confirmBlockRef({- scope: "blocks",- ids: deletedIDs,- deletedIDs,- notebook: data.protyle.notebookId,- }, data.protyle)) {- return;- }- if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {- return;- }- if (!await writeBlockDOMClipboard(data.protyle.lute, response.data)) {- return;- }- if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ }+ }).element);++ // 在后面插入同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "insertSameLevelHeadingAfter",+ icon: "iconAfter",+ label: window.siyuan.languages.insertSameLevelHeadingAfter,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (!data) {return;}- headingTransaction.doOperations.forEach((operation: IOperation) => {- data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {- itemElement.remove();- });- });- if (data.protyle.wysiwyg.element.childElementCount === 0) {- const newID = Lute.NewNodeID();- const emptyElement = genEmptyElement(false, false, newID);- data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);- headingTransaction.doOperations.push({+ const rootID = data.protyle.block.rootID;+ focusBlock(data.blockElement);+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, (deleteResponse) => {+ if (window.siyuan.mobile.editor?.protyle !== data.protyle || this.blockId !== rootID ||+ !deleteResponse.data?.doOperations?.length) {+ return;+ }+ const previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;++ const newId = Lute.NewNodeID();+ const html = `<div data-subtype="h${currentLevel}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;+ const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);+ if (previousElement) {+ previousElement.insertAdjacentHTML("afterend", html);+ const newElement = previousElement.nextElementSibling;+ this.focusInsertedHeading(newElement);+ }+ transaction(data.protyle, [{action: "insert",- data: emptyElement.outerHTML,- id: newID,- parentID: data.protyle.block.parentID- });- headingTransaction.undoOperations.push({+ data: html,+ id: newId,+ previousID,+ }], [{action: "delete",- id: newID,+ id: newId+ }]);+ });+ }+ }).element);++ // 添加子标题+ if (currentLevel < 6) { // 只有当前级别小于6时才能添加子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "addChildHeading",+ icon: "iconAdd",+ label: window.siyuan.languages.addChildHeading,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ if (!data) {+ return;+ }+ const rootID = data.protyle.block.rootID;+ focusBlock(data.blockElement);+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, (deleteResponse) => {+ if (window.siyuan.mobile.editor?.protyle !== data.protyle || this.blockId !== rootID ||+ !deleteResponse.data?.doOperations?.length || !deleteResponse.data?.undoOperations) {+ return;+ }+ let previousID = deleteResponse.data.doOperations[deleteResponse.data.doOperations.length - 1].id;+ deleteResponse.data.undoOperations.find((operationsItem, index: number) => {+ if (typeof operationsItem.data !== "string") {+ return false;+ }+ const startIndex = operationsItem.data.indexOf(' data-subtype="h');+ if (index > 0 && startIndex > -1 && startIndex < 260 && parseInt(operationsItem.data.substring(startIndex + 16, startIndex + 17)) === currentLevel + 1) {+ previousID = deleteResponse.data.undoOperations[index - 1].id;+ return true;+ }+ });+ const newId = Lute.NewNodeID();+ const html = `<div data-subtype="h${currentLevel + 1}" data-node-id="${newId}" data-type="NodeHeading" class="h${currentLevel + 1}"><div contenteditable="true" spellcheck="false"><wbr></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;+ const previousElement = data.protyle.wysiwyg.element.querySelector(`[data-node-id="${previousID}"]`);+ if (previousElement) {+ previousElement.insertAdjacentHTML("afterend", html);+ const newElement = previousElement.nextElementSibling;+ this.focusInsertedHeading(newElement);+ }+ transaction(data.protyle, [{+ action: "insert",+ data: html,+ id: newId,+ previousID,+ }], [{+ action: "delete",+ id: newId+ }]);});- focusBlock(emptyElement);}- transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);- });- });+ }).element);+ }++ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);}- }).element);-- // 删除- window.siyuan.menus.menu.append(new MenuItem({- id: "deleteHeadings1",- icon: "iconTrashcan",- label: `${window.siyuan.languages.delete} ${window.siyuan.languages.headings1}`,- click: () => {- const data = this.getProtyleAndBlockElement(element);- fetchPost("/api/block/getHeadingDeleteTransaction", {- id,- }, async (response) => {- const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = response.data;- const deletedIDs = headingTransaction.doOperations.map((operation: IOperation) => operation.id);- if (!await confirmBlockRef({- scope: "blocks",- ids: deletedIDs,- deletedIDs,- notebook: data.protyle.notebookId,- }, data.protyle)) {- return;- }- if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {- return;- }- headingTransaction.doOperations.forEach((operation: IOperation) => {- data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {- itemElement.remove();- });++ // 复制带子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "copyHeadings1",+ icon: "iconCopy",+ label: `${window.siyuan.languages.copy} ${window.siyuan.languages.headings1}`,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ fetchPost("/api/block/getHeadingChildrenDOM", {+ id,+ removeFoldAttr: false+ }, async (response) => {+ await writeBlockDOMClipboard(data.protyle.lute, response.data);});- if (data.protyle.wysiwyg.element.childElementCount === 0) {- const newID = Lute.NewNodeID();- const emptyElement = genEmptyElement(false, false, newID);- data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);- headingTransaction.doOperations.push({- action: "insert",- data: emptyElement.outerHTML,- id: newID,- parentID: data.protyle.block.parentID+ }+ }).element);++ if (!window.siyuan.config.readonly) {+ // 剪切带子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "cutHeadings1",+ icon: "iconCut",+ label: `${window.siyuan.languages.cut} ${window.siyuan.languages.headings1}`,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ fetchPost("/api/block/getHeadingChildrenDOM", {+ id,+ removeFoldAttr: false+ }, (response) => {+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, async (deleteResponse) => {+ const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = deleteResponse.data;+ const deletedIDs = headingTransaction.doOperations.map(+ (operation: IOperation) => operation.id);+ if (!await confirmBlockRef({+ scope: "blocks",+ ids: deletedIDs,+ deletedIDs,+ notebook: data.protyle.notebookId,+ }, data.protyle)) {+ return;+ }+ if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ return;+ }+ if (!await writeBlockDOMClipboard(data.protyle.lute, response.data)) {+ return;+ }+ if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ return;+ }+ headingTransaction.doOperations.forEach((operation: IOperation) => {+ data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {+ itemElement.remove();+ });+ });+ if (data.protyle.wysiwyg.element.childElementCount === 0) {+ const newID = Lute.NewNodeID();+ const emptyElement = genEmptyElement(false, false, newID);+ data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);+ headingTransaction.doOperations.push({+ action: "insert",+ data: emptyElement.outerHTML,+ id: newID,+ parentID: data.protyle.block.parentID+ });+ headingTransaction.undoOperations.push({+ action: "delete",+ id: newID,+ });+ focusBlock(emptyElement);+ }+ transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);+ });});- headingTransaction.undoOperations.push({- action: "delete",- id: newID,+ }+ }).element);++ // 删除+ window.siyuan.menus.menu.append(new MenuItem({+ id: "deleteHeadings1",+ icon: "iconTrashcan",+ label: `${window.siyuan.languages.delete} ${window.siyuan.languages.headings1}`,+ click: () => {+ const data = this.getProtyleAndBlockElement(element);+ fetchPost("/api/block/getHeadingDeleteTransaction", {+ id,+ }, async (response) => {+ const headingTransaction: {doOperations: IOperation[], undoOperations: IOperation[]} = response.data;+ const deletedIDs = headingTransaction.doOperations.map((operation: IOperation) => operation.id);+ if (!await confirmBlockRef({+ scope: "blocks",+ ids: deletedIDs,+ deletedIDs,+ notebook: data.protyle.notebookId,+ }, data.protyle)) {+ return;+ }+ if (!data.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`)) {+ return;+ }+ headingTransaction.doOperations.forEach((operation: IOperation) => {+ data.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {+ itemElement.remove();+ });+ });+ if (data.protyle.wysiwyg.element.childElementCount === 0) {+ const newID = Lute.NewNodeID();+ const emptyElement = genEmptyElement(false, false, newID);+ data.protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement);+ headingTransaction.doOperations.push({+ action: "insert",+ data: emptyElement.outerHTML,+ id: newID,+ parentID: data.protyle.block.parentID+ });+ headingTransaction.undoOperations.push({+ action: "delete",+ id: newID,+ });+ focusBlock(emptyElement);+ }+ transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);});- focusBlock(emptyElement);}- transaction(data.protyle, headingTransaction.doOperations, headingTransaction.undoOperations);- });+ }).element);}- }).element);- }- window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);-- // 展开子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "expandChildHeading",- icon: "iconExpand",- label: window.siyuan.languages.expandChildHeading,- accelerator: "⌘" + window.siyuan.languages.clickArrow,- click: () => this.collapseChildren(element, true)- }).element);-- // 折叠子标题- window.siyuan.menus.menu.append(new MenuItem({- id: "foldChildHeading",- icon: "iconContract",- label: window.siyuan.languages.foldChildHeading,- accelerator: "⌘" + window.siyuan.languages.clickArrow,- click: () => this.collapseChildren(element, false)- }).element);-- // 展开同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "expandSameLevelHeading",- icon: "iconExpand",- label: window.siyuan.languages.expandSameLevelHeading,- accelerator: "⌥" + window.siyuan.languages.clickArrow,- click: () => this.collapseSameLevel(element, true)- }).element);-- // 折叠同级标题- window.siyuan.menus.menu.append(new MenuItem({- id: "foldSameLevelHeading",- icon: "iconContract",- label: window.siyuan.languages.foldSameLevelHeading,- accelerator: "⌥" + window.siyuan.languages.clickArrow,- click: () => this.collapseSameLevel(element, false)- }).element);-- // 全部展开- window.siyuan.menus.menu.append(new MenuItem({- id: "expandAll",- icon: "iconExpand",- label: window.siyuan.languages.expandAll,- click: () => this.setAllExpanded(true)- }).element);-- // 全部折叠- window.siyuan.menus.menu.append(new MenuItem({- id: "foldAll",- icon: "iconContract",- label: window.siyuan.languages.foldAll,- click: () => this.setAllExpanded(false)- }).element);-- window.siyuan.menus.menu.fullscreen("bottom");+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);++ // 展开子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandChildHeading",+ icon: "iconExpand",+ label: window.siyuan.languages.expandChildHeading,+ accelerator: "⌘" + window.siyuan.languages.clickArrow,+ click: () => this.collapseChildren(element, true)+ }).element);++ // 折叠子标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldChildHeading",+ icon: "iconContract",+ label: window.siyuan.languages.foldChildHeading,+ accelerator: "⌘" + window.siyuan.languages.clickArrow,+ click: () => this.collapseChildren(element, false)+ }).element);++ // 展开同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandSameLevelHeading",+ icon: "iconExpand",+ label: window.siyuan.languages.expandSameLevelHeading,+ accelerator: "⌥" + window.siyuan.languages.clickArrow,+ click: () => this.collapseSameLevel(element, true)+ }).element);++ // 折叠同级标题+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldSameLevelHeading",+ icon: "iconContract",+ label: window.siyuan.languages.foldSameLevelHeading,+ accelerator: "⌥" + window.siyuan.languages.clickArrow,+ click: () => this.collapseSameLevel(element, false)+ }).element);++ // 全部展开+ window.siyuan.menus.menu.append(new MenuItem({+ id: "expandAll",+ icon: "iconExpand",+ label: window.siyuan.languages.expandAll,+ click: () => this.setAllExpanded(true)+ }).element);++ // 全部折叠+ window.siyuan.menus.menu.append(new MenuItem({+ id: "foldAll",+ icon: "iconContract",+ label: window.siyuan.languages.foldAll,+ click: () => this.setAllExpanded(false)+ }).element);++ session.show(() => window.siyuan.menus.menu.fullscreen("bottom"));++ },+ });}private getProtyleAndBlockElement(element: HTMLElement) {diff --git a/app/src/mobile/dock/MobileTags.ts b/app/src/mobile/dock/MobileTags.tsindex 1f64fd8d40..79c8434307 100644--- a/app/src/mobile/dock/MobileTags.ts+++ b/app/src/mobile/dock/MobileTags.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {bindPanelSearch} from "../../layout/dock/panelSearch";import {Tree} from "../../util/Tree";import {fetchPost} from "../../util/fetch";@@ -94,57 +95,63 @@ export class MobileTags {showMobileFilterInput(inputElement, target);break;case "sort":- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 0 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameASC,- click: () => {- window.siyuan.config.tag.sort = 0;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 1 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameDESC,- click: () => {- window.siyuan.config.tag.sort = 1;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 4 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameNatASC,- click: () => {- window.siyuan.config.tag.sort = 4;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 5 ? "iconSelect" : undefined,- label: window.siyuan.languages.fileNameNatDESC,- click: () => {- window.siyuan.config.tag.sort = 5;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 7 ? "iconSelect" : undefined,- label: window.siyuan.languages.refCountASC,- click: () => {- window.siyuan.config.tag.sort = 7;- this.update();- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: window.siyuan.config.tag.sort === 8 ? "iconSelect" : undefined,- label: window.siyuan.languages.refCountDESC,- click: () => {- window.siyuan.config.tag.sort = 8;- this.update();++ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 0 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameASC,+ click: () => {+ window.siyuan.config.tag.sort = 0;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 1 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameDESC,+ click: () => {+ window.siyuan.config.tag.sort = 1;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 4 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameNatASC,+ click: () => {+ window.siyuan.config.tag.sort = 4;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 5 ? "iconSelect" : undefined,+ label: window.siyuan.languages.fileNameNatDESC,+ click: () => {+ window.siyuan.config.tag.sort = 5;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 7 ? "iconSelect" : undefined,+ label: window.siyuan.languages.refCountASC,+ click: () => {+ window.siyuan.config.tag.sort = 7;+ this.update();+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: window.siyuan.config.tag.sort === 8 ? "iconSelect" : undefined,+ label: window.siyuan.languages.refCountDESC,+ click: () => {+ window.siyuan.config.tag.sort = 8;+ this.update();+ },+ }).element);+ session.show(() => window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY}));+},- }).element);- window.siyuan.menus.menu.popup({x: event.clientX, y: event.clientY});- event.preventDefault();+ });+ event.preventDefault();event.stopPropagation();break;}diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.tsindex 9bde92c65c..f8bf771d0d 100644--- a/app/src/mobile/menu/search.ts+++ b/app/src/mobile/menu/search.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {closePanel} from "../util/closePanel";import {updateSearchMethodControls} from "../../search/methodCapabilities";import {buildSearchRequest, refreshSearchConfigHPath} from "../../search/config";@@ -627,29 +628,35 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTabevent.preventDefault();break;} else if (type === "more") {- moreMenu(config, criteriaData, element, () => {- config.page = 1;- updateSearchResult(config, element, true);- }, () => {- config = updateConfig(element, {- removed: true,- sort: 0,- group: 0,- hasReplace: false,- method: 0,- hPath: "",- idPath: [],- k: "",- r: "",- page: 1,- types: getDefaultType(),- subTypes: getDefaultSubType(),- replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),- }, config, true);- element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ moreMenu(config, criteriaData, element, () => {+ config.page = 1;+ updateSearchResult(config, element, true);+ }, () => {+ config = updateConfig(element, {+ removed: true,+ sort: 0,+ group: 0,+ hasReplace: false,+ method: 0,+ hPath: "",+ idPath: [],+ k: "",+ r: "",+ page: 1,+ types: getDefaultType(),+ subTypes: getDefaultSubType(),+ replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),+ }, config, true);+ element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");+ });+ session.show(() => window.siyuan.menus.menu.fullscreen());++ },});- window.siyuan.menus.menu.fullscreen();- event.stopPropagation();+ event.stopPropagation();event.preventDefault();break;} else if (type === "replace-all") {diff --git a/app/src/mobile/tabs/MobileTabs.ts b/app/src/mobile/tabs/MobileTabs.tsindex cd4ab815db..f4431dbc3b 100644--- a/app/src/mobile/tabs/MobileTabs.ts+++ b/app/src/mobile/tabs/MobileTabs.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {Constants} from "../../constants";import {getDocumentIconHTML} from "../../emoji/fileTreeIcon";import type {App} from "../../index";@@ -830,48 +831,55 @@ export class MobileTabs {this.persist();}- private openTabMenu(tabID: string) {- const tab = this.state.tabs.find((item) => item.id === tabID);- if (!tab) {- return;- }- const pinned = !!tab.pin;- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_MOBILE_TABS);- window.siyuan.menus.menu.append(new MenuItem({- id: "close",- icon: "iconClose",- label: window.siyuan.languages.close,- click: () => {- void this.close(tabID);- },- }).element);- if (this.state.tabs.length > 1) {- window.siyuan.menus.menu.append(new MenuItem({- id: "closeOthers",- label: window.siyuan.languages.closeOthers,- click: () => {- this.closeOthers(tabID);- },- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "closeAll",- label: window.siyuan.languages.closeAll,- click: () => {- this.closeAll();- },- }).element);- }- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- id: pinned ? "unpin" : "pin",- icon: getPinIcon(pinned),- label: pinned ? window.siyuan.languages.unpin : window.siyuan.languages.pin,- click: () => {- this.togglePin(tabID);+ private openTabMenu(tabID: string, target?: Element) {+ toggleMenu({+ target,+ toggle: false,+ build: (_menu, session) => {+ const tab = this.state.tabs.find((item) => item.id === tabID);+ if (!tab) {+ return;+ }+ const pinned = !!tab.pin;++ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_MOBILE_TABS);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "close",+ icon: "iconClose",+ label: window.siyuan.languages.close,+ click: () => {+ void this.close(tabID);+ },+ }).element);+ if (this.state.tabs.length > 1) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "closeOthers",+ label: window.siyuan.languages.closeOthers,+ click: () => {+ this.closeOthers(tabID);+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "closeAll",+ label: window.siyuan.languages.closeAll,+ click: () => {+ this.closeAll();+ },+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: pinned ? "unpin" : "pin",+ icon: getPinIcon(pinned),+ label: pinned ? window.siyuan.languages.unpin : window.siyuan.languages.pin,+ click: () => {+ this.togglePin(tabID);+ },+ }).element);+ session.show(() => window.siyuan.menus.menu.fullscreen("bottom"));+},- }).element);- window.siyuan.menus.menu.fullscreen("bottom");+ });}private togglePin(tabID: string) {@@ -1051,7 +1059,7 @@ export class MobileTabs {}this.overviewLongPressTriggered = true;this.suppressOverviewClickUntil = Date.now() + Constants.TIMEOUT_LONGPRESS;- this.openTabMenu(tabID);+ this.openTabMenu(tabID, itemElement);}, Constants.TIMEOUT_LONGPRESS);});element.addEventListener("pointermove", processPointerMove);diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 4c5fbd6f72..9d907c00da 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {listIndent, listOutdent} from "../../protyle/wysiwyg/list";import {hasClosestBlock,@@ -1931,41 +1932,51 @@ export const initKeyboardToolbar = () => {hideAndroidKeyboardForPanel(protyle);return;} else if (type === "block") {- event.preventDefault();- protyle.toolbar.range = range;- keyboardPanelClosing = false;- hideKeyboardToolbarUtil();- if (!protyle.gutter && getTableCellRichContext(protyle)) {- const {MenuItem} = await import("../../menus/Menu");- if (!nodeElement.isConnected || protyle.disabled || !getTableCellRichContext(protyle)) {- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.append(new MenuItem({- id: "insertBefore",- icon: "iconBefore",- label: window.siyuan.languages.insertBefore,- click: () => insertEmptyBlock(protyle, "beforebegin", nodeElement),- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "insertAfter",- icon: "iconAfter",- label: window.siyuan.languages.insertAfter,- click: () => insertEmptyBlock(protyle, "afterend", nodeElement),- }).element);- window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard);- return;- }- // 多选时以已选块打开共享块菜单,使列表项转换作用于整个选区。- const selectedBlock = protyle.wysiwyg.element.querySelector<HTMLElement>(".protyle-wysiwyg--select");- protyle.gutter?.renderMenu(protyle, selectedBlock || nodeElement);- window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard);- return;+ await toggleMenu({+ target: target,+ build: async (_menu, session) => {+ event.preventDefault();+ protyle.toolbar.range = range;+ keyboardPanelClosing = false;+ hideKeyboardToolbarUtil();+ if (!protyle.gutter && getTableCellRichContext(protyle)) {+ const {MenuItem} = await import("../../menus/Menu");+ if (!session.isCurrent()) {+ return;+ }+ if (!nodeElement.isConnected || protyle.disabled || !getTableCellRichContext(protyle)) {+ return;+ }+ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.append(new MenuItem({+ id: "insertBefore",+ icon: "iconBefore",+ label: window.siyuan.languages.insertBefore,+ click: () => insertEmptyBlock(protyle, "beforebegin", nodeElement),+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "insertAfter",+ icon: "iconAfter",+ label: window.siyuan.languages.insertAfter,+ click: () => insertEmptyBlock(protyle, "afterend", nodeElement),+ }).element);+ session.show(() => window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard));+ return;+ }+ // 多选时以已选块打开共享块菜单,使列表项转换作用于整个选区。+ const selectedBlock = protyle.wysiwyg.element.querySelector<HTMLElement>(".protyle-wysiwyg--select");+ protyle.gutter?.renderMenu(protyle, selectedBlock || nodeElement);+ session.show(() => window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard));++ },+ });+ return;} else if (type === "outdent") {if (nodeElement.classList.contains("code-block")) {tabCodeBlock(protyle, nodeElement, range, true);} else {await listOutdent(protyle, [nodeElement.parentElement], range);+}focusByRange(range);return;@@ -1974,6 +1985,7 @@ export const initKeyboardToolbar = () => {tabCodeBlock(protyle, nodeElement, range);} else {await listIndent(protyle, [nodeElement.parentElement], range);+}focusByRange(range);return;diff --git a/app/src/mobile/util/multiSelectToolbar.test.ts b/app/src/mobile/util/multiSelectToolbar.test.tsindex df1e6ddace..086afae007 100644--- a/app/src/mobile/util/multiSelectToolbar.test.ts+++ b/app/src/mobile/util/multiSelectToolbar.test.ts@@ -40,7 +40,9 @@ describe("shared mobile multi-select toolbar", () => {before(() => {Object.defineProperty(globalThis, "window", {configurable: true,- value: {siyuan: {languages: {more: "More", close: "Close", selectAll: "Select all"}}},+ value: {siyuan: {languages: {more: "More", close: "Close", selectAll: "Select all"}, menus: {menu: {+ data: undefined, element: {classList: {contains: () => true}}, remove() { this.data = undefined; },+ }}}},});});after(() => {@@ -53,7 +55,7 @@ describe("shared mobile multi-select toolbar", () => {const createToolbar = (onSelectAll?: () => void) => {const count = {textContent: ""};- const menu = {dataset: {type: "menu"}, disabled: false};+ const menu = {dataset: {type: "menu"}, disabled: false, closest: (): null => null, setAttribute: () => {}};const close = {dataset: {type: "exitMultiSelectMode"}, disabled: false};let listener: (event: unknown) => void;let menuCalls = 0;@@ -65,7 +67,7 @@ describe("shared mobile multi-select toolbar", () => {firstElementChild: {addEventListener: (_type: string, callback: typeof listener) => { listener = callback; }},} as unknown as HTMLElement;renderMultiSelectToolbar(element, 1, () => { menuCalls++; }, () => { exitCalls++; }, onSelectAll);- const click = (button: typeof menu | null) => {+ const click = (button: {dataset: {type: string}, disabled: boolean} | null) => {let prevented = false;let stopped = false;listener({diff --git a/app/src/mobile/util/multiSelectToolbar.ts b/app/src/mobile/util/multiSelectToolbar.tsindex 26f26bff02..3a247bde2d 100644--- a/app/src/mobile/util/multiSelectToolbar.ts+++ b/app/src/mobile/util/multiSelectToolbar.ts@@ -1,3 +1,5 @@+import {toggleMenu} from "../../menus/menuToggle";+export const insertMobileMultiSelectMenu = (itemsElement: Element, menuItem: HTMLElement) => {const openInNewTab = Array.from(itemsElement.children).find(item => item.getAttribute("data-id") === "openInNewTab");if (openInNewTab) {@@ -31,7 +33,7 @@ export const renderMultiSelectToolbar = (element: HTMLElement, count: number, onconst button = (event.target as HTMLElement).closest<HTMLButtonElement>("button[data-type]");if (button && !button.disabled) {if (button.dataset.type === "menu") {- onMenu();+ toggleMenu({target: button, build: onMenu});} else if (button.dataset.type === "exitMultiSelectMode") {onExit();} else if (button.dataset.type === "selectAll") {diff --git a/app/src/plugin/Menu.ts b/app/src/plugin/Menu.tsindex b0a6d0b524..e679649869 100644--- a/app/src/plugin/Menu.ts+++ b/app/src/plugin/Menu.ts@@ -1,8 +1,30 @@import {Menu as SiyuanMenu} from "../menus/Menu";+import {toggleMenu} from "../menus/menuToggle";const independentMenus = new WeakMap<HTMLElement, Menu>();export class Menu {+ // 在创建共享菜单前按触发元素切换,保留构造器及独立菜单的既有行为。+ static toggle(options: {+ target?: Element;+ toggle?: boolean;+ id?: string;+ closeCB?: () => void;+ build: (menu: Menu) => void;+ show: (menu: Menu) => void;+ }) {+ let menu: Menu;+ toggleMenu({+ target: options.target,+ toggle: options.toggle,+ build: () => {+ menu = new Menu(options.id, options.closeCB);+ options.build(menu);+ },+ show: () => options.show(menu),+ });+ }+private menu: SiyuanMenu;private parentMenu?: Menu;private childMenus = new Set<Menu>();diff --git a/app/src/plugin/openTopBarMenu.ts b/app/src/plugin/openTopBarMenu.tsindex 8ed70e1095..92435e10a5 100644--- a/app/src/plugin/openTopBarMenu.ts+++ b/app/src/plugin/openTopBarMenu.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import type {App} from "../index";import {Menu} from "./Menu";import {setStorageVal} from "../protyle/util/compatibility";@@ -7,127 +8,133 @@ import {hasPluginSetting} from "./index";import {isMobile} from "../util/functions";export const openTopBarMenu = (app: App, target?: Element) => {- const menu = new Menu(Constants.MENU_BAR_PLUGIN);- const manageElement = menu.addItem({- id: "manage",- icon: "iconSettings",- label: window.siyuan.languages.manage,- ignore: !isBazaarAvailable() || window.siyuan.config.readonly,- click() {- void import("../config").then(({openSetting}) => openSetting(app, "bazaar"));- }- });- const manageSeparatorElement = menu.addSeparator({- id: "separator_1",- ignore: !isBazaarAvailable() || window.siyuan.config.readonly,- });- let hasPlugin = false;- const settingItems: IMenu[] = [];- app.plugins.forEach((plugin) => {- const hasSetting = hasPluginSetting(plugin);- for (let i = 0; i < plugin.topBarIcons.length; i++) {- const item = plugin.topBarIcons[i];- const hasUnpin = isMobile() && window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].includes(item.id);- if (!document.contains(item) && !hasUnpin) {- plugin.topBarIcons.splice(i, 1);- i--;- continue;- }- const submenu: IMenu[] = [];- if (isMobile()) {- submenu.push({- id: hasUnpin ? "pin" : "unpin",- icon: hasUnpin ? "iconPin" : "iconUnpin",- label: hasUnpin ? window.siyuan.languages.pin : window.siyuan.languages.unpin,- click() {- if (hasUnpin) {- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].splice(- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].indexOf(item.id), 1);- item.classList.remove("fn__none");- if (!document.contains(item)) {- document.getElementById("menuPluginTopBar")?.after(item);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ const menu = new Menu(Constants.MENU_BAR_PLUGIN);+ const manageElement = menu.addItem({+ id: "manage",+ icon: "iconSettings",+ label: window.siyuan.languages.manage,+ ignore: !isBazaarAvailable() || window.siyuan.config.readonly,+ click() {+ void import("../config").then(({openSetting}) => openSetting(app, "bazaar"));+ }+ });+ const manageSeparatorElement = menu.addSeparator({+ id: "separator_1",+ ignore: !isBazaarAvailable() || window.siyuan.config.readonly,+ });+ let hasPlugin = false;+ const settingItems: IMenu[] = [];+ app.plugins.forEach((plugin) => {+ const hasSetting = hasPluginSetting(plugin);+ for (let i = 0; i < plugin.topBarIcons.length; i++) {+ const item = plugin.topBarIcons[i];+ const hasUnpin = isMobile() && window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].includes(item.id);+ if (!document.contains(item) && !hasUnpin) {+ plugin.topBarIcons.splice(i, 1);+ i--;+ continue;+ }+ const submenu: IMenu[] = [];+ if (isMobile()) {+ submenu.push({+ id: hasUnpin ? "pin" : "unpin",+ icon: hasUnpin ? "iconPin" : "iconUnpin",+ label: hasUnpin ? window.siyuan.languages.pin : window.siyuan.languages.unpin,+ click() {+ if (hasUnpin) {+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].splice(+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].indexOf(item.id), 1);+ item.classList.remove("fn__none");+ if (!document.contains(item)) {+ document.getElementById("menuPluginTopBar")?.after(item);+ }+ } else {+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].push(item.id);+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN] = Array.from(new Set(+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]));+ item.classList.add("fn__none");+ }+ setStorageVal(Constants.LOCAL_PLUGINTOPUNPIN,+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]);}- } else {- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].push(item.id);- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN] = Array.from(new Set(- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]));- item.classList.add("fn__none");- }- setStorageVal(Constants.LOCAL_PLUGINTOPUNPIN,- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]);+ });}- });- }- const itemLabel = target ? item.getAttribute("aria-label") : item.textContent.trim();- if (!target) {- submenu.push({- id: "play",- icon: "iconPlay",- label: itemLabel,- click() {- item.dispatchEvent(new CustomEvent("click"));- return true;- },- });- }- const menuOption: IMenu = {- id: item.id,- icon: "iconInfo",- label: itemLabel,- click: target ? () => {- item.dispatchEvent(new CustomEvent("click"));- } : undefined,- };- if (submenu.length > 0) {- menuOption.type = "submenu";- menuOption.submenu = submenu;+ const itemLabel = target ? item.getAttribute("aria-label") : item.textContent.trim();+ if (!target) {+ submenu.push({+ id: "play",+ icon: "iconPlay",+ label: itemLabel,+ click() {+ item.dispatchEvent(new CustomEvent("click"));+ return true;+ },+ });+ }+ const menuOption: IMenu = {+ id: item.id,+ icon: "iconInfo",+ label: itemLabel,+ click: target ? () => {+ item.dispatchEvent(new CustomEvent("click"));+ } : undefined,+ };+ if (submenu.length > 0) {+ menuOption.type = "submenu";+ menuOption.submenu = submenu;+ }+ const customIconElement = item.querySelector(":scope > .b3-menu__icon--custom");+ const sourceIconElement = customIconElement || item.querySelector("svg");+ if (sourceIconElement) {+ const iconElement = sourceIconElement.cloneNode(true) as HTMLElement;+ iconElement.classList.add("b3-menu__icon");+ menuOption.iconHTML = iconElement.outerHTML;+ }+ menu.addItem(menuOption);+ hasPlugin = true;+ }+ if (hasSetting) {+ settingItems.push({+ id: plugin.name,+ icon: "iconSettings",+ label: plugin.displayName,+ click() {+ plugin.openSetting();+ }+ });+ }+ });+ if (settingItems.length > 0) {+ if (hasPlugin) {+ menu.addSeparator({id: "separator_settings"});+ }+ settingItems.forEach((item) => menu.addItem(item));+ hasPlugin = true;}- const customIconElement = item.querySelector(":scope > .b3-menu__icon--custom");- const sourceIconElement = customIconElement || item.querySelector("svg");- if (sourceIconElement) {- const iconElement = sourceIconElement.cloneNode(true) as HTMLElement;- iconElement.classList.add("b3-menu__icon");- menuOption.iconHTML = iconElement.outerHTML;+ if (!hasPlugin) {+ manageSeparatorElement?.remove();+ if (!manageElement && !target) {+ menu.addItem({+ id: "emptyContent",+ iconHTML: "",+ type: "readonly",+ label: window.siyuan.languages.emptyContent,+ });+ }}- menu.addItem(menuOption);- hasPlugin = true;- }- if (hasSetting) {- settingItems.push({- id: plugin.name,- icon: "iconSettings",- label: plugin.displayName,- click() {- plugin.openSetting();+ if (target) {+ let rect = target.getBoundingClientRect();+ if (rect.width === 0) {+ rect = document.querySelector("#barMore").getBoundingClientRect();}- });- }+ session.show(() => menu.open({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));+ } else {+ session.show(() => menu.fullscreen());+ }++ },});- if (settingItems.length > 0) {- if (hasPlugin) {- menu.addSeparator({id: "separator_settings"});- }- settingItems.forEach((item) => menu.addItem(item));- hasPlugin = true;- }- if (!hasPlugin) {- manageSeparatorElement?.remove();- if (!manageElement && !target) {- menu.addItem({- id: "emptyContent",- iconHTML: "",- type: "readonly",- label: window.siyuan.languages.emptyContent,- });- }- }- if (target) {- let rect = target.getBoundingClientRect();- if (rect.width === 0) {- rect = document.querySelector("#barMore").getBoundingClientRect();- }- menu.open({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- } else {- menu.fullscreen();- }};diff --git a/app/src/plugin/topBar.test.ts b/app/src/plugin/topBar.test.tsindex c7e4b8ecd2..1b193eb663 100644--- a/app/src/plugin/topBar.test.ts+++ b/app/src/plugin/topBar.test.ts@@ -6,6 +6,7 @@ import {runInNewContext} from "node:vm";import * as ts from "typescript";import {setTopBarContextMenu, fillTopBarContextMenu} from "./topBarContextMenu";import {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "./topBarKey";+const {loadMenuToggle} = require("../../tests/menu-toggle-fixture.cjs");const buildPluginMenu = (counts: number[], settings: boolean[], mobile = false, readonly = false,initiallyUnpinned: string[] = []) => {@@ -53,9 +54,11 @@ const buildPluginMenu = (counts: number[], settings: boolean[], mobile = false,compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},}).outputText;const exports: {openTopBarMenu?: typeof import("./openTopBarMenu").openTopBarMenu} = {};+ const menu = {element: {classList: {contains: () => true}}, remove() {}};+ const menuToggle = loadMenuToggle({window: {siyuan: {menus: {menu}}}});runInNewContext(compiled, {exports,- require: () => dependencies,+ require: (name: string) => name.endsWith("menuToggle") ? menuToggle : dependencies,CustomEvent: class {},document: {contains: (item: {id: string}) => !initiallyUnpinned.includes(item.id) || mounted.includes(item.id),@@ -63,7 +66,8 @@ const buildPluginMenu = (counts: number[], settings: boolean[], mobile = false,},window: {siyuan: {languages: {}, config: {readonly}, storage: {unpinned}}},});- const target = {getBoundingClientRect: () => ({width: 10, right: 10, bottom: 10, height: 10})};+ const target = {closest: (): null => null, setAttribute() {},+ getBoundingClientRect: () => ({width: 10, right: 10, bottom: 10, height: 10})};exports.openTopBarMenu({plugins} as never, mobile ? undefined : target as never);return {items, opened, clicked, unpinned, mounted, plugins};};@@ -334,7 +338,9 @@ test("plugin menu supports custom content without SVG icons", () => {const exports: {openTopBarMenu?: typeof import("./openTopBarMenu").openTopBarMenu} = {};runInNewContext(compiled, {exports,- require: () => dependencies,+ require: (name: string) => name.endsWith("menuToggle") ? loadMenuToggle({window: {siyuan: {menus: {+ menu: {element: {classList: {contains: () => true}}, remove() {}},+ }}}}) : dependencies,document: {contains: () => true},window: {siyuan: {languages: {}, config: {readonly: false}}},});@@ -342,7 +348,8 @@ test("plugin menu supports custom content without SVG icons", () => {element.id = "plugin_test:timer";element.setAttribute("aria-label", "Timer");Object.assign(element, {querySelector: (): null => null});- const target = {getBoundingClientRect: () => ({width: 10, right: 10, bottom: 10, height: 10})};+ const target = {closest: (): null => null, setAttribute() {},+ getBoundingClientRect: () => ({width: 10, right: 10, bottom: 10, height: 10})};exports.openTopBarMenu({plugins: [{topBarIcons: [element]}]} as never, target as never);const item = items.find(entry => entry.id === element.id);assert.equal(item.label, "Timer");diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.tsindex fbdbff7e12..58d40feaeb 100644--- a/app/src/protyle/breadcrumb/index.ts+++ b/app/src/protyle/breadcrumb/index.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import type {FileTreeGetDocRequestInput} from "../../types/api";import type {BlockBreadcrumbRequestInput, BlockQueryRequestInput, TreeStatRequestInput} from "../../types/api";import {getIconByType} from "../../editor/getIcon";@@ -66,7 +67,6 @@ export class Breadcrumb {private uploadingRecordFiles = new Set<File>();private startingRecord = false;private stoppingRecord = false;- private mobileMenuLoading = false;private renderRequestID = 0;private menuRequestID = 0;private previousFocusElement: HTMLElement;@@ -119,7 +119,7 @@ ${isMobile() ? `<button class="block__icon fn__flex-center ariaLabel" data-type=const itemElement = arrowElement.previousElementSibling as HTMLElement;if (itemElement?.classList.contains("protyle-breadcrumb__item")) {const targetRect = arrowElement.getBoundingClientRect();- this.openChildrenMenu(protyle, itemElement.getAttribute("data-node-id"), {+ this.openChildrenMenu(protyle, itemElement.getAttribute("data-node-id"), {target: arrowElement as HTMLElement,x: targetRect.left,y: targetRect.bottom,h: targetRect.height,@@ -176,7 +176,7 @@ ${isMobile() ? `<button class="block__icon fn__flex-center ariaLabel" data-type=});} else {const targetRect = target.getBoundingClientRect();- openTitleMenu(protyle, {x: targetRect.right, y: targetRect.bottom, h: targetRect.height, isLeft: true},+ openTitleMenu(protyle, {target: target, x: targetRect.right, y: targetRect.bottom, h: targetRect.height, isLeft: true},Constants.MENU_FROM_TITLE_BREADCRUMB, restoreMenuKeyboard);}event.stopPropagation();@@ -184,7 +184,7 @@ ${isMobile() ? `<button class="block__icon fn__flex-center ariaLabel" data-type=break;} else if (type === "more") {const targetRect = target.getBoundingClientRect();- this.showMenu(protyle, {+ this.showMenu(protyle, {target: target,x: targetRect.right,y: targetRect.bottom,h: targetRect.height,@@ -344,73 +344,86 @@ ${isMobile() ? `<button class="block__icon fn__flex-center ariaLabel" data-type=}private async openChildrenMenu(protyle: IProtyle, id: string, position: IPosition, keyboard = false) {- if (!id) {- return;- }+ await toggleMenu({+ target: position.target,+ toggle: !keyboard,+ build: async (_menu, session) => {+ if (!id) {+ return;+ }- const keyboardItemElement = keyboard ? document.activeElement : undefined;- const menuName = `${Constants.MENU_BREADCRUMB_CHILDREN}-${id}`;- const menu = new Menu(menuName);- if (menu.isOpen) {- return;- }+ const keyboardItemElement = keyboard ? document.activeElement : undefined;+ const menuName = `${Constants.MENU_BREADCRUMB_CHILDREN}-${id}`;+ const menu = new Menu(menuName);+ if (menu.isOpen) {+ return;+ }- const currentPathIDs = new Set<string>();- this.element.querySelectorAll(".protyle-breadcrumb__item").forEach((item) => {- const itemID = item.getAttribute("data-node-id");- if (itemID) {- currentPathIDs.add(itemID);- }- });- let currentBlockElement = this.id ?- protyle.wysiwyg.element.querySelector(`[data-node-id="${this.id}"]`) as HTMLElement : undefined;- while (currentBlockElement) {- const currentBlockID = currentBlockElement.getAttribute("data-node-id");- if (currentBlockID) {- currentPathIDs.add(currentBlockID);- }- const parentBlockElement = hasClosestBlock(currentBlockElement.parentElement) as HTMLElement;- if (!parentBlockElement || !protyle.wysiwyg.element.contains(parentBlockElement)) {- break;- }- currentBlockElement = parentBlockElement;- }- const excludeTypes: string[] = [];- if (this.element.parentElement?.parentElement?.classList.contains("card__block")) {- excludeTypes.push("NodeTextMark-mark");- }+ const currentPathIDs = new Set<string>();+ this.element.querySelectorAll(".protyle-breadcrumb__item").forEach((item) => {+ const itemID = item.getAttribute("data-node-id");+ if (itemID) {+ currentPathIDs.add(itemID);+ }+ });+ let currentBlockElement = this.id ?+ protyle.wysiwyg.element.querySelector(`[data-node-id="${this.id}"]`) as HTMLElement : undefined;+ while (currentBlockElement) {+ const currentBlockID = currentBlockElement.getAttribute("data-node-id");+ if (currentBlockID) {+ currentPathIDs.add(currentBlockID);+ }+ const parentBlockElement = hasClosestBlock(currentBlockElement.parentElement) as HTMLElement;+ if (!parentBlockElement || !protyle.wysiwyg.element.contains(parentBlockElement)) {+ break;+ }+ currentBlockElement = parentBlockElement;+ }+ const excludeTypes: string[] = [];+ if (this.element.parentElement?.parentElement?.classList.contains("card__block")) {+ excludeTypes.push("NodeTextMark-mark");+ }- let items: IMenu[];- try {- items = await this.genChildrenMenuItems(protyle, id, currentPathIDs, excludeTypes);- } catch (e) {- console.warn("get breadcrumb children failed", e);- if (window.siyuan.menus.menu.element.getAttribute("data-name") === menuName) {- window.siyuan.menus.menu.remove();- }- return;- }- if (keyboard && document.activeElement !== keyboardItemElement) {- if (window.siyuan.menus.menu.element.getAttribute("data-name") === menuName) {- window.siyuan.menus.menu.remove();- }- return;- }- if (window.siyuan.menus.menu.element.getAttribute("data-name") !== menuName) {- return;- }- if (items.length === 0) {- window.siyuan.menus.menu.remove();- return;- }+ let items: IMenu[];+ try {+ items = await this.genChildrenMenuItems(protyle, id, currentPathIDs, excludeTypes);+ if (!session.isCurrent()) {+ return;+ }+ } catch (e) {+ if (!session.isCurrent()) {+ return;+ }+ console.warn("get breadcrumb children failed", e);+ if (window.siyuan.menus.menu.element.getAttribute("data-name") === menuName) {+ window.siyuan.menus.menu.remove();+ }+ return;+ }+ if (keyboard && document.activeElement !== keyboardItemElement) {+ if (window.siyuan.menus.menu.element.getAttribute("data-name") === menuName) {+ window.siyuan.menus.menu.remove();+ }+ return;+ }+ if (window.siyuan.menus.menu.element.getAttribute("data-name") !== menuName) {+ return;+ }+ if (items.length === 0) {+ window.siyuan.menus.menu.remove();+ return;+ }++ items.forEach((item) => {+ menu.addItem(item);+ });+ session.show(() => menu.open(position));+ if (keyboard) {+ menu.element.querySelector(".b3-menu__item:not([disabled])")?.classList.add("b3-menu__item--current");+ }- items.forEach((item) => {- menu.addItem(item);+ },});- menu.open(position);- if (keyboard) {- menu.element.querySelector(".b3-menu__item:not([disabled])")?.classList.add("b3-menu__item--current");- }}private getSiblingItem(itemElement: HTMLElement, forward: boolean) {@@ -648,64 +661,73 @@ ${isMobile() ? `<button class="block__icon fn__flex-center ariaLabel" data-type=}private async genMobileMenu(protyle: IProtyle, restoreKeyboard?: () => void) {- if (protyle.lite || protyle.toolbar.isMultiSelectMode() || this.mobileMenuLoading) {- return;- }- if (window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BREADCRUMB_MOBILE_PATH) {- window.siyuan.menus.menu.closeSheet();- return;- }- const menu = new Menu(Constants.MENU_BREADCRUMB_MOBILE_PATH);- if (menu.isOpen) {- return;- }- let blockElement: Element;- if (getSelection().rangeCount > 0) {- const range = getSelection().getRangeAt(0);- if (!protyle.wysiwyg.element.isEqualNode(range.startContainer) && !protyle.wysiwyg.element.contains(range.startContainer)) {- blockElement = getNoContainerElement(protyle.wysiwyg.element.firstElementChild) || protyle.wysiwyg.element.firstElementChild;- } else {- blockElement = hasClosestBlock(range.startContainer) as Element;- }- }- if (!blockElement) {- blockElement = getNoContainerElement(protyle.wysiwyg.element.firstElementChild) || protyle.wysiwyg.element.firstElementChild;- }- if (!blockElement) {- return;- }- const id = blockElement.getAttribute("data-node-id");- const breadcrumbParam: BlockBreadcrumbRequestInput = {id, excludeTypes: [], notebook: protyle.notebookId};- this.mobileMenuLoading = true;- const rootID = protyle.block.rootID;- await waitForPendingTransactions(protyle);- if (!blockElement.isConnected || rootID !== protyle.block.rootID) {- this.mobileMenuLoading = false;- return;- }- fetchPost("/api/block/getBlockBreadcrumb", breadcrumbParam, (response) => {- if (!blockElement.isConnected || rootID !== protyle.block.rootID) {- return;- }- response.data.forEach((item: IBreadcrumb) => {- let isCurrent = false;- if (!protyle.block.showAll && item.id === protyle.block.parentID) {- isCurrent = true;- } else if (protyle.block.showAll && item.id === protyle.block.id) {- isCurrent = true;+ await toggleMenu({+ target: this.element.querySelector("[data-type=mobile-menu]"),+ build: async (_menu, session) => {+ if (protyle.lite || protyle.toolbar.isMultiSelectMode()) {+ return;+ }+ if (window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BREADCRUMB_MOBILE_PATH) {+ window.siyuan.menus.menu.closeSheet();+ return;+ }+ const menu = new Menu(Constants.MENU_BREADCRUMB_MOBILE_PATH);+ if (menu.isOpen) {+ return;}- menu.addItem({- current: isCurrent,- icon: getIconByType(item.type, item.subType),- label: item.name,- click() {- zoomOut({protyle, id: item.id});+ let blockElement: Element;+ if (getSelection().rangeCount > 0) {+ const range = getSelection().getRangeAt(0);+ if (!protyle.wysiwyg.element.isEqualNode(range.startContainer) && !protyle.wysiwyg.element.contains(range.startContainer)) {+ blockElement = getNoContainerElement(protyle.wysiwyg.element.firstElementChild) || protyle.wysiwyg.element.firstElementChild;+ } else {+ blockElement = hasClosestBlock(range.startContainer) as Element;}+ }+ if (!blockElement) {+ blockElement = getNoContainerElement(protyle.wysiwyg.element.firstElementChild) || protyle.wysiwyg.element.firstElementChild;+ }+ if (!blockElement) {+ return;+ }+ const id = blockElement.getAttribute("data-node-id");+ const breadcrumbParam: BlockBreadcrumbRequestInput = {id, excludeTypes: [], notebook: protyle.notebookId};+ const rootID = protyle.block.rootID;+ await waitForPendingTransactions(protyle);+ if (!session.isCurrent()) {+ return;+ }+ if (!blockElement.isConnected || rootID !== protyle.block.rootID) {+ return;+ }+ fetchPost("/api/block/getBlockBreadcrumb", breadcrumbParam, (response) => {+ if (!session.isCurrent()) {+ return;+ }++ if (!blockElement.isConnected || rootID !== protyle.block.rootID) {+ return;+ }+ response.data.forEach((item: IBreadcrumb) => {+ let isCurrent = false;+ if (!protyle.block.showAll && item.id === protyle.block.parentID) {+ isCurrent = true;+ } else if (protyle.block.showAll && item.id === protyle.block.id) {+ isCurrent = true;+ }+ menu.addItem({+ current: isCurrent,+ icon: getIconByType(item.type, item.subType),+ label: item.name,+ click() {+ zoomOut({protyle, id: item.id});+ }+ });+ });+ session.show(() => window.siyuan.menus.menu.fullscreen("all", restoreKeyboard));});- });- window.siyuan.menus.menu.fullscreen("all", restoreKeyboard);- }).finally(() => {- this.mobileMenuLoading = false;++ },});}@@ -719,442 +741,447 @@ ${isMobile() ? `<button class="block__icon fn__flex-center ariaLabel" data-type=}public async showMenu(protyle: IProtyle, position: IPosition, restoreKeyboard?: () => void) {- const requestID = ++this.menuRequestID;- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BREADCRUMB_MORE) {- if (isMobile()) {- window.siyuan.menus.menu.closeSheet();- } else {- window.siyuan.menus.menu.remove();- }- return;- }- let id;- const cursorNodeElement = hasClosestBlock(getEditorRange(protyle.element).startContainer);- if (cursorNodeElement) {- id = cursorNodeElement.getAttribute("data-node-id");- }- const statRequest: TreeStatRequestInput = {- id: id || (protyle.block.showAll ? protyle.block.id : protyle.block.rootID)- };- if (isEncryptedBox(protyle.notebookId)) {- statRequest.notebook = protyle.notebookId;- }- const rootID = protyle.block.rootID;- const isCurrent = () => requestID === this.menuRequestID && rootID === protyle.block.rootID &&- protyle.element.isConnected && (!cursorNodeElement || cursorNodeElement.isConnected);- await waitForPendingTransactions(protyle);- if (!isCurrent()) {- return;- }- fetchPost("/api/block/getTreeStat", statRequest, (response) => {- if (!isCurrent()) {- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BREADCRUMB_MORE);- if (!protyle.contentElement.classList.contains("fn__none") && !protyle.disabled) {- let uploadHTML = "";- uploadHTML = '<input class="b3-form__upload" type="file" multiple="multiple"';- if (protyle.options.upload.accept) {- uploadHTML += ` accept="${protyle.options.upload.accept}">`;- } else {- uploadHTML += ">";+ await toggleMenu({+ target: position.target,+ build: async (_menu, session) => {+ const requestID = ++this.menuRequestID;++ let id;+ const cursorNodeElement = hasClosestBlock(getEditorRange(protyle.element).startContainer);+ if (cursorNodeElement) {+ id = cursorNodeElement.getAttribute("data-node-id");}- if (isInAndroid()) {- const imageUploadMenu = new MenuItem({- id: "insertImage",- icon: "iconImage",- label: `${window.siyuan.languages.insertImage}<input class="b3-form__upload" type="file" multiple="multiple" accept="image/*,application/x-siyuan-image-picker">`,- }).element;- imageUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- if (event.target.files.length === 0) {- return;- }- uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {- source: "file-picker",- target: "editor",- });- window.siyuan.menus.menu.remove();- });- window.siyuan.menus.menu.append(imageUploadMenu);+ const statRequest: TreeStatRequestInput = {+ id: id || (protyle.block.showAll ? protyle.block.id : protyle.block.rootID)+ };+ if (isEncryptedBox(protyle.notebookId)) {+ statRequest.notebook = protyle.notebookId;}- const uploadMenu = new MenuItem({- id: "insertAsset",- icon: "iconDownload",- label: `${window.siyuan.languages.insertAsset}${uploadHTML}`,- }).element;- uploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- if (event.target.files.length === 0) {+ const rootID = protyle.block.rootID;+ const isCurrent = () => requestID === this.menuRequestID && rootID === protyle.block.rootID &&+ protyle.element.isConnected && (!cursorNodeElement || cursorNodeElement.isConnected);+ await waitForPendingTransactions(protyle);+ if (!session.isCurrent()) {+ return;+ }+ if (!isCurrent()) {+ return;+ }+ fetchPost("/api/block/getTreeStat", statRequest, (response) => {+ if (!session.isCurrent()) {+ return;+ }++ if (!isCurrent()) {return;}- uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {- source: "file-picker",- target: "editor",- });window.siyuan.menus.menu.remove();- });- window.siyuan.menus.menu.append(uploadMenu);- if (getHostCapabilities().localFileSystem) {- const htmlUploadMenu = new MenuItem({- id: "insertHTMLFile",- icon: "iconHTML5",- label: `${window.siyuan.languages.insertHTMLFile}<input class="b3-form__upload" type="file" multiple="multiple" accept=".html,.htm">`,- }).element;- htmlUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- if (event.target.files.length === 0) {- return;+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BREADCRUMB_MORE);+ if (!protyle.contentElement.classList.contains("fn__none") && !protyle.disabled) {+ let uploadHTML = "";+ uploadHTML = '<input class="b3-form__upload" type="file" multiple="multiple"';+ if (protyle.options.upload.accept) {+ uploadHTML += ` accept="${protyle.options.upload.accept}">`;+ } else {+ uploadHTML += ">";}- uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {- htmlAsIframe: true,- source: "file-picker",- target: "editor",- });- window.siyuan.menus.menu.remove();- });- window.siyuan.menus.menu.append(htmlUploadMenu);- }- window.siyuan.menus.menu.append(new MenuItem({- id: this.mediaRecorder?.isRecording ? "endRecord" : "startRecord",- current: this.mediaRecorder && this.mediaRecorder.isRecording,- icon: "iconRecord",- label: this.mediaRecorder?.isRecording ? window.siyuan.languages.endRecord : window.siyuan.languages.startRecord,- click: async () => {- if (this.startingRecord || this.stoppingRecord) {- return;+ if (isInAndroid()) {+ const imageUploadMenu = new MenuItem({+ id: "insertImage",+ icon: "iconImage",+ label: `${window.siyuan.languages.insertImage}<input class="b3-form__upload" type="file" multiple="multiple" accept="image/*,application/x-siyuan-image-picker">`,+ }).element;+ imageUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {+ target: HTMLInputElement+ }) => {+ if (event.target.files.length === 0) {+ return;+ }+ uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {+ source: "file-picker",+ target: "editor",+ });+ window.siyuan.menus.menu.remove();+ });+ window.siyuan.menus.menu.append(imageUploadMenu);}- if (this.mediaRecorder?.isRecording) {- this.stopRecord(protyle);- return;+ const uploadMenu = new MenuItem({+ id: "insertAsset",+ icon: "iconDownload",+ label: `${window.siyuan.languages.insertAsset}${uploadHTML}`,+ }).element;+ uploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {+ target: HTMLInputElement+ }) => {+ if (event.target.files.length === 0) {+ return;+ }+ uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {+ source: "file-picker",+ target: "editor",+ });+ window.siyuan.menus.menu.remove();+ });+ window.siyuan.menus.menu.append(uploadMenu);+ if (getHostCapabilities().localFileSystem) {+ const htmlUploadMenu = new MenuItem({+ id: "insertHTMLFile",+ icon: "iconHTML5",+ label: `${window.siyuan.languages.insertHTMLFile}<input class="b3-form__upload" type="file" multiple="multiple" accept=".html,.htm">`,+ }).element;+ htmlUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {+ target: HTMLInputElement+ }) => {+ if (event.target.files.length === 0) {+ return;+ }+ uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {+ htmlAsIframe: true,+ source: "file-picker",+ target: "editor",+ });+ window.siyuan.menus.menu.remove();+ });+ window.siyuan.menus.menu.append(htmlUploadMenu);}-- this.startingRecord = true;- let mediaStream: MediaStream;- try {- /// #if !BROWSER- if (window.siyuan.config.system.os === "darwin") {- const status = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "getMicrophone"});- if (["denied", "restricted", "unknown"].includes(status)) {- showMessage(window.siyuan.languages.microphoneDenied);+ window.siyuan.menus.menu.append(new MenuItem({+ id: this.mediaRecorder?.isRecording ? "endRecord" : "startRecord",+ current: this.mediaRecorder && this.mediaRecorder.isRecording,+ icon: "iconRecord",+ label: this.mediaRecorder?.isRecording ? window.siyuan.languages.endRecord : window.siyuan.languages.startRecord,+ click: async () => {+ if (this.startingRecord || this.stoppingRecord) {return;- } else if (status === "not-determined") {- const isAccess = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "askMicrophone"});- if (!isAccess) {- showMessage(window.siyuan.languages.microphoneNotAccess);- return;+ }+ if (this.mediaRecorder?.isRecording) {+ this.stopRecord(protyle);+ return;+ }++ this.startingRecord = true;+ let mediaStream: MediaStream;+ try {+ /// #if !BROWSER+ if (window.siyuan.config.system.os === "darwin") {+ const status = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "getMicrophone"});+ if (["denied", "restricted", "unknown"].includes(status)) {+ showMessage(window.siyuan.languages.microphoneDenied);+ return;+ } else if (status === "not-determined") {+ const isAccess = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "askMicrophone"});+ if (!isAccess) {+ showMessage(window.siyuan.languages.microphoneNotAccess);+ return;+ }+ }+ }+ /// #endif++ mediaStream = await navigator.mediaDevices.getUserMedia({+ audio: isInAndroid() || isInHarmony() ? {+ autoGainControl: false,+ echoCancellation: false,+ noiseSuppression: false,+ } : true,+ });+ await this.startRecord(protyle, mediaStream);+ } catch (error) {+ mediaStream?.getTracks().forEach((track) => track.stop());+ if (error instanceof RecordMediaInputEndedError) {+ showMessage(window.siyuan.languages.recordInterrupted);+ } else if ((!isInAndroid() && !isInHarmony()) ||+ !(error instanceof DOMException && error.name === "NotAllowedError")) {+ showMessage(window.siyuan.languages["record-tip"]);}+ } finally {+ this.startingRecord = false;}}- /// #endif-- mediaStream = await navigator.mediaDevices.getUserMedia({- audio: isInAndroid() || isInHarmony() ? {- autoGainControl: false,- echoCancellation: false,- noiseSuppression: false,- } : true,- });- await this.startRecord(protyle, mediaStream);- } catch (error) {- mediaStream?.getTracks().forEach((track) => track.stop());- if (error instanceof RecordMediaInputEndedError) {- showMessage(window.siyuan.languages.recordInterrupted);- } else if ((!isInAndroid() && !isInHarmony()) ||- !(error instanceof DOMException && error.name === "NotAllowedError")) {- showMessage(window.siyuan.languages["record-tip"]);+ }).element);+ }+ if (!protyle.disabled) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "netImg2LocalAsset",+ label: window.siyuan.languages.netImg2LocalAsset,+ icon: "iconImgDown",+ accelerator: window.siyuan.config.keymap.editor.general.netImg2LocalAsset.custom,+ click() {+ net2LocalAssets(protyle, "Img");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "netAssets2LocalAssets",+ label: window.siyuan.languages.netAssets2LocalAssets,+ icon: "iconDownloadAssets",+ accelerator: window.siyuan.config.keymap.editor.general.netAssets2LocalAssets.custom,+ click() {+ net2LocalAssets(protyle, "Assets");+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "uploadAssets2CDN",+ label: window.siyuan.languages.uploadAssets2CDN,+ icon: "iconUploadAssets",+ click() {+ if (!needSubscribe()) {+ confirmDialog("📦 " + window.siyuan.languages.uploadAssets2CDN, window.siyuan.languages.uploadAssets2CDNConfirmTip, () => {+ fetchPost("/api/asset/uploadCloud", {id: protyle.block.id});+ });+ }}- } finally {- this.startingRecord = false;+ }).element);+ if (window.siyuan.user && getHostCapabilities().importExport) { // 登录链滴账号后即可使用 `分享到链滴` https://github.com/siyuan-note/siyuan/issues/7392+ window.siyuan.menus.menu.append(new MenuItem({+ id: "share2Liandi",+ label: window.siyuan.languages.share2Liandi,+ icon: "iconLiandi",+ click() {+ if (!getHostCapabilities().importExport) {+ return;+ }+ confirmDialog("🤩 " + window.siyuan.languages.share2Liandi,+ window.siyuan.languages.share2LiandiConfirmTip.replace("${accountServer}", getCloudURL("")), () => {+ fetchPost("/api/export/export2Liandi", {id: protyle.block.parentID});+ });+ }+ }).element);}}- }).element);- }- if (!protyle.disabled) {- window.siyuan.menus.menu.append(new MenuItem({- id: "netImg2LocalAsset",- label: window.siyuan.languages.netImg2LocalAsset,- icon: "iconImgDown",- accelerator: window.siyuan.config.keymap.editor.general.netImg2LocalAsset.custom,- click() {- net2LocalAssets(protyle, "Img");+ if (!protyle.scroll?.element.classList.contains("fn__none")) {+ if (hasUnloadedDocumentBlocks(protyle.wysiwyg.element, true)) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "loadAllContent",+ icon: "iconSelectAll",+ label: window.siyuan.languages.loadAllContent,+ click: () => {+ void protyle.scroll.loadAll(protyle);+ }+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({+ id: "keepLazyLoad",+ icon: "iconKeepContent",+ current: protyle.scroll.keepLoadedContent,+ label: window.siyuan.languages.keepLazyLoad,+ click: () => {+ protyle.scroll.keepLoadedContent = !protyle.scroll.keepLoadedContent;+ }+ }).element);}- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "netAssets2LocalAssets",- label: window.siyuan.languages.netAssets2LocalAssets,- icon: "iconDownloadAssets",- accelerator: window.siyuan.config.keymap.editor.general.netAssets2LocalAssets.custom,- click() {- net2LocalAssets(protyle, "Assets");+ if (window.siyuan.menus.menu.element.lastElementChild.childElementCount > 0) {+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);}- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "uploadAssets2CDN",- label: window.siyuan.languages.uploadAssets2CDN,- icon: "iconUploadAssets",- click() {- if (!needSubscribe()) {- confirmDialog("📦 " + window.siyuan.languages.uploadAssets2CDN, window.siyuan.languages.uploadAssets2CDNConfirmTip, () => {- fetchPost("/api/asset/uploadCloud", {id: protyle.block.id});- });+ window.siyuan.menus.menu.append(new MenuItem({+ id: "refresh",+ icon: "iconRefresh",+ accelerator: window.siyuan.config.keymap.editor.general.refresh.custom,+ label: window.siyuan.languages.refresh,+ click: () => {+ reloadProtyle(protyle, !isMobile());}+ }).element);+ if (!protyle.disabled) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "optimizeTypography",+ label: window.siyuan.languages.optimizeTypography,+ accelerator: window.siyuan.config.keymap.editor.general.optimizeTypography.custom,+ icon: "iconFormat",+ click: () => {+ hideElements(["toolbar"], protyle);+ fetchPost("/api/format/autoSpace", {+ id: protyle.block.rootID+ });+ }+ }).element);}- }).element);- if (window.siyuan.user && getHostCapabilities().importExport) { // 登录链滴账号后即可使用 `分享到链滴` https://github.com/siyuan-note/siyuan/issues/7392+ /// #if !MOBILEwindow.siyuan.menus.menu.append(new MenuItem({- id: "share2Liandi",- label: window.siyuan.languages.share2Liandi,- icon: "iconLiandi",- click() {- if (!getHostCapabilities().importExport) {- return;- }- confirmDialog("🤩 " + window.siyuan.languages.share2Liandi,- window.siyuan.languages.share2LiandiConfirmTip.replace("${accountServer}", getCloudURL("")), () => {- fetchPost("/api/export/export2Liandi", {id: protyle.block.parentID});- });+ id: "fullscreen",+ icon: protyle.getInstance().isFullscreen() ? "iconFullscreenExit" : "iconFullscreen",+ accelerator: window.siyuan.config.keymap.editor.general.fullscreen.custom,+ label: window.siyuan.languages.fullscreen,+ click: () => {+ const editor = protyle.getInstance();+ editor.setFullscreen(!editor.isFullscreen());}}).element);- }- }- if (!protyle.scroll?.element.classList.contains("fn__none")) {- if (hasUnloadedDocumentBlocks(protyle.wysiwyg.element, true)) {+ /// #endifwindow.siyuan.menus.menu.append(new MenuItem({- id: "loadAllContent",- icon: "iconSelectAll",- label: window.siyuan.languages.loadAllContent,+ id: "editMode",+ icon: "iconEdit",+ label: protyle.preview.element.classList.contains("fn__none") ?+ window.siyuan.languages.switchToPreview : window.siyuan.languages.switchToWYSIWYG,+ accelerator: window.siyuan.config.keymap.editor.general.editMode.custom,click: () => {- void protyle.scroll.loadAll(protyle);+ toggleEditMode(protyle);+ window.siyuan.menus.menu.remove();+ /// #if !MOBILE+ saveLayout();+ /// #endif}}).element);- }- window.siyuan.menus.menu.append(new MenuItem({- id: "keepLazyLoad",- icon: "iconKeepContent",- current: protyle.scroll.keepLoadedContent,- label: window.siyuan.languages.keepLazyLoad,- click: () => {- protyle.scroll.keepLoadedContent = !protyle.scroll.keepLoadedContent;- }- }).element);- }- if (window.siyuan.menus.menu.element.lastElementChild.childElementCount > 0) {- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);- }- window.siyuan.menus.menu.append(new MenuItem({- id: "refresh",- icon: "iconRefresh",- accelerator: window.siyuan.config.keymap.editor.general.refresh.custom,- label: window.siyuan.languages.refresh,- click: () => {- reloadProtyle(protyle, !isMobile());- }- }).element);- if (!protyle.disabled) {- window.siyuan.menus.menu.append(new MenuItem({- id: "optimizeTypography",- label: window.siyuan.languages.optimizeTypography,- accelerator: window.siyuan.config.keymap.editor.general.optimizeTypography.custom,- icon: "iconFormat",- click: () => {- hideElements(["toolbar"], protyle);- fetchPost("/api/format/autoSpace", {- id: protyle.block.rootID- });+ if (!window.siyuan.config.editor.readOnly && !window.siyuan.config.readonly) {+ const isCustomReadonly = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_READONLY);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "editReadonly",+ label: window.siyuan.languages.editReadonly,+ icon: "iconLock",+ type: "submenu",+ submenu: [{+ id: "enable",+ iconHTML: "",+ current: isCustomReadonly === "true",+ label: window.siyuan.languages.enable,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_READONLY]: "true"}+ });+ }+ }, {+ id: "disable",+ iconHTML: "",+ current: !isCustomReadonly || isCustomReadonly === "false",+ label: window.siyuan.languages.disable,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_READONLY]: "false"}+ });+ }+ }]+ }).element);}- }).element);- }- /// #if !MOBILE- window.siyuan.menus.menu.append(new MenuItem({- id: "fullscreen",- icon: protyle.getInstance().isFullscreen() ? "iconFullscreenExit" : "iconFullscreen",- accelerator: window.siyuan.config.keymap.editor.general.fullscreen.custom,- label: window.siyuan.languages.fullscreen,- click: () => {- const editor = protyle.getInstance();- editor.setFullscreen(!editor.isFullscreen());- }- }).element);- /// #endif- window.siyuan.menus.menu.append(new MenuItem({- id: "editMode",- icon: "iconEdit",- label: protyle.preview.element.classList.contains("fn__none") ?- window.siyuan.languages.switchToPreview : window.siyuan.languages.switchToWYSIWYG,- accelerator: window.siyuan.config.keymap.editor.general.editMode.custom,- click: () => {- toggleEditMode(protyle);- window.siyuan.menus.menu.remove();/// #if !MOBILE- saveLayout();+ if (!protyle.disabled) {+ const isCustomFullWidth = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_FULLWIDTH);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "fullWidth",+ label: window.siyuan.languages.fullWidth,+ icon: "iconFullWidth",+ type: "submenu",+ submenu: [{+ id: "enable",+ iconHTML: "",+ current: isCustomFullWidth === "true",+ label: window.siyuan.languages.enable,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_FULLWIDTH]: "true"}+ });+ }+ }, {+ id: "disable",+ iconHTML: "",+ current: isCustomFullWidth === "false",+ label: window.siyuan.languages.disable,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_FULLWIDTH]: "false"}+ });+ }+ }, {+ id: "default",+ iconHTML: "",+ current: !isCustomFullWidth,+ label: window.siyuan.languages.default,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_FULLWIDTH]: ""}+ });+ }+ }]+ }).element);+ const isCustomHeadingNumber = protyle.wysiwyg.element.getAttribute(+ Constants.CUSTOM_SY_HEADING_NUMBER+ );+ window.siyuan.menus.menu.append(new MenuItem({+ id: "headingNumber",+ label: window.siyuan.languages.headingNumber,+ icon: "iconHeadings",+ type: "submenu",+ submenu: [{+ id: "enable",+ iconHTML: "",+ current: isCustomHeadingNumber === "true",+ label: window.siyuan.languages.enable,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_HEADING_NUMBER]: "true"}+ });+ }+ }, {+ id: "disable",+ iconHTML: "",+ current: isCustomHeadingNumber === "false",+ label: window.siyuan.languages.disable,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_HEADING_NUMBER]: "false"}+ });+ }+ }, {+ id: "default",+ iconHTML: "",+ current: !isCustomHeadingNumber,+ label: window.siyuan.languages.default,+ click() {+ fetchPost("/api/attr/setBlockAttrs", {+ id: protyle.block.rootID,+ attrs: {[Constants.CUSTOM_SY_HEADING_NUMBER]: ""}+ });+ }+ }]+ }).element);+ }/// #endif- }- }).element);- if (!window.siyuan.config.editor.readOnly && !window.siyuan.config.readonly) {- const isCustomReadonly = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_READONLY);- window.siyuan.menus.menu.append(new MenuItem({- id: "editReadonly",- label: window.siyuan.languages.editReadonly,- icon: "iconLock",- type: "submenu",- submenu: [{- id: "enable",- iconHTML: "",- current: isCustomReadonly === "true",- label: window.siyuan.languages.enable,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_READONLY]: "true"}- });- }- }, {- id: "disable",- iconHTML: "",- current: !isCustomReadonly || isCustomReadonly === "false",- label: window.siyuan.languages.disable,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_READONLY]: "false"}- });- }- }]- }).element);- }- /// #if !MOBILE- if (!protyle.disabled) {- const isCustomFullWidth = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_FULLWIDTH);- window.siyuan.menus.menu.append(new MenuItem({- id: "fullWidth",- label: window.siyuan.languages.fullWidth,- icon: "iconFullWidth",- type: "submenu",- submenu: [{- id: "enable",- iconHTML: "",- current: isCustomFullWidth === "true",- label: window.siyuan.languages.enable,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_FULLWIDTH]: "true"}- });- }- }, {- id: "disable",- iconHTML: "",- current: isCustomFullWidth === "false",- label: window.siyuan.languages.disable,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_FULLWIDTH]: "false"}- });- }- }, {- id: "default",- iconHTML: "",- current: !isCustomFullWidth,- label: window.siyuan.languages.default,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_FULLWIDTH]: ""}- });- }- }]- }).element);- const isCustomHeadingNumber = protyle.wysiwyg.element.getAttribute(- Constants.CUSTOM_SY_HEADING_NUMBER- );- window.siyuan.menus.menu.append(new MenuItem({- id: "headingNumber",- label: window.siyuan.languages.headingNumber,- icon: "iconHeadings",- type: "submenu",- submenu: [{- id: "enable",- iconHTML: "",- current: isCustomHeadingNumber === "true",- label: window.siyuan.languages.enable,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_HEADING_NUMBER]: "true"}- });- }- }, {- id: "disable",- iconHTML: "",- current: isCustomHeadingNumber === "false",- label: window.siyuan.languages.disable,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_HEADING_NUMBER]: "false"}- });- }- }, {- id: "default",+ if (protyle) {+ emitOpenMenu({+ type: "open-menu-breadcrumbmore",+ detail: {+ protyle,+ data: response.data.stat,+ },+ separatorPosition: "top",+ });+ }+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);+ const docInfoElement = new MenuItem({+ id: "docInfo",iconHTML: "",- current: !isCustomHeadingNumber,- label: window.siyuan.languages.default,- click() {- fetchPost("/api/attr/setBlockAttrs", {- id: protyle.block.rootID,- attrs: {[Constants.CUSTOM_SY_HEADING_NUMBER]: ""}- });- }- }]- }).element);- }- /// #endif- if (protyle) {- emitOpenMenu({- type: "open-menu-breadcrumbmore",- detail: {- protyle,- data: response.data.stat,- },- separatorPosition: "top",- });- }- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);- const docInfoElement = new MenuItem({- id: "docInfo",- iconHTML: "",- type: "readonly",- // 不能换行,否则移动端间距过大- label: genDocumentStatLabel(response.data.stat),- }).element;- window.siyuan.menus.menu.append(docInfoElement);- if (response.data.containsEmbed) {- fetchPost("/api/block/getTreeStat", {...statRequest, includeEmbed: true}, (embedResponse) => {- if (!docInfoElement.isConnected ||- window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BREADCRUMB_MORE) {- return;+ type: "readonly",+ // 不能换行,否则移动端间距过大+ label: genDocumentStatLabel(response.data.stat),+ }).element;+ window.siyuan.menus.menu.append(docInfoElement);+ if (response.data.containsEmbed) {+ fetchPost("/api/block/getTreeStat", {...statRequest, includeEmbed: true}, (embedResponse) => {+ if (!docInfoElement.isConnected ||+ window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BREADCRUMB_MORE) {+ return;+ }+ docInfoElement.querySelector(".b3-menu__label").innerHTML = genDocumentStatLabel(+ embedResponse.data.stat,+ embedResponse.data.statWithEmbed,+ embedResponse.data.embedStat+ );+ });}- docInfoElement.querySelector(".b3-menu__label").innerHTML = genDocumentStatLabel(- embedResponse.data.stat,- embedResponse.data.statWithEmbed,- embedResponse.data.embedStat- );+ /// #if MOBILE+ session.show(() => window.siyuan.menus.menu.fullscreen("all", restoreKeyboard));+ /// #else+ session.show(() => window.siyuan.menus.menu.popup(position));+ /// #endif+ const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);+ window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover" : "app");});- }- /// #if MOBILE- window.siyuan.menus.menu.fullscreen("all", restoreKeyboard);- /// #else- window.siyuan.menus.menu.popup(position);- /// #endif- const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);- window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover" : "app");++ },});}diff --git a/app/src/protyle/gutter/click.test.ts b/app/src/protyle/gutter/click.test.tsindex 8fb5ab7b18..6460c92623 100644--- a/app/src/protyle/gutter/click.test.ts+++ b/app/src/protyle/gutter/click.test.ts@@ -3,6 +3,7 @@ import test from "node:test";import {readFileSync} from "node:fs";import {join} from "node:path";import {createSourceFile, forEachChild, isCallExpression, ScriptTarget, transpileModule} from "typescript";+const {loadMenuToggle} = require("../../../tests/menu-toggle-fixture.cjs");const source = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest, true);const listeners = new Map<string, string>();@@ -22,17 +23,21 @@ const fixture = (type: string, mobile: boolean, cached: Record<string, boolean>)const calls: string[] = [];const noop = () => {};const button = {+ closest: (): null => null,+ setAttribute: noop,dataset: {type: "NodeList"},classList: {contains: () => false},getAttribute: (key: string) => key === "data-node-id" ? "list-id" : "NodeList",getBoundingClientRect: () => ({left: 10, bottom: 30}),};const menu = {- element: {setAttribute: noop},+ element: {setAttribute: noop, classList: {contains: () => true}},+ remove: noop,fullscreen: () => calls.push("fullscreen"),popup: () => calls.push("popup"),};const dependencies = {+ ...loadMenuToggle({window: {siyuan: {menus: {menu}}}}),window: {siyuan: {...cached, menus: {menu}}},hasClosestByTag: () => button,hideTooltip: noop,diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex b777bf2599..44bd140cb2 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {copyBlockSelection} from "../util/blockClipboard";import {hasClosestBlock,@@ -423,19 +424,25 @@ export class Gutter {const br = activeBlockButton.getBoundingClientRect();if (event.clientX >= br.left && event.clientX <= br.right &&event.clientY >= br.top && event.clientY <= br.bottom) {- this.renderMenu(protyle, activeBlockButton as HTMLElement);- if (!protyle.toolbar.range &&- window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BLOCK_MULTI) {- protyle.toolbar.range = getEditorRange(- this.getNodeElement(protyle, activeBlockButton) || protyle.wysiwyg.element.firstElementChild);+ toggleMenu({+ target: activeBlockButton,+ build: (_menu, session) => {+ this.renderMenu(protyle, activeBlockButton as HTMLElement);+ if (!protyle.toolbar.range &&+ window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BLOCK_MULTI) {+ protyle.toolbar.range = getEditorRange(+ this.getNodeElement(protyle, activeBlockButton) || protyle.wysiwyg.element.firstElementChild);+ }+ /// #if MOBILE+ session.show(() => window.siyuan.menus.menu.fullscreen());+ /// #else+ session.show(() => window.siyuan.menus.menu.popup({x: br.left, y: br.bottom, h: br.height, isLeft: true}));+ restoreGutterRange(protyle);+ /// #endif++ },+ });}- /// #if MOBILE- window.siyuan.menus.menu.fullscreen();- /// #else- window.siyuan.menus.menu.popup({x: br.left, y: br.bottom, h: br.height, isLeft: true});- restoreGutterRange(protyle);- /// #endif- }}return;}@@ -610,21 +617,27 @@ export class Gutter {// 不使用 window.siyuan.shiftIsPressed ,否则窗口未激活时按 Shift 点击块标无法打开属性面板 https://github.com/siyuan-note/siyuan/issues/15075openAttr(this.getNodeElement(protyle, buttonElement), "bookmark", protyle);} else if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {- this.renderMenu(protyle, buttonElement);- // https://ld246.com/article/1648433751993- if (!protyle.toolbar.range &&- window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BLOCK_MULTI) {- protyle.toolbar.range = getEditorRange(- this.getNodeElement(protyle, buttonElement) || protyle.wysiwyg.element.firstElementChild);- }- /// #if MOBILE- window.siyuan.menus.menu.fullscreen();- /// #else- window.siyuan.menus.menu.popup({x: gutterRect.left, y: gutterRect.bottom, isLeft: true});- const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);- window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover" : "app");- restoreGutterRange(protyle);- /// #endif+ toggleMenu({+ target: buttonElement,+ build: (_menu, session) => {+ this.renderMenu(protyle, buttonElement);+ // https://ld246.com/article/1648433751993+ if (!protyle.toolbar.range &&+ window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BLOCK_MULTI) {+ protyle.toolbar.range = getEditorRange(+ this.getNodeElement(protyle, buttonElement) || protyle.wysiwyg.element.firstElementChild);+ }+ /// #if MOBILE+ session.show(() => window.siyuan.menus.menu.fullscreen());+ /// #else+ session.show(() => window.siyuan.menus.menu.popup({x: gutterRect.left, y: gutterRect.bottom, isLeft: true}));+ const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);+ window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover" : "app");+ restoreGutterRange(protyle);+ /// #endif++ },+ });}});this.element.addEventListener("contextmenu", (event: MouseEvent & { target: HTMLInputElement }) => {diff --git a/app/src/protyle/header/Background.ts b/app/src/protyle/header/Background.tsindex 865cef48a5..aaa07812a5 100644--- a/app/src/protyle/header/Background.ts+++ b/app/src/protyle/header/Background.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {hasClosestByClassName} from "../util/hasClosest";import {getRandom, isMobile} from "../../util/functions";import {hideElements} from "../ui/hideElements";@@ -413,7 +414,7 @@ export class Background {break;} else if (type === "asset" && !protyle.disabled) {const rect = target.getBoundingClientRect();- assetMenu(protyle, {+ assetMenu(protyle, {target: target,x: target.parentElement.getBoundingClientRect().right,y: rect.bottom + 8,isLeft: true,@@ -815,120 +816,125 @@ export class Background {}private openTag(protyle: IProtyle, target: HTMLElement) {- window.siyuan.menus.menu.remove();- const menu = new Menu();- menu.addItem({- iconHTML: "",- type: "empty",- label: `<div class="fn__flex-column b3-menu__filter">- <input class="b3-text-field fn__flex-shrink" placeholder="${window.siyuan.languages.tag}"/>- <div class="fn__hr"></div>- <div class="b3-list fn__flex-1 b3-list--background">- <img style="margin: 0 auto;display: block;width: 64px;height: 64px" src="/stage/loading-pure.svg">- </div>-</div>`,- bind: (element) => {- const listElement = element.querySelector(".b3-list--background");- const renderTagList = (html: string) => {- if (!listElement.isConnected || !menu.element.contains(listElement)) {- return;- }- listElement.innerHTML = html;- const filterElement = listElement.parentElement;- filterElement.style.maxHeight = "";- // 异步列表更新后重新计算菜单高度,避免沿用加载占位的高度限制。- window.siyuan.menus.menu.resetPosition();- const maxHeight = (menu.element.lastElementChild as HTMLElement).style.maxHeight;- if (maxHeight) {- filterElement.style.maxHeight = `min(50vh, ${maxHeight})`;- }- };- fetchPost("/api/search/searchTag", {- k: "",- }, (response) => {- if (!listElement.isConnected) {- return;- }- let html = "";- const currentTags = this.getTags();- response.data.tags.forEach((item: string, index: number) => {- html += `<div class="b3-list-item b3-list-item--narrow${index === 0 ? " b3-list-item--focus" : ""}">- <div class="fn__flex-1">${item}</div>- ${currentTags.includes(Lute.UnEscapeHTMLStr(item)) ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}-</div>`;- });- renderTagList(html);- });- const inputElement = element.querySelector("input");- inputElement.addEventListener("keydown", (event: KeyboardEvent) => {- event.stopPropagation();- if (event.isComposing) {- return;- }- upDownHint(listElement, event);- if (event.key === "Enter") {- const currentElement = listElement.querySelector(".b3-list-item--focus") as HTMLElement;- this.addTags(currentElement ?- (currentElement.dataset.type === "new" ? currentElement.querySelector("mark").textContent.trim() : currentElement.textContent.trim()) :- inputElement.value.trim(), protyle, () => {- inputElement.value = "";- inputElement.dispatchEvent(new CustomEvent("input"));+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ const menu = new Menu();+ menu.addItem({+ iconHTML: "",+ type: "empty",+ label: `<div class="fn__flex-column b3-menu__filter">+ <input class="b3-text-field fn__flex-shrink" placeholder="${window.siyuan.languages.tag}"/>+ <div class="fn__hr"></div>+ <div class="b3-list fn__flex-1 b3-list--background">+ <img style="margin: 0 auto;display: block;width: 64px;height: 64px" src="/stage/loading-pure.svg">+ </div>+ </div>`,+ bind: (element) => {+ const listElement = element.querySelector(".b3-list--background");+ const renderTagList = (html: string) => {+ if (!listElement.isConnected || !menu.element.contains(listElement)) {+ return;+ }+ listElement.innerHTML = html;+ const filterElement = listElement.parentElement;+ filterElement.style.maxHeight = "";+ // 异步列表更新后重新计算菜单高度,避免沿用加载占位的高度限制。+ window.siyuan.menus.menu.resetPosition();+ const maxHeight = (menu.element.lastElementChild as HTMLElement).style.maxHeight;+ if (maxHeight) {+ filterElement.style.maxHeight = `min(50vh, ${maxHeight})`;+ }+ };+ fetchPost("/api/search/searchTag", {+ k: "",+ }, (response) => {+ if (!listElement.isConnected) {+ return;+ }+ let html = "";+ const currentTags = this.getTags();+ response.data.tags.forEach((item: string, index: number) => {+ html += `<div class="b3-list-item b3-list-item--narrow${index === 0 ? " b3-list-item--focus" : ""}">+ <div class="fn__flex-1">${item}</div>+ ${currentTags.includes(Lute.UnEscapeHTMLStr(item)) ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}+ </div>`;+ });+ renderTagList(html);});- } else if (event.key === "Escape") {- window.siyuan.menus.menu.remove();- }- });- inputElement.addEventListener("input", (event) => {- event.stopPropagation();- fetchPost("/api/search/searchTag", {- k: inputElement.value.trim(),- }, (response) => {- if (!listElement.isConnected) {- return;- }- let searchHTML = "";- let hasKey = false;- const currentTags = this.getTags();- response.data.tags.forEach((item: string, index: number) => {- searchHTML += `<div class="b3-list-item b3-list-item--narrow${index === 0 ? " b3-list-item--focus" : ""}">- <div class="fn__flex-1">${item}</div>- ${currentTags.includes(Lute.UnEscapeHTMLStr(item.replace(/<mark>/g, "").replace(/<\/mark>/g, ""))) ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}-</div>`;- if (item === `<mark>${response.data.k}</mark>`) {- hasKey = true;+ const inputElement = element.querySelector("input");+ inputElement.addEventListener("keydown", (event: KeyboardEvent) => {+ event.stopPropagation();+ if (event.isComposing) {+ return;+ }+ upDownHint(listElement, event);+ if (event.key === "Enter") {+ const currentElement = listElement.querySelector(".b3-list-item--focus") as HTMLElement;+ this.addTags(currentElement ?+ (currentElement.dataset.type === "new" ? currentElement.querySelector("mark").textContent.trim() : currentElement.textContent.trim()) :+ inputElement.value.trim(), protyle, () => {+ inputElement.value = "";+ inputElement.dispatchEvent(new CustomEvent("input"));+ });+ } else if (event.key === "Escape") {+ window.siyuan.menus.menu.remove();}});- if (!hasKey && response.data.k) {- searchHTML = `<div data-type="new" class="b3-list-item b3-list-item--narrow${searchHTML ? "" : " b3-list-item--focus"}"><div class="fn__flex-1">${window.siyuan.languages.new} <mark>${escapeHtml(response.data.k)}</mark></div></div>` + searchHTML;- }- renderTagList(searchHTML);- });- });- listElement.addEventListener("click", (event) => {- const target = event.target as HTMLElement;- const listItemElement = hasClosestByClassName(target, "b3-list-item");- if (!listItemElement) {- return;- }- this.addTags(listItemElement.dataset.type === "new" ? listItemElement.querySelector("mark").textContent.trim() : listItemElement.textContent.trim(),- protyle, () => {- inputElement.value = "";- inputElement.dispatchEvent(new CustomEvent("input"));- inputElement.focus();+ inputElement.addEventListener("input", (event) => {+ event.stopPropagation();+ fetchPost("/api/search/searchTag", {+ k: inputElement.value.trim(),+ }, (response) => {+ if (!listElement.isConnected) {+ return;+ }+ let searchHTML = "";+ let hasKey = false;+ const currentTags = this.getTags();+ response.data.tags.forEach((item: string, index: number) => {+ searchHTML += `<div class="b3-list-item b3-list-item--narrow${index === 0 ? " b3-list-item--focus" : ""}">+ <div class="fn__flex-1">${item}</div>+ ${currentTags.includes(Lute.UnEscapeHTMLStr(item.replace(/<mark>/g, "").replace(/<\/mark>/g, ""))) ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}+ </div>`;+ if (item === `<mark>${response.data.k}</mark>`) {+ hasKey = true;+ }+ });+ if (!hasKey && response.data.k) {+ searchHTML = `<div data-type="new" class="b3-list-item b3-list-item--narrow${searchHTML ? "" : " b3-list-item--focus"}"><div class="fn__flex-1">${window.siyuan.languages.new} <mark>${escapeHtml(response.data.k)}</mark></div></div>` + searchHTML;+ }+ renderTagList(searchHTML);+ });+ });+ listElement.addEventListener("click", (event) => {+ const target = event.target as HTMLElement;+ const listItemElement = hasClosestByClassName(target, "b3-list-item");+ if (!listItemElement) {+ return;+ }+ this.addTags(listItemElement.dataset.type === "new" ? listItemElement.querySelector("mark").textContent.trim() : listItemElement.textContent.trim(),+ protyle, () => {+ inputElement.value = "";+ inputElement.dispatchEvent(new CustomEvent("input"));+ inputElement.focus();+ });});+ }});- }+ const itemsElement = menu.element.querySelector(".b3-menu__items");+ itemsElement.setAttribute("style", "overflow: initial");+ /// #if MOBILE+ session.show(() => menu.fullscreen("bottom"));+ itemsElement.firstElementChild.setAttribute("style", "padding: 0 8px;height: 100%;");+ /// #else+ const rect = target.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.top + rect.height, h: rect.height}));+ menu.element.querySelector("input").focus();+ /// #endif++ },});- const itemsElement = menu.element.querySelector(".b3-menu__items");- itemsElement.setAttribute("style", "overflow: initial");- /// #if MOBILE- menu.fullscreen("bottom");- itemsElement.firstElementChild.setAttribute("style", "padding: 0 8px;height: 100%;");- /// #else- const rect = target.getBoundingClientRect();- menu.open({x: rect.left, y: rect.top + rect.height, h: rect.height});- menu.element.querySelector("input").focus();- /// #endif}private getTags(removeTag?: string) {diff --git a/app/src/protyle/header/Title.ts b/app/src/protyle/header/Title.tsindex 9e545b8c2e..c30589e459 100644--- a/app/src/protyle/header/Title.ts+++ b/app/src/protyle/header/Title.ts@@ -204,7 +204,7 @@ export class Title {});} else {const iconRect = iconElement.getBoundingClientRect();- openTitleMenu(protyle, {x: iconRect.left, y: iconRect.bottom, h: iconRect.height}, Constants.MENU_FROM_TITLE_PROTYLE);+ openTitleMenu(protyle, {target: iconElement, x: iconRect.left, y: iconRect.bottom, h: iconRect.height}, Constants.MENU_FROM_TITLE_PROTYLE);}});this.element.addEventListener("contextmenu", async (event) => {diff --git a/app/src/protyle/header/documentMenu.test.ts b/app/src/protyle/header/documentMenu.test.tsindex 9b2b7cda9b..2df3ea7ebf 100644--- a/app/src/protyle/header/documentMenu.test.ts+++ b/app/src/protyle/header/documentMenu.test.ts@@ -5,6 +5,7 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";import {getEntryCatalogChildren} from "../../config/entryVisibility/catalog";+const {loadMenuToggle} = require("../../../tests/menu-toggle-fixture.cjs");const {parse} = require("ifdef-loader/preprocessor");const noop = () => {};@@ -98,6 +99,7 @@ const setup = (mobile = false, readonly = false, encrypted = false) => {return exports;};const documentModule = load("documentMenu") as typeof import("./documentMenu");+ dependencies["../../menus/menuToggle"] = loadMenuToggle(globals);dependencies["./documentMenu"] = documentModule;const titleModule = load("openTitleMenu") as typeof import("./openTitleMenu");const options: Parameters<typeof documentModule.openDocumentMenu>[0] = {diff --git a/app/src/protyle/header/openDocTagMenu.ts b/app/src/protyle/header/openDocTagMenu.tsindex 46f15109a6..12c40a47fc 100644--- a/app/src/protyle/header/openDocTagMenu.ts+++ b/app/src/protyle/header/openDocTagMenu.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {escapeHtmlTextAndAttr} from "../../util/escape";import {MenuItem} from "../../menus/Menu";import {Constants} from "../../constants";@@ -39,116 +40,121 @@ const copyTag = async (protyle: IProtyle, tag: string) => {};export const openDocTagMenu = (options: IOpenDocTagMenuOptions) => {- window.siyuan.menus.menu.remove();- const tagName = getSemanticInlineVisibleText(options.tagElement).trim();- let inputElement: HTMLInputElement;- let skipUpdate = false;- window.siyuan.menus.menu.removeCB = () => {- if (!skipUpdate) {- options.update(inputElement.value.trim());- }- };- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_DOC_TAG);- window.siyuan.menus.menu.append(new MenuItem({- id: "tag",- iconHTML: "",- type: "readonly",- label: `<input ${Constants.ATTRIBUTE_MENU_KEYMAP}="true" class="b3-text-field fn__block" style="margin: 4px 0" placeholder="${window.siyuan.languages.tag}">-<div class="fn__none b3-list fn__flex-1 b3-list--background protyle-hint" style="position: fixed"></div>`,- bind(element) {- const listElement = element.querySelector(".b3-list") as HTMLElement;- inputElement = element.querySelector("input");- inputElement.value = tagName;- const renderTagList = () => {- genTagList(listElement, inputElement.value.trim());- const inputRect = inputElement.getBoundingClientRect();- setPosition(listElement, inputRect.right + 8, inputRect.top, inputRect.height);- };- inputElement.addEventListener("compositionend", renderTagList);- inputElement.addEventListener("input", (event: InputEvent) => {- event.stopPropagation();- if (!event.isComposing) {- renderTagList();- }- });- inputElement.addEventListener("keydown", (event: KeyboardEvent) => {- if (event.isComposing) {- return;+ toggleMenu({+ target: options.tagElement,+ build: (_menu, session) => {+ const tagName = getSemanticInlineVisibleText(options.tagElement).trim();+ let inputElement: HTMLInputElement;+ let skipUpdate = false;+ window.siyuan.menus.menu.removeCB = () => {+ if (!skipUpdate) {+ options.update(inputElement.value.trim());}- if (!listElement.classList.contains("fn__none")) {- upDownHint(listElement, event);- if (event.key === "Enter" || event.key === "Escape") {- listElement.classList.add("fn__none");- }- if (event.key === "Enter") {- const currentElement = listElement.querySelector(".b3-list-item--focus") as HTMLElement;- if (currentElement) {- inputElement.value = currentElement.dataset.type === "new" ?- currentElement.querySelector("mark").textContent.trim() : currentElement.textContent.trim();+ };+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_DOC_TAG);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "tag",+ iconHTML: "",+ type: "readonly",+ label: `<input ${Constants.ATTRIBUTE_MENU_KEYMAP}="true" class="b3-text-field fn__block" style="margin: 4px 0" placeholder="${window.siyuan.languages.tag}">+ <div class="fn__none b3-list fn__flex-1 b3-list--background protyle-hint" style="position: fixed"></div>`,+ bind(element) {+ const listElement = element.querySelector(".b3-list") as HTMLElement;+ inputElement = element.querySelector("input");+ inputElement.value = tagName;+ const renderTagList = () => {+ genTagList(listElement, inputElement.value.trim());+ const inputRect = inputElement.getBoundingClientRect();+ setPosition(listElement, inputRect.right + 8, inputRect.top, inputRect.height);+ };+ inputElement.addEventListener("compositionend", renderTagList);+ inputElement.addEventListener("input", (event: InputEvent) => {+ event.stopPropagation();+ if (!event.isComposing) {+ renderTagList();+ }+ });+ inputElement.addEventListener("keydown", (event: KeyboardEvent) => {+ if (event.isComposing) {+ return;+ }+ if (!listElement.classList.contains("fn__none")) {+ upDownHint(listElement, event);+ if (event.key === "Enter" || event.key === "Escape") {+ listElement.classList.add("fn__none");+ }+ if (event.key === "Enter") {+ const currentElement = listElement.querySelector(".b3-list-item--focus") as HTMLElement;+ if (currentElement) {+ inputElement.value = currentElement.dataset.type === "new" ?+ currentElement.querySelector("mark").textContent.trim() : currentElement.textContent.trim();+ }+ }+ event.preventDefault();+ event.stopPropagation();+ return;}- }- event.preventDefault();- event.stopPropagation();- return;+ if (event.key === "Enter") {+ window.siyuan.menus.menu.remove();+ event.preventDefault();+ event.stopPropagation();+ } else if (event.key === "Escape") {+ window.siyuan.menus.menu.removeCB = null;+ }+ });+ listElement.addEventListener("click", (event) => {+ const listItemElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item");+ if (!listItemElement) {+ return;+ }+ inputElement.value = listItemElement.dataset.type === "new" ?+ listItemElement.querySelector("mark").textContent.trim() : listItemElement.textContent.trim();+ listElement.classList.add("fn__none");+ inputElement.focus();+ });}- if (event.key === "Enter") {+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "search",+ label: window.siyuan.languages.search,+ accelerator: window.siyuan.languages.click,+ icon: "iconSearch",+ click() {+ openGlobalSearch(options.protyle.app, `#${tagName}#`, false, {method: 0});+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "rename",+ label: window.siyuan.languages.rename,+ icon: "iconEdit",+ click() {window.siyuan.menus.menu.remove();- event.preventDefault();- event.stopPropagation();- } else if (event.key === "Escape") {- window.siyuan.menus.menu.removeCB = null;+ renameTag(tagName);+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "copy",+ label: window.siyuan.languages.copy,+ icon: "iconCopy",+ click() {+ void copyTag(options.protyle, tagName);}- });- listElement.addEventListener("click", (event) => {- const listItemElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item");- if (!listItemElement) {- return;+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "remove",+ label: window.siyuan.languages.remove,+ icon: "iconTrashcan",+ click() {+ skipUpdate = true;+ options.remove();}- inputElement.value = listItemElement.dataset.type === "new" ?- listItemElement.querySelector("mark").textContent.trim() : listItemElement.textContent.trim();- listElement.classList.add("fn__none");- inputElement.focus();- });- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "search",- label: window.siyuan.languages.search,- accelerator: window.siyuan.languages.click,- icon: "iconSearch",- click() {- openGlobalSearch(options.protyle.app, `#${tagName}#`, false, {method: 0});- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "rename",- label: window.siyuan.languages.rename,- icon: "iconEdit",- click() {- window.siyuan.menus.menu.remove();- renameTag(tagName);- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "copy",- label: window.siyuan.languages.copy,- icon: "iconCopy",- click() {- void copyTag(options.protyle, tagName);- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "remove",- label: window.siyuan.languages.remove,- icon: "iconTrashcan",- click() {- skipUpdate = true;- options.remove();- }- }).element);- window.siyuan.menus.menu.popup(options.position);- inputElement.focus();- inputElement.select();+ }).element);+ session.show(() => window.siyuan.menus.menu.popup(options.position));+ inputElement.focus();+ inputElement.select();++ },+ });};diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.tsindex 8fa7711897..f66ff571e1 100644--- a/app/src/protyle/header/openTitleMenu.ts+++ b/app/src/protyle/header/openTitleMenu.ts@@ -1,46 +1,47 @@+import {toggleMenu} from "../../menus/menuToggle";import type {BlockQueryRequestInput} from "../../types/api";import {fetchPost} from "../../util/fetch";-import {Constants} from "../../constants";import {hideTooltip} from "../../dialog/tooltip";import {isEncryptedBox} from "../../util/pathName";-import {isMobile} from "../../util/functions";import {openDocumentMenu} from "./documentMenu";export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: string, restoreKeyboard?: () => void) => {- hideTooltip();- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TITLE) {- if (isMobile()) {- window.siyuan.menus.menu.closeSheet();- } else {- window.siyuan.menus.menu.remove();- }- return;- }- const docInfoParam: BlockQueryRequestInput = {- id: protyle.block.rootID- };- if (isEncryptedBox(protyle.notebookId)) {- docInfoParam.notebook = protyle.notebookId;- }- fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {- if (response.code !== 0 || !response.data) {- return;- }- openDocumentMenu({- app: protyle.app,- id: protyle.block.rootID,- notebookId: protyle.notebookId,- path: protyle.path,- docInfo: response.data,- target: protyle.element,- position,- from,- disabled: protyle.disabled,- protyle,- blockId: protyle.block.id,- showAll: protyle.block.showAll,- restoreKeyboard,- });+ toggleMenu({+ target: position.target,+ build: (_menu, session) => {+ hideTooltip();++ const docInfoParam: BlockQueryRequestInput = {+ id: protyle.block.rootID+ };+ if (isEncryptedBox(protyle.notebookId)) {+ docInfoParam.notebook = protyle.notebookId;+ }+ fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {+ if (!session.isCurrent()) {+ return;+ }++ if (response.code !== 0 || !response.data) {+ return;+ }+ session.show(() => openDocumentMenu({+ app: protyle.app,+ id: protyle.block.rootID,+ notebookId: protyle.notebookId,+ path: protyle.path,+ docInfo: response.data,+ target: protyle.element,+ position,+ from,+ disabled: protyle.disabled,+ protyle,+ blockId: protyle.block.id,+ showAll: protyle.block.showAll,+ restoreKeyboard,+ }));+ });++ },});};diff --git a/app/src/protyle/lite/codeActions.ts b/app/src/protyle/lite/codeActions.tsindex 1a77ec2a48..0543f1f252 100644--- a/app/src/protyle/lite/codeActions.ts+++ b/app/src/protyle/lite/codeActions.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {MenuItem} from "../../menus/Menu";import {Constants} from "../../constants";import {showMessage} from "../../dialog/message";@@ -71,28 +72,35 @@ export const bindLiteCodeActions = (host: HTMLElement, protyle: IProtyle, optionif (!options.canEdit()) {return;}- const menu = window.siyuan.menus.menu;- menu.remove();- getLiteCodeMenuItems(code, (attribute, value) => {- if (options.signal.aborted || !options.canEdit() || !protyle.wysiwyg.element.contains(code)) {- return;- }- options.beforeChange?.();- if (value === "") {- code.removeAttribute(attribute);- } else {- code.setAttribute(attribute, value);- }- // 属性变化不会触发片段的正文观察器,需显式交由宿主事务保存。- options.onChange();- content.removeAttribute("data-render");- highlightRender(code);- }).forEach(item => menu.append(new MenuItem(item).element));- if (isMobile()) {- menu.fullscreen();- } else {- const rect = button.getBoundingClientRect();- menu.popup({x: rect.left, y: rect.top, isLeft: true});- }++ toggleMenu({+ target: button,+ build: (_menu, session) => {+ const menu = window.siyuan.menus.menu;++ getLiteCodeMenuItems(code, (attribute, value) => {+ if (options.signal.aborted || !options.canEdit() || !protyle.wysiwyg.element.contains(code)) {+ return;+ }+ options.beforeChange?.();+ if (value === "") {+ code.removeAttribute(attribute);+ } else {+ code.setAttribute(attribute, value);+ }+ // 属性变化不会触发片段的正文观察器,需显式交由宿主事务保存。+ options.onChange();+ content.removeAttribute("data-render");+ highlightRender(code);+ }).forEach(item => menu.append(new MenuItem(item).element));+ if (isMobile()) {+ session.show(() => menu.fullscreen());+ } else {+ const rect = button.getBoundingClientRect();+ session.show(() => menu.popup({x: rect.left, y: rect.top, isLeft: true}));+ }++ },+ });}, {capture: true, signal: options.signal});};diff --git a/app/src/protyle/render/listMindmap/fold.test.ts b/app/src/protyle/render/listMindmap/fold.test.tsindex 13072dc91e..2307cadf4b 100644--- a/app/src/protyle/render/listMindmap/fold.test.ts+++ b/app/src/protyle/render/listMindmap/fold.test.ts@@ -6,6 +6,7 @@ import {createSourceFile, isClassDeclaration, isPropertyAssignment, ScriptTargetimport {getListMindmapFoldStates, getListMindmapSiblingFoldStates} from "./fold";import type {ListMindmapFoldTarget} from "./fold";import type {ListMindmapNode} from "./model";+const {loadMenuToggle} = require("../../../../tests/menu-toggle-fixture.cjs");const node = (id: string, children: ListMindmapNode[] = [], collapsed = false): ListMindmapNode => ({id, children, collapsed, virtual: false, contentBlocks: [],@@ -83,12 +84,14 @@ test("desktop and mobile menus offer six levels without icon placeholders followopen(position: unknown) { positions.push(position); }},isMobile: () => mobile,- window: {siyuan: {languages: {listMindmapExpandToLevel: "Level ${level}", expandAll: "Expand", foldAll: "Collapse"}}},+ window: {siyuan: {menus: {menu: {element: {classList: {contains: () => true}}, remove() {}}},+ languages: {listMindmapExpandToLevel: "Level ${level}", expandAll: "Expand", foldAll: "Collapse"}}},};+ Object.assign(context, loadMenuToggle(context));const open = runInNewContext(transpileModule(`(${callback})`, {compilerOptions: {target: ScriptTarget.ES2021},}).outputText, context);- open({getBoundingClientRect: () => ({left: 10, bottom: 30, height: 20})},+ open({closest: (): null => null, setAttribute() {}, getBoundingClientRect: () => ({left: 10, bottom: 30, height: 20})},(level: ListMindmapFoldTarget) => selected.push(level));assert.deepEqual(entries.map(item => item.id), [...Array.from({length: 6}, (_, i) => `level${i + 1}`),"separator_all", "expandAll", "foldAll"]);diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsindex b3558d955e..54532c198a 100644--- a/app/src/protyle/render/listMindmap/index.ts+++ b/app/src/protyle/render/listMindmap/index.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../../menus/menuToggle";import {Constants} from "../../../constants";import {showMessage} from "../../../dialog/message";import {fetchSyncPost} from "../../../util/fetch";@@ -211,26 +212,36 @@ class ListMindmapController {metadata.viewLocked = locked;}) : Promise.resolve(true),onExpandLevelMenu: (anchor, select) => {- const menu = new Menu();- for (let level = 1; level <= 6; level++) {- menu.addItem({- id: `level${level}`,- iconHTML: "",- label: window.siyuan.languages.listMindmapExpandToLevel.replace("${level}", String(level)),- click: () => select(level),- });- }- menu.addSeparator({id: "separator_all"});- menu.addItem({id: "expandAll", icon: "iconExpand", label: window.siyuan.languages.expandAll,- click: () => select("expandAll")});- menu.addItem({id: "foldAll", icon: "iconContract", label: window.siyuan.languages.foldAll,- click: () => select("foldAll")});- if (isMobile()) {- menu.fullscreen("bottom");- } else {- const rect = anchor.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height});- }+ toggleMenu({+ target: anchor,+ build: (_menu, session) => {+ const menu = new Menu();+ for (let level = 1; level <= 6; level++) {+ menu.addItem({+ id: `level${level}`,+ iconHTML: "",+ label: window.siyuan.languages.listMindmapExpandToLevel.replace("${level}", String(level)),+ click: () => select(level),+ });+ }+ menu.addSeparator({id: "separator_all"});+ menu.addItem({+ id: "expandAll", icon: "iconExpand", label: window.siyuan.languages.expandAll,+ click: () => select("expandAll")+ });+ menu.addItem({+ id: "foldAll", icon: "iconContract", label: window.siyuan.languages.foldAll,+ click: () => select("foldAll")+ });+ if (isMobile()) {+ session.show(() => menu.fullscreen("bottom"));+ } else {+ const rect = anchor.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height}));+ }++ },+ });},onFoldLevel: level => this.change(() => {const model = readListMindmap(list);@@ -312,28 +323,40 @@ class ListMindmapController {onTaskToggle: (id, cycle) => this.setTask(id, cycle ? nextTaskListStatus : nextTaskListMarker),onTabTaskToggle: (id, itemId) => this.setTabTask(id, itemId, nextTaskListMarker),onTabTaskMenu: (id, itemId, anchor) => {- const item = getListMindmapTabItem(list, id, itemId);- const marker = item && getTabTask(item);- if (!canEdit(owner, list) || marker == null) {- return;- }- const menu = new Menu();- getTaskStatusItems(marker, next => this.setTabTask(id, itemId, () => next)).forEach(entry => menu.addItem(entry));- const rect = anchor.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height});+ toggleMenu({+ target: anchor,+ build: (_menu, session) => {+ const item = getListMindmapTabItem(list, id, itemId);+ const marker = item && getTabTask(item);+ if (!canEdit(owner, list) || marker == null) {+ return;+ }+ const menu = new Menu();+ getTaskStatusItems(marker, next => this.setTabTask(id, itemId, () => next)).forEach(entry => menu.addItem(entry));+ const rect = anchor.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height}));++ },+ });},onTaskMenu: (id, anchor) => {- if (!canEdit(owner, list)) {- return;- }- const marker = readListMindmap(list).nodes.get(id)?.taskMarker;- if (marker === undefined) {- return;- }- const menu = new Menu();- getTaskStatusItems(marker, next => this.setTask(id, () => next)).forEach(item => menu.addItem(item));- const rect = anchor.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height});+ toggleMenu({+ target: anchor,+ build: (_menu, session) => {+ if (!canEdit(owner, list)) {+ return;+ }+ const marker = readListMindmap(list).nodes.get(id)?.taskMarker;+ if (marker === undefined) {+ return;+ }+ const menu = new Menu();+ getTaskStatusItems(marker, next => this.setTask(id, () => next)).forEach(item => menu.addItem(item));+ const rect = anchor.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height}));++ },+ });},isTaskCycle: event => matchHotKey(window.siyuan.config.keymap.editor.list.checkToggle, event),isTaskCompletionToggle: event => matchHotKey(window.siyuan.config.keymap.editor.list.taskCompletionToggle, event),diff --git a/app/src/protyle/toolbar/BlockType.test.ts b/app/src/protyle/toolbar/BlockType.test.tsindex 9a5582f157..b7b5e0043e 100644--- a/app/src/protyle/toolbar/BlockType.test.ts+++ b/app/src/protyle/toolbar/BlockType.test.ts@@ -5,6 +5,7 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {createSourceFile, isClassDeclaration, isMethodDeclaration, ModuleKind, ScriptTarget, transpileModule} from "typescript";import {getBlockTypeOptions, isSameTextRange} from "./blockTypeCore";+const {loadMenuToggle} = require("../../../tests/menu-toggle-fixture.cjs");const source = transpileModule(readFileSync(resolve(process.cwd(), "src/protyle/toolbar/BlockType.ts"), "utf8"),{compilerOptions: {module: ModuleKind.CommonJS}}).outputText;@@ -41,6 +42,9 @@ const setup = (mobile = false) => {embed: undefined as {allowChildOperation: boolean, targetElement?: HTMLElement} | undefined};const menu = {close: (): void => undefined};const commonMenu = {+ data: undefined as Element,+ remove: () => { menu.close(); commonMenu.data = undefined; },+ closeSheet: () => sheetExports.close.call(commonMenu),restoreKeyboard: undefined as (() => void) | undefined,element: {classList: {contains: () => true}},fullscreen: (_position: string, restore: () => void) => {@@ -93,6 +97,7 @@ const setup = (mobile = false) => {addEventListener: (name: string, listener: () => void) => listeners.set(name, listener),removeEventListener: (name: string) => listeners.delete(name),};+ modules["../../menus/menuToggle"] = loadMenuToggle({window: {siyuan: {menus: {menu: commonMenu}}}});runInNewContext(source, {exports,require: (name: string) => {assert.ok(modules[name], name);@@ -105,7 +110,7 @@ const setup = (mobile = false) => {languages: new Proxy({blockTypeParentChange: "Changes outer block"} as Record<string, string>,{get: (target, key: string) => target[key] || key})}},});- const button = {isConnected: true, contains: (): boolean => false,+ const button = {isConnected: true, contains: (): boolean => false, closest: (): null => null, setAttribute: () => {},getBoundingClientRect: () => ({left: 0, bottom: 30, height: 30, width: 60})} as unknown as HTMLElement;const open = () => exports.openBlockTypeMenu(protyle, button, snapshot as Parameters<typeof exports.openBlockTypeMenu>[2],{isCurrent: () => state.current, onClose: () => state.restored++});diff --git a/app/src/protyle/toolbar/BlockType.ts b/app/src/protyle/toolbar/BlockType.tsindex 5e89778948..1a67293ee4 100644--- a/app/src/protyle/toolbar/BlockType.ts+++ b/app/src/protyle/toolbar/BlockType.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {Menu} from "../../plugin/Menu";import {ToolbarItem} from "./ToolbarItem";import {@@ -56,96 +57,102 @@ export const updateBlockTypeButton = (protyle: IProtyle, button: HTMLElement, raexport const openBlockTypeMenu = (protyle: IProtyle, button: HTMLElement, snapshot: TTextBlockSelection,options: {onClose?: () => void, isCurrent?: () => boolean} = {}) => {- const valid = () => options.isCurrent?.() !== false && button.isConnected &&- isTextBlockSelectionValid(snapshot, context(protyle), protyle.block.rootID) &&- getBlockTypeSelection(protyle, snapshot.range)?.block === snapshot.block;- if (!valid()) {- return;- }- closeSubElement(protyle.toolbar);- protyle.toolbar.subElement.classList.add("fn__none");- let applied = false;- let changedSelection = false;- let restored = false;- const selectionChanged = () => {- const selection = window.getSelection();- const active = document.activeElement;- if (selection?.rangeCount && !isSameTextRange(selection.getRangeAt(0), snapshot.range) &&- (!selection.isCollapsed || active && protyle.wysiwyg.element.contains(active))) {- changedSelection = true;- }- };- const movedOutside = (event: PointerEvent) => {- if ((event.target as Element).closest?.("#commonMenuScrim")) {- return;- }- if (!menu.element.contains(event.target as Node) && !button.contains(event.target as Node)) {- changedSelection = true;- }- };- const restoreSelection = () => {- const active = document.activeElement;- if (active && active !== document.body && active !== button &&- !protyle.wysiwyg.element.contains(active) && !menu.element.contains(active)) {- return;- }- selectionChanged();- if (!restored && !applied && !changedSelection && valid()) {- restored = true;- if (options.onClose) {- options.onClose();- } else if (!isMobile()) {- focusByRange(snapshot.range);+ toggleMenu({+ target: button,+ build: (_menu, session) => {+ const valid = () => options.isCurrent?.() !== false && button.isConnected &&+ isTextBlockSelectionValid(snapshot, context(protyle), protyle.block.rootID) &&+ getBlockTypeSelection(protyle, snapshot.range)?.block === snapshot.block;+ if (!valid()) {+ return;}- }- };- const menu = new Menu("selectionBlockType", () => {- document.removeEventListener("selectionchange", selectionChanged);- document.removeEventListener("pointerdown", movedOutside, true);- restoreSelection();- });- if (menu.isOpen) {- return;- }- document.addEventListener("selectionchange", selectionChanged);- document.addEventListener("pointerdown", movedOutside, true);- getBlockTypeOptions(snapshot.block).forEach(option => {- const label = window.siyuan.languages[option.lang];- const reason = option.disabled ? window.siyuan.languages.blockTypeParentChange : "";- menu.addItem({- icon: option.icon,- checked: option.current,- disabled: option.disabled,- label: escapeHtml(label) + (reason ? `<span class="fn__block ft__smaller">${escapeHtml(reason)}</span>` : ""),- bind: element => element.setAttribute("aria-label", reason ? `${label} ${reason}` : label),- click: () => {- selectionChanged();- if (changedSelection || !valid()) {+ closeSubElement(protyle.toolbar);+ protyle.toolbar.subElement.classList.add("fn__none");+ let applied = false;+ let changedSelection = false;+ let restored = false;+ const selectionChanged = () => {+ const selection = window.getSelection();+ const active = document.activeElement;+ if (selection?.rangeCount && !isSameTextRange(selection.getRangeAt(0), snapshot.range) &&+ (!selection.isCollapsed || active && protyle.wysiwyg.element.contains(active))) {+ changedSelection = true;+ }+ };+ const movedOutside = (event: PointerEvent) => {+ if ((event.target as Element).closest?.("#commonMenuScrim")) {return;}- const current = getBlockTypeOptions(snapshot.block).find(item => item.key === option.key);- if (!current || current.disabled || current.current) {+ if (!menu.element.contains(event.target as Node) && !button.contains(event.target as Node)) {+ changedSelection = true;+ }+ };+ const restoreSelection = () => {+ const active = document.activeElement;+ if (active && active !== document.body && active !== button &&+ !protyle.wysiwyg.element.contains(active) && !menu.element.contains(active)) {return;}- // 菜单显式设置目标类型,不经过快捷键的同级标题切换和整块多选路径。- applied = true;- menu.close();- protyle.toolbar.element.classList.add("fn__none");- if (current.type === "Blocks2Ps" || current.type === "Blocks2Hs") {- turnsIntoTransaction({protyle, selectsElement: [snapshot.block], type: current.type, level: current.level});- } else {- void turnsIntoOneTransaction({protyle, selectsElement: [snapshot.block], type: current.type});+ selectionChanged();+ if (!restored && !applied && !changedSelection && valid()) {+ restored = true;+ if (options.onClose) {+ options.onClose();+ } else if (!isMobile()) {+ focusByRange(snapshot.range);+ }}- },- });+ };+ const menu = new Menu("selectionBlockType", () => {+ document.removeEventListener("selectionchange", selectionChanged);+ document.removeEventListener("pointerdown", movedOutside, true);+ restoreSelection();+ });+ if (menu.isOpen) {+ return;+ }+ document.addEventListener("selectionchange", selectionChanged);+ document.addEventListener("pointerdown", movedOutside, true);+ getBlockTypeOptions(snapshot.block).forEach(option => {+ const label = window.siyuan.languages[option.lang];+ const reason = option.disabled ? window.siyuan.languages.blockTypeParentChange : "";+ menu.addItem({+ icon: option.icon,+ checked: option.current,+ disabled: option.disabled,+ label: escapeHtml(label) + (reason ? `<span class="fn__block ft__smaller">${escapeHtml(reason)}</span>` : ""),+ bind: element => element.setAttribute("aria-label", reason ? `${label} ${reason}` : label),+ click: () => {+ selectionChanged();+ if (changedSelection || !valid()) {+ return;+ }+ const current = getBlockTypeOptions(snapshot.block).find(item => item.key === option.key);+ if (!current || current.disabled || current.current) {+ return;+ }+ // 菜单显式设置目标类型,不经过快捷键的同级标题切换和整块多选路径。+ applied = true;+ menu.close();+ protyle.toolbar.element.classList.add("fn__none");+ if (current.type === "Blocks2Ps" || current.type === "Blocks2Hs") {+ turnsIntoTransaction({protyle, selectsElement: [snapshot.block], type: current.type, level: current.level});+ } else {+ void turnsIntoOneTransaction({protyle, selectsElement: [snapshot.block], type: current.type});+ }+ },+ });+ });+ if (isMobile()) {+ session.show(() => window.siyuan.menus.menu.fullscreen("bottom", restoreSelection));+ } else {+ const rect = button.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: button}));+ }++ },});- if (isMobile()) {- window.siyuan.menus.menu.fullscreen("bottom", restoreSelection);- } else {- const rect = button.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: button});- }-};+ };export class BlockType extends ToolbarItem {constructor(protyle: IProtyle, item: IMenuItem) {diff --git a/app/src/protyle/toolbar/fontControls.ts b/app/src/protyle/toolbar/fontControls.tsindex 10292c241f..5ba231a651 100644--- a/app/src/protyle/toolbar/fontControls.ts+++ b/app/src/protyle/toolbar/fontControls.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {Menu} from "../../plugin/Menu";import {ToolbarItem} from "./ToolbarItem";import {convertFontSize, fontEvent, getFontNodeElements, getFontSizeInfo} from "./Font";@@ -139,23 +140,32 @@ export class FontControl extends ToolbarItem {});return;}- const menu = new Menu("inlineFontSize", () => {- if (valid()) {- focusByRange(protyle.toolbar.range);- }++ toggleMenu({+ target: this.element,+ build: (_menu, session) => {+ const menu = new Menu("inlineFontSize", () => {+ if (valid()) {+ focusByRange(protyle.toolbar.range);+ }+ });+ if (menu.isOpen) {+ return;+ }+ menu.addItem({+ type: "empty", label: "", bind: element => {+ element.append(createFontSizePicker(protyle, value => {+ menu.close();+ apply("fontSize", value);+ }, undefined, () => menu.close()));+ }+ });+ const rect = this.element.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.element}));+ menu.element.querySelector<HTMLInputElement>('input[type="number"]')?.focus();++ },});- if (menu.isOpen) {- return;- }- menu.addItem({type: "empty", label: "", bind: element => {- element.append(createFontSizePicker(protyle, value => {- menu.close();- apply("fontSize", value);- }, undefined, () => menu.close()));- }});- const rect = this.element.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.element});- menu.element.querySelector<HTMLInputElement>('input[type="number"]')?.focus();});}}diff --git a/app/src/protyle/toolbar/fontFamilyMenu.ts b/app/src/protyle/toolbar/fontFamilyMenu.tsindex 9a814a1136..ce2ceed41e 100644--- a/app/src/protyle/toolbar/fontFamilyMenu.ts+++ b/app/src/protyle/toolbar/fontFamilyMenu.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {Menu} from "../../plugin/Menu";import {observeFontPreview} from "../../util/fontPreview";import {escapeAttr, escapeHtml} from "../../util/escape";@@ -298,54 +299,67 @@ export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamiif (options.disabled) {return;}- const requestID = ++desktopRequestID;- if (!desktopMenuIDs.has(target)) {- desktopMenuIDs.set(target, `inlineFontFamily${requestID}`);- }- let closed = false;- let cleanup: () => void = undefined;- const menu = new Menu(desktopMenuIDs.get(target), () => {- closed = true;- cleanup?.();- target.setAttribute("aria-expanded", "false");- });- if (menu.isOpen) {- return;- }- const pickerElement = menu.addItem({- iconHTML: "",- type: "empty",- label: `<div class="b3-menu__filter">${escapeHtml(window.siyuan.languages.loading)}</div>`,- });- const openMenu = () => {- const rect = target.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target});- menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");- };- target.setAttribute("aria-expanded", "true");- openMenu();- const fonts = await loadFontFamilies(options.family);- if (closed) {- return;- }- if (requestID !== desktopRequestID || !target.isConnected || options.isOpenValid?.() === false) {- menu.close();- return;- }- if (target.tagName === "INPUT") {- (target as HTMLInputElement).value = getInlineFontFamilyLabel(options);- }- pickerElement.innerHTML = genFontPickerHTML(fonts, options, false);- cleanup = bindFontPicker(pickerElement, {- ...options,- onClose: () => target.focus(),- onSelect(family) {- menu.close();- options.onSelect(family);- }+ await toggleMenu({+ target: target,+ build: async (_menu, session) => {+ const requestID = ++desktopRequestID;+ if (!desktopMenuIDs.has(target)) {+ desktopMenuIDs.set(target, `inlineFontFamily${requestID}`);+ }+ let closed = false;+ let cleanup: () => void = undefined;+ const menu = new Menu(desktopMenuIDs.get(target), () => {+ closed = true;+ cleanup?.();+ target.setAttribute("aria-expanded", "false");+ });+ if (menu.isOpen) {+ return;+ }+ const pickerElement = menu.addItem({+ iconHTML: "",+ type: "empty",+ label: `<div class="b3-menu__filter">${escapeHtml(window.siyuan.languages.loading)}</div>`,+ });+ const openMenu = () => {+ if (!session.isCurrent()) {+ return;+ }++ const rect = target.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target}));+ menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");+ };+ target.setAttribute("aria-expanded", "true");+ openMenu();+ const fonts = await loadFontFamilies(options.family);+ if (!session.isCurrent()) {+ return;+ }+ if (closed) {+ return;+ }+ if (requestID !== desktopRequestID || !target.isConnected || options.isOpenValid?.() === false) {+ menu.close();+ return;+ }+ if (target.tagName === "INPUT") {+ (target as HTMLInputElement).value = getInlineFontFamilyLabel(options);+ }+ pickerElement.innerHTML = genFontPickerHTML(fonts, options, false);+ cleanup = bindFontPicker(pickerElement, {+ ...options,+ onClose: () => target.focus(),+ onSelect(family) {+ menu.close();+ options.onSelect(family);+ }+ });+ openMenu();+ menu.element.querySelector<HTMLInputElement>('[data-type="font-family-search"]')?.focus();++ },});- openMenu();- menu.element.querySelector<HTMLInputElement>('[data-type="font-family-search"]')?.focus();};let mobileRequestID = 0;diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex 3940c78c40..a33da655ac 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {Divider} from "./Divider";import {BlockType, updateBlockTypeButton} from "./BlockType";import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";@@ -2460,6 +2461,7 @@ export class Toolbar {} else {try {const text = await readClipboard();+paste(protyle, Object.assign(text, {target: nodeElement as HTMLElement}));} catch (e) {console.log(e);@@ -2493,16 +2495,21 @@ export class Toolbar {this.subElement.lastElementChild.innerHTML = html;setContentPosition();} else if (action === "plugin") {- window.siyuan.menus.menu.remove();- pluginMenus.forEach(item => window.siyuan.menus.menu.addItem({...item, index: undefined}));- const triggerRect = btnElemen.getBoundingClientRect();- const selectionRect = this.range.getBoundingClientRect();- window.siyuan.menus.menu.popup({- x: triggerRect.left,- y: selectionRect.bottom + 8,- h: selectionRect.height + 8,+ await toggleMenu({+ target: btnElemen,+ build: (_menu, session) => {+ pluginMenus.forEach(item => window.siyuan.menus.menu.addItem({...item, index: undefined}));+ const triggerRect = btnElemen.getBoundingClientRect();+ const selectionRect = this.range.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({+ x: triggerRect.left,+ y: selectionRect.bottom + 8,+ h: selectionRect.height + 8,+ }));+ this.subElement.classList.add("fn__none");++ },});- this.subElement.classList.add("fn__none");} else if (action === "more") {this.subElement.lastElementChild.innerHTML = `<button class="keyboard__action${hasCopy ? "" : " fn__none"}" data-action="copyPlainText"><span>${window.siyuan.languages.copyPlainText}</span></button><div class="keyboard__split${hasCopy ? "" : " fn__none"}"></div>diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.tsindex dea1faa348..3afd3cfaca 100644--- a/app/src/protyle/toolbar/util.ts+++ b/app/src/protyle/toolbar/util.ts@@ -222,7 +222,7 @@ export const toolbarKeyToMenu = (toolbar: Array<string | IMenuItem>) => {const editor = protyle.protyle;const range = editor.toolbar.range?.cloneRange();if (range && !range.collapsed) {- AIActions([], editor, range);+ AIActions([], editor, range, editor.toolbar.element.querySelector('[data-type="ai"]'));}},}, {diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.tsindex 1e58564494..b57e22df5b 100644--- a/app/src/protyle/util/tableControl.ts+++ b/app/src/protyle/util/tableControl.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {MenuItem} from "../../menus/Menu";import {getTableGridRect, TableGridCache} from "./tableGridCache";import {getVirtualTableGrid, setTableVirtualSelection, TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";@@ -883,7 +884,7 @@ export class TableControl {if (!isPrimaryModifier(event) && !event.shiftKey) {const handle = type === "row" ? this.rowHandle : this.columnHandle;const rect = handle.getBoundingClientRect();- this.openMenu(rect.right, rect.bottom);+ this.openMenu(rect.right, rect.bottom, handle);}return;}@@ -892,7 +893,7 @@ export class TableControl {}if (!isPrimaryModifier(event) && !event.shiftKey) {const rect = this.cellHandle.getBoundingClientRect();- this.openMenu(rect.right, rect.bottom);+ this.openMenu(rect.right, rect.bottom, this.cellHandle);}}@@ -1505,140 +1506,147 @@ export class TableControl {}}- private openMenu(x: number, y: number) {- if (!this.selection) {- return;- }- const menu = window.siyuan.menus.menu;- menu.remove();- menu.element.setAttribute("data-name", `table-${this.selection.mode}`);- const merged = buildTableGrid(this.selection.table).cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);- const mergedSelection = this.selection.mode !== "cell" && merged;- const rectangle = this.selection.mode !== "cell" || this.isRectangle();- menu.append(new MenuItem({- icon: "iconCopy",- label: window.siyuan.languages.copy,- disabled: !rectangle,- accelerator: rectangle ? undefined : window.siyuan.languages.tableRectangleSelectionRequired,- click: () => this.execClipboardCommand("copy"),- }).element);- if (this.selection.mode === "cell" && rectangle && this.getSelectedCells().length > 1) {- menu.append(new MenuItem({- id: "copyRichText",- label: window.siyuan.languages.copyRichText,- accelerator: window.siyuan.config.keymap.editor.general.copyRichText.custom,- click: () => this.copySelectionAsRichText(),- }).element);- menu.append(new MenuItem({- id: "copyPlainText",- label: window.siyuan.languages.copyPlainText,- click: () => {- const content = this.getSelectionClipboardContent();- if (content) {- copyPlainText(content.text);- }- },- }).element);- }- menu.append(new MenuItem({- icon: "iconCut",- label: window.siyuan.languages.cut,- disabled: this.protyle.disabled || !rectangle || mergedSelection,- accelerator: !rectangle ? window.siyuan.languages.tableRectangleSelectionRequired : undefined,- action: mergedSelection ? "iconInfo" : undefined,- actionLabel: mergedSelection ? window.siyuan.languages.splitMergedCellTip : undefined,- click: () => this.execClipboardCommand("cut"),- }).element);- if (!this.protyle.disabled && this.selection.mode === "cell") {- menu.append(new MenuItem({- icon: "iconPaste",- label: window.siyuan.languages.paste,- click: () => this.paste(),- }).element);- menu.append(new MenuItem({- icon: "iconClear",- label: window.siyuan.languages.clear,- warning: true,- click: () => this.clearCells(),- }).element);- }- if (!this.protyle.disabled) {- menu.append(new MenuItem({type: "separator"}).element);- this.appendInsertMenus();- if (this.selection.mode !== "cell") {+ private openMenu(x: number, y: number, target?: Element) {+ toggleMenu({+ target: target,+ toggle: Boolean(target),+ build: (_menu, session) => {+ if (!this.selection) {+ return;+ }+ const menu = window.siyuan.menus.menu;++ menu.element.setAttribute("data-name", `table-${this.selection.mode}`);+ const merged = buildTableGrid(this.selection.table).cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);+ const mergedSelection = this.selection.mode !== "cell" && merged;+ const rectangle = this.selection.mode !== "cell" || this.isRectangle();menu.append(new MenuItem({icon: "iconCopy",- label: window.siyuan.languages.duplicateCopy,- disabled: merged,- action: merged ? "iconInfo" : undefined,- actionLabel: merged ? window.siyuan.languages.splitMergedCellTip : undefined,- click: () => this.duplicateRowsOrColumns(),+ label: window.siyuan.languages.copy,+ disabled: !rectangle,+ accelerator: rectangle ? undefined : window.siyuan.languages.tableRectangleSelectionRequired,+ click: () => this.execClipboardCommand("copy"),}).element);- if (this.selection.indexes.size === 1 && this.selection.indexes.has(0)) {- const headerType = this.selection.mode === "row" ? "row" : "column";+ if (this.selection.mode === "cell" && rectangle && this.getSelectedCells().length > 1) {+ menu.append(new MenuItem({+ id: "copyRichText",+ label: window.siyuan.languages.copyRichText,+ accelerator: window.siyuan.config.keymap.editor.general.copyRichText.custom,+ click: () => this.copySelectionAsRichText(),+ }).element);menu.append(new MenuItem({- id: headerType === "row" ? "tableHeaderRow" : "tableHeaderColumn",- label: headerType === "row" ? window.siyuan.languages.tableHeaderRow :- window.siyuan.languages.tableHeaderColumn,- checked: isTableHeaderEnabled(this.selection.node, headerType),- click: () => toggleTableHeader(this.protyle, this.selection.node, headerType),+ id: "copyPlainText",+ label: window.siyuan.languages.copyPlainText,+ click: () => {+ const content = this.getSelectionClipboardContent();+ if (content) {+ copyPlainText(content.text);+ }+ },}).element);}- if (this.selection.mode === "column") {- const columns = this.getSelectedColumns();+ menu.append(new MenuItem({+ icon: "iconCut",+ label: window.siyuan.languages.cut,+ disabled: this.protyle.disabled || !rectangle || mergedSelection,+ accelerator: !rectangle ? window.siyuan.languages.tableRectangleSelectionRequired : undefined,+ action: mergedSelection ? "iconInfo" : undefined,+ actionLabel: mergedSelection ? window.siyuan.languages.splitMergedCellTip : undefined,+ click: () => this.execClipboardCommand("cut"),+ }).element);+ if (!this.protyle.disabled && this.selection.mode === "cell") {menu.append(new MenuItem({- id: "autoFitColWidth",- icon: "iconWidth",- label: window.siyuan.languages.autoFitColWidth,- click: () => this.setSelectedColumnWidth(),+ icon: "iconPaste",+ label: window.siyuan.languages.paste,+ click: () => this.paste(),}).element);menu.append(new MenuItem({- id: "distributeSelectedColWidths",- icon: "iconScale",- label: window.siyuan.languages.distributeSelectedColWidths,- disabled: columns.length < 2,- click: () => this.distributeSelectedColumnWidths(),+ icon: "iconClear",+ label: window.siyuan.languages.clear,+ warning: true,+ click: () => this.clearCells(),+ }).element);+ }+ if (!this.protyle.disabled) {+ menu.append(new MenuItem({type: "separator"}).element);+ this.appendInsertMenus();+ if (this.selection.mode !== "cell") {+ menu.append(new MenuItem({+ icon: "iconCopy",+ label: window.siyuan.languages.duplicateCopy,+ disabled: merged,+ action: merged ? "iconInfo" : undefined,+ actionLabel: merged ? window.siyuan.languages.splitMergedCellTip : undefined,+ click: () => this.duplicateRowsOrColumns(),+ }).element);+ if (this.selection.indexes.size === 1 && this.selection.indexes.has(0)) {+ const headerType = this.selection.mode === "row" ? "row" : "column";+ menu.append(new MenuItem({+ id: headerType === "row" ? "tableHeaderRow" : "tableHeaderColumn",+ label: headerType === "row" ? window.siyuan.languages.tableHeaderRow :+ window.siyuan.languages.tableHeaderColumn,+ checked: isTableHeaderEnabled(this.selection.node, headerType),+ click: () => toggleTableHeader(this.protyle, this.selection.node, headerType),+ }).element);+ }+ if (this.selection.mode === "column") {+ const columns = this.getSelectedColumns();+ menu.append(new MenuItem({+ id: "autoFitColWidth",+ icon: "iconWidth",+ label: window.siyuan.languages.autoFitColWidth,+ click: () => this.setSelectedColumnWidth(),+ }).element);+ menu.append(new MenuItem({+ id: "distributeSelectedColWidths",+ icon: "iconScale",+ label: window.siyuan.languages.distributeSelectedColWidths,+ disabled: columns.length < 2,+ click: () => this.distributeSelectedColumnWidths(),+ }).element);+ menu.append(new MenuItem({+ id: "useDefaultWidth",+ label: window.siyuan.languages.useDefaultWidth,+ disabled: columns.length === 0 || columns.every(column =>+ isDefaultTableColumnWidth(column.style.width, column.style.minWidth)),+ click: () => this.setSelectedColumnWidth(TABLE_DEFAULT_COLUMN_WIDTH),+ }).element);+ }+ menu.append(new MenuItem({type: "separator"}).element);+ }+ menu.append(new MenuItem({+ icon: "iconFont",+ label: window.siyuan.languages.fontStyle,+ submenu: getTableCellTextStyleMenus(this.protyle, this.getSelectedCells(), () => this.scheduleRender()),}).element);menu.append(new MenuItem({- id: "useDefaultWidth",- label: window.siyuan.languages.useDefaultWidth,- disabled: columns.length === 0 || columns.every(column =>- isDefaultTableColumnWidth(column.style.width, column.style.minWidth)),- click: () => this.setSelectedColumnWidth(TABLE_DEFAULT_COLUMN_WIDTH),+ icon: "iconTheme",+ label: window.siyuan.languages.colorPrimary,+ submenu: this.getBackgroundMenus(),}).element);+ if (this.selection.mode === "cell") {+ this.appendCellMenus(rectangle);+ } else {+ this.appendAlignmentMenu();+ menu.append(new MenuItem({type: "separator"}).element);+ menu.append(new MenuItem({+ icon: "iconClear",+ label: window.siyuan.languages.clear,+ warning: true,+ click: () => this.clearCells(),+ }).element);+ menu.append(new MenuItem({+ icon: "iconTrashcan",+ label: this.selection.mode === "row" ? window.siyuan.languages["delete-row"] :+ window.siyuan.languages["delete-column"],+ click: () => this.deleteSelection(false),+ }).element);+ }}- menu.append(new MenuItem({type: "separator"}).element);- }- menu.append(new MenuItem({- icon: "iconFont",- label: window.siyuan.languages.fontStyle,- submenu: getTableCellTextStyleMenus(this.protyle, this.getSelectedCells(), () => this.scheduleRender()),- }).element);- menu.append(new MenuItem({- icon: "iconTheme",- label: window.siyuan.languages.colorPrimary,- submenu: this.getBackgroundMenus(),- }).element);- if (this.selection.mode === "cell") {- this.appendCellMenus(rectangle);- } else {- this.appendAlignmentMenu();- menu.append(new MenuItem({type: "separator"}).element);- menu.append(new MenuItem({- icon: "iconClear",- label: window.siyuan.languages.clear,- warning: true,- click: () => this.clearCells(),- }).element);- menu.append(new MenuItem({- icon: "iconTrashcan",- label: this.selection.mode === "row" ? window.siyuan.languages["delete-row"] :- window.siyuan.languages["delete-column"],- click: () => this.deleteSelection(false),- }).element);- }- }- menu.popup({x, y});+ session.show(() => menu.popup({x, y}));++ },+ });}private appendInsertMenus() {diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 0aa16937bd..bd1dbfa93c 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {recordReplacementUndo} from "./replacementInput";import {expandAndroidWordSelection, isAndroidWordSelectionPending} from "../../mobile/util/wordSelection";import {bindBoundedBlockDragSelect} from "./boundedBlockDragSelect";@@ -5186,23 +5187,29 @@ export class WYSIWYG {const menuElement = hasClosestByClassName(event.target, "protyle-action__menu");if (menuElement) {- if (!protyle.gutter) {- event.stopPropagation();- event.preventDefault();- return;- }- protyle.gutter.renderMenu(protyle, menuElement.parentElement.parentElement);- /// #if MOBILE- window.siyuan.menus.menu.fullscreen();- /// #else- const rect = menuElement.getBoundingClientRect();- window.siyuan.menus.menu.popup({- x: rect.left,- y: rect.top,- isLeft: true+ toggleMenu({+ target: menuElement,+ build: (_menu, session) => {+ if (!protyle.gutter) {+ event.stopPropagation();+ event.preventDefault();+ return;+ }+ protyle.gutter.renderMenu(protyle, menuElement.parentElement.parentElement);+ /// #if MOBILE+ session.show(() => window.siyuan.menus.menu.fullscreen());+ /// #else+ const rect = menuElement.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({+ x: rect.left,+ y: rect.top,+ isLeft: true+ }));+ /// #endif++ },});- /// #endif- event.stopPropagation();+ event.stopPropagation();event.preventDefault();return;}@@ -5460,7 +5467,7 @@ export class WYSIWYG {}// https://github.com/siyuan-note/siyuan/issues/14481const inlineMathElement = hasClosestByAttribute(newRange.startContainer, "data-type", "inline-math");- if (inlineMathElement) {+ if (newRange.collapsed && inlineMathElement) {newRange.setEndAfter(inlineMathElement);newRange.collapse(false);focusByRange(newRange);diff --git a/app/src/protyle/wysiwyg/tabs.ts b/app/src/protyle/wysiwyg/tabs.tsindex bc308c9af6..408dd3e781 100644--- a/app/src/protyle/wysiwyg/tabs.ts+++ b/app/src/protyle/wysiwyg/tabs.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../../menus/menuToggle";import {getTabContent, getTabItems, getTabTask, getTabTitle, getTabTitleBlock, hasTabsTasks, revealTabAncestors, tabsRender} from "../render/tabsRender";import {repairActiveTab} from "./tabsRemoval";import {transaction} from "./transaction";@@ -158,53 +159,64 @@ export const setTabsPosition = (protyle: IProtyle, tabs: HTMLElement, position:}};-export const openTabsMenu = (protyle: IProtyle, tabs: HTMLElement, item: HTMLElement, anchor: HTMLElement) => {- if (!item) {- return;- }- const lang = window.siyuan.languages;- const menu = new Menu();- menu.addItem({icon: "iconCopy", label: lang.copy, submenu: copySubMenu([item.dataset.nodeId], false)});- if (canFocusTabItem(protyle, item)) {- menu.addItem({icon: "iconEnter", label: lang.enter, click: () => zoomOut({protyle, id: item.dataset.nodeId})});- }- if (canEdit(protyle, tabs)) {- if (getTabTask(item) !== null) {- menu.addSeparator({id: "separator_taskStatusBefore"});- getTaskStatusItems(getTabTask(item), marker => setTabTask(protyle, item, marker))- .forEach(option => menu.addItem(option));- menu.addSeparator({id: "separator_taskStatus"});- }- menu.addItem({icon: "iconEdit", label: lang.rename, click: () => renameTab(protyle, item)});- }- if (canEdit(protyle, tabs) && tabs.classList.contains("tabs")) {- menu.addItem({icon: "iconCopy", label: lang.duplicateCopy, click: () => {- const copy = item.cloneNode(true) as HTMLElement;- const ids = new Map<string, string>();- [copy, ...Array.from(copy.querySelectorAll<HTMLElement>("[data-node-id]"))].forEach(block => {- const id = Lute.NewNodeID();- ids.set(block.dataset.nodeId, id);- block.dataset.nodeId = id;- block.setAttribute("updated", id.substring(0, 14));- });- remapTabsDOMIDs(copy, ids);- remapListMindmapIDs(copy, ids);- changeTabs(protyle, [tabs], () => {- item.after(copy);- tabs.setAttribute("tabs-active-id", copy.dataset.nodeId);- });- }});- menu.addItem({icon: "iconTrashcan", label: lang.delete, click: () => {- const ids = getTabItems(tabs).map(entry => entry.dataset.nodeId);- changeTabs(protyle, [tabs], () => {- item.remove();- repairActiveTab(tabs, ids, item.dataset.nodeId);- });- focusBlock(tabs);- }});- }- const rect = anchor.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height});+export const openTabsMenu = (protyle: IProtyle, tabs: HTMLElement, item: HTMLElement, anchor: HTMLElement, toggle = true) => {+ toggleMenu({+ target: anchor,+ toggle,+ build: (_menu, session) => {+ if (!item) {+ return;+ }+ const lang = window.siyuan.languages;+ const menu = new Menu();+ menu.addItem({icon: "iconCopy", label: lang.copy, submenu: copySubMenu([item.dataset.nodeId], false)});+ if (canFocusTabItem(protyle, item)) {+ menu.addItem({icon: "iconEnter", label: lang.enter, click: () => zoomOut({protyle, id: item.dataset.nodeId})});+ }+ if (canEdit(protyle, tabs)) {+ if (getTabTask(item) !== null) {+ menu.addSeparator({id: "separator_taskStatusBefore"});+ getTaskStatusItems(getTabTask(item), marker => setTabTask(protyle, item, marker))+ .forEach(option => menu.addItem(option));+ menu.addSeparator({id: "separator_taskStatus"});+ }+ menu.addItem({icon: "iconEdit", label: lang.rename, click: () => renameTab(protyle, item)});+ }+ if (canEdit(protyle, tabs) && tabs.classList.contains("tabs")) {+ menu.addItem({+ icon: "iconCopy", label: lang.duplicateCopy, click: () => {+ const copy = item.cloneNode(true) as HTMLElement;+ const ids = new Map<string, string>();+ [copy, ...Array.from(copy.querySelectorAll<HTMLElement>("[data-node-id]"))].forEach(block => {+ const id = Lute.NewNodeID();+ ids.set(block.dataset.nodeId, id);+ block.dataset.nodeId = id;+ block.setAttribute("updated", id.substring(0, 14));+ });+ remapTabsDOMIDs(copy, ids);+ remapListMindmapIDs(copy, ids);+ changeTabs(protyle, [tabs], () => {+ item.after(copy);+ tabs.setAttribute("tabs-active-id", copy.dataset.nodeId);+ });+ }+ });+ menu.addItem({+ icon: "iconTrashcan", label: lang.delete, click: () => {+ const ids = getTabItems(tabs).map(entry => entry.dataset.nodeId);+ changeTabs(protyle, [tabs], () => {+ item.remove();+ repairActiveTab(tabs, ids, item.dataset.nodeId);+ });+ focusBlock(tabs);+ }+ });+ }+ const rect = anchor.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height}));++ },+ });};export const initEditorTabs = (protyle: IProtyle) => {@@ -221,7 +233,7 @@ export const initEditorTabs = (protyle: IProtyle) => {if (item?.parentElement === root && info?.parentElement === item) {event.preventDefault();event.stopPropagation();- openTabsMenu(protyle, item, item, info as HTMLElement);+ openTabsMenu(protyle, item, item, info as HTMLElement, false);}}, true);}diff --git a/app/src/search/assets.ts b/app/src/search/assets.tsindex 3274120f30..c5257579ed 100644--- a/app/src/search/assets.ts+++ b/app/src/search/assets.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {Constants} from "../constants";import {fetchPost} from "../util/fetch";import {setStorageVal, updateHotkeyTip} from "../protyle/util/compatibility";@@ -266,47 +267,49 @@ export const renderNextAssetMark = (element: Element) => {};export const assetMethodMenu = (target: HTMLElement, cb: () => void) => {- const method = window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method;- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_SEARCH_ASSET_METHOD) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_SEARCH_ASSET_METHOD);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconExact",- label: window.siyuan.languages.keyword,- current: method === 0,- click() {- window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method = 0;- cb();- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconQuote",- label: window.siyuan.languages.querySyntax,- current: method === 1,- click() {- window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method = 1;- cb();- }- }).element);- window.siyuan.menus.menu.append(new MenuItem({- icon: "iconRegex",- label: window.siyuan.languages.regex,- current: method === 3,- click() {- window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method = 3;- cb();- }- }).element);- /// #if MOBILE- window.siyuan.menus.menu.fullscreen();- /// #else- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- /// #endif+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ const method = window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method;+++ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_SEARCH_ASSET_METHOD);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconExact",+ label: window.siyuan.languages.keyword,+ current: method === 0,+ click() {+ window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method = 0;+ cb();+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconQuote",+ label: window.siyuan.languages.querySyntax,+ current: method === 1,+ click() {+ window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method = 1;+ cb();+ }+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconRegex",+ label: window.siyuan.languages.regex,+ current: method === 3,+ click() {+ window.siyuan.storage[Constants.LOCAL_SEARCHASSET].method = 3;+ cb();+ }+ }).element);+ /// #if MOBILE+ session.show(() => window.siyuan.menus.menu.fullscreen());+ /// #else+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));+ /// #endif++ },+ });};const filterTypesHTML = (types: IObject) => {@@ -353,111 +356,111 @@ export const assetFilterMenu = (assetsElement: Element) => {};export const assetMoreMenu = (target: Element, element: Element, cb: () => void) => {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&- window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_SEARCH_ASSET_MORE) {- window.siyuan.menus.menu.remove();- return;- }- window.siyuan.menus.menu.remove();- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_SEARCH_ASSET_MORE);- const localData = window.siyuan.storage[Constants.LOCAL_SEARCHASSET];- const sortMenu = [{- iconHTML: "",- label: window.siyuan.languages.sortByRankAsc,- current: localData.sort === 1,- click() {- localData.sort = 1;- cb();- }- }, {- iconHTML: "",- label: window.siyuan.languages.sortByRankDesc,- current: localData.sort === 0,- click() {- localData.sort = 0;- cb();- }- }, {- iconHTML: "",- label: window.siyuan.languages.modifiedASC,- current: localData.sort === 3,- click() {- localData.sort = 3;- cb();- }- }, {- iconHTML: "",- label: window.siyuan.languages.modifiedDESC,- current: localData.sort === 2,- click() {- localData.sort = 2;- cb();- }- }];- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: window.siyuan.languages.sort,- type: "submenu",- submenu: sortMenu,- }).element);- /// #if !MOBILE- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: window.siyuan.languages.layout,- type: "submenu",- submenu: [{- iconHTML: "",- label: window.siyuan.languages.topBottomLayout,- current: localData.layout === 0,- click() {- element.querySelector(".search__layout").classList.remove("search__layout--row");- const previewElement = element.querySelector("#searchAssetPreview") as HTMLElement;- previewElement.style.width = "";- if (localData.row) {- previewElement.style.height = localData.row;- previewElement.classList.remove("fn__flex-1");- } else {- previewElement.classList.add("fn__flex-1");+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_SEARCH_ASSET_MORE);+ const localData = window.siyuan.storage[Constants.LOCAL_SEARCHASSET];+ const sortMenu = [{+ iconHTML: "",+ label: window.siyuan.languages.sortByRankAsc,+ current: localData.sort === 1,+ click() {+ localData.sort = 1;+ cb();}- localData.layout = 0;- setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);- }- }, {- iconHTML: "",- label: window.siyuan.languages.leftRightLayout,- current: localData.layout === 1,- click() {- const previewElement = element.querySelector("#searchAssetPreview") as HTMLElement;- element.querySelector(".search__layout").classList.add("search__layout--row");- previewElement.style.height = "";- if (localData.col) {- previewElement.style.width = localData.col;- previewElement.classList.remove("fn__flex-1");- } else {- previewElement.classList.add("fn__flex-1");+ }, {+ iconHTML: "",+ label: window.siyuan.languages.sortByRankDesc,+ current: localData.sort === 0,+ click() {+ localData.sort = 0;+ cb();}- localData.layout = 1;- setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);- }- }]- }).element);- /// #endif- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: window.siyuan.languages.rebuildAssetContentIndex,- click() {- const loadingElement = element.parentElement.querySelector(".fn__loading") as HTMLElement;- loadingElement.classList.remove("fn__none");- loadingElement.style.top = "84px";- fetchPost("/api/asset/fullReindexAssetContent", {}, () => {- assetInputEvent(element, localData);- });+ }, {+ iconHTML: "",+ label: window.siyuan.languages.modifiedASC,+ current: localData.sort === 3,+ click() {+ localData.sort = 3;+ cb();+ }+ }, {+ iconHTML: "",+ label: window.siyuan.languages.modifiedDESC,+ current: localData.sort === 2,+ click() {+ localData.sort = 2;+ cb();+ }+ }];+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: window.siyuan.languages.sort,+ type: "submenu",+ submenu: sortMenu,+ }).element);+ /// #if !MOBILE+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: window.siyuan.languages.layout,+ type: "submenu",+ submenu: [{+ iconHTML: "",+ label: window.siyuan.languages.topBottomLayout,+ current: localData.layout === 0,+ click() {+ element.querySelector(".search__layout").classList.remove("search__layout--row");+ const previewElement = element.querySelector("#searchAssetPreview") as HTMLElement;+ previewElement.style.width = "";+ if (localData.row) {+ previewElement.style.height = localData.row;+ previewElement.classList.remove("fn__flex-1");+ } else {+ previewElement.classList.add("fn__flex-1");+ }+ localData.layout = 0;+ setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);+ }+ }, {+ iconHTML: "",+ label: window.siyuan.languages.leftRightLayout,+ current: localData.layout === 1,+ click() {+ const previewElement = element.querySelector("#searchAssetPreview") as HTMLElement;+ element.querySelector(".search__layout").classList.add("search__layout--row");+ previewElement.style.height = "";+ if (localData.col) {+ previewElement.style.width = localData.col;+ previewElement.classList.remove("fn__flex-1");+ } else {+ previewElement.classList.add("fn__flex-1");+ }+ localData.layout = 1;+ setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);+ }+ }]+ }).element);+ /// #endif+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: window.siyuan.languages.rebuildAssetContentIndex,+ click() {+ const loadingElement = element.parentElement.querySelector(".fn__loading") as HTMLElement;+ loadingElement.classList.remove("fn__none");+ loadingElement.style.top = "84px";+ fetchPost("/api/asset/fullReindexAssetContent", {}, () => {+ assetInputEvent(element, localData);+ });+ },+ }).element);+ /// #if MOBILE+ session.show(() => window.siyuan.menus.menu.fullscreen());+ /// #else+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));+ /// #endif+},- }).element);- /// #if MOBILE- window.siyuan.menus.menu.fullscreen();- /// #else- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- /// #endif+ });};diff --git a/app/src/search/toggleHistory.ts b/app/src/search/toggleHistory.tsindex 1031978ca1..9d8e2ecdd0 100644--- a/app/src/search/toggleHistory.ts+++ b/app/src/search/toggleHistory.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {Constants} from "../constants";import {Menu} from "../plugin/Menu";import {isSensitiveSearchConfig, setStorageVal} from "../protyle/util/compatibility";@@ -12,220 +13,238 @@ import {inputEvent} from "./util";/// #endifexport const toggleReplaceHistory = (replaceInputElement: HTMLInputElement) => {- const list = window.siyuan.storage[Constants.LOCAL_SEARCHKEYS];- if (!list.replaceKeys || list.replaceKeys.length === 0 || (list.replaceKeys.length === 1 && list.replaceKeys[0] === replaceInputElement.value)) {- return;- }- const menu = new Menu(Constants.MENU_SEARCH_REPLACE_HISTORY);- if (menu.isOpen) {- return;- }- menu.element.classList.add("b3-menu--list");- menu.addItem({- iconHTML: "",- label: window.siyuan.languages.clearHistory,- click() {- window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].replaceKeys = [];- setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);- }- });- const separatorElement = menu.addSeparator(1);- let current = true;- list.replaceKeys.forEach((s: string) => {- if (s !== replaceInputElement.value && s) {- const menuItem = menu.addItem({+ toggleMenu({+ target: replaceInputElement.previousElementSibling,+ build: (_menu, session) => {+ const list = window.siyuan.storage[Constants.LOCAL_SEARCHKEYS];+ if (!list.replaceKeys || list.replaceKeys.length === 0 || (list.replaceKeys.length === 1 && list.replaceKeys[0] === replaceInputElement.value)) {+ return;+ }+ const menu = new Menu(Constants.MENU_SEARCH_REPLACE_HISTORY);+ if (menu.isOpen) {+ return;+ }+ menu.element.classList.add("b3-menu--list");+ menu.addItem({iconHTML: "",- label: escapeHtml(s),- action: "iconCloseRound",- bind(element) {- element.addEventListener("click", (itemEvent) => {- if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {- list.replaceKeys.find((item: string, index: number) => {- if (item === s) {- list.replaceKeys.splice(index, 1);- return true;+ label: window.siyuan.languages.clearHistory,+ click() {+ window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].replaceKeys = [];+ setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);+ }+ });+ const separatorElement = menu.addSeparator(1);+ let current = true;+ list.replaceKeys.forEach((s: string) => {+ if (s !== replaceInputElement.value && s) {+ const menuItem = menu.addItem({+ iconHTML: "",+ label: escapeHtml(s),+ action: "iconCloseRound",+ bind(element) {+ element.addEventListener("click", (itemEvent) => {+ if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {+ list.replaceKeys.find((item: string, index: number) => {+ if (item === s) {+ list.replaceKeys.splice(index, 1);+ return true;+ }+ });+ window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].replaceKeys = list.replaceKeys;+ setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);+ if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {+ window.siyuan.menus.menu.remove();+ } else {+ element.remove();+ }+ } else {+ replaceInputElement.value = element.textContent;+ replaceInputElement.dispatchEvent(new Event("change"));+ window.siyuan.menus.menu.remove();}+ itemEvent.preventDefault();+ itemEvent.stopPropagation();});- window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].replaceKeys = list.replaceKeys;- setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);- if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {- window.siyuan.menus.menu.remove();- } else {- element.remove();- }- } else {- replaceInputElement.value = element.textContent;- replaceInputElement.dispatchEvent(new Event("change"));- window.siyuan.menus.menu.remove();}- itemEvent.preventDefault();- itemEvent.stopPropagation();});+ if (current) {+ menuItem.classList.add("b3-menu__item--current");+ }+ current = false;}});if (current) {- menuItem.classList.add("b3-menu__item--current");+ separatorElement.remove();}- current = false;- }- });- if (current) {- separatorElement.remove();- }- const rect = replaceInputElement.previousElementSibling.getBoundingClientRect();- menu.open({- x: rect.left,- y: rect.bottom,- h: rect.height+ const rect = replaceInputElement.previousElementSibling.getBoundingClientRect();+ session.show(() => menu.open({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));++ },});};export const toggleSearchHistory = (searchElement: Element, config: Config.IUILayoutTabSearchConfig, edit: Protyle,requestElement = searchElement) => {- const searchInputElement = searchElement.querySelector("#searchInput, #toolbarSearch") as HTMLInputElement;- const list = window.siyuan.storage[Constants.LOCAL_SEARCHKEYS];- if (!list.keys || list.keys.length === 0) {- return;- }- const menu = new Menu(Constants.MENU_SEARCH_HISTORY);- if (menu.isOpen) {- return;- }- menu.element.classList.add("b3-menu--list");- menu.addItem({- iconHTML: "",- label: window.siyuan.languages.clearHistory,- click() {- window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].keys = [];- setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);- }- });- const separatorElement = menu.addSeparator(1);- let current = true;- list.keys.forEach((s: string) => {- if (s) {- const menuItem = menu.addItem({+ toggleMenu({+ target: searchElement.querySelector("#searchInput, #toolbarSearch").previousElementSibling,+ build: (_menu, session) => {+ const searchInputElement = searchElement.querySelector("#searchInput, #toolbarSearch") as HTMLInputElement;+ const list = window.siyuan.storage[Constants.LOCAL_SEARCHKEYS];+ if (!list.keys || list.keys.length === 0) {+ return;+ }+ const menu = new Menu(Constants.MENU_SEARCH_HISTORY);+ if (menu.isOpen) {+ return;+ }+ menu.element.classList.add("b3-menu--list");+ menu.addItem({iconHTML: "",- label: escapeHtml(s),- action: "iconCloseRound",- bind(element) {- element.addEventListener("click", (itemEvent) => {- if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {- list.keys.find((item: string, index: number) => {- if (item === s) {- list.keys.splice(index, 1);- return true;+ label: window.siyuan.languages.clearHistory,+ click() {+ window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].keys = [];+ setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);+ }+ });+ const separatorElement = menu.addSeparator(1);+ let current = true;+ list.keys.forEach((s: string) => {+ if (s) {+ const menuItem = menu.addItem({+ iconHTML: "",+ label: escapeHtml(s),+ action: "iconCloseRound",+ bind(element) {+ element.addEventListener("click", (itemEvent) => {+ if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {+ list.keys.find((item: string, index: number) => {+ if (item === s) {+ list.keys.splice(index, 1);+ return true;+ }+ });+ window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].keys = list.keys;+ setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);+ if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {+ window.siyuan.menus.menu.remove();+ } else {+ element.remove();+ }+ } else {+ searchInputElement.value = s;+ searchInputElement.dispatchEvent(new Event("change"));+ saveKeyList("keys", s, config);+ config.page = 1;+ /// #if MOBILE+ updateSearchResult(config, requestElement, true);+ /// #else+ inputEvent(searchElement, config, edit, true);+ /// #endif+ window.siyuan.menus.menu.remove();}+ itemEvent.preventDefault();+ itemEvent.stopPropagation();});- window.siyuan.storage[Constants.LOCAL_SEARCHKEYS].keys = list.keys;- setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);- if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {- window.siyuan.menus.menu.remove();- } else {- element.remove();- }- } else {- searchInputElement.value = s;- searchInputElement.dispatchEvent(new Event("change"));- saveKeyList("keys", s, config);- config.page = 1;- /// #if MOBILE- updateSearchResult(config, requestElement, true);- /// #else- inputEvent(searchElement, config, edit, true);- /// #endif- window.siyuan.menus.menu.remove();}- itemEvent.preventDefault();- itemEvent.stopPropagation();});+ if (current) {+ menuItem.classList.add("b3-menu__item--current");+ }+ current = false;}});if (current) {- menuItem.classList.add("b3-menu__item--current");+ separatorElement.remove();}- current = false;- }- });- if (current) {- separatorElement.remove();- }- const rect = searchInputElement.previousElementSibling.getBoundingClientRect();- menu.open({- x: rect.left,- y: rect.bottom,- h: rect.height+ const rect = searchInputElement.previousElementSibling.getBoundingClientRect();+ session.show(() => menu.open({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));++ },});-};+ };export const toggleAssetHistory = (assetElement: Element) => {- const assetInputElement = assetElement.querySelector("#searchAssetInput") as HTMLInputElement;- const keys = window.siyuan.storage[Constants.LOCAL_SEARCHASSET].keys;- if (!keys || keys.length === 0 || (keys.length === 1 && keys[0] === assetInputElement.value)) {- return;- }- const menu = new Menu(Constants.MENU_SEARCH_ASSET_HISTORY);- if (menu.isOpen) {- return;- }- menu.element.classList.add("b3-menu--list");- menu.addItem({- iconHTML: "",- label: window.siyuan.languages.clearHistory,- click() {- window.siyuan.storage[Constants.LOCAL_SEARCHASSET].keys = [];- setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);- }- });- const separatorElement = menu.addSeparator(1);- let current = true;- keys.forEach((s: string) => {- if (s !== assetInputElement.value && s) {- const menuItem = menu.addItem({+ toggleMenu({+ target: assetElement.querySelector("#searchAssetInput").previousElementSibling,+ build: (_menu, session) => {+ const assetInputElement = assetElement.querySelector("#searchAssetInput") as HTMLInputElement;+ const keys = window.siyuan.storage[Constants.LOCAL_SEARCHASSET].keys;+ if (!keys || keys.length === 0 || (keys.length === 1 && keys[0] === assetInputElement.value)) {+ return;+ }+ const menu = new Menu(Constants.MENU_SEARCH_ASSET_HISTORY);+ if (menu.isOpen) {+ return;+ }+ menu.element.classList.add("b3-menu--list");+ menu.addItem({iconHTML: "",- label: escapeHtml(s),- action: "iconCloseRound",- bind(element) {- element.addEventListener("click", (itemEvent) => {- if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {- keys.find((item: string, index: number) => {- if (item === s) {- keys.splice(index, 1);- return true;+ label: window.siyuan.languages.clearHistory,+ click() {+ window.siyuan.storage[Constants.LOCAL_SEARCHASSET].keys = [];+ setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);+ }+ });+ const separatorElement = menu.addSeparator(1);+ let current = true;+ keys.forEach((s: string) => {+ if (s !== assetInputElement.value && s) {+ const menuItem = menu.addItem({+ iconHTML: "",+ label: escapeHtml(s),+ action: "iconCloseRound",+ bind(element) {+ element.addEventListener("click", (itemEvent) => {+ if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {+ keys.find((item: string, index: number) => {+ if (item === s) {+ keys.splice(index, 1);+ return true;+ }+ });+ window.siyuan.storage[Constants.LOCAL_SEARCHASSET].keys = keys;+ setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);+ if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {+ window.siyuan.menus.menu.remove();+ } else {+ element.remove();+ }+ } else {+ assetInputElement.value = element.textContent;+ assetInputElement.dispatchEvent(new Event("change"));+ assetInputEvent(assetElement);+ window.siyuan.menus.menu.remove();}+ itemEvent.preventDefault();+ itemEvent.stopPropagation();});- window.siyuan.storage[Constants.LOCAL_SEARCHASSET].keys = keys;- setStorageVal(Constants.LOCAL_SEARCHASSET, window.siyuan.storage[Constants.LOCAL_SEARCHASSET]);- if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {- window.siyuan.menus.menu.remove();- } else {- element.remove();- }- } else {- assetInputElement.value = element.textContent;- assetInputElement.dispatchEvent(new Event("change"));- assetInputEvent(assetElement);- window.siyuan.menus.menu.remove();}- itemEvent.preventDefault();- itemEvent.stopPropagation();});+ if (current) {+ menuItem.classList.add("b3-menu__item--current");+ }+ current = false;}});if (current) {- menuItem.classList.add("b3-menu__item--current");+ separatorElement.remove();}- current = false;- }- });- if (current) {- separatorElement.remove();- }- const rect = assetInputElement.previousElementSibling.getBoundingClientRect();- menu.open({- x: rect.left,- y: rect.bottom,- h: rect.height+ const rect = assetInputElement.previousElementSibling.getBoundingClientRect();+ session.show(() => menu.open({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));++ },});};diff --git a/app/src/search/unRef.ts b/app/src/search/unRef.tsindex 627617d5a3..14c534b79b 100644--- a/app/src/search/unRef.ts+++ b/app/src/search/unRef.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {Constants} from "../constants";import {fetchPost} from "../util/fetch";import {setStorageVal} from "../protyle/util/compatibility";@@ -136,67 +137,73 @@ ${getAttr(item)}};export const unRefMoreMenu = (target: Element, element: Element, edit: Protyle) => {- const menu = new Menu(Constants.MENU_SEARCH_UNREF_MORE);- if (menu.isOpen) {- return;- }- const localData = window.siyuan.storage[Constants.LOCAL_SEARCHUNREF];- /// #if !MOBILE- menu.addItem({- icon: "iconLayout",- label: window.siyuan.languages.layout,- type: "submenu",- submenu: [{- iconHTML: "",- label: window.siyuan.languages.topBottomLayout,- current: localData.layout === 0,- click() {- element.querySelector(".search__layout").classList.remove("search__layout--row");- edit.protyle.element.style.width = "";- if (localData.row) {- edit.protyle.element.style.height = localData.row;- edit.protyle.element.classList.remove("fn__flex-1");- } else {- edit.protyle.element.classList.add("fn__flex-1");- }- resize(edit.protyle);- localData.layout = 0;- setStorageVal(Constants.LOCAL_SEARCHUNREF, window.siyuan.storage[Constants.LOCAL_SEARCHUNREF]);- }- }, {- iconHTML: "",- label: window.siyuan.languages.leftRightLayout,- current: localData.layout === 1,- click() {- element.querySelector(".search__layout").classList.add("search__layout--row");- edit.protyle.element.style.height = "";- if (localData.col) {- edit.protyle.element.style.width = localData.col;- edit.protyle.element.classList.remove("fn__flex-1");- } else {- edit.protyle.element.classList.add("fn__flex-1");- }- resize(edit.protyle);- localData.layout = 1;- setStorageVal(Constants.LOCAL_SEARCHUNREF, window.siyuan.storage[Constants.LOCAL_SEARCHUNREF]);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ const menu = new Menu(Constants.MENU_SEARCH_UNREF_MORE);+ if (menu.isOpen) {+ return;}- }]- });- /// #endif- menu.addItem({- icon: "iconRefresh",- label: window.siyuan.languages.refresh,- click() {- const loadingElement = element.parentElement.querySelector(".fn__loading") as HTMLElement;- loadingElement.classList.remove("fn__none");- loadingElement.style.top = "42px";- getUnRefList(element, edit);+ const localData = window.siyuan.storage[Constants.LOCAL_SEARCHUNREF];+ /// #if !MOBILE+ menu.addItem({+ icon: "iconLayout",+ label: window.siyuan.languages.layout,+ type: "submenu",+ submenu: [{+ iconHTML: "",+ label: window.siyuan.languages.topBottomLayout,+ current: localData.layout === 0,+ click() {+ element.querySelector(".search__layout").classList.remove("search__layout--row");+ edit.protyle.element.style.width = "";+ if (localData.row) {+ edit.protyle.element.style.height = localData.row;+ edit.protyle.element.classList.remove("fn__flex-1");+ } else {+ edit.protyle.element.classList.add("fn__flex-1");+ }+ resize(edit.protyle);+ localData.layout = 0;+ setStorageVal(Constants.LOCAL_SEARCHUNREF, window.siyuan.storage[Constants.LOCAL_SEARCHUNREF]);+ }+ }, {+ iconHTML: "",+ label: window.siyuan.languages.leftRightLayout,+ current: localData.layout === 1,+ click() {+ element.querySelector(".search__layout").classList.add("search__layout--row");+ edit.protyle.element.style.height = "";+ if (localData.col) {+ edit.protyle.element.style.width = localData.col;+ edit.protyle.element.classList.remove("fn__flex-1");+ } else {+ edit.protyle.element.classList.add("fn__flex-1");+ }+ resize(edit.protyle);+ localData.layout = 1;+ setStorageVal(Constants.LOCAL_SEARCHUNREF, window.siyuan.storage[Constants.LOCAL_SEARCHUNREF]);+ }+ }]+ });+ /// #endif+ menu.addItem({+ icon: "iconRefresh",+ label: window.siyuan.languages.refresh,+ click() {+ const loadingElement = element.parentElement.querySelector(".fn__loading") as HTMLElement;+ loadingElement.classList.remove("fn__none");+ loadingElement.style.top = "42px";+ getUnRefList(element, edit);+ },+ });+ /// #if MOBILE+ session.show(() => menu.fullscreen());+ /// #else+ const rect = target.getBoundingClientRect();+ session.show(() => menu.open({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));+ /// #endif+},});- /// #if MOBILE- menu.fullscreen();- /// #else- const rect = target.getBoundingClientRect();- menu.open({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- /// #endif};diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex 173011e314..f300bef3c5 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import type {FileTreeGetDocRequestInput} from "../types/api";import {updateSearchMethodControls} from "./methodCapabilities";import {getAttr} from "./attrs";@@ -195,7 +196,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele<div class="block__icons"><span id="searchFilter" aria-label="${window.siyuan.languages.searchType}" class="block__icon ariaLabel" data-position="9south"><svg><use xlink:href="#iconFilter"></use></svg>- </span>+ </span><span class="fn__space"></span>${genQueryHTML(config.method, "searchSyntaxCheck")}<span class="fn__space"></span>@@ -673,81 +674,87 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleevent.preventDefault();break;} else if (target.id === "searchMore") {- moreMenu(config, criteriaData, element, () => {- config.page = 1;- inputEvent(element, config, edit, true);- }, () => {- config = updateConfig(element, {- removed: true,- sort: 0,- group: 0,- hasReplace: false,- method: 0,- hPath: "",- idPath: [],- k: "",- r: "",- page: 1,- types: getDefaultType(),- subTypes: getDefaultSubType(),- replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),- }, config, edit, {clear: true, preserveCurrentPath: true});- element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");- }, () => {- const localData = window.siyuan.storage[Constants.LOCAL_SEARCHKEYS];- const isPopover = hasClosestByClassName(element, "b3-dialog__container");- window.siyuan.menus.menu.append(new MenuItem({- iconHTML: "",- label: window.siyuan.languages.layout,- type: "submenu",- submenu: [{- iconHTML: "",- label: window.siyuan.languages.topBottomLayout,- current: isPopover ? localData.layout === 0 : localData.layoutTab === 0,- click() {- element.querySelector(".search__layout").classList.remove("search__layout--row");- edit.protyle.element.style.width = "";- if ((isPopover && localData.row) || (!isPopover && localData.rowTab)) {- edit.protyle.element.style.height = isPopover ? localData.row : localData.rowTab;- edit.protyle.element.classList.remove("fn__flex-1");- } else {- edit.protyle.element.classList.add("fn__flex-1");- }- resize(edit.protyle);- if (isPopover) {- localData.layout = 0;- } else {- localData.layoutTab = 0;- }- setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);- }- }, {- iconHTML: "",- label: window.siyuan.languages.leftRightLayout,- current: isPopover ? localData.layout === 1 : localData.layoutTab === 1,- click() {- element.querySelector(".search__layout").classList.add("search__layout--row");- edit.protyle.element.style.height = "";- if ((isPopover && localData.col) || (!isPopover && localData.colTab)) {- edit.protyle.element.style.width = isPopover ? localData.col : localData.colTab;- edit.protyle.element.classList.remove("fn__flex-1");- } else {- edit.protyle.element.classList.add("fn__flex-1");- }- resize(edit.protyle);- if (isPopover) {- localData.layout = 1;- } else {- localData.layoutTab = 1;- }- setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);- }- }]- }).element);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ moreMenu(config, criteriaData, element, () => {+ config.page = 1;+ inputEvent(element, config, edit, true);+ }, () => {+ config = updateConfig(element, {+ removed: true,+ sort: 0,+ group: 0,+ hasReplace: false,+ method: 0,+ hPath: "",+ idPath: [],+ k: "",+ r: "",+ page: 1,+ types: getDefaultType(),+ subTypes: getDefaultSubType(),+ replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),+ }, config, edit, {clear: true, preserveCurrentPath: true});+ element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");+ }, () => {+ const localData = window.siyuan.storage[Constants.LOCAL_SEARCHKEYS];+ const isPopover = hasClosestByClassName(element, "b3-dialog__container");+ window.siyuan.menus.menu.append(new MenuItem({+ iconHTML: "",+ label: window.siyuan.languages.layout,+ type: "submenu",+ submenu: [{+ iconHTML: "",+ label: window.siyuan.languages.topBottomLayout,+ current: isPopover ? localData.layout === 0 : localData.layoutTab === 0,+ click() {+ element.querySelector(".search__layout").classList.remove("search__layout--row");+ edit.protyle.element.style.width = "";+ if ((isPopover && localData.row) || (!isPopover && localData.rowTab)) {+ edit.protyle.element.style.height = isPopover ? localData.row : localData.rowTab;+ edit.protyle.element.classList.remove("fn__flex-1");+ } else {+ edit.protyle.element.classList.add("fn__flex-1");+ }+ resize(edit.protyle);+ if (isPopover) {+ localData.layout = 0;+ } else {+ localData.layoutTab = 0;+ }+ setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);+ }+ }, {+ iconHTML: "",+ label: window.siyuan.languages.leftRightLayout,+ current: isPopover ? localData.layout === 1 : localData.layoutTab === 1,+ click() {+ element.querySelector(".search__layout").classList.add("search__layout--row");+ edit.protyle.element.style.height = "";+ if ((isPopover && localData.col) || (!isPopover && localData.colTab)) {+ edit.protyle.element.style.width = isPopover ? localData.col : localData.colTab;+ edit.protyle.element.classList.remove("fn__flex-1");+ } else {+ edit.protyle.element.classList.add("fn__flex-1");+ }+ resize(edit.protyle);+ if (isPopover) {+ localData.layout = 1;+ } else {+ localData.layoutTab = 1;+ }+ setStorageVal(Constants.LOCAL_SEARCHKEYS, window.siyuan.storage[Constants.LOCAL_SEARCHKEYS]);+ }+ }]+ }).element);+ });+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },});- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ event.stopPropagation();event.preventDefault();break;} else if (target.id === "searchFilter" && !target.hasAttribute("disabled")) {@@ -810,15 +817,21 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleevent.preventDefault();break;} else if (target.id === "searchSyntaxCheck") {- queryMenu(config, () => {- element.querySelector("#searchSyntaxCheck").outerHTML = genQueryHTML(config.method, "searchSyntaxCheck");- config.page = 1;- inputEvent(element, config, edit, true);- persistSearchConfig(config);+ toggleMenu({+ target: target,+ build: (_menu, session) => {+ queryMenu(config, () => {+ element.querySelector("#searchSyntaxCheck").outerHTML = genQueryHTML(config.method, "searchSyntaxCheck");+ config.page = 1;+ inputEvent(element, config, edit, true);+ persistSearchConfig(config);+ });+ const rect = target.getBoundingClientRect();+ session.show(() => window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true}));++ },});- const rect = target.getBoundingClientRect();- window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, h: rect.height, isLeft: true});- event.stopPropagation();+ event.stopPropagation();event.preventDefault();break;} else if (target.id === "searchHistoryBtn") {diff --git a/app/src/template/manager.ts b/app/src/template/manager.tsindex 236be4bfff..3374c5f5c2 100644--- a/app/src/template/manager.ts+++ b/app/src/template/manager.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import {Dialog} from "../dialog";import {openInputDialog} from "../dialog/inputDialog";import {confirmDialog} from "../dialog/confirmDialog";@@ -522,46 +523,60 @@ ${canOpenFolder ? button("open", lang.showInFolder) : ""}});};const openEntryMenu = (entry: TemplateEntry, anchor: HTMLElement, event?: MouseEvent) => {- void run(async () => {- // 菜单固定操作对象和读取版本,打开菜单不切换编辑器或丢弃未保存的源码。- let target: TemplateActionTarget;- if (entry.path === editing?.path) {- target = {entry, revision: editingRevision, sourceDocID};- } else {- const response = await api({action: "read", path: entry.path});- if (!response?.data || Array.isArray(response.data) || !("content" in response.data) || closed) {- return;- }- target = {entry, revision: response.data.revision, sourceDocID: response.data.sourceDocID};- }- const menu = window.siyuan.menus.menu;- menu.remove();- menu.element.setAttribute("data-name", "template-manager");- const add = (action: string, label: string, icon: string) => {- const state = getTemplateActionState(action, entry, dirty(), false);- const item = new MenuItem({- id: action,- label,- icon,- disabled: state.disabled,- click: () => actOnEntry(action, target),- }).element;- if (state.packageMove) {- item.title = lang.templatePackageMoveTip;- }- menu.append(item);- };- if (target.sourceDocID && !entry.isDir) {- add("source", lang.templateOpenSourceDoc, "iconFile");- }- add("rename", lang.rename, "iconEdit");- add("move", lang.move, "iconMove");- if (canOpenFolder) {- add("open", lang.showInFolder, "iconFolder");- }- add("remove", lang.remove, "iconTrashcan");- const rect = anchor.getBoundingClientRect();- menu.popup(event ? {x: event.clientX, y: event.clientY} : {x: rect.left, y: rect.bottom, h: rect.height});+ toggleMenu({+ target: anchor,+ toggle: !event,+ build: (_menu, session) => {+ void run(async () => {+ if (!session.isCurrent()) {+ return;+ }++ // 菜单固定操作对象和读取版本,打开菜单不切换编辑器或丢弃未保存的源码。+ let target: TemplateActionTarget;+ if (entry.path === editing?.path) {+ target = {entry, revision: editingRevision, sourceDocID};+ } else {+ const response = await api({action: "read", path: entry.path});+ if (!session.isCurrent()) {+ return;+ }+ if (!response?.data || Array.isArray(response.data) || !("content" in response.data) || closed) {+ return;+ }+ target = {entry, revision: response.data.revision, sourceDocID: response.data.sourceDocID};+ }+ const menu = window.siyuan.menus.menu;+ menu.remove();+ menu.element.setAttribute("data-name", "template-manager");+ const add = (action: string, label: string, icon: string) => {+ const state = getTemplateActionState(action, entry, dirty(), false);+ const item = new MenuItem({+ id: action,+ label,+ icon,+ disabled: state.disabled,+ click: () => actOnEntry(action, target),+ }).element;+ if (state.packageMove) {+ item.title = lang.templatePackageMoveTip;+ }+ menu.append(item);+ };+ if (target.sourceDocID && !entry.isDir) {+ add("source", lang.templateOpenSourceDoc, "iconFile");+ }+ add("rename", lang.rename, "iconEdit");+ add("move", lang.move, "iconMove");+ if (canOpenFolder) {+ add("open", lang.showInFolder, "iconFolder");+ }+ add("remove", lang.remove, "iconTrashcan");+ const rect = anchor.getBoundingClientRect();+ session.show(() => menu.popup(event ? {x: event.clientX, y: event.clientY} : {x: rect.left, y: rect.bottom, h: rect.height}));+ });++ },});};editorMore.addEventListener("click", () => {diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex 7a072b07e2..e90e4ce56d 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -1,3 +1,4 @@+import {toggleMenu} from "../menus/menuToggle";import * as path from "path";import {fetchPost} from "./fetch";import {Dialog} from "../dialog";@@ -414,73 +415,79 @@ export const movePathTo = (options: {setStorageVal(Constants.LOCAL_MOVE_PATH, window.siyuan.storage[Constants.LOCAL_MOVE_PATH]);};const toggleMovePathHistory = () => {- const keys = window.siyuan.storage[Constants.LOCAL_MOVE_PATH].keys;- if (!keys || keys.length === 0) {- return;- }- const menu = new Menu(Constants.MENU_MOVE_PATH_HISTORY);- if (menu.isOpen) {- return;- }- menu.element.classList.add("b3-menu--list");- menu.addItem({- iconHTML: "",- label: window.siyuan.languages.clearHistory,- click() {- window.siyuan.storage[Constants.LOCAL_MOVE_PATH].keys = [];- setStorageVal(Constants.LOCAL_MOVE_PATH, window.siyuan.storage[Constants.LOCAL_MOVE_PATH]);- }- });- const separatorElement = menu.addSeparator(1);- let current = true;- keys.forEach((s: string) => {- if (s) {- const menuItem = menu.addItem({+ toggleMenu({+ target: inputElement.previousElementSibling,+ build: (_menu, session) => {+ const keys = window.siyuan.storage[Constants.LOCAL_MOVE_PATH].keys;+ if (!keys || keys.length === 0) {+ return;+ }+ const menu = new Menu(Constants.MENU_MOVE_PATH_HISTORY);+ if (menu.isOpen) {+ return;+ }+ menu.element.classList.add("b3-menu--list");+ menu.addItem({iconHTML: "",- label: escapeHtml(s),- action: "iconCloseRound",- bind(element) {- element.addEventListener("click", (itemEvent) => {- if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {- keys.find((item: string, index: number) => {- if (item === s) {- keys.splice(index, 1);- return true;+ label: window.siyuan.languages.clearHistory,+ click() {+ window.siyuan.storage[Constants.LOCAL_MOVE_PATH].keys = [];+ setStorageVal(Constants.LOCAL_MOVE_PATH, window.siyuan.storage[Constants.LOCAL_MOVE_PATH]);+ }+ });+ const separatorElement = menu.addSeparator(1);+ let current = true;+ keys.forEach((s: string) => {+ if (s) {+ const menuItem = menu.addItem({+ iconHTML: "",+ label: escapeHtml(s),+ action: "iconCloseRound",+ bind(element) {+ element.addEventListener("click", (itemEvent) => {+ if (hasClosestByClassName(itemEvent.target as Element, "b3-menu__action")) {+ keys.find((item: string, index: number) => {+ if (item === s) {+ keys.splice(index, 1);+ return true;+ }+ });+ window.siyuan.storage[Constants.LOCAL_MOVE_PATH].keys = keys;+ setStorageVal(Constants.LOCAL_MOVE_PATH, window.siyuan.storage[Constants.LOCAL_MOVE_PATH]);+ if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {+ window.siyuan.menus.menu.remove();+ } else {+ element.remove();+ }+ } else {+ inputElement.value = s;+ inputElement.dispatchEvent(new Event("change"));+ saveMovePathHistory();+ inputEvent();+ window.siyuan.menus.menu.remove();}+ itemEvent.preventDefault();+ itemEvent.stopPropagation();});- window.siyuan.storage[Constants.LOCAL_MOVE_PATH].keys = keys;- setStorageVal(Constants.LOCAL_MOVE_PATH, window.siyuan.storage[Constants.LOCAL_MOVE_PATH]);- if (element.previousElementSibling?.classList.contains("b3-menu__separator") && !element.nextElementSibling) {- window.siyuan.menus.menu.remove();- } else {- element.remove();- }- } else {- inputElement.value = s;- inputElement.dispatchEvent(new Event("change"));- saveMovePathHistory();- inputEvent();- window.siyuan.menus.menu.remove();}- itemEvent.preventDefault();- itemEvent.stopPropagation();});+ if (current) {+ menuItem.classList.add("b3-menu__item--current");+ }+ current = false;}});if (current) {- menuItem.classList.add("b3-menu__item--current");+ separatorElement.remove();}- current = false;- }- });- if (current) {- separatorElement.remove();- }- const rect = inputElement.getBoundingClientRect();- menu.open({- x: rect.left,- y: rect.bottom,- h: rect.height+ const rect = inputElement.getBoundingClientRect();+ session.show(() => menu.open({+ x: rect.left,+ y: rect.bottom,+ h: rect.height+ }));++ },});};inputEvent();diff --git a/app/tests/decisionProviderFocus.test.js b/app/tests/decisionProviderFocus.test.jsindex c309b69215..f4582b05ad 100644--- a/app/tests/decisionProviderFocus.test.js+++ b/app/tests/decisionProviderFocus.test.js@@ -4,6 +4,7 @@ const os = require("node:os");const path = require("node:path");const sourceModules = [+ "menus/menuToggle","config/tabs/ai/aiDecisionUi", "config/tabs/ai/aiProviderUi", "config/render/fragments", "util/escape","config/tabs/ai/aiModelOrder", "config/tabs/ai/aiProviderHeaders", "config/tabs/ai/aiModelTestResult","config/tabs/ai/aiProviderPresets",diff --git a/app/tests/menu-owner.test.js b/app/tests/menu-owner.test.jsnew file mode 100644index 0000000000..0956343c30--- /dev/null+++ b/app/tests/menu-owner.test.js@@ -0,0 +1,36 @@+const assert = require("node:assert/strict");+const {test} = require("node:test");+const {mkdtempSync, mkdirSync, copyFileSync, writeFileSync, rmSync, realpathSync} = require("node:fs");+const {tmpdir} = require("node:os");+const {join, resolve} = require("node:path");+const {spawnSync} = require("node:child_process");++test("menu ownership rejects unowned openings and accepts explicit interaction policies", () => {+ const prefix = join(realpathSync(tmpdir()), "siyuan-menu-owner-");+ const directory = mkdtempSync(prefix);+ try {+ mkdirSync(join(directory, "scripts"));+ mkdirSync(join(directory, "app/src"), {recursive: true});+ writeFileSync(join(directory, "app/package.json"), "{}", "utf8");+ writeFileSync(join(directory, "scripts/menu-owner-exceptions.json"), "{}", "utf8");+ copyFileSync(join(__dirname, "../../scripts/check-menu-owner.mjs"), join(directory, "scripts/check-menu-owner.mjs"));+ for (const [source, accepted, message] of [+ ["window.siyuan.menus.menu.popup({x: 0, y: 0});", false, "unowned menu"],+ ["const picker = new Menu(); picker.open({x: 0, y: 0});", false, "unowned menu"],+ ["new Menu().open({x: 0, y: 0});", false, "unowned menu"],+ ["toggleMenu({build: () => {}, show: menu => menu.popup({x: 0, y: 0})});", false, "requires target"],+ ["toggleMenu({target: button, build: menu => menu.addItem({}), show: menu => menu.fullscreen('bottom')});", true],+ ["toggleMenu({toggle: false, build: menu => menu.popup({x: 0, y: 0})});", true],+ ]) {+ writeFileSync(join(directory, "app/src/probe.ts"), source, "utf8");+ const result = spawnSync(process.execPath, [join(directory, "scripts/check-menu-owner.mjs")], {+ encoding: "utf8", env: {...process.env, NODE_PATH: resolve(__dirname, "../node_modules")},+ });+ assert.equal(result.status, accepted ? 0 : 1, result.stderr);+ if (message) { assert.ok(result.stderr.includes(message), result.stderr); }+ }+ } finally {+ assert.ok(resolve(directory).startsWith(prefix));+ rmSync(directory, {recursive: true, force: true});+ }+});diff --git a/app/tests/menu-toggle-fixture.cjs b/app/tests/menu-toggle-fixture.cjsnew file mode 100644index 0000000000..638084866f--- /dev/null+++ b/app/tests/menu-toggle-fixture.cjs@@ -0,0 +1,19 @@+const {readFileSync} = require("node:fs");+const {join} = require("node:path");+const {runInNewContext} = require("node:vm");+const {transpileModule, ModuleKind, ScriptTarget} = require("typescript");++exports.loadMenuToggle = globals => {+ const exports = {};+ const source = readFileSync(join(__dirname, "../src/menus/menuToggle.ts"), "utf8");+ runInNewContext(transpileModule(source, {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText, {...globals, exports});+ return exports;+};++exports.menuAnchor = () => ({+ marked: false,+ closest() { return this.marked ? this : null; },+ setAttribute() { this.marked = true; },+});diff --git a/app/tests/mobileBacklinks.test.js b/app/tests/mobileBacklinks.test.jsindex 6b5959761e..e64aaa8425 100644--- a/app/tests/mobileBacklinks.test.js+++ b/app/tests/mobileBacklinks.test.js@@ -7,7 +7,7 @@ const sources = () => {const ts = require("typescript");const preprocess = require("ifdef-loader/preprocessor").parse;const modules = {};- for (const name of ["layout/dock/BacklinkContent", "layout/dock/backlinkRefresh",+ for (const name of ["menus/menuToggle", "layout/dock/BacklinkContent", "layout/dock/backlinkRefresh","layout/dock/GlobalBacklinkList", "layout/dock/globalBacklinkPaging","layout/dock/backlinkReadingAnchor", "layout/dock/backlinkSourceFilter", "mobile/util/secondaryEditors","mobile/util/backlinkPanels", "mobile/util/openBacklinks", "mobile/util/MobileEditorDialog", "mobile/util/bindBottomSheetDrag", "mobile/util/bindBottomSheetDialog", "menus/sheetOpen", "protyle/util/transactionQueue",diff --git a/app/tests/mobileContentToolbar.test.js b/app/tests/mobileContentToolbar.test.jsindex 6b89136578..38b8d0af85 100644--- a/app/tests/mobileContentToolbar.test.js+++ b/app/tests/mobileContentToolbar.test.js@@ -5,7 +5,9 @@ const os = require("node:os");const runCases = async () => {const assert = require("node:assert/strict");- window.siyuan = {zIndex: 0, languages: {}, menus: {menu: {remove() {}, fullscreen() {}}}};+ window.siyuan = {zIndex: 0, languages: {}, menus: {menu: {+ element: document.createElement("div"), remove() { this.data = undefined; }, fullscreen() {},+ }}};const commands = [];document.execCommand = command => {commands.push({command, text: getSelection().toString()});@@ -268,7 +270,8 @@ const runElectron = async () => {read("protyle/util/hasClosest"),read("protyle/wysiwyg/blockSelection"),read("protyle/toolbar/subElementLifecycle"),- read("mobile/util/multiSelectToolbar"),+ read("mobile/util/multiSelectToolbar").replace(/^import .*;\r?\n/gm, ""),+ read("menus/menuToggle"),read("mobile/util/wordSelection"),"window.expandAndroidWordSelection = expandAndroidWordSelection;",extract("protyle/wysiwyg/getBlock", ["getContenteditableElement"]),diff --git a/app/tests/mobileEditingToolbar.test.js b/app/tests/mobileEditingToolbar.test.jsindex 28261e964a..b4cea9a47e 100644--- a/app/tests/mobileEditingToolbar.test.js+++ b/app/tests/mobileEditingToolbar.test.js@@ -319,7 +319,7 @@ const runElectron = async () => {let exitCode = 0;try {const ts = require("typescript");- const modules = ["mobile/util/keyboardToolbar", "mobile/util/keyboardSelectionScroll", "mobile/util/toolbarActions",+ const modules = ["menus/menuToggle", "mobile/util/keyboardToolbar", "mobile/util/keyboardSelectionScroll", "mobile/util/toolbarActions","mobile/util/toolbarEntries", "mobile/util/mobileAppUtil", "mobile/util/mobileKeyboardChange","mobile/util/touchSelection", "mobile/util/visibleViewport", "protyle/util/hasClosest","protyle/toolbar/defaults", "protyle/toolbar/entryVisibility", "config/entryVisibility/order",diff --git a/app/tests/shortcutEscape.test.js b/app/tests/shortcutEscape.test.jsindex 3549d758c7..6b40766a76 100644--- a/app/tests/shortcutEscape.test.js+++ b/app/tests/shortcutEscape.test.js@@ -35,7 +35,7 @@ const sources = () => {const renderMenu = find(workspace, node => ts.isVariableDeclaration(node) &&node.name.getText(workspace) === "renderMenu").initializer;const popupIndex = renderMenu.body.statements.findIndex(node =>- node.getText(workspace).startsWith("window.siyuan.menus.menu.popup("));+ node.getText(workspace).startsWith("session.show(() => window.siyuan.menus.menu.popup("));assert.ok(popupIndex >= 0);const menu = sourceFile("menus/Menu.ts");const declaration = name => find(menu, node => ts.isVariableDeclaration(node) &&@@ -53,9 +53,12 @@ const sources = () => {${escape.getText(keyboard)}}` + sourceFile("protyle/toolbar/subElementLifecycle.ts").text.replaceAll("export ", "")),card: compile(`const openCardByData = ${openCard.getText(card)};`),- menu: compile(`async function workspaceMenu(app, rect, openOnly = false) {+ menuToggle: compile(sourceFile("menus/menuToggle.ts").text),+ menu: compile(`async function workspaceMenu(app, rect, openOnly = false, target) {${workspaceMenu.body.statements[0].getText(workspace)}+ await toggleMenu({target, toggle: !openOnly && Boolean(target), build: (_menu, session) => {${renderMenu.body.statements.slice(popupIndex).map(node => node.getText(workspace)).join("\n")}+ }});}const ${declaration("getActionMenu")};const ${declaration("bindMenuKeydown")};`),@@ -199,8 +202,8 @@ const cases = async compiled => {}// 快捷键将焦点移到可操作菜单项,方向键不再被编辑器截获。const menuConstants = {MENU_BAR_WORKSPACE: "workspace", KEYCODELIST: {38: "↑", 40: "↓", 220: "\\"}};- const menuBindings = new Function("window", "Constants", compiled.menu +- "\nreturn {workspaceMenu, bindMenuKeydown};")(window, menuConstants);+ const menuBindings = new Function("window", "Constants", "toggleMenu", compiled.menu ++ "\nreturn {workspaceMenu, bindMenuKeydown};")(window, menuConstants, load(compiled.menuToggle, {}).toggleMenu);const keymap = load(compiled.keymap, {});const hotkey = load(compiled.hotkey, {"../../util/keymapBindings": keymap, "../../constants": {Constants: menuConstants},"./compatibility": {isNotCtrl: event => !event.ctrlKey && !event.metaKey, isMac: () => false,@@ -256,7 +259,7 @@ const cases = async compiled => {editor.dispatchEvent(event);check.equal(event.defaultPrevented, true);} else {- await menuBindings.workspaceMenu({}, {}, false);+ await menuBindings.workspaceMenu({}, {}, false, bar);}check.equal(document.activeElement, openOnly ? menuElement.querySelector("#firstAction") : editor);document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {@@ -274,7 +277,7 @@ const cases = async compiled => {}));check.equal(menuElement.classList.contains("fn__none"), true);check.equal(document.activeElement, editor);- await menuBindings.workspaceMenu({}, {}, true);+ await menuBindings.workspaceMenu({}, {}, true, bar);const newFocus = document.createElement("button");document.body.append(newFocus);newFocus.focus();diff --git a/app/tests/shortcutOpenPanels.test.js b/app/tests/shortcutOpenPanels.test.jsindex 08685024ba..8c15dc6c62 100644--- a/app/tests/shortcutOpenPanels.test.js+++ b/app/tests/shortcutOpenPanels.test.js@@ -5,6 +5,7 @@ const {test} = require("node:test");const {runInNewContext} = require("node:vm");const ts = require("typescript");const {parse} = require("ifdef-loader/preprocessor");+const {loadMenuToggle} = require("./menu-toggle-fixture.cjs");const sourceFile = file => ts.createSourceFile(file, readFileSync(path.join(__dirname, "../src", file), "utf8"),ts.ScriptTarget.Latest, true);@@ -38,12 +39,20 @@ const prefix = (source, fn, marker, scope) => {};`, scope).subject;};const hiddenElement = (hidden = true) => ({classList: {contains: () => hidden}});+const ownedPrefix = (source, fn, scope) => {+ const build = find(fn, node => ts.isPropertyAssignment(node) && node.name.getText(source) === "build").initializer.body;+ const body = fn.body.getText(source);+ const start = build.getStart(source) - fn.body.getStart(source);+ const end = build.end - fn.body.getStart(source);+ const guarded = body.slice(0, start) + '{throw new Error("An existing panel must not be rendered again");}' + body.slice(end);+ return evaluate(`exports.subject = async function(${fn.parameters.map(node => node.getText(source)).join(",")}) ${guarded}`,+ {...scope, ...loadMenuToggle(scope)}).subject;+};for (const [file, name, marker, args] of [["business/openRecentDocs.ts", "openRecentDocs", "const sortBy", openOnly => [openOnly]],["history/history.ts", "openHistory", "const localHistory", openOnly => [{}, "doc", openOnly]],["card/openCard.ts", "openCardByData", "let lastRange", openOnly => [{}, {}, "doc", "id", "title", openOnly]],- ["menus/workspace.ts", "workspaceMenu", "let remoteConnections", openOnly => [{}, {}, openOnly]],]) {test(`${name} retains the open panel for shortcuts and toggles for mouse entry`, async () => {let closes = 0;@@ -61,18 +70,32 @@ for (const [file, name, marker, args] of [});}+test("workspaceMenu retains the open panel for shortcuts and toggles for its mouse anchor", async () => {+ let closes = 0;+ const anchor = {closest: () => null, setAttribute() {}};+ const window = {siyuan: {menus: {menu: {data: anchor,+ element: {...hiddenElement(false), getAttribute: () => "panel"}, remove: () => closes++}}}};+ const source = sourceFile("menus/workspace.ts");+ const subject = ownedPrefix(source, arrow(source, "workspaceMenu"), {window, Constants: {MENU_BAR_WORKSPACE: "panel"}});+ await subject({}, {}, true, anchor);+ assert.equal(closes, 0);+ await subject({}, {}, false, anchor);+ assert.equal(closes, 1);+});+test("tab list and inline appearance retain their existing shortcut panel", async () => {let closes = 0;const source = sourceFile("layout/Wnd.ts");const method = find(source, node => ts.isMethodDeclaration(node) && node.name.getText(source) === "renderTabList");- const subject = prefix(source, method, "window.siyuan.menus.menu.remove();", {- window: {siyuan: {menus: {menu: {element: {...hiddenElement(false), getAttribute: () => "tabs"},+ const anchor = {closest: () => null, setAttribute() {}};+ const subject = ownedPrefix(source, method, {+ window: {siyuan: {menus: {menu: {data: anchor, element: {...hiddenElement(false), getAttribute: () => "tabs"},remove: () => closes++}}}}, Constants: {MENU_TAB_LIST: "tabs"},});const wnd = {headersElement: {children: [{}]}};- await subject.call(wnd, {}, true);+ await subject.call(wnd, anchor, true);assert.equal(closes, 0);- await subject.call(wnd, {}, false);+ await subject.call(wnd, anchor, false);assert.equal(closes, 1);const font = sourceFile("protyle/toolbar/Font.ts");const binding = find(font, node => ts.isCallExpression(node) &&@@ -107,7 +130,8 @@ test("native shortcut sources open panels without toggling while menu commands rtarget[key] || (() => false)}), document: {querySelector: () => ({getBoundingClientRect: () => ({})})}});for (const command of ["mainMenu", "recentDocs", "dataHistory", "riffCard"]) {assert.equal(globalCommand(command, {}, undefined, true), true);- assert.equal(dispatches.at(-1).args.at(-1), true);+ const call = dispatches.at(-1);+ assert.equal(call.name === "workspaceMenu" ? call.args[2] : call.args.at(-1), true);}});diff --git a/app/tests/tabsFocus.test.js b/app/tests/tabsFocus.test.jsindex 4e4fdbbec0..4a27cbb270 100644--- a/app/tests/tabsFocus.test.js+++ b/app/tests/tabsFocus.test.js@@ -27,6 +27,7 @@ const sources = () => {visit(keydownSource);assert.ok(titleKeydown);return [+ compile("menus/menuToggle.ts"),compile("protyle/render/tabsState.ts"),compile("protyle/render/tabsDrag.ts"),compile("protyle/render/tabsAttributes.ts"),@@ -61,6 +62,7 @@ const cases = async (source) => {lute.SetKramdownIAL(true);lute.SetProtyleWYSIWYG(true);window.siyuan = {languages: {enter: "Zoom in", copy: "Copy", delete: "Delete", rename: "Rename"},+ menus: {menu: {element: document.createElement("div"), remove() { this.data = undefined; }}},config: {editor: {spellcheck: false}}};const style = document.createElement("style");style.textContent = ".fn__none, .tab-item[data-tabs-hidden=\"true\"] {display: none !important;} " +@@ -129,7 +131,7 @@ const cases = async (source) => {if (!readonly) {const title = b.querySelector(".tab-item-title");api.bindTitleKeydown(protyle, title);- api.openTabsMenu(protyle, tabs, b, tabs);+ api.openTabsMenu(protyle, tabs, b, tabs, false);menu.find(item => item.label === "Rename").click();title.textContent = "Retained title";title.focus();@@ -148,7 +150,7 @@ const cases = async (source) => {check.equal(root.querySelector(".protyle-wysiwyg--select-mode"), null);}const replayGroup = tabs.outerHTML;- api.openTabsMenu(protyle, tabs, a, tabs);+ api.openTabsMenu(protyle, tabs, a, tabs, false);menu.find(item => item.label === "Zoom in").click();check.deepEqual(navigations, [a.dataset.nodeId]);@@ -279,7 +281,7 @@ const cases = async (source) => {const group = root.firstElementChild;check.equal(group.dataset.type, "NodeTabs");check.equal(group.querySelectorAll(":scope > .tabs-header > .tabs-list > .tabs-tab").length, 2);- api.openTabsMenu(protyle, group, group.querySelector(".tab-item"), group);+ api.openTabsMenu(protyle, group, group.querySelector(".tab-item"), group, false);check.equal(menu.some(item => item.label === "Zoom in"), false);}api.destroyTabsRender(root);diff --git a/app/tests/taskStatus.test.js b/app/tests/taskStatus.test.jsindex c9eada9903..0b386b6366 100644--- a/app/tests/taskStatus.test.js+++ b/app/tests/taskStatus.test.js@@ -64,6 +64,7 @@ const sources = () => {extract("protyle/render/tabsState.ts", ["resolveTabID", "tabKeyboardTarget"]) +extract("protyle/render/tabsAttributes.ts", ["clearTabsAttributes", "renderTabsAttributes"]),menu: extract("protyle/wysiwyg/taskStatusDialog.ts", ["getTaskStatusItems"]),+ menuToggle: extract("menus/menuToggle.ts", ["sessions", "toggleMenu"]),tabMenu: extract("protyle/wysiwyg/tabsFocus.ts", ["canFocusTabItem"]) +extract("protyle/wysiwyg/tabs.ts", ["canEdit", "openTabsMenu"]),normalizeSeparators: extract("config/entryVisibility/runtime.ts", ["normalizeSeparators"]),@@ -113,7 +114,8 @@ const cases = async source => {const taskStyle = document.createElement("style");taskStyle.textContent = source.css;document.head.append(taskStyle);- window.siyuan = {languages: {}};+ window.siyuan = {languages: {}, menus: {menu: {element: document.createElement("div"), remove() { this.data = undefined; }}}};+ const toggleMenu = new Function(source.menuToggle + "; return toggleMenu;")();let customMarker;const getMenu = new Function("openTaskStatusDialog", source.menu + "; return getTaskStatusItems;")(marker => { customMarker = marker; });@@ -147,12 +149,12 @@ const cases = async source => {open() {}}let focusedTab;- const openTabMenu = new Function("Menu", "Constants", "getTabTask", "getTaskStatusItems", "setTabTask", "copySubMenu", "zoomOut",+ const openTabMenu = new Function("toggleMenu", "Menu", "Constants", "getTabTask", "getTaskStatusItems", "setTabTask", "copySubMenu", "zoomOut",source.tabMenu + "; return openTabsMenu;")(- TestMenu, {CB_GET_HISTORY: "history"}, api.getTabTask, getMenu, api.setTabTask, () => [],+ toggleMenu, TestMenu, {CB_GET_HISTORY: "history"}, api.getTabTask, getMenu, api.setTabTask, () => [],options => { focusedTab = options; });const menuFixture = reset();- openTabMenu(protyle, menuFixture.from, menuFixture.item, menuFixture.item);+ openTabMenu(protyle, menuFixture.from, menuFixture.item, menuFixture.item, false);const expectedStates = ["taskStatusTodo", "taskStatusInProgress", "taskStatusDone", "taskStatusCanceled", "customTaskStatus"];check.deepEqual(openedMenu.items.filter(item => expectedStates.includes(item.id)).map(item => item.id), expectedStates);check.equal(openedMenu.items.filter(item => item.id === "customTaskStatus").length, 1);diff --git a/app/tests/templateManager.test.js b/app/tests/templateManager.test.jsindex 551c1ada90..176c5dc871 100644--- a/app/tests/templateManager.test.js+++ b/app/tests/templateManager.test.js@@ -31,7 +31,7 @@ const runCases = async (sources, css, mobile, legacyMobile) => {document.body.append(menuElement);const menu = {element: menuElement,- remove() {menuElement.classList.add("fn__none"); menuElement.replaceChildren();},+ remove() {this.data = undefined; menuElement.classList.add("fn__none"); menuElement.replaceChildren();},append(element) {menuElement.append(element);},popup() {menuElement.classList.remove("fn__none");},};@@ -324,7 +324,7 @@ if (process.versions.electron && process.type === "browser") {icons: fs.readFileSync(path.join(__dirname, "../appearance/icons/litheness/icon.js"), "utf8"),languages: fs.readFileSync(path.join(__dirname, "../appearance/langs/zh-CN.json"), "utf8"),};- for (const name of ["template/manager", "template/actionState", "util/fileTree", "util/escape"]) {+ for (const name of ["menus/menuToggle", "template/manager", "template/actionState", "util/fileTree", "util/escape"]) {sources[name] = ts.transpileModule(preprocess(fs.readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"),{MOBILE: mobile, BROWSER: false}, false, true), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},diff --git a/scripts/check-menu-owner.mjs b/scripts/check-menu-owner.mjsnew file mode 100644index 0000000000..5bdbd4b1ed--- /dev/null+++ b/scripts/check-menu-owner.mjs@@ -0,0 +1,99 @@+import {readFileSync, readdirSync} from "node:fs";+import {dirname, join, relative} from "node:path";+import {fileURLToPath} from "node:url";+import {createRequire} from "node:module";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const require = createRequire(join(root, "app/package.json"));+const ts = require("typescript");+const calls = new Map();+const violations = [];++const property = (object, name) => ts.isObjectLiteralExpression(object) &&+ object.properties.find(entry => entry.name?.getText() === name);+const owned = node => {+ for (let parent = node.parent; parent; parent = parent.parent) {+ if (ts.isCallExpression(parent) && parent.expression.getText() === "toggleMenu") {+ return true;+ }+ }+ return false;+};+const context = node => {+ const names = [];+ for (let parent = node.parent; parent; parent = parent.parent) {+ if (ts.isArrowFunction(parent) || ts.isFunctionExpression(parent)) {+ if (ts.isCallExpression(parent.parent) && parent.parent.expression.getText().endsWith(".addEventListener")) {+ names.push("event:" + parent.parent.arguments[0].getText());+ } else if (ts.isVariableDeclaration(parent.parent) || ts.isPropertyAssignment(parent.parent)) {+ names.push(parent.parent.name.getText());+ }+ } else if (ts.isMethodDeclaration(parent) || ts.isFunctionDeclaration(parent) || ts.isClassDeclaration(parent)) {+ if (parent.name) { names.push(parent.name.getText()); }+ }+ }+ return names.reverse().join("/");+};+const scan = directory => {+ for (const entry of readdirSync(directory, {withFileTypes: true})) {+ const file = join(directory, entry.name);+ if (entry.isDirectory()) { scan(file); continue; }+ if (!file.endsWith(".ts") || file.endsWith(".d.ts") || file.endsWith(".test.ts")) { continue; }+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);+ const menuVariables = new Set();+ const findMenus = node => {+ if (ts.isVariableDeclaration(node) && node.initializer && ts.isNewExpression(node.initializer) &&+ /Menu$/.test(node.initializer.expression.getText())) {+ menuVariables.add(node.name.getText());+ }+ ts.forEachChild(node, findMenus);+ };+ findMenus(source);+ const path = relative(root, file).replaceAll("\\", "/");+ const visit = node => {+ if (ts.isCallExpression(node)) {+ if (node.expression.getText() === "toggleMenu") {+ const options = node.arguments[0];+ if (!options || (!property(options, "target") && property(options, "toggle")?.initializer?.getText() !== "false")) {+ violations.push(path + ": toggleMenu requires target or explicit toggle: false");+ }+ } else if (ts.isPropertyAccessExpression(node.expression)) {+ const method = node.expression.name.text;+ const receiver = node.expression.expression.getText();+ const menu = /menu$/i.test(receiver) || menuVariables.has(receiver) || receiver.startsWith("init") ||+ receiver.startsWith("window.siyuan.menus.menu") ||+ ts.isNewExpression(node.expression.expression) && /Menu$/.test(node.expression.expression.expression.getText());+ if ((method === "popup" || method === "fullscreen" || method === "open" && menu) && !owned(node)) {+ const key = [path, context(node), receiver, method].join(" | ");+ calls.set(key, (calls.get(key) || 0) + 1);+ }+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ }+};+scan(join(root, "app/src"));++if (process.argv.includes("--inventory")) {+ console.log(JSON.stringify(Object.fromEntries([...calls].sort()), null, 2));+} else {+ // 例外逐项记录用途与调用数量,新增直接打开入口必须先明确其交互策略。+ const exemptions = JSON.parse(readFileSync(join(root, "scripts/menu-owner-exceptions.json"), "utf8"));+ for (const [key, count] of calls) {+ const exemption = exemptions[key];+ if (!exemption?.reason || exemption.count !== count) {+ violations.push(key + ": unowned menu call count " + count);+ }+ }+ for (const key of Object.keys(exemptions)) {+ if (!calls.has(key)) { violations.push(key + ": stale exemption"); }+ }+ if (violations.length) {+ console.error(violations.join("\n"));+ process.exitCode = 1;+ } else {+ console.log("Menu ownership: shared openings checked; explicit exceptions unchanged");+ }+}diff --git a/scripts/menu-owner-exceptions.json b/scripts/menu-owner-exceptions.jsonnew file mode 100644index 0000000000..54e4cdd084--- /dev/null+++ b/scripts/menu-owner-exceptions.json@@ -0,0 +1,366 @@+{+ "app/src/ai/actions.ts | openAIActions | menu | fullscreen": {+ "count": 1,+ "reason": "由 AIActions 的会话检查后调用,亦供键盘操作打开"+ },+ "app/src/ai/actions.ts | openAIActions | menu | open": {+ "count": 1,+ "reason": "由 AIActions 的会话检查后调用,亦供键盘操作打开"+ },+ "app/src/boot/globalEvent/command/panel.ts | commandPanel | menu | fullscreen": {+ "count": 1,+ "reason": "键盘或命令打开,保留仅打开和焦点行为"+ },+ "app/src/boot/globalEvent/keydown.ts | fileTreeKeydown | initFileMenu(app, notebookId, pathString, liElements[0]) | popup": {+ "count": 1,+ "reason": "键盘或命令打开,保留仅打开和焦点行为"+ },+ "app/src/boot/globalEvent/keydown.ts | fileTreeKeydown | initNavigationMenu(app, liElements[0] as HTMLElement) | popup": {+ "count": 1,+ "reason": "键盘或命令打开,保留仅打开和焦点行为"+ },+ "app/src/boot/globalEvent/searchKeydown.ts | searchKeydown | initSearchMenu(id) | popup": {+ "count": 1,+ "reason": "键盘或命令打开,保留仅打开和焦点行为"+ },+ "app/src/config/tabs/keymapUi.ts | bindKeymapList/event:\"contextmenu\" | menu | open": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/layout/dock/PinnedDocs.ts | PinnedDocs/menu | menu | fullscreen": {+ "count": 2,+ "reason": "由具体更多按钮的 toggleMenu 构建回调或右键入口调用"+ },+ "app/src/layout/dock/PinnedDocs.ts | PinnedDocs/menu | menu | popup": {+ "count": 2,+ "reason": "由具体更多按钮的 toggleMenu 构建回调或右键入口调用"+ },+ "app/src/layout/topBar.ts | initBar | initTopBarMenu() | popup": {+ "count": 1,+ "reason": "Electron 顶栏原生右键事件转发"+ },+ "app/src/menus/Menu.ts | Menu/popup | this | fullscreen": {+ "count": 1,+ "reason": "既有公共打开方法与平台布局转发,保持插件兼容"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initDockMenu(target) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initDockMenu(undefined, target) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initFileMenu(app, this.getDir(target), target.getAttribute(\"data-path\"), target) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initNavigationMenu(app, target) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initSearchMenu(nodeId) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initStatusBarMenu(target.closest(\"[data-statusbar-entry]\") || undefined) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initTabMenu(app, (getInstanceById(target.getAttribute(\"data-id\")) as Tab)) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initTopBarMenu() | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/index.ts | Menus/event:\"contextmenu\" | initTopBarMenu(target) | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/menus/protyle.ts | fileAnnotationRefMenu | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | fileAnnotationRefMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | imgMenu | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | imgMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | inlineMathMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | linkMenu | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | linkMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | refMenu | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | refMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | renderAssetList/show | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "已有资产菜单的异步内容刷新;按钮入口检查会话,独立及 AV 调用保留既有行为"+ },+ "app/src/menus/protyle.ts | renderAssetList/show | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "已有资产菜单的异步内容刷新;按钮入口检查会话,独立及 AV 调用保留既有行为"+ },+ "app/src/menus/protyle.ts | tagMenu | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/menus/protyle.ts | tagMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "行内内容上下文菜单,保留已有弹出及浮窗归属行为"+ },+ "app/src/mobile/dock/MobileFiles.ts | MobileFiles | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "由 renderMultiSelectToolbar 的具体菜单按钮 toggleMenu 回调打开"+ },+ "app/src/mobile/util/nativeSelect.ts | openSelect | menu | open": {+ "count": 1,+ "reason": "原生表单选择器,包括 AV 表单及独立菜单,保留选择和提交行为"+ },+ "app/src/plugin/Menu.ts | Menu/fullscreen | this.menu | fullscreen": {+ "count": 1,+ "reason": "既有公共打开方法与平台布局转发,保持插件兼容"+ },+ "app/src/plugin/Menu.ts | Menu/open | this.menu | popup": {+ "count": 1,+ "reason": "既有公共打开方法与平台布局转发,保持插件兼容"+ },+ "app/src/protyle/gutter/index.ts | Gutter/event:\"contextmenu\" | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/protyle/gutter/index.ts | Gutter/event:\"contextmenu\" | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/protyle/header/Title.ts | Title/event:\"contextmenu\" | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/protyle/header/documentMenu.ts | openDocumentMenu | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "文档菜单构建器,由标题的会话检查后调用,亦供图谱和右键打开"+ },+ "app/src/protyle/header/documentMenu.ts | openDocumentMenu | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "文档菜单构建器,由标题的会话检查后调用,亦供图谱和右键打开"+ },+ "app/src/protyle/hint/index.ts | Hint/fill | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "输入提示和斜杠命令的程序化打开"+ },+ "app/src/protyle/hint/index.ts | Hint/fill | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "输入提示和斜杠命令的程序化打开"+ },+ "app/src/protyle/render/av/action.ts | avClick | addMenu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/action.ts | avContextmenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/action.ts | openAVEditFieldMenu | menu | fullscreen": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/action.ts | openAVEditFieldMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/asset.ts | addAssetLink | menu | fullscreen": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/asset.ts | addAssetLink | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/asset.ts | editAssetItem | menu | fullscreen": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/asset.ts | editAssetItem | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/automation.ts | openAutomationMenu/chooseField | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/blockAttr.ts | openEdit | addMenu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/calc.ts | openCalcMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/calendar/undated.ts | bindCalendarUndated/setOpen | menu | fullscreen": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/col.ts | bindEditEvent/event:\"click\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/col.ts | showAVColumnWidthMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/col.ts | showColMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/col.ts | showColMenu/click | addMenu | open": {+ "count": 2,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/dateCalendarMenu.ts | bindDateCalendarMenu/event:\"click\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/dateFormatMenu.ts | formatDate | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/fieldValueEditor.ts | bindFieldLunarDates/event:\"click\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/fieldValueEditor.ts | openFieldRelationMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/fieldValueEditor.ts | openFieldSelectMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/filter.ts | addFilter | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/groups.ts | goGroupsDate | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/groups.ts | goGroupsSort | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/kanban/groupMenu.ts | openKanbanGroupMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/map/settings.ts | bindMapSettings/event:\"click\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/map/unplaced.ts | bindMapUnplaced/event:\"click\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/newItemTemplate.ts | openContentTemplateMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/newItemTemplate.ts | openNewItemTemplateDialog/openTemplateActionMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/newItemTemplate.ts | openNewItemTemplateMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/number.ts | formatNumber | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/panels/edit.ts | \"newCol\" | addMenu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/panels/filters.ts | \"addFilterCondition\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/panels/filters.ts | \"moreFilter\" | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/relation.ts | openSearchAV/bind | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/relationLayout.ts | bindRelationLayout/positionMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/rollup.ts | goSearchRollupCol/bind | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/select.ts | setColOption | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/sort.ts | addSort | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/view.ts | addView | addMenu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/view.ts | openViewMenu | menu | open": {+ "count": 1,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/render/av/viewSettingMenu.ts | openViewSettingMenu | menu | open": {+ "count": 2,+ "reason": "AV 菜单保持既有构造和交互"+ },+ "app/src/protyle/toolbar/index.ts | Toolbar/showMultiSelectMode | window.siyuan.menus.menu | fullscreen": {+ "count": 1,+ "reason": "由 renderMultiSelectToolbar 的具体菜单按钮 toggleMenu 回调打开"+ },+ "app/src/protyle/wysiwyg/index.ts | WYSIWYG/bindCommonEvent/event:\"mousedown\"/finishDragSelect | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "框选结束后的程序化打开"+ },+ "app/src/protyle/wysiwyg/index.ts | WYSIWYG/bindEvent/event:\"contextmenu\" | window.siyuan.menus.menu | fullscreen": {+ "count": 2,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/protyle/wysiwyg/index.ts | WYSIWYG/bindEvent/event:\"contextmenu\" | window.siyuan.menus.menu | popup": {+ "count": 4,+ "reason": "右键在当前指针位置重新打开,不参与按钮开关"+ },+ "app/src/protyle/wysiwyg/keydown.ts | keydown/event:\"keydown\" | window.siyuan.menus.menu | popup": {+ "count": 1,+ "reason": "键盘或命令打开,保留仅打开和焦点行为"+ }+}