Skip to content

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

:sparkles: Support format painting for inline styles https://github.com/siyuan-note/siyuan/issues/12732

Danielfe7d734eb4a5
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 5d717c77a1..21c1cfd2bb 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "عطّل مؤلف الإضافة هذه الإضافة في خدمة النشر",
+ "formatPainter": "نسخ التنسيق",
+ "formatPainterContinuous": "نسخ التنسيق المستمر",
+ "formatPainterActive": "نسخ التنسيق نشط؛ انقر للخروج",
+ "formatPainterContinuousActive": "نسخ التنسيق المستمر نشط؛ انقر للخروج",
"aiMcpEnv": "متغيرات البيئة",
"aiMcpEnvTip": "تُمرر الأسرار المشار إليها إلى هذا البرنامج، وتُخزن القيم المدخلة مباشرة كنص عادي",
"aiMcpEnvInvalid": "متغيرات البيئة غير صالحة؛ تحقق من الأسماء الفارغة أو المكررة أو غير الصالحة",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index e7e3868462..f31e707845 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Der Plugin-Autor hat dieses Plugin im Veröffentlichungsdienst deaktiviert",
+ "formatPainter": "Format übertragen",
+ "formatPainterContinuous": "Format fortlaufend übertragen",
+ "formatPainterActive": "Formatübertragung aktiv; zum Beenden klicken",
+ "formatPainterContinuousActive": "Fortlaufende Formatübertragung aktiv; zum Beenden klicken",
"aiMcpEnv": "Umgebungsvariablen",
"aiMcpEnvTip": "Referenzierte Geheimnisse werden diesem Programm bereitgestellt, direkt eingegebene Werte werden im Klartext gespeichert",
"aiMcpEnvInvalid": "Ungültige Umgebungsvariablen; prüfen Sie auf leere, doppelte oder ungültige Namen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index c739a1920b..71716c47d9 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "The plugin author has disabled this plugin in the publish service",
+ "formatPainter": "Format Painter",
+ "formatPainterContinuous": "Continuous Format Painter",
+ "formatPainterActive": "Format Painter active; click to exit",
+ "formatPainterContinuousActive": "Continuous Format Painter active; click to exit",
"aiMcpEnv": "Environment variables",
"aiMcpEnvTip": "Referenced secrets are provided to this program, and direct values are stored in plaintext",
"aiMcpEnvInvalid": "Invalid environment variables; check for empty, duplicate, or invalid names",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 6dc8dbe4b9..59e7ddcac9 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "El autor del complemento ha deshabilitado este complemento en el servicio de publicación",
+ "formatPainter": "Copiar formato",
+ "formatPainterContinuous": "Copiar formato continuamente",
+ "formatPainterActive": "Copia de formato activa; haz clic para salir",
+ "formatPainterContinuousActive": "Copia continua de formato activa; haz clic para salir",
"aiMcpEnv": "Variables de entorno",
"aiMcpEnvTip": "Los secretos referenciados se proporcionan a este programa y los valores directos se almacenan como texto sin formato",
"aiMcpEnvInvalid": "Variables de entorno no válidas; compruebe si hay nombres vacíos, duplicados o no válidos",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 77cb7ea1cc..524ce2a1f0 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "L’auteur du plugin a désactivé ce plugin dans le service de publication",
+ "formatPainter": "Reproduire la mise en forme",
+ "formatPainterContinuous": "Reproduire la mise en forme en continu",
+ "formatPainterActive": "Reproduction de la mise en forme active ; cliquez pour quitter",
+ "formatPainterContinuousActive": "Reproduction continue de la mise en forme active ; cliquez pour quitter",
"aiMcpEnv": "Variables d'environnement",
"aiMcpEnvTip": "Les secrets référencés sont fournis à ce programme et les valeurs saisies directement sont stockées en texte brut",
"aiMcpEnvInvalid": "Variables d'environnement non valides ; vérifiez les noms vides, dupliqués ou non valides",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 6475e23ac6..dff5f5cb7f 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "מחבר התוסף השבית תוסף זה בשירות הפרסום",
+ "formatPainter": "מברשת עיצוב",
+ "formatPainterContinuous": "מברשת עיצוב רציפה",
+ "formatPainterActive": "מברשת העיצוב פעילה; לחיצה תסיים",
+ "formatPainterContinuousActive": "מברשת העיצוב הרציפה פעילה; לחיצה תסיים",
"aiMcpEnv": "משתני סביבה",
"aiMcpEnvTip": "סודות שמופנים יועברו לתוכנית זו, וערכים שיוזנו ישירות יישמרו כטקסט גלוי",
"aiMcpEnvInvalid": "משתני הסביבה אינם תקינים; יש לבדוק שמות ריקים, כפולים או לא תקינים",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 866d60c200..2c2681e213 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "प्लगइन लेखक ने इस प्लगइन को प्रकाशन सेवा में अक्षम किया है",
+ "formatPainter": "फ़ॉर्मैट पेंटर",
+ "formatPainterContinuous": "निरंतर फ़ॉर्मैट पेंटर",
+ "formatPainterActive": "फ़ॉर्मैट पेंटर सक्रिय है; बाहर निकलने के लिए क्लिक करें",
+ "formatPainterContinuousActive": "निरंतर फ़ॉर्मैट पेंटर सक्रिय है; बाहर निकलने के लिए क्लिक करें",
"aiMcpEnv": "पर्यावरण चर",
"aiMcpEnvTip": "संदर्भित रहस्य इस प्रोग्राम को दिए जाते हैं और सीधे दर्ज किए गए मान सादे पाठ में संग्रहीत होते हैं",
"aiMcpEnvInvalid": "पर्यावरण चर अमान्य हैं; खाली, डुप्लिकेट या अमान्य नामों की जाँच करें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 973bf2e607..08c47c166c 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Pembuat plugin telah menonaktifkan plugin ini di layanan penerbitan",
+ "formatPainter": "Salin format",
+ "formatPainterContinuous": "Salin format berkelanjutan",
+ "formatPainterActive": "Penyalinan format aktif; klik untuk keluar",
+ "formatPainterContinuousActive": "Penyalinan format berkelanjutan aktif; klik untuk keluar",
"aiMcpEnv": "Variabel lingkungan",
"aiMcpEnvTip": "Rahasia yang dirujuk diberikan kepada program ini dan nilai yang dimasukkan langsung disimpan sebagai teks biasa",
"aiMcpEnvInvalid": "Variabel lingkungan tidak valid; periksa nama yang kosong, duplikat, atau tidak valid",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 3e1cc45d53..e80420eb36 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "L'autore del plugin ha disabilitato questo plugin nel servizio di pubblicazione",
+ "formatPainter": "Copia formato",
+ "formatPainterContinuous": "Copia formato continua",
+ "formatPainterActive": "Copia formato attiva; fai clic per uscire",
+ "formatPainterContinuousActive": "Copia formato continua attiva; fai clic per uscire",
"aiMcpEnv": "Variabili d'ambiente",
"aiMcpEnvTip": "I segreti referenziati vengono forniti a questo programma e i valori inseriti direttamente vengono archiviati in testo semplice",
"aiMcpEnvInvalid": "Variabili d'ambiente non valide; verifica la presenza di nomi vuoti, duplicati o non validi",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 6ded993fe2..e83900de09 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "プラグインの作者が公開サービスでこのプラグインを無効にしています",
+ "formatPainter": "書式のコピー",
+ "formatPainterContinuous": "書式の連続コピー",
+ "formatPainterActive": "書式のコピーが有効です。クリックして終了",
+ "formatPainterContinuousActive": "書式の連続コピーが有効です。クリックして終了",
"aiMcpEnv": "環境変数",
"aiMcpEnvTip": "参照したシークレットはこのプログラムに渡され、直接入力した値は平文で保存されます",
"aiMcpEnvInvalid": "環境変数が無効です。名前が空、重複、または無効な文字を含んでいないか確認してください",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 1675222528..447414ba0f 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "플러그인 작성자가 게시 서비스에서 이 플러그인을 비활성화했습니다",
+ "formatPainter": "서식 복사",
+ "formatPainterContinuous": "서식 연속 복사",
+ "formatPainterActive": "서식 복사가 활성화됨; 종료하려면 클릭",
+ "formatPainterContinuousActive": "서식 연속 복사가 활성화됨; 종료하려면 클릭",
"aiMcpEnv": "환경 변수",
"aiMcpEnvTip": "참조된 비밀은 이 프로그램에 제공되며 직접 입력한 값은 일반 텍스트로 저장됩니다",
"aiMcpEnvInvalid": "환경 변수가 잘못되었습니다. 비어 있거나 중복되거나 잘못된 이름이 있는지 확인하세요",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 3a36c90e79..4a580592c3 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "De auteur van de plug-in heeft deze plug-in uitgeschakeld in de publicatieservice",
+ "formatPainter": "Opmaak kopiëren",
+ "formatPainterContinuous": "Opmaak doorlopend kopiëren",
+ "formatPainterActive": "Opmaak kopiëren is actief; klik om af te sluiten",
+ "formatPainterContinuousActive": "Opmaak doorlopend kopiëren is actief; klik om af te sluiten",
"aiMcpEnv": "Omgevingsvariabelen",
"aiMcpEnvTip": "Geheimen waarnaar wordt verwezen worden aan dit programma verstrekt en rechtstreeks ingevoerde waarden worden als platte tekst opgeslagen",
"aiMcpEnvInvalid": "Ongeldige omgevingsvariabelen; controleer op lege, dubbele of ongeldige namen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 0822d1fd53..9c298d151d 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Autor wtyczki wyłączył tę wtyczkę w usłudze publikowania",
+ "formatPainter": "Malarz formatów",
+ "formatPainterContinuous": "Ciągły malarz formatów",
+ "formatPainterActive": "Malarz formatów jest aktywny; kliknij, aby zakończyć",
+ "formatPainterContinuousActive": "Ciągły malarz formatów jest aktywny; kliknij, aby zakończyć",
"aiMcpEnv": "Zmienne środowiskowe",
"aiMcpEnvTip": "Wskazane sekrety są udostępniane temu programowi, a wartości wpisane bezpośrednio są przechowywane jako zwykły tekst",
"aiMcpEnvInvalid": "Nieprawidłowe zmienne środowiskowe; sprawdź puste, zduplikowane lub nieprawidłowe nazwy",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 17133e0e24..b0ceae05e4 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "O autor do plugin desativou este plugin no serviço de publicação",
+ "formatPainter": "Pincel de formatação",
+ "formatPainterContinuous": "Pincel de formatação contínuo",
+ "formatPainterActive": "Pincel de formatação ativo; clique para sair",
+ "formatPainterContinuousActive": "Pincel de formatação contínuo ativo; clique para sair",
"aiMcpEnv": "Variáveis de ambiente",
"aiMcpEnvTip": "Os segredos referenciados são fornecidos a este programa e os valores inseridos diretamente são armazenados como texto simples",
"aiMcpEnvInvalid": "Variáveis de ambiente inválidas; verifique se há nomes vazios, duplicados ou inválidos",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 2c210636c7..11054e4b93 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Автор плагина отключил этот плагин в службе публикации",
+ "formatPainter": "Формат по образцу",
+ "formatPainterContinuous": "Непрерывный формат по образцу",
+ "formatPainterActive": "Формат по образцу активен; нажмите, чтобы выйти",
+ "formatPainterContinuousActive": "Непрерывный формат по образцу активен; нажмите, чтобы выйти",
"aiMcpEnv": "Переменные окружения",
"aiMcpEnvTip": "Указанные секреты передаются этой программе, а введённые напрямую значения хранятся в открытом виде",
"aiMcpEnvInvalid": "Недопустимые переменные окружения; проверьте пустые, повторяющиеся или недопустимые имена",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index e93ce0c143..8ec5e3c40e 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Autor doplnku zakázal tento doplnok v publikačnej službe",
+ "formatPainter": "Kopírovať formát",
+ "formatPainterContinuous": "Kopírovať formát nepretržite",
+ "formatPainterActive": "Kopírovanie formátu je aktívne; kliknutím ho ukončíte",
+ "formatPainterContinuousActive": "Nepretržité kopírovanie formátu je aktívne; kliknutím ho ukončíte",
"aiMcpEnv": "Premenné prostredia",
"aiMcpEnvTip": "Odkazované tajomstvá sa poskytnú tomuto programu a priamo zadané hodnoty sa uložia ako obyčajný text",
"aiMcpEnvInvalid": "Neplatné premenné prostredia; skontrolujte prázdne, duplicitné alebo neplatné názvy",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index cb7307ce44..bb1b7f5e83 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "ผู้เขียนปลั๊กอินได้ปิดใช้งานปลั๊กอินนี้ในบริการเผยแพร่",
+ "formatPainter": "คัดลอกรูปแบบ",
+ "formatPainterContinuous": "คัดลอกรูปแบบต่อเนื่อง",
+ "formatPainterActive": "การคัดลอกรูปแบบเปิดอยู่; คลิกเพื่อออก",
+ "formatPainterContinuousActive": "การคัดลอกรูปแบบต่อเนื่องเปิดอยู่; คลิกเพื่อออก",
"aiMcpEnv": "ตัวแปรสภาพแวดล้อม",
"aiMcpEnvTip": "ข้อมูลลับที่อ้างอิงจะถูกส่งให้โปรแกรมนี้ และค่าที่ป้อนโดยตรงจะถูกจัดเก็บเป็นข้อความธรรมดา",
"aiMcpEnvInvalid": "ตัวแปรสภาพแวดล้อมไม่ถูกต้อง โปรดตรวจสอบชื่อที่ว่าง ซ้ำ หรือไม่ถูกต้อง",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 229afe8fd4..84246c2c60 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Eklenti yazarı bu eklentiyi yayımlama hizmetinde devre dışı bıraktı",
+ "formatPainter": "Biçim Boyacısı",
+ "formatPainterContinuous": "Sürekli Biçim Boyacısı",
+ "formatPainterActive": "Biçim Boyacısı etkin; çıkmak için tıklayın",
+ "formatPainterContinuousActive": "Sürekli Biçim Boyacısı etkin; çıkmak için tıklayın",
"aiMcpEnv": "Ortam değişkenleri",
"aiMcpEnvTip": "Başvurulan gizli bilgiler bu programa sağlanır ve doğrudan girilen değerler düz metin olarak saklanır",
"aiMcpEnvInvalid": "Geçersiz ortam değişkenleri; boş, yinelenen veya geçersiz adları kontrol edin",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 58206a4017..61e18aa775 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "Автор плагіна вимкнув цей плагін у службі публікації",
+ "formatPainter": "Формат за зразком",
+ "formatPainterContinuous": "Безперервний формат за зразком",
+ "formatPainterActive": "Формат за зразком активний; натисніть, щоб вийти",
+ "formatPainterContinuousActive": "Безперервний формат за зразком активний; натисніть, щоб вийти",
"aiMcpEnv": "Змінні середовища",
"aiMcpEnvTip": "Указані секрети передаються цій програмі, а введені безпосередньо значення зберігаються як звичайний текст",
"aiMcpEnvInvalid": "Недопустимі змінні середовища; перевірте порожні, повторювані або недопустимі назви",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 8d094b0c60..0297ec9ccc 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "插件作者已禁止该插件在发布服务中运行",
+ "formatPainter": "格式刷",
+ "formatPainterContinuous": "连续格式刷",
+ "formatPainterActive": "格式刷已启用,点击退出",
+ "formatPainterContinuousActive": "连续格式刷已启用,点击退出",
"aiMcpEnv": "环境变量",
"aiMcpEnvTip": "引用的密钥会提供给该程序,直接填写的值将以明文存储",
"aiMcpEnvInvalid": "环境变量无效,请检查名称是否为空、重复或包含非法字符",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index af72af3f7e..7ea892d11d 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,5 +1,9 @@
{
"pluginDisabledInPublishTip": "插件作者已禁止該插件在發布服務中執行",
+ "formatPainter": "格式刷",
+ "formatPainterContinuous": "連續格式刷",
+ "formatPainterActive": "格式刷已啟用,點擊退出",
+ "formatPainterContinuousActive": "連續格式刷已啟用,點擊退出",
"aiMcpEnv": "環境變數",
"aiMcpEnvTip": "引用的金鑰會提供給該程式,直接填寫的值將以明文儲存",
"aiMcpEnvInvalid": "環境變數無效,請檢查名稱是否為空、重複或包含無效字元",
diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scss
index d8048e08ec..3188b68d5b 100644
--- a/app/src/assets/scss/main/_main.scss
+++ b/app/src/assets/scss/main/_main.scss
@@ -226,6 +226,10 @@ html[data-frontend="browser-desktop"] {
font-size: 12px;
}
+ &__format-painter {
+ color: var(--b3-theme-primary);
+ }
+
.fn__space:last-child {
width: 5px;
}
diff --git a/app/src/assets/scss/protyle/_toolbar.scss b/app/src/assets/scss/protyle/_toolbar.scss
index bad8fcd74c..50caa45bb5 100644
--- a/app/src/assets/scss/protyle/_toolbar.scss
+++ b/app/src/assets/scss/protyle/_toolbar.scss
@@ -57,6 +57,23 @@
border-left: 1px solid var(--b3-theme-surface-lighter);
margin: 6px 4px;
}
+
+ &__format-painter {
+ display: flex;
+
+ > .protyle-toolbar__item:first-child {
+ padding-right: 4px;
+ }
+
+ &-menu {
+ padding: 1px 3px 1px 0;
+
+ svg {
+ height: 10px;
+ width: 10px;
+ }
+ }
+ }
}
&-hint {
diff --git a/app/src/boot/globalEvent/event.ts b/app/src/boot/globalEvent/event.ts
index 04aba61547..b26de21c71 100644
--- a/app/src/boot/globalEvent/event.ts
+++ b/app/src/boot/globalEvent/event.ts
@@ -16,6 +16,7 @@ import {getDockByType} from "../../layout/tabUtil";
import {fetchPost} from "../../util/fetch";
import {initHarmonyTextSelectionMenu} from "../../util/harmonyTextSelectionMenu";
import {clearDragTipGhost, hideDragTip} from "../../protyle/util/dragTip";
+import {formatPainter} from "../../protyle/toolbar/FormatPainter";
const KANBAN_GROUP_DRAG_TYPE = `${Constants.SIYUAN_DROP_GUTTER}NodeAttributeView${Constants.ZWSP}Group${Constants.ZWSP}`.toLowerCase();
@@ -219,6 +220,7 @@ export const initWindowEvent = (app: App) => {
});
window.addEventListener("mousedown", (event: MouseEvent & { target: HTMLElement }) => {
+ formatPainter.deactivateByPointer(event.target);
const tabBarElement = hasClosestByClassName(event.target, "layout-tab-bar", true);
const isWindowTabBar = tabBarElement && Array.from(tabBarElement.parentElement.children).some((item) =>
item.classList.contains("layout-tab-bar--readonly"));
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 2975ab3908..adf49da35f 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -75,6 +75,7 @@ import {copyTextByType} from "../../protyle/toolbar/util";
import {onlyProtyleCommand} from "./command/protyle";
import {cancelDrag} from "./dragover";
import {bindAVPanelKeydown} from "../../protyle/render/av/keydown";
+import {formatPainter} from "../../protyle/toolbar/FormatPainter";
const switchDialogEvent = (app: App, event: MouseEvent) => {
event.preventDefault();
@@ -1527,6 +1528,10 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
}
if (event.key === "Escape" && !event.isComposing) {
+ if (formatPainter.deactivate()) {
+ event.preventDefault();
+ return;
+ }
cancelDrag();
const imgPreviewElement = document.querySelector(".protyle-img");
if (imgPreviewElement) {
diff --git a/app/src/protyle/toolbar/FormatPainter.ts b/app/src/protyle/toolbar/FormatPainter.ts
new file mode 100644
index 0000000000..145888d605
--- /dev/null
+++ b/app/src/protyle/toolbar/FormatPainter.ts
@@ -0,0 +1,187 @@
+import {Constants} from "../../constants";
+import {MenuItem} from "../../menus/Menu";
+import {getBlockRanges} from "../util/selection";
+import {
+ FORMAT_PAINTER_TYPES,
+ getCommonFormatPainterSnapshot,
+ IFormatPainterSegment,
+ IFormatPainterSnapshot,
+ IFormatPainterStyle,
+} from "./formatPainterCore";
+
+export type TFormatPainterMode = "once" | "continuous";
+
+const getSegment = (textNode: Text, editableElement: Element) => {
+ const types: string[] = [];
+ const styles: IFormatPainterStyle = {};
+ let element = textNode.parentElement;
+ while (element && editableElement.contains(element)) {
+ const elementTypes = (element.getAttribute("data-type") || "").split(" ").filter(Boolean);
+ types.push(...elementTypes);
+ if (elementTypes.includes("inline-math")) {
+ return;
+ }
+ if (elementTypes.includes("text")) {
+ styles.backgroundColor = styles.backgroundColor || element.style.backgroundColor || undefined;
+ styles.color = styles.color || element.style.color || undefined;
+ styles.fontSize = styles.fontSize || element.style.fontSize || undefined;
+ styles.shadow = styles.shadow || !!element.style.textShadow || undefined;
+ styles.hollow = styles.hollow || !!element.style.webkitTextStroke || undefined;
+ }
+ if (element === editableElement) {
+ break;
+ }
+ element = element.parentElement;
+ }
+ return {
+ styles,
+ types: [...new Set(types)].filter(type => FORMAT_PAINTER_TYPES.includes(type)),
+ };
+};
+
+export const getFormatPainterSnapshot = (rootElement: Element, range: Range) => {
+ const segments: IFormatPainterSegment[] = [];
+ getBlockRanges(rootElement, range, ["NodeCodeBlock", "NodeAttributeView"]).forEach(item => {
+ const walker = document.createTreeWalker(item.editableElement, NodeFilter.SHOW_TEXT);
+ let textNode = walker.nextNode() as Text;
+ while (textNode) {
+ if (item.range.intersectsNode(textNode)) {
+ const start = item.range.startContainer === textNode ? item.range.startOffset : 0;
+ const end = item.range.endContainer === textNode ? item.range.endOffset : textNode.data.length;
+ if (start < end && textNode.data.substring(start, end).split(Constants.ZWSP).join("")) {
+ const segment = getSegment(textNode, item.editableElement);
+ if (segment) {
+ segments.push(segment);
+ }
+ }
+ }
+ textNode = walker.nextNode() as Text;
+ }
+ });
+ return getCommonFormatPainterSnapshot(segments);
+};
+
+class FormatPainterController {
+ private mode?: TFormatPainterMode;
+ private snapshot?: IFormatPainterSnapshot;
+
+ public isActive() {
+ return !!this.mode && !!this.snapshot;
+ }
+
+ public activate(protyle: IProtyle, mode: TFormatPainterMode) {
+ if (!protyle.toolbar?.range) {
+ return false;
+ }
+ const snapshot = getFormatPainterSnapshot(protyle.wysiwyg.element, protyle.toolbar.range);
+ if (!snapshot) {
+ return false;
+ }
+ this.mode = mode;
+ this.snapshot = snapshot;
+ document.body.dataset.formatPainter = mode;
+ this.renderStatus();
+ protyle.toolbar.element.classList.add("fn__none");
+ return true;
+ }
+
+ public paint(protyle: IProtyle, range: Range) {
+ if (!this.snapshot || !this.mode || !protyle.toolbar || protyle.disabled) {
+ return;
+ }
+ protyle.toolbar.range = range;
+ if (!protyle.toolbar.applyFormatPainter(protyle, this.snapshot)) {
+ return;
+ }
+ const paintedRange = protyle.toolbar.range;
+ protyle.toolbar.element.classList.add("fn__none");
+ if (this.mode === "once") {
+ this.deactivate();
+ }
+ return paintedRange;
+ }
+
+ public deactivate() {
+ if (!this.isActive()) {
+ return false;
+ }
+ this.mode = undefined;
+ this.snapshot = undefined;
+ delete document.body.dataset.formatPainter;
+ document.getElementById("statusFormatPainter")?.remove();
+ return true;
+ }
+
+ public deactivateByPointer(target: Element) {
+ if (!this.isActive() || target.closest(".protyle-wysiwyg") || target.closest("#statusFormatPainter") ||
+ target.closest('[data-type="tab-header"]')) {
+ return;
+ }
+ this.deactivate();
+ }
+
+ private renderStatus() {
+ const statusElement = document.getElementById("status");
+ if (!statusElement) {
+ return;
+ }
+ let element = document.getElementById("statusFormatPainter");
+ if (!element) {
+ element = document.createElement("button");
+ element.id = "statusFormatPainter";
+ element.className = "toolbar__item ariaLabel status__format-painter";
+ element.innerHTML = '<svg><use xlink:href="#iconFormat"></use></svg>';
+ element.addEventListener("click", () => this.deactivate());
+ const helpElement = statusElement.querySelector("#statusHelp");
+ if (helpElement) {
+ helpElement.before(element);
+ } else {
+ statusElement.append(element);
+ }
+ }
+ element.setAttribute("aria-label", this.mode === "continuous" ?
+ window.siyuan.languages.formatPainterContinuousActive : window.siyuan.languages.formatPainterActive);
+ }
+}
+
+export const formatPainter = new FormatPainterController();
+
+export class FormatPainter {
+ public element: HTMLElement;
+
+ constructor(protyle: IProtyle, menuItem: IMenuItem) {
+ this.element = document.createElement("div");
+ this.element.className = "protyle-toolbar__format-painter";
+
+ const buttonElement = document.createElement("button");
+ buttonElement.className = "protyle-toolbar__item b3-tooltips b3-tooltips__n";
+ buttonElement.setAttribute("data-type", menuItem.name);
+ buttonElement.setAttribute("aria-label", window.siyuan.languages.formatPainter);
+ buttonElement.innerHTML = '<svg><use xlink:href="#iconFormat"></use></svg>';
+ buttonElement.addEventListener("mousedown", event => event.preventDefault());
+ buttonElement.addEventListener("click", event => {
+ event.preventDefault();
+ formatPainter.activate(protyle, "once");
+ });
+
+ const menuElement = document.createElement("button");
+ menuElement.className = "protyle-toolbar__item protyle-toolbar__format-painter-menu " +
+ "b3-tooltips b3-tooltips__n";
+ menuElement.setAttribute("aria-label", window.siyuan.languages.formatPainterContinuous);
+ menuElement.innerHTML = '<svg><use xlink:href="#iconDown"></use></svg>';
+ menuElement.addEventListener("mousedown", event => event.preventDefault());
+ menuElement.addEventListener("click", event => {
+ event.preventDefault();
+ window.siyuan.menus.menu.remove();
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconFormat",
+ label: window.siyuan.languages.formatPainterContinuous,
+ click: () => formatPainter.activate(protyle, "continuous"),
+ }).element);
+ const rect = menuElement.getBoundingClientRect();
+ window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height});
+ });
+
+ this.element.append(buttonElement, menuElement);
+ }
+}
diff --git a/app/src/protyle/toolbar/formatPainter.test.ts b/app/src/protyle/toolbar/formatPainter.test.ts
new file mode 100644
index 0000000000..29a9bf7266
--- /dev/null
+++ b/app/src/protyle/toolbar/formatPainter.test.ts
@@ -0,0 +1,42 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getCommonFormatPainterSnapshot} from "./formatPainterCore";
+
+describe("getCommonFormatPainterSnapshot", () => {
+ it("keeps only formats shared by every selected text segment", () => {
+ assert.deepEqual(getCommonFormatPainterSnapshot([{
+ types: ["strong", "em"],
+ styles: {color: "red", fontSize: "16px"},
+ }, {
+ types: ["strong", "u"],
+ styles: {color: "blue", fontSize: "16px"},
+ }]), {
+ types: ["strong"],
+ styles: {fontSize: "16px"},
+ });
+ });
+
+ it("returns an empty format for unformatted text so it can clear the target", () => {
+ assert.deepEqual(getCommonFormatPainterSnapshot([{
+ types: [],
+ styles: {},
+ }]), {
+ types: [],
+ styles: {},
+ });
+ });
+
+ it("ignores formats that are not supported by the painter", () => {
+ assert.deepEqual(getCommonFormatPainterSnapshot([{
+ types: ["a", "block-ref", "strong"],
+ styles: {shadow: true},
+ }]), {
+ types: ["strong"],
+ styles: {shadow: true},
+ });
+ });
+
+ it("requires at least one selected text segment", () => {
+ assert.equal(getCommonFormatPainterSnapshot([]), undefined);
+ });
+});
diff --git a/app/src/protyle/toolbar/formatPainterCore.ts b/app/src/protyle/toolbar/formatPainterCore.ts
new file mode 100644
index 0000000000..7e908db71e
--- /dev/null
+++ b/app/src/protyle/toolbar/formatPainterCore.ts
@@ -0,0 +1,43 @@
+export interface IFormatPainterStyle {
+ backgroundColor?: string;
+ color?: string;
+ fontSize?: string;
+ shadow?: boolean;
+ hollow?: boolean;
+}
+
+export interface IFormatPainterSnapshot {
+ styles: IFormatPainterStyle;
+ types: string[];
+}
+
+export interface IFormatPainterSegment {
+ styles: IFormatPainterStyle;
+ types: string[];
+}
+
+export const FORMAT_PAINTER_TYPES = ["strong", "em", "u", "s", "mark", "sup", "sub", "code", "kbd"];
+
+const getCommonStyles = (segments: IFormatPainterSegment[]) => {
+ const styles: IFormatPainterStyle = {};
+ const keys: (keyof IFormatPainterStyle)[] = [
+ "backgroundColor", "color", "fontSize", "shadow", "hollow"
+ ];
+ keys.forEach(key => {
+ const value = segments[0].styles[key];
+ if (value && segments.every(item => item.styles[key] === value)) {
+ (styles as Record<keyof IFormatPainterStyle, string | boolean>)[key] = value;
+ }
+ });
+ return styles;
+};
+
+export const getCommonFormatPainterSnapshot = (segments: IFormatPainterSegment[]) => {
+ if (segments.length === 0) {
+ return;
+ }
+ return {
+ styles: getCommonStyles(segments),
+ types: FORMAT_PAINTER_TYPES.filter(type => segments.every(item => item.types.includes(type))),
+ } as IFormatPainterSnapshot;
+};
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index f1a49f963c..44f0de0e67 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -56,6 +56,8 @@ import {paste, pasteAsPlainText, pasteEscaped} from "../util/paste";
import {escapeHtml} from "../../util/escape";
import {resizeSide} from "../../history/resizeSide";
import {activeBlur, updateMobilePluginToolbar} from "../../mobile/util/keyboardToolbar";
+import {FormatPainter} from "./FormatPainter";
+import {IFormatPainterSnapshot} from "./formatPainterCore";
const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean) => {
if (!lite) {
@@ -157,6 +159,7 @@ export class Toolbar {
"sup",
"sub",
"clear",
+ "format-painter",
"|",
"code",
"kbd",
@@ -383,6 +386,82 @@ export class Toolbar {
return this.setInlineMarkInBlock(protyle, type, action, textObj, undefined, focusRange, undoContext);
}
+ public applyFormatPainter(protyle: IProtyle, snapshot: IFormatPainterSnapshot) {
+ const selectedRange = this.range.cloneRange();
+ const startRange = selectedRange.cloneRange();
+ startRange.collapse(true);
+ const startsAtBlockEnd = isEndOfBlock(startRange);
+ const ranges = getBlockRanges(protyle.wysiwyg.element, selectedRange,
+ ["NodeCodeBlock", "NodeAttributeView"]).filter(item =>
+ !(startsAtBlockEnd && item.editableElement.contains(selectedRange.startContainer)) &&
+ item.range.toString().split(Constants.ZWSP).join(""));
+ if (ranges.length === 0) {
+ return false;
+ }
+ const preserveStart = !ranges.some(item => item.editableElement.contains(selectedRange.startContainer));
+ const preserveEnd = !ranges.some(item => item.editableElement.contains(selectedRange.endContainer));
+ const visibleOffsets = new Map(ranges.map(item =>
+ [item, getSelectionOffset(item.editableElement, undefined, item.range, true)]));
+ const rangesByBlock = new Map<HTMLElement, typeof ranges>();
+ ranges.forEach(item => {
+ const blockRanges = rangesByBlock.get(item.blockElement) || [];
+ blockRanges.push(item);
+ rangesByBlock.set(item.blockElement, blockRanges);
+ });
+ let selectionRange: Range;
+ updateBatchTransaction(Array.from(rangesByBlock.keys()), protyle, blockElement => {
+ rangesByBlock.get(blockElement).forEach(item => {
+ const position = visibleOffsets.get(item);
+ const resetRange = () => focusByOffset(
+ item.editableElement, position.start, position.end, false, true
+ ) as Range;
+ let range = resetRange();
+ if (!range || range.collapsed) {
+ return;
+ }
+ const applyMark = (type: string, textObj?: ITextOption) => {
+ this.range = range;
+ this.setInlineMarkInBlock(protyle, type, "range", textObj, type === "clear", false);
+ range = resetRange() || this.range;
+ };
+ applyMark("clear");
+ snapshot.types.forEach(type => applyMark(type));
+ if (snapshot.styles.backgroundColor) {
+ applyMark("text", {type: "backgroundColor", color: snapshot.styles.backgroundColor});
+ }
+ if (snapshot.styles.color) {
+ applyMark("text", {type: "color", color: snapshot.styles.color});
+ }
+ if (snapshot.styles.fontSize) {
+ applyMark("text", {type: "fontSize", color: snapshot.styles.fontSize});
+ }
+ if (snapshot.styles.shadow) {
+ applyMark("text", {type: "style4"});
+ }
+ if (snapshot.styles.hollow) {
+ applyMark("text", {type: "style2"});
+ }
+ const offsetRange = resetRange() || range;
+ if (selectionRange) {
+ selectionRange.setEnd(offsetRange.endContainer, offsetRange.endOffset);
+ } else {
+ selectionRange = offsetRange.cloneRange();
+ }
+ });
+ }, getUndoFocusContext(protyle.wysiwyg.element, selectedRange, true));
+ if (selectionRange) {
+ if (preserveStart) {
+ selectionRange.setStart(selectedRange.startContainer, selectedRange.startOffset);
+ }
+ if (preserveEnd) {
+ selectionRange.setEnd(selectedRange.endContainer, selectedRange.endOffset);
+ }
+ this.range = selectionRange;
+ focusByRange(selectionRange);
+ }
+ return true;
+ }
+
private setBlockRangesInlineMark(protyle: IProtyle, type: string, action: "range" | "toolbar",
textObj?: ITextOption, focusRange = true) {
const selectedRange = this.range.cloneRange();
@@ -2151,6 +2230,10 @@ export class Toolbar {
case "text":
menuItemObj = new Font(protyle, menuItem);
break;
+ case "format-painter":
+ menuItemObj = menuItem.click ? new ToolbarItem(protyle, menuItem) :
+ new FormatPainter(protyle, menuItem);
+ break;
case "a":
menuItemObj = new Link(protyle, menuItem);
break;
diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.ts
index 3bee202f29..3dd821ab28 100644
--- a/app/src/protyle/toolbar/util.ts
+++ b/app/src/protyle/toolbar/util.ts
@@ -228,6 +228,11 @@ export const toolbarKeyToMenu = (toolbar: Array<string | IMenuItem>) => {
hotkey: window.siyuan.config.keymap.editor.insert.clearInline.custom,
icon: "iconClear",
tipPosition: "n",
+ }, {
+ name: "format-painter",
+ lang: "formatPainter",
+ icon: "iconFormat",
+ tipPosition: "n",
}, {
name: "|",
}];
diff --git a/app/src/protyle/util/Options.ts b/app/src/protyle/util/Options.ts
index 795f884727..8d832def87 100644
--- a/app/src/protyle/util/Options.ts
+++ b/app/src/protyle/util/Options.ts
@@ -117,6 +117,7 @@ export class Options {
"sup",
"sub",
"clear",
+ "format-painter",
"|",
"code",
"kbd",
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index ac3397ccc8..2c0f4ac030 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -190,6 +190,7 @@ import {
resolveBlockDragSelectStart
} from "./blockDragSelect";
import {isCrossBlockTextRange} from "../gutter/multiSelect";
+import {formatPainter} from "../toolbar/FormatPainter";
interface IShiftClickBlockPoint {
blockElement: HTMLElement;
@@ -4768,11 +4769,16 @@ export class WYSIWYG {
}
/// #if !MOBILE
if (newRange.toString().replace(Constants.ZWSP, "") !== "") {
- protyle.toolbar.render(protyle, newRange, event.detail > 0 ? {
- x: event.clientX,
- y: event.clientY,
- detail: event.detail,
- } : undefined);
+ const paintedRange = formatPainter.paint(protyle, newRange);
+ if (paintedRange) {
+ newRange = paintedRange;
+ } else {
+ protyle.toolbar.render(protyle, newRange, event.detail > 0 ? {
+ x: event.clientX,
+ y: event.clientY,
+ detail: event.detail,
+ } : undefined);
+ }
} else {
// https://github.com/siyuan-note/siyuan/issues/9785
protyle.toolbar.range = newRange;
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index ea44033cf0..3496b7f7a0 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -65,6 +65,7 @@ import {
import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";
import {fontEvent} from "../toolbar/Font";
import {applyTableCellStyleHotkey} from "../toolbar/tableCell";
+import {formatPainter} from "../toolbar/FormatPainter";
import {
addSubList,
appendListItem,
@@ -1602,6 +1603,11 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
// esc
if (event.key === "Escape") {
+ if (formatPainter.deactivate()) {
+ event.stopPropagation();
+ event.preventDefault();
+ return;
+ }
if (event.repeat) {
// https://github.com/siyuan-note/siyuan/issues/12989
const cardElement = hasClosestByClassName(range.startContainer, "card__main", true);