Skip to content

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

:sparkles: Improve image OCR actions and copying https://github.com/siyuan-note/siyuan/issues/20396

Daniel0985bf451850
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
index 7c6766665a..e4fa02e395 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
@@ -6,7 +6,7 @@
"id": "20200924100744-br924ar",
"title": "Assets",
"type": "doc",
- "updated": "20261006114009"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1355,7 +1355,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202934-1h96or8",
- "updated": "20261006110222"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1482,7 +1482,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-3zn8sf9",
- "updated": "20260930090802"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1519,6 +1519,37 @@
{
"Type": "NodeText",
"Data": " to show or hide it. The image menu remains available for copying and editing OCR text."
+ },
+ {
+ "Type": "NodeText",
+ "Data": " Hover over a local image to view its OCR text; an empty result is shown explicitly. The text selection icon identifies the OCR action, while the image icon copies the image as PNG, even when no OCR text is available. In a custom appearance profile, use "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Editor"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Image"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Copy as PNG"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to show or hide the image copy button; it is hidden in the Simple profile."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
index 50fe8a531d..613d69513a 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
@@ -6,7 +6,7 @@
"id": "20200915214115-42b8zma",
"title": "资源文件",
"type": "doc",
- "updated": "20261006114009"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1363,7 +1363,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202710-a51lo76",
- "updated": "20261006110222"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1490,7 +1490,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-qkecuzx",
- "updated": "20260930090802"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1527,6 +1527,37 @@
{
"Type": "NodeText",
"Data": " 设置显示或隐藏。也可继续通过图片菜单复制和编辑 OCR 文本。"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "悬浮在本地图片上可查看 OCR 文字,无识别结果时会显示空内容提示。文字选择图标表示 OCR 操作,图片图标则将图片复制为 PNG,无 OCR 文字时也可复制图片。在自定义外观方案中,可通过 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "编辑器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "图片"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "复制为 PNG"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 显示或隐藏图片复制按钮;该按钮在简洁方案中默认隐藏。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
index 958412d8f5..2b0dc23442 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
@@ -6,7 +6,7 @@
"id": "20211226123038-4umgpxy",
"title": "資料文件",
"type": "doc",
- "updated": "20261006114009"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1349,7 +1349,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414203058-foirrwk",
- "updated": "20261006110222"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1476,7 +1476,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-ffpq13r",
- "updated": "20260930090802"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1513,6 +1513,37 @@
{
"Type": "NodeText",
"Data": " 設定顯示或隱藏。也可繼續透過圖片選單複製和編輯 OCR 文字。"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "懸浮在本機圖片上可查看 OCR 文字,無辨識結果時會顯示空內容提示。文字選取圖示表示 OCR 操作,圖片圖示則將圖片複製為 PNG,無 OCR 文字時也可複製圖片。在自訂外觀方案中,可透過 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "編輯器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "圖片"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "複製為 PNG"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 顯示或隱藏圖片複製按鈕;該按鈕在簡潔方案中預設隱藏。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
index 6b746934fb..e2c19cbd40 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-1m5un7l",
"title": "アセット",
"type": "doc",
- "updated": "20261006114009"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1398,7 +1398,7 @@
"Properties": {
"ID": "20240530101000-aefldsk",
"id": "20240530101000-cpod2qy",
- "updated": "20261006110222"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1540,7 +1540,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-fdfc9yh",
- "updated": "20260930090802"
+ "updated": "20261010133056"
},
"Children": [
{
@@ -1577,6 +1577,37 @@
{
"Type": "NodeText",
"Data": " で表示を切り替えられます。画像メニューからも OCR テキストのコピーと編集ができます。"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " ローカル画像にマウスを合わせると OCR テキストを確認でき、認識結果が空の場合も表示されます。文字選択アイコンは OCR 操作を示し、画像アイコンは OCR テキストの有無にかかわらず画像を PNG としてコピーします。カスタム外観プロファイルでは "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "エディター"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "画像"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "PNG としてコピー"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で画像コピーボタンの表示を切り替えられます。シンプルプロファイルでは既定で非表示です。"
}
]
},
diff --git a/app/scripts/css-contract-baseline.json b/app/scripts/css-contract-baseline.json
index 7cc93c95ef..5e93184757 100644
--- a/app/scripts/css-contract-baseline.json
+++ b/app/scripts/css-contract-baseline.json
@@ -414,6 +414,12 @@
"src/protyle/render/imageActions.ts"
]
},
+ "protyle-action__copy-image": {
+ "reason": "图片复制按钮的行为标识和主题钩子,基础外观复用 protyle-icon,不需要独立样式",
+ "references": [
+ "src/protyle/render/imageActions.ts"
+ ]
+ },
"protyle-action__reload": {
"reason": "存量类名,已记录字面量使用位置;不能仅凭内置样式缺失排除其行为或外部主题用途,保留现有接口",
"references": [
diff --git a/app/src/asset/imageOCR.test.ts b/app/src/asset/imageOCR.test.ts
index a97cca45f3..a3bc31a0ab 100644
--- a/app/src/asset/imageOCR.test.ts
+++ b/app/src/asset/imageOCR.test.ts
@@ -67,16 +67,22 @@ const browserCases = async (source: string, actionsSource: string, statusSource:
check.equal(dialog.element.isConnected, false);
let opens = 0;
let copies = 0;
+ const images: string[] = [];
let visible = true;
- const render = new Function("Constants", "copyImageOCRText", "openImageOCR", "isEncryptedBox", "isEntryVisible", "getImageOCRStatus", actionsSource +
+ const render = new Function("Constants", "copyImageOCRText", "openImageOCR", "isEncryptedBox", "isEntryVisible", "getImageOCRStatus", "copyPNGByLink", actionsSource +
"\nreturn renderImageActions;")({TIMEOUT_DBLCLICK: 20}, () => copies++, () => opens++, () => false,
- () => visible, status.getImageOCRStatus);
+ () => visible, status.getImageOCRStatus, (source: string) => images.push(source));
const root = document.createElement("div");
root.className = "protyle-wysiwyg";
- root.innerHTML = '<span class="img"><span></span><span><span class="protyle-icons"><span class="protyle-icon--only"></span></span><img data-src="assets/image.png"></span></span>';
+ root.innerHTML = '<span class="img"><span></span><span><span class="protyle-icons"><span class="protyle-icon protyle-icon--only"></span></span><img data-src="assets/image.png"></span></span>';
document.body.append(root);
render(root);
render(root);
+ check.equal(root.querySelectorAll(".protyle-action__copy-image").length, 1);
+ const copyImage = root.querySelector<HTMLElement>(".protyle-action__copy-image");
+ check.match(copyImage.innerHTML, /#iconImage/);
+ copyImage.click();
+ check.deepEqual(images, ["assets/image.png"]);
check.equal(requests, 0, "rendering does not query every image");
const hover = async () => {
const count = requests;
@@ -93,6 +99,7 @@ const browserCases = async (source: string, actionsSource: string, statusSource:
check.equal(requests, 1, "hover, focus, and pointer interactions reuse the status");
check.equal(root.querySelectorAll(".protyle-action__ocr").length, 1);
let action = root.querySelector<HTMLElement>(".protyle-action__ocr");
+ check.match(action.innerHTML, /#iconSelectText/);
action.click();
await new Promise(resolve => setTimeout(resolve, 30));
check.equal(copies, 1);
@@ -114,10 +121,13 @@ const browserCases = async (source: string, actionsSource: string, statusSource:
action.click();
await new Promise(resolve => setTimeout(resolve, 30));
check.equal(copies, 2, "restored image actions still copy OCR text");
+ root.querySelector<HTMLElement>(".protyle-action__copy-image").dispatchEvent(new KeyboardEvent("keydown", {key: "Enter"}));
+ check.deepEqual(images, ["assets/image.png", "assets/image.png"], "restored image actions copy images by keyboard");
text = " \n ";
status.invalidateImageOCRStatus("assets/image.png");
await hover();
check.equal(root.querySelector(".protyle-action__ocr"), null, "empty OCR text hides the action");
+ check.ok(root.querySelector(".protyle-action__copy-image"), "image copying is available without OCR");
await hover();
check.equal(requests, 2, "empty text is cached too");
text = "recognized again";
@@ -127,6 +137,8 @@ const browserCases = async (source: string, actionsSource: string, statusSource:
visible = false;
window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));
check.equal(root.querySelector(".protyle-action__ocr"), null, "profile changes hide existing actions");
+ check.equal(root.querySelector(".protyle-action__copy-image"), null);
+ check.ok(root.querySelector(".protyle-icon--only"));
visible = true;
render(root);
status.invalidateImageOCRStatus("assets/image.png");
diff --git a/app/src/asset/imageOCRStatus.test.ts b/app/src/asset/imageOCRStatus.test.ts
index 4682e7e52f..392527e303 100644
--- a/app/src/asset/imageOCRStatus.test.ts
+++ b/app/src/asset/imageOCRStatus.test.ts
@@ -31,15 +31,19 @@ test("OCR presence caches text and empty results, merges requests, expires and r
const cache = loadCache();
const {api, pending} = cache;
const first = api.getImageOCRStatus("assets/image.png");
+ const text = api.getImageOCRText("assets/image.png");
assert.equal(api.getImageOCRStatus("assets/image.png"), first);
assert.equal(cache.requests(), 1);
pending.shift().resolve({code: 0, data: {text: "recognized"}});
assert.equal(await first, true);
+ assert.equal(await text, "recognized");
+ assert.equal(await api.getImageOCRText("assets/image.png"), "recognized");
assert.equal(await api.getImageOCRStatus("assets/image.png"), true);
assert.equal(cache.requests(), 1);
const empty = api.getImageOCRStatus("assets/empty.png");
pending.shift().resolve({code: 0, data: {text: " \n "}});
assert.equal(await empty, false);
+ assert.equal(await api.getImageOCRText("assets/empty.png"), " \n ");
assert.equal(await api.getImageOCRStatus("assets/empty.png"), false);
assert.equal(cache.requests(), 2);
cache.advance();
diff --git a/app/src/asset/imageOCRStatus.ts b/app/src/asset/imageOCRStatus.ts
index 7e1e0027d2..3aa2bfd37e 100644
--- a/app/src/asset/imageOCRStatus.ts
+++ b/app/src/asset/imageOCRStatus.ts
@@ -1,23 +1,25 @@
import {fetchSyncPost} from "../util/fetch";
-// 仅缓存按钮显示状态,短期过期以反映后台识别和其他客户端的修改。
-const statuses = new Map<string, {expires: number, result: Promise<boolean | undefined>}>();
+// 悬浮提示和按钮共享识别结果,短期过期以反映后台识别和其他客户端的修改。
+const statuses = new Map<string, {expires: number, result: Promise<string | undefined>, status: Promise<boolean | undefined>}>();
const cacheDuration = 60000;
const cacheLimit = 128;
-export const getImageOCRStatus = (path: string): Promise<boolean | undefined> => {
+const getImageOCREntry = (path: string) => {
const cached = statuses.get(path);
if (cached && cached.expires > Date.now()) {
- return cached.result;
+ return cached;
}
- const entry = {
- expires: Infinity,
- result: fetchSyncPost("/api/asset/getImageOCRText", {path}, undefined, false).then(response => {
+ const result = fetchSyncPost("/api/asset/getImageOCRText", {path}, undefined, false).then(response => {
if (response.code !== 0) {
return undefined;
}
- return response.data.text.trim().length > 0;
- }).catch(() => undefined),
+ return response.data.text;
+ }).catch(() => undefined);
+ const entry = {
+ expires: Infinity,
+ result,
+ status: result.then(text => text === undefined ? undefined : text.trim().length > 0),
};
statuses.delete(path);
statuses.set(path, entry);
@@ -34,9 +36,13 @@ export const getImageOCRStatus = (path: string): Promise<boolean | undefined> =>
entry.expires = Date.now() + cacheDuration;
}
});
- return entry.result;
+ return entry;
};
+export const getImageOCRStatus = (path: string): Promise<boolean | undefined> => getImageOCREntry(path).status;
+
+export const getImageOCRText = (path: string): Promise<string | undefined> => getImageOCREntry(path).result;
+
export const invalidateImageOCRStatus = (path: string) => {
statuses.delete(path);
window.dispatchEvent(new CustomEvent("siyuan-image-ocr"));
diff --git a/app/src/block/popover.test.ts b/app/src/block/popover.test.ts
index e13107332e..2b7d44b7a0 100644
--- a/app/src/block/popover.test.ts
+++ b/app/src/block/popover.test.ts
@@ -12,6 +12,7 @@ const browserCases = async (source: string) => {
const requests: ((response: unknown) => void)[] = [];
let tooltip = "";
const assetRequests: {path: string, signal: AbortSignal, receive: (response: unknown) => void}[] = [];
+ const ocrRequests: ((text: string | undefined) => void)[] = [];
class Panel {
element = document.createElement("div");
editors: {protyle: IProtyle}[] = [];
@@ -37,6 +38,7 @@ const browserCases = async (source: string) => {
const dependencies = {
BlockPanel: Panel,
fetchSyncPost: () => new Promise(resolve => requests.push(resolve)),
+ getImageOCRText: () => new Promise<string | undefined>(resolve => ocrRequests.push(resolve)),
hideTooltip: () => {},
showTooltip: (text: string) => { tooltip = text; },
fetchPost: (_url: string, body: {path: string}, receive: (response: unknown) => void,
@@ -49,6 +51,8 @@ const browserCases = async (source: string) => {
.replace(/-\d{14}-\w{7}$/, ""),
Constants: {TIMEOUT_INPUT: 5},
isTouchDevice: () => false,
+ isTouchHoverInput: () => false,
+ isInteractiveTooltipTarget: () => false,
isEncryptedBox: () => false,
isListItemActionElement: () => false,
isAbove: () => false,
@@ -59,6 +63,7 @@ const browserCases = async (source: string) => {
config: {editor: {floatWindowMode: 0, floatWindowDelay: 20}},
menus: {menu: {element: document.createElement("div")}},
blockPanels: [],
+ languages: {ocrResult: "OCR text", emptyContent: "No related content found"},
} as unknown as typeof window.siyuan;
window.JSAndroid = {} as typeof window.JSAndroid;
const root = document.createElement("div");
@@ -173,23 +178,34 @@ const browserCases = async (source: string) => {
check.equal(assetRequests.length, 1);
assetRequests[0].receive({code: 0, data: {hSize: "2 MiB"}});
check.match(tooltip, /PNG · 1920 × 1080 · 2 MiB$/);
+ ocrRequests[0]("<script> & text\nsecond line");
+ await Promise.resolve();
+ check.match(tooltip, /OCR text:<br>&lt;script> &amp; text<br>second line$/);
+ check.match(tooltip, /2 MiB/);
image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
document.body.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
check.equal(assetRequests[1].signal.aborted, true);
tooltip = "later target";
assetRequests[1].receive({code: 0, data: {hSize: "stale"}});
+ ocrRequests[1]("stale OCR");
+ await Promise.resolve();
check.equal(tooltip, "later target");
image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
const unavailable = tooltip;
assetRequests[2].receive({code: 1, data: null});
check.equal(tooltip, unavailable);
+ ocrRequests[2](" \n ");
+ await Promise.resolve();
+ check.match(tooltip, /OCR text:<br>No related content found$/);
image.setAttribute("data-src", "https://example.com/photo.webp");
image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
check.match(tooltip, /photo.webp.*WEBP · 1920 × 1080/);
check.equal(assetRequests.length, 3);
+ check.equal(ocrRequests.length, 3, "remote images do not query OCR");
image.setAttribute("data-src", "assets/encrypted.png?box=encrypted");
image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
check.equal(assetRequests.length, 3);
+ check.equal(ocrRequests.length, 3, "encrypted resources do not query OCR");
check.equal(image.title, "");
check.equal(image.alt, "");
return "Popover interaction cases passed";
diff --git a/app/src/block/popover.ts b/app/src/block/popover.ts
index bf9139c3d5..5575b26b74 100644
--- a/app/src/block/popover.ts
+++ b/app/src/block/popover.ts
@@ -15,6 +15,7 @@ import {isTouchDevice} from "../util/functions";
import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../util/escape";
import {isListItemActionElement} from "../protyle/wysiwyg/listContext";
import {getImageTooltip} from "../protyle/render/imageTooltip";
+import {getImageOCRText} from "../asset/imageOCRStatus";
import {
cancelPendingPopover,
getPopoverGeneration,
@@ -192,15 +193,27 @@ export const initBlockPopover = (app: App) => {
!isEncryptedBox(image.closest("[data-notebook-id]")?.getAttribute("data-notebook-id"))) {
tooltipAbortController = new AbortController();
const capturedController = tooltipAbortController;
+ let size: string;
+ let ocrText: string;
+ const updateImageTooltip = () => {
+ if (!capturedController.signal.aborted && image.isConnected &&
+ (image.getAttribute("data-src") || image.getAttribute("src")) === imagePath) {
+ showTooltip(getImageTooltip(image, size, ocrText), image, undefined, event);
+ }
+ };
+ if (imagePath.startsWith("assets/")) {
+ getImageOCRText(imagePath).then(text => {
+ ocrText = text;
+ updateImageTooltip();
+ });
+ }
fetchPost("/api/asset/statAsset", {path: imagePath}, (response) => {
if (capturedController.signal.aborted || !image.isConnected) {
return;
}
if (response.code === 0 && response.data) {
- showTooltip(getImageTooltip(image, response.data.hSize), image, undefined, event);
- }
- if (tooltipAbortController === capturedController) {
- tooltipAbortController = null;
+ size = response.data.hSize;
+ updateImageTooltip();
}
}, undefined, undefined, capturedController.signal);
}
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 102e04a32d..37c5abf199 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -60,7 +60,12 @@ test("image OCR actions retain their configurable paths and order", t => {
assert.equal(imageAction.simple, false);
assert.equal(imageAction.sortable, false);
assert.equal(getEntryParentPath("editor.image.ocrText"), "editor.image");
- assert.deepEqual(getEntryCatalogChildren("editor.image").map(item => item.key), ["ocrText"]);
+ assert.deepEqual(getEntryCatalogChildren("editor.image").map(item => item.key), ["ocrText", "copyAsPNG"]);
+ const copyImage = getEntryCatalogNode("editor.image.copyAsPNG");
+ assert.equal(copyImage.type, "entry");
+ assert.equal(copyImage.simple, false);
+ assert.equal(copyImage.sortable, false);
+ assert.equal(getEntryParentPath("editor.image.copyAsPNG"), "editor.image");
assert.deepEqual(getEntryCatalogChildren("inline.image.ocr").map(item => item.key), [
"ocrResult", "copyOCRText", "separator_reOCR", "reOCR", "reAIOCR",
]);
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 4ded088ba8..eaeee056d3 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -902,7 +902,10 @@ export const entryCatalog: IEntryCatalogSection[] = [
key: "editor.image",
label: location(lang("editor"), lang("image")),
sortable: false,
- children: [node("ocrText", lang("ocrResult"), false, undefined, false)],
+ children: [
+ node("ocrText", lang("ocrResult"), false, undefined, false),
+ node("copyAsPNG", lang("copyAsPNG"), false, undefined, false),
+ ],
},
{
key: "editor.slash",
diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.ts
index a5609f712b..4602ecfc13 100644
--- a/app/src/config/entryVisibility/mobileUi.test.ts
+++ b/app/src/config/entryVisibility/mobileUi.test.ts
@@ -132,6 +132,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<s
select.value = "editor.image";
select.dispatchEvent(new Event("change", {bubbles: true}));
check(view.querySelector("[data-entry-path='editor.image.ocrText']"), "Mobile exposes image OCR visibility");
+ check(view.querySelector("[data-entry-path='editor.image.copyAsPNG']"), "Mobile exposes image copy visibility");
check(select.options.length === 3, "Mobile must offer toolbar, slash, and image categories");
select.value = "editor.slash";
select.dispatchEvent(new Event("change", {bubbles: true}));
@@ -417,7 +418,7 @@ const runEntryUiCases = async (mobileBuild: boolean) => {
"config/entryVisibility/profile", "config/entryVisibility/mobileToolbarContext",
"config/entryVisibility/dockOrder", "config/entryVisibility/touchOrder",
"protyle/toolbar/defaults", "mobile/util/toolbarActions", "protyle/wysiwyg/codeBlockUtil", "protyle/gutter/turnIntoMenu",
- "plugin/dockKey", "plugin/topBarKey", "util/escape"];
+ "plugin/dockKey", "plugin/topBarKey", "util/escape", "menus/declarations/imageOCRMenu", "menus/declarations/menuDeclaration"];
if (mobileBuild) {
modules.push("config/setting/windowContext");
}
diff --git a/app/src/protyle/render/imageActions.ts b/app/src/protyle/render/imageActions.ts
index bbdf084d83..6381d175b4 100644
--- a/app/src/protyle/render/imageActions.ts
+++ b/app/src/protyle/render/imageActions.ts
@@ -3,16 +3,28 @@ import {copyImageOCRText, openImageOCR} from "../../asset/imageOCR";
import {isEncryptedBox} from "../../util/pathName";
import {getImageOCRStatus} from "../../asset/imageOCRStatus";
import {isEntryVisible} from "../../config/entryVisibility/runtime";
+import {copyPNGByLink} from "../../menus/util";
const boundImageActions = new WeakSet<HTMLElement>();
const boundImages = new WeakSet<HTMLImageElement>();
const requests = new WeakMap<HTMLImageElement, AbortController>();
+const updateActionCorners = (actions: Element) => {
+ const icons = Array.from(actions.querySelectorAll(".protyle-icon"));
+ icons.forEach(icon => icon.classList.remove("protyle-icon--first", "protyle-icon--last", "protyle-icon--only"));
+ if (icons.length === 1) {
+ icons[0].classList.add("protyle-icon--only");
+ } else if (icons.length > 1) {
+ icons[0].classList.add("protyle-icon--first");
+ icons[icons.length - 1].classList.add("protyle-icon--last");
+ }
+};
+
const removeImageAction = (image: HTMLImageElement) => {
const actions = image.parentElement?.querySelector(".protyle-icons");
actions?.querySelector(".protyle-action__ocr")?.remove();
- if (actions?.childElementCount === 1) {
- actions.querySelector(".protyle-icon--last")?.classList.replace("protyle-icon--last", "protyle-icon--only");
+ if (actions) {
+ updateActionCorners(actions);
}
};
@@ -22,6 +34,7 @@ const canShowImageAction = (image: HTMLImageElement) => !window.siyuan.isPublish
export const renderImageActions = (root: Element) => {
root.querySelectorAll<HTMLImageElement>(".img img").forEach(image => {
+ renderCopyImageAction(image);
requests.get(image)?.abort();
requests.delete(image);
removeImageAction(image);
@@ -85,7 +98,7 @@ const addImageAction = (image: HTMLImageElement) => {
action.setAttribute("role", "button");
action.setAttribute("aria-label", window.siyuan.languages.imageOCRActionTip);
action.setAttribute("data-position", "north");
- action.innerHTML = '<svg><use xlink:href="#iconCopy"></use></svg>';
+ action.innerHTML = '<svg><use xlink:href="#iconSelectText"></use></svg>';
let timer: number;
action.addEventListener("click", event => {
event.stopPropagation();
@@ -115,6 +128,49 @@ const addImageAction = (image: HTMLImageElement) => {
const more = actions.querySelector(".protyle-icon--only");
more?.classList.replace("protyle-icon--only", "protyle-icon--last");
actions.prepend(action);
+ updateActionCorners(actions);
+};
+
+const renderCopyImageAction = (image: HTMLImageElement) => {
+ const actions = image.parentElement?.querySelector(".protyle-icons");
+ const existing = actions?.querySelector<HTMLElement>(".protyle-action__copy-image");
+ if (!actions) {
+ return;
+ }
+ if (window.siyuan.isPublish || !image.closest(".protyle-wysiwyg") || !isEntryVisible("editor.image.copyAsPNG")) {
+ existing?.remove();
+ updateActionCorners(actions);
+ return;
+ }
+ if (existing && boundImageActions.has(existing)) {
+ return;
+ }
+ existing?.remove();
+ const action = document.createElement("span");
+ boundImageActions.add(action);
+ action.className = "protyle-icon protyle-icon--first protyle-action__copy-image ariaLabel";
+ action.tabIndex = 0;
+ action.setAttribute("role", "button");
+ action.setAttribute("aria-label", window.siyuan.languages.copyAsPNG);
+ action.setAttribute("data-position", "north");
+ action.innerHTML = '<svg><use xlink:href="#iconImage"></use></svg>';
+ const copy = () => copyPNGByLink(image.getAttribute("src") || image.getAttribute("data-src"));
+ action.addEventListener("click", event => {
+ event.preventDefault();
+ event.stopPropagation();
+ copy();
+ });
+ action.addEventListener("keydown", (event: KeyboardEvent) => {
+ if ((event.key === "Enter" || event.key === " ") && !event.isComposing) {
+ event.preventDefault();
+ event.stopPropagation();
+ copy();
+ }
+ });
+ actions.querySelector(".protyle-icon--only")?.classList.replace("protyle-icon--only", "protyle-icon--last");
+ const more = actions.querySelector(".protyle-icon--last");
+ actions.insertBefore(action, more);
+ updateActionCorners(actions);
};
window.addEventListener("siyuan-entry-visibility", () => renderImageActions(document.documentElement));
diff --git a/app/src/protyle/render/imageTooltip.ts b/app/src/protyle/render/imageTooltip.ts
index 065f755632..bca4416d2d 100644
--- a/app/src/protyle/render/imageTooltip.ts
+++ b/app/src/protyle/render/imageTooltip.ts
@@ -1,7 +1,7 @@
import {escapeHtml} from "../../util/escape";
import {getAssetExtension, getAssetName} from "../../util/pathName";
-export const getImageTooltip = (image: HTMLImageElement, size?: string) => {
+export const getImageTooltip = (image: HTMLImageElement, size?: string, ocrText?: string) => {
const source = image.getAttribute("data-src") || image.getAttribute("src") || "";
const path = source.split(/[?#]/)[0];
const inline = /^(data|blob):/.test(path);
@@ -21,5 +21,10 @@ export const getImageTooltip = (image: HTMLImageElement, size?: string) => {
// 原始尺寸不受编辑器缩放和图片排版宽度影响。
const dimensions = image.naturalWidth && image.naturalHeight ? `${image.naturalWidth} × ${image.naturalHeight}` : "";
const information = [format, dimensions, size].filter(Boolean).map(value => escapeHtml(value)).join(" · ");
- return text + (text && information ? '<div class="fn__hr"></div>' : "") + information;
+ const tooltip = text + (text && information ? '<div class="fn__hr"></div>' : "") + information;
+ if (ocrText === undefined) {
+ return tooltip;
+ }
+ const ocr = escapeHtml(ocrText.trim() || window.siyuan.languages.emptyContent).replace(/\r\n|\r|\n/g, "<br>");
+ return tooltip + '<div class="fn__hr"></div>' + escapeHtml(window.siyuan.languages.ocrResult) + ":<br>" + ocr;
};