Skip to content

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

:bug: Correct image viewer initialization and unify toolbar tooltips https://github.com/siyuan-note/siyuan/issues/19151

Danielae345218eb14
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index e82597ccc1..bf1a343535 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "تشغيل عرض الشرائح",
+ "imageFlipHorizontal": "قلب أفقي",
+ "imageFlipVertical": "قلب عمودي",
"imageCopyFailed": "تعذر نسخ الصورة. تحقق من إمكانية تحميلها وحاول مرة أخرى.",
"syncAssetSnapshotIncomplete": "يعتمد محتوى بعض الموارد على التخزين السحابي؛ هذه اللقطة المحلية غير مكتملة",
"syncAssetDownloadMode": "تنزيل ملفات الموارد",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index a0fb8c67f2..a8119210ad 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Diashow starten",
+ "imageFlipHorizontal": "Horizontal spiegeln",
+ "imageFlipVertical": "Vertikal spiegeln",
"imageCopyFailed": "Das Bild konnte nicht kopiert werden. Prüfe, ob es geladen werden kann, und versuche es erneut.",
"syncAssetSnapshotIncomplete": "Einige Ressourceninhalte sind vom Cloudspeicher abhängig; dieser lokale Schnappschuss ist unvollständig",
"syncAssetDownloadMode": "Ressourcendownloads",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 27cb25360d..ae86ad2bbe 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Play slideshow",
+ "imageFlipHorizontal": "Flip horizontally",
+ "imageFlipVertical": "Flip vertically",
"imageCopyFailed": "Unable to copy the image. Check that it can be loaded and try again.",
"syncAssetSnapshotIncomplete": "Some asset content depends on cloud storage; this local snapshot is incomplete",
"syncAssetDownloadMode": "Asset downloads",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index f532e393a6..5467538c91 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Reproducir presentación",
+ "imageFlipHorizontal": "Voltear horizontalmente",
+ "imageFlipVertical": "Voltear verticalmente",
"imageCopyFailed": "No se pudo copiar la imagen. Comprueba que se pueda cargar e inténtalo de nuevo.",
"syncAssetSnapshotIncomplete": "El contenido de algunos recursos depende del almacenamiento en la nube; esta instantánea local está incompleta",
"syncAssetDownloadMode": "Descarga de recursos",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index a34d44e400..55b440608a 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Lancer le diaporama",
+ "imageFlipHorizontal": "Retourner horizontalement",
+ "imageFlipVertical": "Retourner verticalement",
"imageCopyFailed": "Impossible de copier l’image. Vérifiez qu’elle peut être chargée et réessayez.",
"syncAssetSnapshotIncomplete": "Le contenu de certaines ressources dépend du stockage cloud ; cet instantané local est incomplet",
"syncAssetDownloadMode": "Téléchargement des ressources",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 6b362b720d..d34103403e 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "הפעלת מצגת",
+ "imageFlipHorizontal": "היפוך אופקי",
+ "imageFlipVertical": "היפוך אנכי",
"imageCopyFailed": "לא ניתן להעתיק את התמונה. יש לבדוק שניתן לטעון אותה ולנסות שוב.",
"syncAssetSnapshotIncomplete": "התוכן של חלק מהמשאבים תלוי באחסון בענן; תמונת מצב מקומית זו אינה שלמה",
"syncAssetDownloadMode": "הורדת קובצי משאבים",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d0845214c8..f37ecc1ae8 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "स्लाइड शो चलाएँ",
+ "imageFlipHorizontal": "क्षैतिज रूप से पलटें",
+ "imageFlipVertical": "लंबवत रूप से पलटें",
"imageCopyFailed": "चित्र कॉपी नहीं किया जा सका। जाँचें कि इसे लोड किया जा सकता है और फिर से प्रयास करें।",
"syncAssetSnapshotIncomplete": "कुछ संसाधनों की सामग्री क्लाउड स्टोरेज पर निर्भर है; यह स्थानीय स्नैपशॉट अधूरा है",
"syncAssetDownloadMode": "संसाधन फ़ाइल डाउनलोड",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index e0f1a9c75c..e28ebaa1e5 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Putar tayangan slide",
+ "imageFlipHorizontal": "Balik secara horizontal",
+ "imageFlipVertical": "Balik secara vertikal",
"imageCopyFailed": "Tidak dapat menyalin gambar. Pastikan gambar dapat dimuat dan coba lagi.",
"syncAssetSnapshotIncomplete": "Sebagian konten sumber daya bergantung pada penyimpanan awan; snapshot lokal ini belum lengkap",
"syncAssetDownloadMode": "Unduhan berkas sumber daya",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index c4dc97aca3..931d822dbf 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Avvia presentazione",
+ "imageFlipHorizontal": "Capovolgi orizzontalmente",
+ "imageFlipVertical": "Capovolgi verticalmente",
"imageCopyFailed": "Impossibile copiare l’immagine. Verifica che possa essere caricata e riprova.",
"syncAssetSnapshotIncomplete": "Il contenuto di alcune risorse dipende dall’archiviazione cloud; questa istantanea locale è incompleta",
"syncAssetDownloadMode": "Download delle risorse",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index cd92584a37..8b51e323c1 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "スライドショーを再生",
+ "imageFlipHorizontal": "左右反転",
+ "imageFlipVertical": "上下反転",
"imageCopyFailed": "画像をコピーできません。画像を読み込めることを確認して、もう一度お試しください。",
"syncAssetSnapshotIncomplete": "一部のリソースファイルはクラウドに依存しているため、このローカルスナップショットは不完全です",
"syncAssetDownloadMode": "リソースファイルのダウンロード",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 68b605af0b..94e392ce93 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "슬라이드 쇼 재생",
+ "imageFlipHorizontal": "좌우 반전",
+ "imageFlipVertical": "상하 반전",
"imageCopyFailed": "이미지를 복사할 수 없습니다. 이미지를 불러올 수 있는지 확인한 후 다시 시도하세요.",
"syncAssetSnapshotIncomplete": "일부 리소스 내용이 클라우드 저장소에 의존하므로 이 로컬 스냅샷은 완전하지 않습니다",
"syncAssetDownloadMode": "리소스 파일 다운로드",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index e07ddc76b8..c5c632f972 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Diavoorstelling afspelen",
+ "imageFlipHorizontal": "Horizontaal spiegelen",
+ "imageFlipVertical": "Verticaal spiegelen",
"imageCopyFailed": "De afbeelding kan niet worden gekopieerd. Controleer of deze kan worden geladen en probeer het opnieuw.",
"syncAssetSnapshotIncomplete": "De inhoud van sommige bronbestanden is afhankelijk van cloudopslag; deze lokale momentopname is onvolledig",
"syncAssetDownloadMode": "Bronbestanden downloaden",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 231ece0ac7..937c9d82b8 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Odtwórz pokaz slajdów",
+ "imageFlipHorizontal": "Odwróć w poziomie",
+ "imageFlipVertical": "Odwróć w pionie",
"imageCopyFailed": "Nie można skopiować obrazu. Sprawdź, czy można go załadować, i spróbuj ponownie.",
"syncAssetSnapshotIncomplete": "Zawartość niektórych zasobów zależy od pamięci w chmurze; ta lokalna migawka jest niekompletna",
"syncAssetDownloadMode": "Pobieranie zasobów",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 23cb3a8424..b19b2d6abb 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Reproduzir apresentação de slides",
+ "imageFlipHorizontal": "Inverter horizontalmente",
+ "imageFlipVertical": "Inverter verticalmente",
"imageCopyFailed": "Não foi possível copiar a imagem. Verifique se ela pode ser carregada e tente novamente.",
"syncAssetSnapshotIncomplete": "O conteúdo de alguns recursos depende do armazenamento em nuvem; este instantâneo local está incompleto",
"syncAssetDownloadMode": "Download de recursos",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 95d0c0e60b..aa503417b0 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Запустить слайд-шоу",
+ "imageFlipHorizontal": "Отразить по горизонтали",
+ "imageFlipVertical": "Отразить по вертикали",
"imageCopyFailed": "Не удалось скопировать изображение. Убедитесь, что оно загружается, и повторите попытку.",
"syncAssetSnapshotIncomplete": "Содержимое некоторых ресурсов зависит от облачного хранилища; этот локальный снимок неполон",
"syncAssetDownloadMode": "Загрузка файлов ресурсов",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index eaef01e9a7..2685723ef7 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Spustiť prezentáciu",
+ "imageFlipHorizontal": "Prevrátiť vodorovne",
+ "imageFlipVertical": "Prevrátiť zvislo",
"imageCopyFailed": "Obrázok sa nepodarilo skopírovať. Skontrolujte, či sa dá načítať, a skúste to znova.",
"syncAssetSnapshotIncomplete": "Obsah niektorých zdrojových súborov závisí od cloudového úložiska; táto lokálna snímka je neúplná",
"syncAssetDownloadMode": "Sťahovanie zdrojových súborov",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 1ef3ad841e..c47999fc72 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "เล่นสไลด์โชว์",
+ "imageFlipHorizontal": "พลิกแนวนอน",
+ "imageFlipVertical": "พลิกแนวตั้ง",
"imageCopyFailed": "ไม่สามารถคัดลอกรูปภาพได้ โปรดตรวจสอบว่าสามารถโหลดรูปภาพได้แล้วลองอีกครั้ง",
"syncAssetSnapshotIncomplete": "เนื้อหาทรัพยากรบางส่วนขึ้นอยู่กับที่เก็บข้อมูลบนคลาวด์ สแนปช็อตในเครื่องนี้จึงยังไม่สมบูรณ์",
"syncAssetDownloadMode": "การดาวน์โหลดไฟล์ทรัพยากร",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 6846ce8f7e..cfdb5ca68f 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Slayt gösterisini oynat",
+ "imageFlipHorizontal": "Yatay çevir",
+ "imageFlipVertical": "Dikey çevir",
"imageCopyFailed": "Görüntü kopyalanamadı. Yüklenebildiğini kontrol edip tekrar deneyin.",
"syncAssetSnapshotIncomplete": "Bazı kaynakların içeriği bulut depolamaya bağlıdır; bu yerel anlık görüntü eksiktir",
"syncAssetDownloadMode": "Kaynak dosyası indirmeleri",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index be398bdbe6..c8da5b1bdf 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "Запустити показ слайдів",
+ "imageFlipHorizontal": "Віддзеркалити горизонтально",
+ "imageFlipVertical": "Віддзеркалити вертикально",
"imageCopyFailed": "Не вдалося скопіювати зображення. Переконайтеся, що воно завантажується, і спробуйте ще раз.",
"syncAssetSnapshotIncomplete": "Вміст деяких ресурсів залежить від хмарного сховища; цей локальний знімок неповний",
"syncAssetDownloadMode": "Завантаження файлів ресурсів",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 15f358c733..dcf35adbd0 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "播放幻灯片",
+ "imageFlipHorizontal": "水平翻转",
+ "imageFlipVertical": "垂直翻转",
"imageCopyFailed": "无法复制图片,请确认图片能够加载后重试。",
"syncAssetSnapshotIncomplete": "部分资源文件内容依赖云端,本地快照尚不完整",
"syncAssetDownloadMode": "资源文件下载",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index e14ba98aa5..1b1c8e23af 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "imageViewerPlay": "播放投影片",
+ "imageFlipHorizontal": "水平翻轉",
+ "imageFlipVertical": "垂直翻轉",
"imageCopyFailed": "無法複製圖片,請確認圖片能夠載入後重試。",
"syncAssetSnapshotIncomplete": "部分資源檔案內容依賴雲端,本機快照尚不完整",
"syncAssetDownloadMode": "資源檔案下載",
diff --git a/app/src/protyle/preview/image.test.ts b/app/src/protyle/preview/image.test.ts
new file mode 100644
index 0000000000..e411949d24
--- /dev/null
+++ b/app/src/protyle/preview/image.test.ts
@@ -0,0 +1,76 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+test("image preview initializes its toolbar when ready is dispatched on the source element", async () => {
+ const actions = ["zoom-in", "zoom-out", "one-to-one", "reset", "prev", "play", "next",
+ "rotate-left", "rotate-right", "flip-horizontal", "flip-vertical", "copy", "close"];
+ const buttons = new Map(actions.map(action => {
+ const attributes = new Map<string, string>();
+ return [`.viewer-${action}`, {
+ innerHTML: "",
+ attributes,
+ classList: new Set<string>(),
+ setAttribute: (name: string, value: string) => attributes.set(name, value),
+ }];
+ }));
+ const copied: string[] = [];
+ const sourceElement = new EventTarget();
+ class TestViewer {
+ public viewed = true;
+ public image = {src: "blob:first"};
+ public toolbar = {
+ querySelector: (selector: string) => {
+ assert.ok(buttons.has(selector));
+ return buttons.get(selector);
+ },
+ };
+
+ constructor(element: EventTarget, public options: {
+ ready: EventListener,
+ toolbar: {copy: () => void},
+ }) {
+ element.addEventListener("ready", options.ready);
+ }
+
+ public show() {
+ // Viewer.js 将生命周期事件派发给源元素,回调的 this 指向该元素。
+ sourceElement.dispatchEvent(new Event("ready"));
+ }
+ }
+ const source = readFileSync("src/protyle/preview/image.ts", "utf8");
+ const compiled = transpileModule(source, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const exports = {} as {previewImages: (sources: string[]) => void};
+ const languages = JSON.parse(readFileSync("appearance/langs/en.json", "utf8"));
+ const previewWindow = {siyuan: {languages, viewer: undefined as TestViewer}};
+ runInNewContext(compiled, {
+ exports,
+ require: () => ({
+ Constants: {PROTYLE_CDN: ""},
+ addScript: () => Promise.resolve(),
+ copyPNGByLink: (src: string) => copied.push(src),
+ }),
+ document: {createElement: () => sourceElement},
+ window: previewWindow,
+ Viewer: TestViewer,
+ });
+ exports.previewImages(["blob:first", "blob:second"]);
+ await Promise.resolve();
+ const instance = previewWindow.siyuan.viewer;
+ assert.match(buttons.get(".viewer-copy").innerHTML, /#iconCopy/);
+ assert.equal(buttons.get(".viewer-copy").attributes.get("aria-label"), "Copy as PNG");
+ buttons.forEach(button => {
+ assert.ok(button.classList.has("ariaLabel"));
+ assert.equal(button.attributes.has("title"), false);
+ assert.ok(button.attributes.get("aria-label"));
+ assert.equal(button.attributes.get("data-position"), "north");
+ });
+ instance.options.toolbar.copy();
+ instance.image.src = "blob:second";
+ instance.options.toolbar.copy();
+ assert.deepEqual(copied, ["blob:first", "blob:second"]);
+});
diff --git a/app/src/protyle/preview/image.ts b/app/src/protyle/preview/image.ts
index 51debd241b..341d667a78 100644
--- a/app/src/protyle/preview/image.ts
+++ b/app/src/protyle/preview/image.ts
@@ -38,11 +38,31 @@ export const previewImages = (srcList: string[], currentSrc?: string, onHidden?:
}],
button: false,
transition: false,
- ready: function (this: Viewer) {
- const copyElement = this.toolbar.querySelector(".viewer-copy");
+ ready: () => {
+ const copyElement = viewer.toolbar.querySelector(".viewer-copy");
copyElement.innerHTML = '<svg><use xlink:href="#iconCopy"></use></svg>';
- copyElement.setAttribute("title", window.siyuan.languages.copyAsPNG);
- copyElement.setAttribute("aria-label", window.siyuan.languages.copyAsPNG);
+ const languages = window.siyuan.languages;
+ const labels: Record<string, string> = {
+ "zoom-in": languages.zoomIn,
+ "zoom-out": languages.zoomOut,
+ "one-to-one": languages.pageScaleActual,
+ reset: languages.reset,
+ prev: languages.previous,
+ play: languages.imageViewerPlay,
+ next: languages.next,
+ "rotate-left": languages.rotateCcw,
+ "rotate-right": languages.rotateCw,
+ "flip-horizontal": languages.imageFlipHorizontal,
+ "flip-vertical": languages.imageFlipVertical,
+ copy: languages.copyAsPNG,
+ close: languages.close,
+ };
+ Object.entries(labels).forEach(([action, label]) => {
+ const button = viewer.toolbar.querySelector(`.viewer-${action}`);
+ button.classList.add("ariaLabel");
+ button.setAttribute("aria-label", label);
+ button.setAttribute("data-position", "north");
+ });
},
hidden: close,
toolbar: {
diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.ts
index fabd3df980..978195a4d3 100644
--- a/app/src/types/protyle.d.ts
+++ b/app/src/types/protyle.d.ts
@@ -152,7 +152,7 @@ declare class Viewer {
initialViewIndex?: number,
transition: boolean,
hidden: () => void,
- ready?: (this: Viewer) => void,
+ ready?: (this: HTMLElement, event: CustomEvent) => void,
toolbar: {
zoomIn: boolean,
zoomOut: boolean,