An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lipstick: Improve image title editing with a floating input https://github.com/siyuan-note/siyuan/issues/20397
Daniel4ce0e36b6e8f
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.syindex 449ee3c504..12774c01f7 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy@@ -7,7 +7,7 @@"id": "20200924100950-9op5xi1","title": "Shortcuts","type": "doc",- "updated": "20261011091952"+ "updated": "20261011142010"},"Children": [{@@ -4315,7 +4315,7 @@"HeadingLevel": 2,"Properties": {"id": "20210106154056-koo4wdj",- "updated": "20261010202520"+ "updated": "20261011142010"},"Children": [{@@ -10275,7 +10275,7 @@"Type": "NodeHeading","Properties": {"id": "20261010134815-v9k29uo",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{@@ -10290,12 +10290,12 @@"Type": "NodeParagraph","Properties": {"id": "20261010134815-bb1k769",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{"Type": "NodeText",- "Data": "Click or tap the title below an image to edit it inline. When the title is focused, press "+ "Data": "Click or tap the title below an image to edit it in a floating input. A full-screen mask appears while editing, and the document layout stays unchanged. When the title is focused, press "},{"Type": "NodeTextMark",@@ -10320,6 +10320,15 @@"TextMarkType": "kbd","TextMarkTextContent": "Enter"},+ {+ "Type": "NodeText",+ "Data": " or "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Tab"+ },{"Type": "NodeText","Data": " to save or "@@ -10331,7 +10340,7 @@},{"Type": "NodeText",- "Data": " to cancel. Leaving the field also saves. The change applies to this image reference and does not rename the asset file. Read-only documents do not allow title editing."+ "Data": " to cancel. Clicking outside the input or leaving the field also saves. On mobile, Back saves and closes the input first. The change applies to this image reference and does not rename the asset file. Read-only documents do not allow title editing."}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.syindex 180be2a269..05cb61aea2 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy@@ -7,7 +7,7 @@"id": "20200813004551-gm0pbn1","title": "快捷键","type": "doc",- "updated": "20261011091952"+ "updated": "20261011142010"},"Children": [{@@ -4313,7 +4313,7 @@"HeadingLevel": 2,"Properties": {"id": "20201227133317-rkh4bji",- "updated": "20261010202520"+ "updated": "20261011142010"},"Children": [{@@ -10263,7 +10263,7 @@"Type": "NodeHeading","Properties": {"id": "20261010134815-nlwueda",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{@@ -10278,12 +10278,12 @@"Type": "NodeParagraph","Properties": {"id": "20261010134815-gzdtswz",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{"Type": "NodeText",- "Data": "点击图片下方的标题可就地编辑,移动端可轻点标题。标题获得焦点时,按 "+ "Data": "点击图片下方的标题可通过悬浮输入框编辑,移动端可轻点标题。输入框显示时有全局遮罩,不影响正文布局。标题获得焦点时,按 "},{"Type": "NodeTextMark",@@ -10308,6 +10308,15 @@"TextMarkType": "kbd","TextMarkTextContent": "Enter"},+ {+ "Type": "NodeText",+ "Data": " 或 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Tab"+ },{"Type": "NodeText","Data": " 保存,按 "@@ -10319,7 +10328,7 @@},{"Type": "NodeText",- "Data": " 取消,离开输入框也会保存。修改仅作用于当前图片引用,不会重命名资源文件。只读文档不支持编辑标题。"+ "Data": " 取消。点击输入框外部或离开输入框也会保存,移动端返回会先保存并关闭输入框。修改仅作用于当前图片引用,不会重命名资源文件。只读文档不支持编辑标题。"}]},diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.syindex b8727505ed..9618c99019 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy@@ -7,7 +7,7 @@"id": "20211226122549-jktxego","title": "快捷鍵","type": "doc",- "updated": "20261011091952"+ "updated": "20261011142010"},"Children": [{@@ -4307,7 +4307,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226122652-htptsmh",- "updated": "20261010202520"+ "updated": "20261011142010"},"Children": [{@@ -10252,7 +10252,7 @@"Type": "NodeHeading","Properties": {"id": "20261010134815-lhna2cb",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{@@ -10267,12 +10267,12 @@"Type": "NodeParagraph","Properties": {"id": "20261010134815-mtfjptp",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{"Type": "NodeText",- "Data": "點擊圖片下方的標題可就地編輯,行動裝置可輕觸標題。標題取得焦點時,按 "+ "Data": "點擊圖片下方的標題可透過浮動輸入框編輯,行動裝置可輕觸標題。輸入框顯示時有全域遮罩,不影響正文版面。標題取得焦點時,按 "},{"Type": "NodeTextMark",@@ -10297,6 +10297,15 @@"TextMarkType": "kbd","TextMarkTextContent": "Enter"},+ {+ "Type": "NodeText",+ "Data": " 或 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Tab"+ },{"Type": "NodeText","Data": " 儲存,按 "@@ -10308,7 +10317,7 @@},{"Type": "NodeText",- "Data": " 取消,離開輸入框也會儲存。修改僅作用於目前的圖片引用,不會重新命名資源文件。唯讀文檔不支援編輯標題。"+ "Data": " 取消。點擊輸入框外部或離開輸入框也會儲存,行動裝置返回時會先儲存並關閉輸入框。修改僅作用於目前的圖片引用,不會重新命名資源文件。唯讀文檔不支援編輯標題。"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.syindex d317d6050c..1382dcc3c3 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy@@ -9,7 +9,7 @@"id": "20240530101000-xsbxokr","title": "ショートカット","type": "doc",- "updated": "20261011091952"+ "updated": "20261011142010"},"Children": [{@@ -4265,7 +4265,7 @@"Properties": {"ID": "20240530101000-twmuxke","id": "20240530101000-675gu9g",- "updated": "20261010202520"+ "updated": "20261011142010"},"Children": [{@@ -10188,7 +10188,7 @@"Type": "NodeHeading","Properties": {"id": "20261010134815-h903uwh",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{@@ -10203,12 +10203,12 @@"Type": "NodeParagraph","Properties": {"id": "20261010134815-pbj3gz0",- "updated": "20261010134815"+ "updated": "20261011142010"},"Children": [{"Type": "NodeText",- "Data": "画像の下にあるタイトルをクリックまたはタップすると、その場で編集できます。タイトルにフォーカスがあるときは "+ "Data": "画像の下にあるタイトルをクリックまたはタップすると、フローティング入力欄で編集できます。編集中は画面全体を覆うマスクが表示され、本文のレイアウトは変わりません。タイトルにフォーカスがあるときは "},{"Type": "NodeTextMark",@@ -10233,6 +10233,15 @@"TextMarkType": "kbd","TextMarkTextContent": "Enter"},+ {+ "Type": "NodeText",+ "Data": " または "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Tab"+ },{"Type": "NodeText","Data": " で保存、"@@ -10244,7 +10253,7 @@},{"Type": "NodeText",- "Data": " でキャンセルできます。入力欄からフォーカスを移しても保存されます。変更は現在の画像参照にのみ適用され、アセットファイル名は変更されません。読み取り専用ドキュメントでは編集できません。"+ "Data": " でキャンセルできます。入力欄の外側をクリックするか、フォーカスを移しても保存されます。モバイルで戻る操作を行うと、まず保存して入力欄を閉じます。変更は現在の画像参照にのみ適用され、アセットファイル名は変更されません。読み取り専用ドキュメントでは編集できません。"}]},diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scssindex ebdd2b4ac3..3ad13996c1 100644--- a/app/src/assets/scss/business/_av.scss+++ b/app/src/assets/scss/business/_av.scss@@ -1063,14 +1063,6 @@}}- &__mask {- position: fixed;- top: 0;- bottom: 0;- right: 0;- left: 0;- }-&__richtext-mask {background: rgba(0, 0, 0, .08);}diff --git a/app/src/assets/scss/component/_text-field.scss b/app/src/assets/scss/component/_text-field.scssindex c58e69d7ad..51ebaa0cfc 100644--- a/app/src/assets/scss/component/_text-field.scss+++ b/app/src/assets/scss/component/_text-field.scss@@ -1,3 +1,14 @@+.b3-text-field__mask,+.av__mask {+ position: fixed;+ inset: 0;+}++.b3-text-field__mask > .b3-text-field {+ position: absolute;+ resize: none;+}+.b3-text-field {border: 0;border-radius: var(--b3-border-radius);diff --git a/app/src/block/panelOwnership.test.ts b/app/src/block/panelOwnership.test.tsindex 14649b741f..0ebfe21d43 100644--- a/app/src/block/panelOwnership.test.ts+++ b/app/src/block/panelOwnership.test.ts@@ -160,6 +160,7 @@ const fixture = () => {const zIndex = loadSource(readFileSync("src/util/zIndex.ts", "utf8"), globals);const Dialog = loadDialogMethods({...globals, ...ownership, ...zIndex,+ getAnchoredInputMask: () => document.querySelector?.(".b3-text-field__mask"),Constants: {TIMEOUT_DBLCLICK: 200},setTimeout: (callback: () => void) => timers.push(callback),getComputedStyle: (node: TestElement) => node.style,@@ -196,6 +197,24 @@ const fixture = () => {return {document, window, element, ownership, dialog, panel, destroyed, timers, removedListeners};};+test("dialog focus trap leaves the higher floating input in control of Tab", () => {+ const f = fixture();+ const owner = f.dialog();+ const mask = f.document.body.append(f.element("div", "b3-text-field__mask"));+ mask.style.zIndex = "100";+ const input = mask.append(f.element("textarea"));+ f.document.querySelector = () => mask;+ input.focus();+ const event = keyboardEvent();+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, false);+ assert.equal(f.document.activeElement, input);+ mask.style.zIndex = "1";+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, true);+ assert.equal(f.document.activeElement, owner.first);+});+test("panel ownership survives detached and moved recent-document anchors", () => {const f = fixture();const owner = f.dialog();diff --git a/app/src/dialog/anchoredInput.ts b/app/src/dialog/anchoredInput.tsnew file mode 100644index 0000000000..52db4eb2c2--- /dev/null+++ b/app/src/dialog/anchoredInput.ts@@ -0,0 +1,92 @@+import {bindAnchoredInputPosition} from "./anchoredInputPosition";+import {callMobileAppShowKeyboard} from "../mobile/util/mobileAppUtil";++let activeInput: {mask: HTMLElement, close: (save: boolean, restoreFocus?: boolean) => void};++export const getAnchoredInputMask = () => activeInput?.mask;++export const closeAnchoredInput = (save: boolean) => activeInput?.close(save, true);++export const openAnchoredInput = (options: {+ anchor: HTMLElement,+ value: string,+ label: string,+ isValid: () => boolean,+ save: (value: string) => void+}) => {+ activeInput?.close(true);+ const mask = document.createElement("div");+ mask.className = "b3-text-field__mask";+ mask.style.zIndex = (++window.siyuan.zIndex).toString();+ mask.setAttribute("role", "dialog");+ mask.setAttribute("aria-modal", "true");+ mask.setAttribute("aria-label", options.label);+ const input = document.createElement("textarea");+ input.className = "b3-text-field";+ input.rows = 1;+ input.value = options.value;+ input.setAttribute("aria-label", options.label);+ mask.append(input);+ document.body.append(mask);+ const disposePosition = bindAnchoredInputPosition(input, () => options.anchor, undefined, true);+ let finished = false;+ const close = (save: boolean, restoreFocus = false) => {+ if (finished) {+ return;+ }+ finished = true;+ if (activeInput?.mask === mask) {+ activeInput = undefined;+ }+ ownerObserver.disconnect();+ disposePosition();+ mask.remove();+ if (save && options.isValid()) {+ options.save(input.value);+ }+ if (restoreFocus && options.anchor.isConnected) {+ options.anchor.focus({preventScroll: true});+ }+ };+ // 正文重绘、锁定或标题更新后,关闭失效草稿,避免留下遮罩或覆盖新内容。+ const ownerObserver = new MutationObserver(() => {+ if (!mask.isConnected || !options.isValid()) {+ close(false);+ }+ });+ ownerObserver.observe(document.body, {childList: true, subtree: true, attributes: true,+ attributeFilter: ["class", "data-readonly", "data-title", "title"]});+ activeInput = {mask, close};+ input.addEventListener("blur", () => close(true));+ input.addEventListener("keydown", event => {+ event.stopPropagation();+ if (event.isComposing || event.keyCode === 229) {+ return;+ }+ if (event.key === "Enter" || event.key === "Escape" || event.key === "Tab") {+ event.preventDefault();+ close(event.key !== "Escape", true);+ }+ });+ for (const name of ["input", "beforeinput", "keyup", "compositionstart", "compositionend", "paste", "cut", "copy", "focusout", "dblclick"]) {+ input.addEventListener(name, event => event.stopPropagation());+ }+ mask.addEventListener("mousedown", event => {+ event.stopPropagation();+ if (event.target === mask) {+ event.preventDefault();+ }+ });+ mask.addEventListener("pointerdown", event => event.stopPropagation());+ mask.addEventListener("click", event => {+ event.stopPropagation();+ if (event.target === mask) {+ event.preventDefault();+ close(true, true);+ }+ });+ input.focus({preventScroll: true});+ input.select();+ callMobileAppShowKeyboard();+ return close;+};diff --git a/app/src/protyle/render/av/cellInputPosition.ts b/app/src/dialog/anchoredInputPosition.tssimilarity index 68%rename from app/src/protyle/render/av/cellInputPosition.tsrename to app/src/dialog/anchoredInputPosition.tsindex 0d954e34d4..94a72490f0 100644--- a/app/src/protyle/render/av/cellInputPosition.ts+++ b/app/src/dialog/anchoredInputPosition.ts@@ -1,5 +1,5 @@-export const bindAVCellInputPosition = (inputElement: HTMLElement, getAnchor: () => HTMLElement,- contentElement?: HTMLElement) => {+export const bindAnchoredInputPosition = (inputElement: HTMLElement, getAnchor: () => HTMLElement,+ contentElement?: HTMLElement, fitContent = false) => {const maskElement = inputElement.parentElement;let frame = 0;let disposed = false;@@ -25,6 +25,24 @@ export const bindAVCellInputPosition = (inputElement: HTMLElement, getAnchor: ()const cellRect = anchorElement.getBoundingClientRect();const maskRect = maskElement.getBoundingClientRect();const contentRect = contentElement?.getBoundingClientRect();+ if (fitContent) {+ const viewport = window.visualViewport;+ const viewportLeft = viewport?.offsetLeft || 0;+ const viewportTop = viewport?.offsetTop || 0;+ const viewportWidth = viewport?.width || window.innerWidth;+ const viewportHeight = viewport?.height || window.innerHeight;+ const width = Math.min(Math.max(cellRect.width, 240), Math.max(0, viewportWidth - 16));+ inputElement.style.width = `${width}px`;+ inputElement.style.height = "auto";+ const height = Math.min(Math.max(cellRect.height, inputElement.scrollHeight), Math.max(0, viewportHeight - 16));+ const left = Math.max(viewportLeft + 8, Math.min(cellRect.left, viewportLeft + viewportWidth - width - 8));+ const top = Math.max(viewportTop + 8, Math.min(cellRect.top, viewportTop + viewportHeight - height - 8));+ inputElement.style.left = `${left - maskRect.left}px`;+ inputElement.style.top = `${top - maskRect.top}px`;+ inputElement.style.height = `${height}px`;+ inputElement.style.visibility = "";+ return;+ }const width = contentRect ? Math.min(Math.max(cellRect.width, 25), contentRect.width) :Math.max(cellRect.width, 25);const left = contentRect && (cellRect.left < contentRect.left || cellRect.left + width > contentRect.right) ?@@ -69,11 +87,17 @@ export const bindAVCellInputPosition = (inputElement: HTMLElement, getAnchor: ()window.removeEventListener("resize", schedule);viewport?.removeEventListener("resize", schedule);viewport?.removeEventListener("scroll", schedule);+ if (fitContent) {+ inputElement.removeEventListener("input", schedule);+ }};window.addEventListener("scroll", schedule, {capture: true, passive: true});window.addEventListener("resize", schedule);viewport?.addEventListener("resize", schedule);viewport?.addEventListener("scroll", schedule);+ if (fitContent) {+ inputElement.addEventListener("input", schedule);+ }ownerObserver.observe(document.body, {childList: true, subtree: true, attributes: true, attributeFilter: ["class"]});update();// 焦点及键盘桥接调用结束后再次测量,避免沿用聚焦前的布局位置。diff --git a/app/src/dialog/index.ts b/app/src/dialog/index.tsindex ec7012c02f..7c647f7eb9 100644--- a/app/src/dialog/index.ts+++ b/app/src/dialog/index.ts@@ -6,6 +6,7 @@ import {isNotCtrl} from "../protyle/util/compatibility";import {Protyle} from "../protyle";import {Constants} from "../constants";import {destroyDialogBlockPanels, getDialogBlockPanel} from "../block/panelOwnership";+import {getAnchoredInputMask} from "./anchoredInput";export class Dialog {private destroyCallback: (options?: IObject) => void;@@ -26,6 +27,10 @@ export class Dialog {// 对话框上方的菜单也需要约束 Tab,避免从菜单末尾进入背景。const menu = window.siyuan.menus.menu.element;const dialog = this.element.querySelector(".b3-dialog") as HTMLElement;+ const inputMask = getAnchoredInputMask();+ if (inputMask?.contains(document.activeElement) && isAbove(inputMask, dialog)) {+ return;+ }const popover = getDialogBlockPanel(this.element, document.activeElement);const activePopover = popover && isAbove(popover, dialog) ? popover : undefined;// 浮窗正文中的 Tab 由编辑器处理,保留列表、表格和代码块的缩进操作。diff --git a/app/src/mobile/util/MobileBackFoward.test.ts b/app/src/mobile/util/MobileBackFoward.test.tsindex 1c9dc96d06..f76c3f2f05 100644--- a/app/src/mobile/util/MobileBackFoward.test.ts+++ b/app/src/mobile/util/MobileBackFoward.test.ts@@ -6,6 +6,45 @@ import {runInNewContext} from "node:vm";import {transpileModule, ModuleKind, ScriptTarget} from "typescript";import {isAbove} from "../../util/zIndex";+test("mobile back saves floating image titles before navigating or closing their owner", () => {+ const source = transpileModule(readFileSync(join(__dirname, "MobileBackFoward.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText;+ for (const overlay of ["document", "row", "dialog", "menu"]) {+ let saved = 0;+ let closedDialog = 0;+ let closedMenu = 0;+ let navigated = 0;+ const mask = {style: {zIndex: "2"}};+ const menu = {style: {zIndex: "3"}, classList: {contains: (name: string) =>+ name === "fn__none" ? overlay !== "menu" : true}, dispatchEvent: () => closedMenu++};+ const dialogs = overlay === "document" || overlay === "menu" ? [] : [{+ element: {querySelector: () => ({style: {zIndex: overlay === "dialog" ? "3" : "1"}})},+ destroy: () => closedDialog++,+ }];+ const modules: Record<string, unknown> = {+ "../editor": {getCurrentEditor: (): undefined => undefined},+ "../../util/zIndex": {isAbove},+ "./nativeSelect": {getMobileSelectMenuElement: (): undefined => undefined},+ "../../dialog/anchoredInput": {getAnchoredInputMask: () => mask,+ closeAnchoredInput: (save: boolean) => {assert.equal(save, true); saved++;}},+ };+ const api = {} as typeof import("./MobileBackFoward");+ runInNewContext(source, {+ exports: api, require: (name: string) => modules[name] || {}, CustomEvent: class {},+ document: {getElementById: () => ({style: {}}), querySelector: (): undefined => undefined},+ window: {siyuan: {dialogs, menus: {menu: {element: menu}}, mobile: {+ tabs: {goBack: () => {navigated++; return Promise.resolve(true);}},+ }}},+ });+ api.goBack();+ assert.equal(saved, overlay === "document" || overlay === "row" ? 1 : 0);+ assert.equal(closedDialog, overlay === "dialog" ? 1 : 0);+ assert.equal(closedMenu, overlay === "menu" ? 1 : 0);+ assert.equal(navigated, 0);+ }+});+test("mobile back saves the database text editor before leaving its owner", () => {const source = transpileModule(readFileSync(join(__dirname, "MobileBackFoward.ts"), "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},@@ -31,6 +70,7 @@ test("mobile back saves the database text editor before leaving its owner", () =}},"../../util/zIndex": {isAbove},"./nativeSelect": {getMobileSelectMenuElement: (): undefined => undefined},+ "../../dialog/anchoredInput": {getAnchoredInputMask: (): undefined => undefined},};const api = {} as typeof import("./MobileBackFoward");runInNewContext(source, {@@ -62,6 +102,7 @@ test("mobile back closes a select menu before its containing menu or dialog", ()"../editor": {getCurrentEditor: (): undefined => undefined},"../../util/zIndex": {isAbove},"./nativeSelect": {getMobileSelectMenuElement: () => selectMenu},+ "../../dialog/anchoredInput": {getAnchoredInputMask: (): undefined => undefined},};runInNewContext(source, {exports: api, require: (name: string) => modules[name] || {}, CustomEvent: class {},diff --git a/app/src/mobile/util/MobileBackFoward.ts b/app/src/mobile/util/MobileBackFoward.tsindex 703c0427ce..67cd2cbf6b 100644--- a/app/src/mobile/util/MobileBackFoward.ts+++ b/app/src/mobile/util/MobileBackFoward.ts@@ -6,6 +6,7 @@ import {backModel, destroyModel} from "../menu/model";import {destroyAVRichTextEditor} from "../../protyle/render/av/richTextEditor";import {isAbove} from "../../util/zIndex";import {getMobileSelectMenuElement} from "./nativeSelect";+import {closeAnchoredInput, getAnchoredInputMask} from "../../dialog/anchoredInput";export const pushBack = () => {window.siyuan.mobile.tabs?.pushCurrent();@@ -21,7 +22,14 @@ export const goBack = () => {const richTextElement = document.querySelector<HTMLElement>(".av__richtext-mask");const topDialog = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];const selectMenuElement = getMobileSelectMenuElement();- if (selectMenuElement && (!topDialog ||+ const inputMask = getAnchoredInputMask();+ const activeMenu = window.siyuan.menus.menu.element;+ if (inputMask && (!topDialog || isAbove(inputMask, topDialog.element.querySelector(".b3-dialog"))) &&+ (!selectMenuElement || isAbove(inputMask, selectMenuElement)) &&+ (activeMenu.classList.contains("fn__none") || isAbove(inputMask, activeMenu))) {+ closeAnchoredInput(true);+ return;+ } else if (selectMenuElement && (!topDialog ||isAbove(selectMenuElement, topDialog.element.querySelector(".b3-dialog")))) {selectMenuElement.dispatchEvent(new CustomEvent("click", {detail: "back"}));return;diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex 29c9fd6aaa..efce44904b 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -63,7 +63,7 @@ import {openAVRichTextEditor} from "./richTextEditor";import {getAVData, getAVPrimaryCell} from "./virtualScroll";import {AV_CELL_EDITOR_CLOSE_EVENT, getAVCellEditorOwner} from "./cellEditor";import {getAVBlockIconHTML, renderAVBlockIcon} from "./blockIcon";-import {bindAVCellInputPosition} from "./cellInputPosition";+import {bindAnchoredInputPosition} from "../../../dialog/anchoredInputPosition";import {createAVLocationFromText, createAVLocationReplacement, getAVLocationDisplayText, getAVLocationText, isAVLocationCoordinateInput, isAVLocationEmpty} from "./locationValue";import {openAVLocationEditor} from "./locationEditor";import {showMessage} from "../../../dialog/message";@@ -858,7 +858,7 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], typeconst anchorSelector = anchorRow && fieldID ?`${groupID ? `.av__body[data-group-id="${escapeAttr(groupID)}"] ` : ""}` +`.${anchorRow.classList.contains("av__row") ? "av__row" : "av__gallery-item"}[data-id="${anchorRow.dataset.id}"] .av__cell[${fieldAttr}="${fieldID}"]` : "";- bindAVCellInputPosition(inputElement, () => {+ bindAnchoredInputPosition(inputElement, () => {if (!cellElements[0].isConnected && anchorSelector && blockElement.isConnected) {// 行重绘后按原分组、行和字段重新绑定,输入内容继续保留在同一个编辑框中。const anchor = blockElement.querySelector<HTMLElement>(anchorSelector);diff --git a/app/src/protyle/render/av/cellInputPosition.test.ts b/app/src/protyle/render/av/cellInputPosition.test.tsindex 2a716bda98..57b374b4a8 100644--- a/app/src/protyle/render/av/cellInputPosition.test.ts+++ b/app/src/protyle/render/av/cellInputPosition.test.ts@@ -5,7 +5,7 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";-const compiled = transpileModule(readFileSync("src/protyle/render/av/cellInputPosition.ts", "utf8"), {+const compiled = transpileModule(readFileSync("src/dialog/anchoredInputPosition.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS},}).outputText;@@ -13,11 +13,13 @@ const rect = (left: number, top: number, width: number, height: number) => ({left, top, width, height, right: left + width, bottom: top + height,});-const setup = () => {+const setup = (fitContent = false) => {const frames = new Map<number, FrameRequestCallback>();let nextFrame = 0;class TestWindow extends EventTarget {- visualViewport = new EventTarget();+ visualViewport = Object.assign(new EventTarget(), {offsetLeft: 0, offsetTop: 0, width: 360, height: 800});+ innerWidth = 360;+ innerHeight = 800;requestAnimationFrame(callback: FrameRequestCallback) {frames.set(++nextFrame, callback);return nextFrame;@@ -52,12 +54,14 @@ const setup = () => {const mask = {isConnected: true, rect: rect(0, 0, 360, 800), getBoundingClientRect() {return this.rect;}};let anchor = {isConnected: true, rect: rect(40, 500, 220, 36), getBoundingClientRect() {return this.rect;}};const content = {rect: rect(16, 90, 328, 710), getBoundingClientRect() {return this.rect;}};- const input = {parentElement: mask, style: {} as Record<string, string>, value: "draft"};- const exports: {bindAVCellInputPosition?: (input: unknown, anchor: () => unknown, content?: unknown) => () => void} = {};+ const input = Object.assign(new EventTarget(), {parentElement: mask, style: {} as Record<string, string>,+ value: "draft", scrollHeight: 400});+ const exports: {bindAnchoredInputPosition?: (input: unknown, anchor: () => unknown, content?: unknown,+ fitContent?: boolean) => () => void} = {};runInNewContext(compiled, {exports, window, document: {body: {}}, MutationObserver: TestObserver, ResizeObserver: TestObserver,});- const dispose = exports.bindAVCellInputPosition(input, () => anchor, content);+ const dispose = exports.bindAnchoredInputPosition(input, () => anchor, content, fitContent);const flush = () => {const pending = Array.from(frames.values());frames.clear();@@ -67,6 +71,34 @@ const setup = () => {get anchor() {return anchor;}, set anchor(value) {anchor = value;}};};+test("floating input fits its draft inside the visible viewport when the mobile keyboard opens", () => {+ const f = setup(true);+ assert.equal(f.input.style.width, "240px");+ assert.equal(f.input.style.height, "400px");+ assert.equal(f.input.style.top, "392px");+ f.window.visualViewport.height = 320;+ f.window.visualViewport.dispatchEvent(new Event("resize"));+ f.flush();+ assert.equal(f.input.style.height, "304px");+ assert.equal(f.input.style.top, "8px");+ Object.assign(f.window.visualViewport, {width: 180, height: 250, offsetLeft: 12, offsetTop: 150});+ f.mask.rect = rect(8, 120, 180, 250);+ f.window.visualViewport.dispatchEvent(new Event("scroll"));+ f.flush();+ assert.equal(f.input.style.width, "164px");+ assert.equal(f.input.style.left, "12px");+ assert.equal(f.input.style.top, "38px");+ assert.equal(f.input.style.height, "234px");+ f.input.scrollHeight = 60;+ f.input.dispatchEvent(new Event("input"));+ f.flush();+ assert.equal(f.input.style.height, "60px");+ assert.equal(f.input.value, "draft");+ f.dispose();+ f.input.dispatchEvent(new Event("input"));+ assert.equal(f.frames.size, 0);+});+test("cell input follows native keyboard opening and closing without replacing the draft", () => {const fixture = setup();assert.equal(fixture.input.style.top, "500px");@@ -212,7 +244,7 @@ const openInput = (positionByMenu = false) => {AV_CELL_EDITOR_CLOSE_EVENT: "close", callMobileAppShowKeyboard: () => {},window: {siyuan: {menus: {menu: {remove: () => {}}}, zIndex: 0}},document: {querySelector: () => inserted ? mask : null, body: {insertAdjacentHTML: () => {inserted = true;}}},- bindAVCellInputPosition: (_input: unknown, getter: () => unknown) => {getAnchor = getter;},+ bindAnchoredInputPosition: (_input: unknown, getter: () => unknown) => {getAnchor = getter;},setPosition: () => {menuPositioned = true;},});exports.popTextCell({}, cells, "block", {scrollIntoView: false, positionByMenu});diff --git a/app/src/protyle/render/av/locationIntegration.test.ts b/app/src/protyle/render/av/locationIntegration.test.tsindex 220c12f65d..7c09230be2 100644--- a/app/src/protyle/render/av/locationIntegration.test.ts+++ b/app/src/protyle/render/av/locationIntegration.test.ts@@ -20,7 +20,7 @@ const unusedDependencies = ["../../../util/pathName", "./select", "../../undo", "./dateFormat", "./row", "./view", "../../../util/image","../../../util/imageURL", "../../../mobile/util/mobileAppUtil", "../../../mobile/util/keyboardToolbar","../../../util/setPosition", "./selectionState", "./color", "./richText", "./richTextEditor", "./virtualScroll",- "./cellEditor", "./blockIcon", "./cellInputPosition", "./locationEditor", "../../../dialog/message",+ "./cellEditor", "./blockIcon", "../../../dialog/anchoredInputPosition", "./locationEditor", "../../../dialog/message","../../../util/hostCapabilities", "../../../plugin/Menu", "../../../util/upDownHint", "./richTextValue","../../../emoji/fileTreeIcon", "./lunarDate",];diff --git a/app/src/protyle/render/imageTitleEditor.test.ts b/app/src/protyle/render/imageTitleEditor.test.tsindex c470de8938..8416ad5c56 100644--- a/app/src/protyle/render/imageTitleEditor.test.ts+++ b/app/src/protyle/render/imageTitleEditor.test.ts@@ -6,24 +6,33 @@ import * as path from "node:path";import {test} from "node:test";import {promisify} from "node:util";import {ScriptTarget, transpileModule} from "typescript";+import {compile} from "sass";-const browserCases = async (source: string, luteSource: string) => {+const browserCases = async (source: string, luteSource: string, css: string, caseName: string) => {const check: typeof assert = require("node:assert/strict");new Function(luteSource)();const lute = Lute.New();Object.assign(window, {siyuan: {config: {editor: {displayImgName: false, displayImgAlt: false}, readonly: false},- languages: {title: "Title"}}});+ languages: {title: "Title"}, zIndex: 1}});+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);const root = document.createElement("div");root.className = "protyle-wysiwyg";root.innerHTML = lute.Md2BlockDOM('');document.body.append(root);+ root.style.width = "min(600px, calc(100vw - 32px))";+ root.style.margin = "40px 16px";+ const next = document.createElement("p");+ next.textContent = "Following paragraph";+ document.body.append(next);const transactions: {oldHTML: string, newHTML: string}[] = [];const api = new Function("dayjs", "hideTooltip", "hasClosestBlock", "updateTransaction", "TABLE_CELL_RICH_ATTRIBUTE",- "getAssetName", "getAssetExtension", "renameAsset", "isEncryptedBox", source +- "\nreturn {bindImageTitleEditor, renderImageDisplay, getImageTitle, setImageTitle};")(+ "getAssetName", "getAssetExtension", "renameAsset", "isEncryptedBox", "callMobileAppShowKeyboard", source ++ "\nreturn {bindImageTitleEditor, renderImageDisplay, getImageTitle, setImageTitle, getAnchoredInputMask};")(() => ({format: () => "20261010140000"}), () => {}, (element: HTMLElement) => element.closest("[data-node-id]"),(_protyle: IProtyle, block: HTMLElement, oldHTML: string) => transactions.push({oldHTML, newHTML: block.outerHTML}),- "custom-sy-cell-rich", () => "image", () => ".png", () => {}, () => false,+ "custom-sy-cell-rich", () => "image", () => ".png", () => {}, () => false, () => {},);const protyle = {disabled: false, toolbar: {isMultiSelectMode: () => false}};api.renderImageDisplay(root);@@ -36,15 +45,34 @@ const browserCases = async (source: string, luteSource: string) => {root.addEventListener("keydown", () => editorKeys++);const caption = () => root.querySelector<HTMLElement>(".protyle-action__title");const image = () => root.querySelector<HTMLImageElement>("img");- const textarea = () => root.querySelector<HTMLTextAreaElement>("textarea");+ const textarea = () => document.querySelector<HTMLTextAreaElement>(".b3-text-field__mask textarea");const original = lute.BlockDOM2StdMd(root.innerHTML);+ image().style.width = "180px";+ image().style.height = "140px";+ await document.fonts.ready;+ await new Promise(requestAnimationFrame);+ const originalHTML = root.innerHTML;+ const originalNextTop = next.getBoundingClientRect().top;check.equal(caption().tabIndex, 0);caption().dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));check.equal(editorKeys, 0, "caption activation does not insert a paragraph");check.equal(textarea().value, "original");+ check.equal(root.querySelector("textarea"), null, "draft input is outside the editable document");+ check.equal(api.getAnchoredInputMask().parentElement, document.body);+ check.equal(api.getAnchoredInputMask().getAttribute("aria-modal"), "true");+ check.equal(document.elementFromPoint(innerWidth - 8, innerHeight - 8), api.getAnchoredInputMask(),+ "global mask intercepts background pointer actions");+ if (process.env.SIYUAN_IMAGE_TITLE_CAPTURE) {+ await require("electron").ipcRenderer.invoke("capture", caseName);+ }check.equal(editorClicks, 0, "caption clicks do not trigger image menus or previews");- textarea().value = "cancelled";+ textarea().value = "cancelled\n".repeat(50);textarea().dispatchEvent(new InputEvent("input", {bubbles: true}));+ await new Promise(requestAnimationFrame);+ check.equal(root.innerHTML, originalHTML, "typing does not mutate document nodes");+ check.equal(next.getBoundingClientRect().top, originalNextTop, "growing input does not shift following content");+ check.ok(textarea().getBoundingClientRect().bottom <= innerHeight - 8);+ check.equal(getComputedStyle(textarea()).resize, "none", "resizing cannot stretch the editor layout");check.equal(editorInputs, 0);textarea().dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));check.equal(textarea(), null);@@ -77,7 +105,7 @@ const browserCases = async (source: string, luteSource: string) => {check.equal(document.activeElement, textarea(), "title textarea receives focus on touch editing");textarea().blur();textarea()?.dispatchEvent(new FocusEvent("blur"));- check.equal(textarea(), null, "blur closes the inline title editor");+ check.equal(textarea(), null, "blur closes the floating title editor");check.equal(transactions.length, 2);check.equal(api.getImageTitle(image()), "touch edit");@@ -112,10 +140,37 @@ const browserCases = async (source: string, luteSource: string) => {check.equal(api.getImageTitle(image()), "remote title");check.equal(caption().textContent, "remote title");check.equal(transactions.length, 3, "concurrent title updates are not overwritten");+ const clicksBeforeMask = editorClicks;+ caption().click();+ textarea().value = "outside save";+ const mask = api.getAnchoredInputMask();+ mask.dispatchEvent(new MouseEvent("mousedown", {bubbles: true, cancelable: true}));+ check.ok(textarea(), "mask stays in place until click to prevent click-through");+ mask.click();+ check.equal(api.getImageTitle(image()), "outside save");+ check.equal(editorClicks, clicksBeforeMask, "outside click does not reach the editor behind the mask");+ check.equal(transactions.length, 4);+ caption().click();+ textarea().value = "tab save";+ textarea().dispatchEvent(new KeyboardEvent("keydown", {key: "Tab", bubbles: true, cancelable: true}));+ check.equal(api.getImageTitle(image()), "tab save");+ check.equal(document.activeElement, caption());+ check.equal(transactions.length, 5);+ caption().click();+ textarea().value = "detached draft";+ const block = image().closest("[data-node-id]");+ const savedBlock = block.outerHTML;+ block.remove();+ await new Promise(requestAnimationFrame);+ check.equal(textarea(), null, "removing the owning image releases the global mask");+ check.equal(api.getAnchoredInputMask(), undefined);+ check.equal(transactions.length, 5);+ root.insertAdjacentHTML("afterbegin", savedBlock);+ api.renderImageDisplay(root);caption().click();textarea().value = "";binding.destroy();- check.equal(transactions.length, 4);+ check.equal(transactions.length, 6);check.equal(api.getImageTitle(image()), "");check.equal(image().hasAttribute("data-title"), false);check.equal(textarea(), null);@@ -124,25 +179,44 @@ const browserCases = async (source: string, luteSource: string) => {return "Image title editor cases passed";};-test("image titles support inline saving, cancellation, IME, touch and undo without leaking draft controls", {+test("image titles use a global floating input without changing document layout or leaking drafts", {skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,timeout: 45000,}, async () => {- const source = ["imageTitle.ts", "imageDisplay.ts", "imageTitleEditor.ts"].map(file =>+ const source = ["../../dialog/anchoredInputPosition.ts", "../../dialog/anchoredInput.ts",+ "imageTitle.ts", "imageDisplay.ts", "imageTitleEditor.ts"].map(file =>transpileModule(readFileSync(path.join(__dirname, file), "utf8").replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),{compilerOptions: {target: ScriptTarget.ES2021}}).outputText).join("\n");const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-image-title-test-"));const script = path.join(temporary, "run.cjs");- const code = "const __name = value => value; (" + browserCases.toString() + ")(" + JSON.stringify(source) + "," +- JSON.stringify(readFileSync("stage/protyle/js/lute/lute.min.js", "utf8")) + ")";- writeFileSync(script, `const {app, BrowserWindow} = require("electron");+ const css = compile("src/assets/scss/base.scss", {logger: {warn: () => {}}}).css;+ const cases = [{name: "daylight", width: 800, theme: "daylight"}, {name: "dark", width: 800, theme: "midnight"},+ {name: "narrow-large-font", width: 320, theme: "daylight"}].map(fixture => ({...fixture,+ code: "const __name = value => value; (" + browserCases.toString() + ")(" + JSON.stringify(source) + "," ++ JSON.stringify(readFileSync("stage/protyle/js/lute/lute.min.js", "utf8")) + "," ++ JSON.stringify(css + readFileSync(`appearance/themes/${fixture.theme}/theme.css`, "utf8") ++ (fixture.width === 320 ? ".protyle-wysiwyg {font-size:32px;}" : "")) + "," ++ JSON.stringify(fixture.name) + ")",+ }));+ writeFileSync(script, `const {app, BrowserWindow, ipcMain} = require("electron");+const {writeFileSync} = require("node:fs");+const path = require("node:path");app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.on("window-all-closed", () => {});app.whenReady().then(async () => {- const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ let win;+ ipcMain.handle("capture", async (_event, name) => {+ writeFileSync(path.join(process.env.SIYUAN_IMAGE_TITLE_CAPTURE, name + ".png"), (await win.capturePage()).toPNG());+ });try {- await win.loadURL("data:text/html,<html><body></body></html>");- console.log(await win.webContents.executeJavaScript(${JSON.stringify(code)}));+ for (const fixture of ${JSON.stringify(cases)}) {+ win = new BrowserWindow({show: false, width: fixture.width, height: 600,+ webPreferences: {nodeIntegration: true, contextIsolation: false}});+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(fixture.code));+ win.destroy();+ }app.exit(0);} catch (error) { console.error(error); app.exit(1); }});`, "utf8");diff --git a/app/src/protyle/render/imageTitleEditor.ts b/app/src/protyle/render/imageTitleEditor.tsindex 50a00bc7a3..b3e1e3cdef 100644--- a/app/src/protyle/render/imageTitleEditor.ts+++ b/app/src/protyle/render/imageTitleEditor.ts@@ -4,6 +4,7 @@ import {getImageTitle, setImageTitle} from "./imageTitle";import {hasClosestBlock} from "../util/hasClosest";import {updateTransaction} from "../wysiwyg/transaction";import {TABLE_CELL_RICH_ATTRIBUTE} from "../util/tableCellRichValue";+import {openAnchoredInput} from "../../dialog/anchoredInput";export const bindImageTitleEditor = (protyle: IProtyle, root: HTMLElement) => {let finishActive: (save: boolean) => void;@@ -20,70 +21,35 @@ export const bindImageTitleEditor = (protyle: IProtyle, root: HTMLElement) => {if (!image || !text || !block || !canEdit(title)) {return false;}- if (text.querySelector("textarea")) {- return true;- }finishActive?.(true);hideTooltip();const originalTitle = getImageTitle(image);- const originalContent = Array.from(text.childNodes);- const input = document.createElement("textarea");- input.className = "b3-text-field fn__block";- input.rows = 1;- input.value = originalTitle;- input.setAttribute("aria-label", window.siyuan.languages.title);- const resize = () => {- input.style.height = "auto";- input.style.height = `${Math.min(input.scrollHeight, Math.max(60, window.innerHeight * 0.4))}px`;- };- input.addEventListener("input", resize);- let finished = false;- const finish = (save: boolean) => {- if (finished) {- return;- }- finished = true;- finishActive = undefined;- const value = input.value;- const current = root.contains(image) && root.contains(text) && text.contains(input);- if (!current) {- return;- }- text.replaceChildren(...originalContent);- const currentTitle = getImageTitle(image);- if (currentTitle !== originalTitle) {- text.textContent = currentTitle;- return;- }- if (!save || !canEdit(title) || value === originalTitle) {- return;- }- const oldHTML = block.outerHTML;- setImageTitle(image, value);- text.textContent = value;- block.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));- updateTransaction(protyle, block, oldHTML);- };- finishActive = finish;- input.addEventListener("blur", () => finish(true));- input.addEventListener("keydown", event => {- event.stopPropagation();- if (event.isComposing || event.keyCode === 229) {- return;- }- if (event.key === "Enter" || event.key === "Escape") {- event.preventDefault();- finish(event.key === "Enter");- title.focus();- }+ finishActive = openAnchoredInput({+ anchor: title,+ value: originalTitle,+ label: window.siyuan.languages.title,+ isValid: () => {+ if (!root.contains(image) || !root.contains(text) || !canEdit(title)) {+ return false;+ }+ const currentTitle = getImageTitle(image);+ if (currentTitle !== originalTitle) {+ text.textContent = currentTitle;+ return false;+ }+ return true;+ },+ save: value => {+ if (value === originalTitle) {+ return;+ }+ const oldHTML = block.outerHTML;+ setImageTitle(image, value);+ text.textContent = value;+ block.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));+ updateTransaction(protyle, block, oldHTML);+ },});- for (const name of ["input", "beforeinput", "keyup", "compositionstart", "compositionend", "paste", "cut", "copy", "focusout", "dblclick"]) {- input.addEventListener(name, event => event.stopPropagation());- }- text.replaceChildren(input);- resize();- input.focus();- input.select();return true;};const getTitle = (event: Event) => {