Skip to content

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

:sparkles: Support inline image title editing https://github.com/siyuan-note/siyuan/issues/20397

Daniel98d6a3ab8aa8
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.sy
index e381bf81aa..e2aa3e22c2 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": "20261009184321"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -4274,7 +4274,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210106154056-koo4wdj",
- "updated": "20261008221006"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10165,7 +10165,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260928091724-mshqwvb",
- "updated": "20260930171029"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10229,6 +10229,71 @@
}
]
},
+ {
+ "ID": "20261010134815-v9k29uo",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261010134815-v9k29uo",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Image title"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261010134815-bb1k769",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010134815-bb1k769",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Click or tap the title below an image to edit it inline. When the title is focused, press "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " or "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Space"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to start editing. While editing, press "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to save or "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "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."
+ }
+ ]
+ },
{
"ID": "20210106154319-d0mxz1p",
"Type": "NodeHeading",
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.sy
index ffb4a61eda..c0f46ce924 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": "20261009184321"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -4272,7 +4272,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20201227133317-rkh4bji",
- "updated": "20261008221006"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10153,7 +10153,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260928091724-31ks0a6",
- "updated": "20260930171029"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10217,6 +10217,71 @@
}
]
},
+ {
+ "ID": "20261010134815-nlwueda",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261010134815-nlwueda",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "图片标题"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261010134815-gzdtswz",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010134815-gzdtswz",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "点击图片下方的标题可就地编辑,移动端可轻点标题。标题获得焦点时,按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 或 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Space"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 开始编辑;编辑时按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 保存,按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 取消,离开输入框也会保存。修改仅作用于当前图片引用,不会重命名资源文件。只读文档不支持编辑标题。"
+ }
+ ]
+ },
{
"ID": "20210102174148-tq925jm",
"Type": "NodeHeading",
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.sy
index ac5b5040a0..3cce32fada 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": "20261009184321"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -4266,7 +4266,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226122652-htptsmh",
- "updated": "20261008221006"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10142,7 +10142,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260928091724-sj0935a",
- "updated": "20260930171029"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10206,6 +10206,71 @@
}
]
},
+ {
+ "ID": "20261010134815-lhna2cb",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261010134815-lhna2cb",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "圖片標題"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261010134815-mtfjptp",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010134815-mtfjptp",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "點擊圖片下方的標題可就地編輯,行動裝置可輕觸標題。標題取得焦點時,按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 或 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Space"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 開始編輯;編輯時按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 儲存,按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 取消,離開輸入框也會儲存。修改僅作用於目前的圖片引用,不會重新命名資源文件。唯讀文檔不支援編輯標題。"
+ }
+ ]
+ },
{
"ID": "20211226122652-8191vgw",
"Type": "NodeHeading",
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.sy
index f1f58b9152..19f6c8576f 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": "20261009184321"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -4228,7 +4228,7 @@
"Properties": {
"ID": "20240530101000-twmuxke",
"id": "20240530101000-675gu9g",
- "updated": "20261008221006"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10082,7 +10082,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260928091724-dfq9c2s",
- "updated": "20260930171029"
+ "updated": "20261010134815"
},
"Children": [
{
@@ -10146,6 +10146,71 @@
}
]
},
+ {
+ "ID": "20261010134815-h903uwh",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261010134815-h903uwh",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "画像のタイトル"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261010134815-pbj3gz0",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010134815-pbj3gz0",
+ "updated": "20261010134815"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "画像の下にあるタイトルをクリックまたはタップすると、その場で編集できます。タイトルにフォーカスがあるときは "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " または "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Space"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で編集を開始します。編集中は "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Enter"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で保存、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " でキャンセルできます。入力欄からフォーカスを移しても保存されます。変更は現在の画像参照にのみ適用され、アセットファイル名は変更されません。読み取り専用ドキュメントでは編集できません。"
+ }
+ ]
+ },
{
"ID": "20240530101000-zy0pmo3",
"Type": "NodeHeading",
diff --git a/app/src/protyle/render/imageDisplay.ts b/app/src/protyle/render/imageDisplay.ts
index 59e0607a3e..4a0e5f9b11 100644
--- a/app/src/protyle/render/imageDisplay.ts
+++ b/app/src/protyle/render/imageDisplay.ts
@@ -14,6 +14,21 @@ export const renderImageDisplay = (root: Element) => {
root.querySelectorAll<HTMLImageElement>(".img img").forEach(image => {
setImageTitle(image, getImageTitle(image));
const container = image.parentElement;
+ const title = container.querySelector<HTMLElement>(".protyle-action__title");
+ if (title) {
+ const wysiwyg = image.closest(".protyle-wysiwyg");
+ if (getImageTitle(image) && wysiwyg && wysiwyg.getAttribute("data-readonly") !== "true" &&
+ !window.siyuan.config.readonly && !window.siyuan.isPublish &&
+ !image.closest(".protyle-wysiwyg__embed, .mindmap-view__preview-block")) {
+ title.tabIndex = 0;
+ title.setAttribute("role", "button");
+ title.setAttribute("aria-label", window.siyuan.languages.title);
+ } else {
+ title.removeAttribute("tabindex");
+ title.removeAttribute("role");
+ title.removeAttribute("aria-label");
+ }
+ }
let alt = container.querySelector<HTMLElement>(".img__alt");
if (window.siyuan.config.editor.displayImgAlt && image.alt) {
if (!alt) {
diff --git a/app/src/protyle/render/imageTitleEditor.test.ts b/app/src/protyle/render/imageTitleEditor.test.ts
new file mode 100644
index 0000000000..c470de8938
--- /dev/null
+++ b/app/src/protyle/render/imageTitleEditor.test.ts
@@ -0,0 +1,160 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string, luteSource: 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"}}});
+ const root = document.createElement("div");
+ root.className = "protyle-wysiwyg";
+ root.innerHTML = lute.Md2BlockDOM('![description](assets/image.png "original")');
+ document.body.append(root);
+ 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};")(
+ () => ({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,
+ );
+ const protyle = {disabled: false, toolbar: {isMultiSelectMode: () => false}};
+ api.renderImageDisplay(root);
+ const binding = api.bindImageTitleEditor(protyle, root);
+ let editorClicks = 0;
+ let editorInputs = 0;
+ let editorKeys = 0;
+ root.addEventListener("click", () => editorClicks++);
+ root.addEventListener("input", () => editorInputs++);
+ 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 original = lute.BlockDOM2StdMd(root.innerHTML);
+ 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(editorClicks, 0, "caption clicks do not trigger image menus or previews");
+ textarea().value = "cancelled";
+ textarea().dispatchEvent(new InputEvent("input", {bubbles: true}));
+ check.equal(editorInputs, 0);
+ textarea().dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
+ check.equal(textarea(), null);
+ check.equal(transactions.length, 0);
+ check.equal(lute.BlockDOM2StdMd(root.innerHTML), original);
+
+ caption().click();
+ textarea().value = "<literal> & updated";
+ textarea().dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", isComposing: true, bubbles: true}));
+ check.ok(textarea(), "IME confirmation does not save the draft");
+ textarea().dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));
+ check.equal(transactions.length, 1);
+ check.equal(api.getImageTitle(image()), "<literal> & updated");
+ check.equal(caption().textContent, "<literal> & updated");
+ check.equal(caption().querySelector("literal"), null);
+ check.equal(image().hasAttribute("title"), false);
+ check.match(lute.BlockDOM2StdMd(root.innerHTML), /"<literal> & updated"/);
+ check.equal(lute.BlockDOM2StdMd(transactions[0].oldHTML), original);
+ check.equal(transactions[0].newHTML.includes("textarea"), false);
+ check.equal(transactions[0].oldHTML.includes("textarea"), false);
+
+ root.innerHTML = transactions[0].oldHTML;
+ api.renderImageDisplay(root);
+ check.equal(lute.BlockDOM2StdMd(root.innerHTML), original, "undo restores the previous caption");
+ root.setAttribute("contenteditable", "false");
+ caption().dispatchEvent(new PointerEvent("pointerdown", {pointerType: "touch", bubbles: true}));
+ caption().click();
+ check.ok(textarea(), "mobile captions use the same editing entry point");
+ textarea().value = "touch edit";
+ 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(transactions.length, 2);
+ check.equal(api.getImageTitle(image()), "touch edit");
+
+ root.setAttribute("data-readonly", "true");
+ caption().click();
+ check.equal(textarea(), null);
+ root.removeAttribute("data-readonly");
+ caption().click();
+ textarea().value = "locked draft";
+ protyle.disabled = true;
+ binding.flush();
+ check.equal(transactions.length, 2);
+ check.equal(api.getImageTitle(image()), "touch edit");
+ protyle.disabled = false;
+ caption().click();
+ textarea().value = "pending draft";
+ binding.flush();
+ check.equal(transactions.length, 3, "editor handoff saves the pending draft");
+ check.equal(textarea(), null);
+
+ api.setImageTitle(image(), "first\nsecond");
+ caption().firstElementChild.textContent = "first\nsecond";
+ caption().click();
+ check.equal(textarea().value, "first\nsecond");
+ textarea().blur();
+ textarea()?.dispatchEvent(new FocusEvent("blur"));
+ check.equal(transactions.length, 3, "opening a multiline title preserves it without creating a transaction");
+ caption().click();
+ textarea().value = "stale draft";
+ api.setImageTitle(image(), "remote title");
+ binding.flush();
+ check.equal(api.getImageTitle(image()), "remote title");
+ check.equal(caption().textContent, "remote title");
+ check.equal(transactions.length, 3, "concurrent title updates are not overwritten");
+ caption().click();
+ textarea().value = "";
+ binding.destroy();
+ check.equal(transactions.length, 4);
+ check.equal(api.getImageTitle(image()), "");
+ check.equal(image().hasAttribute("data-title"), false);
+ check.equal(textarea(), null);
+ caption().click();
+ check.equal(textarea(), null, "destroy removes delegated listeners");
+ return "Image title editor cases passed";
+};
+
+test("image titles support inline saving, cancellation, IME, touch and undo without leaking draft controls", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const source = ["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");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code)}));
+ app.exit(0);
+ } catch (error) { console.error(error); app.exit(1); }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, windowsHide: true, timeout: 40000});
+ assert.match(result.stdout, /Image title editor cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) && path.basename(temporary).startsWith("siyuan-image-title-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/protyle/render/imageTitleEditor.ts b/app/src/protyle/render/imageTitleEditor.ts
new file mode 100644
index 0000000000..50a00bc7a3
--- /dev/null
+++ b/app/src/protyle/render/imageTitleEditor.ts
@@ -0,0 +1,132 @@
+import * as dayjs from "dayjs";
+import {hideTooltip} from "../../dialog/tooltip";
+import {getImageTitle, setImageTitle} from "./imageTitle";
+import {hasClosestBlock} from "../util/hasClosest";
+import {updateTransaction} from "../wysiwyg/transaction";
+import {TABLE_CELL_RICH_ATTRIBUTE} from "../util/tableCellRichValue";
+
+export const bindImageTitleEditor = (protyle: IProtyle, root: HTMLElement) => {
+ let finishActive: (save: boolean) => void;
+ const canEdit = (title: HTMLElement) => !protyle.disabled && !window.siyuan.config.readonly &&
+ !window.siyuan.isPublish && root.getAttribute("data-readonly") !== "true" &&
+ title.closest(".protyle-wysiwyg") === root &&
+ !title.closest(".protyle-wysiwyg__embed, .mindmap-view__preview-block") &&
+ (!title.closest(`[${TABLE_CELL_RICH_ATTRIBUTE}]`) || title.closest(".table__cell-editor")) &&
+ !protyle.toolbar?.isMultiSelectMode();
+ const open = (title: HTMLElement) => {
+ const image = title.parentElement.querySelector<HTMLImageElement>("img");
+ const text = title.querySelector<HTMLElement>(":scope > span");
+ const block = hasClosestBlock(title);
+ 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();
+ }
+ });
+ 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) => {
+ const title = event.target instanceof Element ? event.target.closest<HTMLElement>(".protyle-action__title") : null;
+ return title?.closest(".img") ? title : null;
+ };
+ const onPress = (event: Event) => {
+ if (event instanceof MouseEvent && (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey)) {
+ return;
+ }
+ const title = getTitle(event);
+ if (title && canEdit(title)) {
+ event.stopPropagation();
+ }
+ };
+ const onClick = (event: MouseEvent) => {
+ const title = getTitle(event);
+ if (title && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey && open(title)) {
+ if (!(event.target instanceof HTMLTextAreaElement)) {
+ event.preventDefault();
+ }
+ event.stopImmediatePropagation();
+ }
+ };
+ const onKeydown = (event: KeyboardEvent) => {
+ const title = getTitle(event);
+ if (title === event.target && !event.isComposing && (event.key === "Enter" || event.key === " ") && open(title)) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ };
+ root.addEventListener("mousedown", onPress, true);
+ root.addEventListener("pointerdown", onPress, true);
+ root.addEventListener("click", onClick, true);
+ root.addEventListener("keydown", onKeydown);
+ return {
+ flush: () => finishActive?.(true),
+ destroy: () => {
+ finishActive?.(true);
+ root.removeEventListener("mousedown", onPress, true);
+ root.removeEventListener("pointerdown", onPress, true);
+ root.removeEventListener("click", onClick, true);
+ root.removeEventListener("keydown", onKeydown);
+ },
+ };
+};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index f50547ab5b..0aa16937bd 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -243,6 +243,7 @@ import {LargeTableVirtualizer} from "./tableVirtualization";
import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";
import {syncRootAttributes} from "../util/syncRootAttributes";
+import {bindImageTitleEditor} from "../render/imageTitleEditor";
import {isDirectCalloutStructureClick} from "./calloutClick";
import {
BLOCK_SELECTION_CLASS,
@@ -415,6 +416,7 @@ export class WYSIWYG {
private disposeHeadingFoldIndicators?: () => void;
private disposeBoundedBlockDragSelect?: () => void;
private disposeTouchCaret?: () => void;
+ private imageTitleEditor: ReturnType<typeof bindImageTitleEditor>;
private scheduleInput(callback: () => void | Promise<void>, delay = 0, replace = true) {
if (replace && this.inputTimeout) {
@@ -445,6 +447,7 @@ export class WYSIWYG {
}
public async flushPendingInput() {
+ this.imageTitleEditor?.flush();
this.persistComposition?.();
// 输入处理可能等待块引用查询,交接编辑器前也需等待已经开始执行的任务。
while (this.pendingInputTimeouts.size || this.runningInputTasks.size) {
@@ -542,6 +545,7 @@ export class WYSIWYG {
this.tableControl = new TableControl(protyle, this.element);
}
this.bindCommonEvent(protyle);
+ this.imageTitleEditor = bindImageTitleEditor(protyle, this.element);
this.bindEvent(protyle);
this.disposeEmbedToolbarVisibility = bindEmbedToolbarVisibility(this.element);
/// #if BROWSER
@@ -588,6 +592,7 @@ export class WYSIWYG {
}
public destroy() {
+ this.imageTitleEditor?.destroy();
this.persistComposition?.();
this.persistComposition = undefined;
this.disposeHeadingFoldIndicators?.();