Skip to content

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

:sparkles: Add database field layout options and drag previews https://github.com/siyuan-note/siyuan/issues/20551

Daniel8fd25690d341
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 98fdf21a74..05a0aaaef5 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "تخطيط حقول قاعدة البيانات",
+ "databaseAttrLayoutTip": "تحديد تخطيط الحقول في لوحة قاعدة البيانات أعلى المستند ولوحة العنصر المستقلة، مع استخدام عمود واحد تلقائيًا عند عدم توفر مساحة كافية",
+ "databaseAttrLayoutSingle": "عمود واحد",
+ "databaseAttrLayoutRow": "عمودان (حسب الصفوف)",
+ "databaseAttrLayoutColumn": "عمودان (حسب الأعمدة)",
"mathDelimiterCompatibility": "التوافق مع محددات صيغ LaTeX عند اللصق والاستيراد",
"mathDelimiterCompatibilityTip": "عند التفعيل، يتم التعرف تلقائيًا على \\(...\\) و\\[...\\] في المحتوى الملصق والمستورد كصيغ مضمنة وصيغ كتلية على التوالي",
"automationCollectionScopeLimit": "يمكن تحديد ما يصل إلى 32 دفتر ملاحظات أو مستند في نطاق المراقبة",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index f121029806..45d8be2365 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Layout der Datenbankfelder",
+ "databaseAttrLayoutTip": "Legt das Feldlayout im Datenbankbereich am Dokumentanfang und im separaten Eintragsbereich fest; bei Platzmangel wird automatisch eine Spalte verwendet",
+ "databaseAttrLayoutSingle": "Eine Spalte",
+ "databaseAttrLayoutRow": "Zwei Spalten (zeilenweise)",
+ "databaseAttrLayoutColumn": "Zwei Spalten (spaltenweise)",
"mathDelimiterCompatibility": "LaTeX-Formelbegrenzer beim Einfügen und Importieren unterstützen",
"mathDelimiterCompatibilityTip": "Wenn aktiviert, werden \\(...\\) und \\[...\\] in eingefügten und importierten Inhalten automatisch als Inline- bzw. Blockformeln erkannt",
"automationCollectionScopeLimit": "Der Überwachungsbereich kann höchstens 32 Notizbücher oder Dokumente enthalten",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 38a73565fc..8e5084852b 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Database field layout",
+ "databaseAttrLayoutTip": "Set the field layout in the database panel at the top of a document and the standalone item panel; one column is used automatically when space is limited",
+ "databaseAttrLayoutSingle": "One column",
+ "databaseAttrLayoutRow": "Two columns (by row)",
+ "databaseAttrLayoutColumn": "Two columns (by column)",
"mathDelimiterCompatibility": "Recognize LaTeX math delimiters when pasting and importing",
"mathDelimiterCompatibilityTip": "When enabled, automatically recognize \\(...\\) and \\[...\\] in pasted and imported content as inline and block math, respectively",
"automationCollectionScopeLimit": "The watch scope can contain up to 32 notebooks or documents",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 400a5678ec..365a1f8473 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Disposición de los campos de la base de datos",
+ "databaseAttrLayoutTip": "Configura la disposición de los campos del panel de base de datos en la parte superior del documento y del panel de elemento independiente; se usa una columna automáticamente cuando falta espacio",
+ "databaseAttrLayoutSingle": "Una columna",
+ "databaseAttrLayoutRow": "Dos columnas (por filas)",
+ "databaseAttrLayoutColumn": "Dos columnas (por columnas)",
"mathDelimiterCompatibility": "Reconocer delimitadores de fórmulas LaTeX al pegar e importar",
"mathDelimiterCompatibilityTip": "Al activarlo, se reconocen automáticamente \\(...\\) y \\[...\\] en el contenido pegado e importado como fórmulas en línea y de bloque, respectivamente",
"automationCollectionScopeLimit": "El ámbito de supervisión puede contener hasta 32 cuadernos o documentos",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 8e608186b6..10d48277c3 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Disposition des champs de la base de données",
+ "databaseAttrLayoutTip": "Définit la disposition des champs du panneau de base de données en haut du document et du panneau de fiche indépendant ; une seule colonne est utilisée automatiquement si l’espace est insuffisant",
+ "databaseAttrLayoutSingle": "Une colonne",
+ "databaseAttrLayoutRow": "Deux colonnes (par ligne)",
+ "databaseAttrLayoutColumn": "Deux colonnes (par colonne)",
"mathDelimiterCompatibility": "Reconnaître les délimiteurs de formules LaTeX lors du collage et de l’importation",
"mathDelimiterCompatibilityTip": "Lorsque cette option est activée, \\(...\\) et \\[...\\] sont automatiquement reconnus dans le contenu collé et importé comme des formules en ligne et en bloc, respectivement",
"automationCollectionScopeLimit": "Le périmètre de surveillance peut contenir jusqu’à 32 carnets ou documents",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 9833ea5f44..44db40d87e 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "פריסת שדות מסד הנתונים",
+ "databaseAttrLayoutTip": "קביעת פריסת השדות בלוח מסד הנתונים בראש המסמך ובלוח הפריט העצמאי, עם מעבר אוטומטי לעמודה אחת כשאין מספיק מקום",
+ "databaseAttrLayoutSingle": "עמודה אחת",
+ "databaseAttrLayoutRow": "שתי עמודות (לפי שורות)",
+ "databaseAttrLayoutColumn": "שתי עמודות (לפי עמודות)",
"mathDelimiterCompatibility": "זיהוי תוחמי נוסחאות LaTeX בהדבקה ובייבוא",
"mathDelimiterCompatibilityTip": "כאשר האפשרות מופעלת, \\(...\\) ו־\\[...\\] בתוכן מודבק ומיובא מזוהים אוטומטית כנוסחאות בתוך השורה וכנוסחאות בלוק, בהתאמה",
"automationCollectionScopeLimit": "טווח המעקב יכול להכיל עד 32 מחברות או מסמכים",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index fc56aa250d..f368c3ff5d 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "डेटाबेस फ़ील्ड का लेआउट",
+ "databaseAttrLayoutTip": "दस्तावेज़ के शीर्ष पर डेटाबेस पैनल और अलग आइटम पैनल के फ़ील्ड का लेआउट चुनें, जगह कम होने पर अपने आप एक कॉलम का उपयोग होता है",
+ "databaseAttrLayoutSingle": "एक कॉलम",
+ "databaseAttrLayoutRow": "दो कॉलम (पंक्ति के अनुसार)",
+ "databaseAttrLayoutColumn": "दो कॉलम (कॉलम के अनुसार)",
"mathDelimiterCompatibility": "पेस्ट और आयात करते समय LaTeX सूत्र सीमांकक पहचानें",
"mathDelimiterCompatibilityTip": "सक्षम होने पर, पेस्ट और आयात की गई सामग्री में \\(...\\) और \\[...\\] को क्रमशः इनलाइन और ब्लॉक सूत्रों के रूप में स्वचालित रूप से पहचाना जाता है",
"automationCollectionScopeLimit": "निगरानी के दायरे में अधिकतम 32 नोटबुक या दस्तावेज़ हो सकते हैं",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 6c7b382da4..ccb5dbad36 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Tata letak bidang basis data",
+ "databaseAttrLayoutTip": "Atur tata letak bidang pada panel basis data di bagian atas dokumen dan panel item terpisah; satu kolom digunakan secara otomatis jika ruang tidak cukup",
+ "databaseAttrLayoutSingle": "Satu kolom",
+ "databaseAttrLayoutRow": "Dua kolom (menurut baris)",
+ "databaseAttrLayoutColumn": "Dua kolom (menurut kolom)",
"mathDelimiterCompatibility": "Kenali pembatas rumus LaTeX saat menempel dan mengimpor",
"mathDelimiterCompatibilityTip": "Saat diaktifkan, \\(...\\) dan \\[...\\] dalam konten yang ditempel dan diimpor akan otomatis dikenali sebagai rumus sebaris dan blok",
"automationCollectionScopeLimit": "Cakupan pemantauan dapat memuat hingga 32 buku catatan atau dokumen",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index f205dcd5e7..a6c53d8861 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Disposizione dei campi del database",
+ "databaseAttrLayoutTip": "Imposta la disposizione dei campi nel pannello del database in cima al documento e nel pannello della voce indipendente; quando lo spazio è insufficiente viene usata automaticamente una colonna",
+ "databaseAttrLayoutSingle": "Una colonna",
+ "databaseAttrLayoutRow": "Due colonne (per riga)",
+ "databaseAttrLayoutColumn": "Due colonne (per colonna)",
"mathDelimiterCompatibility": "Riconosci i delimitatori delle formule LaTeX durante incolla e importazione",
"mathDelimiterCompatibilityTip": "Se abilitato, riconosce automaticamente \\(...\\) e \\[...\\] nei contenuti incollati e importati come formule in linea e a blocchi, rispettivamente",
"automationCollectionScopeLimit": "L’ambito di monitoraggio può contenere fino a 32 taccuini o documenti",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 9e7f65632b..cf2108d7b9 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "データベースフィールドのレイアウト",
+ "databaseAttrLayoutTip": "ドキュメント上部のデータベースパネルと独立した項目パネルのフィールドの配置を設定し、スペースが不足する場合は自動的に1列で表示",
+ "databaseAttrLayoutSingle": "1列",
+ "databaseAttrLayoutRow": "2列(行順)",
+ "databaseAttrLayoutColumn": "2列(列順)",
"mathDelimiterCompatibility": "貼り付け・インポート時に LaTeX 数式の区切り文字を認識する",
"mathDelimiterCompatibilityTip": "有効にすると、貼り付け・インポートした内容の \\(...\\) と \\[...\\] を、それぞれインライン数式とブロック数式として自動的に認識します",
"automationCollectionScopeLimit": "監視範囲に含められるノートブックまたはドキュメントは合計32件までです",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 4fc803c067..12828b912c 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "데이터베이스 필드 배치",
+ "databaseAttrLayoutTip": "문서 상단의 데이터베이스 패널과 독립 항목 패널의 필드 배치를 설정하며 공간이 부족하면 자동으로 한 열로 표시",
+ "databaseAttrLayoutSingle": "한 열",
+ "databaseAttrLayoutRow": "두 열 (행 우선)",
+ "databaseAttrLayoutColumn": "두 열 (열 우선)",
"mathDelimiterCompatibility": "붙여넣기 및 가져오기 시 LaTeX 수식 구분자 인식",
"mathDelimiterCompatibilityTip": "활성화하면 붙여넣거나 가져온 내용의 \\(...\\)와 \\[...\\]를 각각 인라인 수식과 블록 수식으로 자동 인식합니다",
"automationCollectionScopeLimit": "모니터링 범위에는 노트북 또는 문서를 합계 32개까지 포함할 수 있습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index d49e6d77b1..e8b8ac3c1b 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Indeling van databasevelden",
+ "databaseAttrLayoutTip": "Stelt de veldindeling in het databasepaneel bovenaan het document en het afzonderlijke itempaneel in; bij onvoldoende ruimte wordt automatisch één kolom gebruikt",
+ "databaseAttrLayoutSingle": "Eén kolom",
+ "databaseAttrLayoutRow": "Twee kolommen (per rij)",
+ "databaseAttrLayoutColumn": "Twee kolommen (per kolom)",
"mathDelimiterCompatibility": "LaTeX-formulescheidingstekens herkennen bij plakken en importeren",
"mathDelimiterCompatibilityTip": "Indien ingeschakeld worden \\(...\\) en \\[...\\] in geplakte en geïmporteerde inhoud automatisch herkend als respectievelijk inline- en blokformules",
"automationCollectionScopeLimit": "Het bewakingsbereik kan maximaal 32 notitieboeken of documenten bevatten",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 19108f35cc..e40ff5a027 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Układ pól bazy danych",
+ "databaseAttrLayoutTip": "Ustawia układ pól w panelu bazy danych u góry dokumentu i w osobnym panelu elementu; przy braku miejsca automatycznie używana jest jedna kolumna",
+ "databaseAttrLayoutSingle": "Jedna kolumna",
+ "databaseAttrLayoutRow": "Dwie kolumny (wierszami)",
+ "databaseAttrLayoutColumn": "Dwie kolumny (kolumnami)",
"mathDelimiterCompatibility": "Rozpoznawaj delimitery formuł LaTeX podczas wklejania i importowania",
"mathDelimiterCompatibilityTip": "Po włączeniu \\(...\\) i \\[...\\] we wklejanej i importowanej treści są automatycznie rozpoznawane odpowiednio jako formuły w wierszu i blokowe",
"automationCollectionScopeLimit": "Zakres monitorowania może zawierać łącznie do 32 notatników lub dokumentów",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index ec0922f6a7..2080fc946e 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Layout dos campos do banco de dados",
+ "databaseAttrLayoutTip": "Define o layout dos campos no painel do banco de dados no topo do documento e no painel de item independente; uma coluna é usada automaticamente quando não há espaço suficiente",
+ "databaseAttrLayoutSingle": "Uma coluna",
+ "databaseAttrLayoutRow": "Duas colunas (por linha)",
+ "databaseAttrLayoutColumn": "Duas colunas (por coluna)",
"mathDelimiterCompatibility": "Reconhecer delimitadores de fórmulas LaTeX ao colar e importar",
"mathDelimiterCompatibilityTip": "Quando ativado, reconhece automaticamente \\(...\\) e \\[...\\] no conteúdo colado e importado como fórmulas em linha e em bloco, respectivamente",
"automationCollectionScopeLimit": "O escopo de monitoramento pode conter até 32 cadernos ou documentos",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 8e60fc465c..f0786ed54d 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Расположение полей базы данных",
+ "databaseAttrLayoutTip": "Задаёт расположение полей панели базы данных вверху документа и отдельной панели записи; при недостатке места автоматически используется один столбец",
+ "databaseAttrLayoutSingle": "Один столбец",
+ "databaseAttrLayoutRow": "Два столбца (по строкам)",
+ "databaseAttrLayoutColumn": "Два столбца (по столбцам)",
"mathDelimiterCompatibility": "Распознавать разделители формул LaTeX при вставке и импорте",
"mathDelimiterCompatibilityTip": "Если включено, \\(...\\) и \\[...\\] во вставляемом и импортируемом содержимом автоматически распознаются как строчные и блочные формулы соответственно",
"automationCollectionScopeLimit": "Область отслеживания может содержать не более 32 блокнотов или документов",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index ad4b9ee76d..52bd0adb65 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Rozloženie polí databázy",
+ "databaseAttrLayoutTip": "Nastaví rozloženie polí na paneli databázy v hornej časti dokumentu a na samostatnom paneli položky; pri nedostatku miesta sa automaticky použije jeden stĺpec",
+ "databaseAttrLayoutSingle": "Jeden stĺpec",
+ "databaseAttrLayoutRow": "Dva stĺpce (po riadkoch)",
+ "databaseAttrLayoutColumn": "Dva stĺpce (po stĺpcoch)",
"mathDelimiterCompatibility": "Rozpoznávať oddeľovače vzorcov LaTeX pri vkladaní a importe",
"mathDelimiterCompatibilityTip": "Ak je táto možnosť zapnutá, \\(...\\) a \\[...\\] vo vloženom a importovanom obsahu sa automaticky rozpoznajú ako riadkové a blokové vzorce",
"automationCollectionScopeLimit": "Rozsah sledovania môže obsahovať najviac 32 zápisníkov alebo dokumentov",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 837c537f1f..e30e940eef 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Распоред поља базе података",
+ "databaseAttrLayoutTip": "Подешава распоред поља у панелу базе података на врху документа и у засебном панелу ставке; када нема довољно простора, аутоматски се користи једна колона",
+ "databaseAttrLayoutSingle": "Једна колона",
+ "databaseAttrLayoutRow": "Две колоне (по редовима)",
+ "databaseAttrLayoutColumn": "Две колоне (по колонама)",
"mathDelimiterCompatibility": "Препознај LaTeX граничнике формула при лепљењу и увозу",
"mathDelimiterCompatibilityTip": "Када је омогућено, \\(...\\) и \\[...\\] у налепљеном и увезеном садржају аутоматски се препознају као формуле у реду и у блоку",
"automationCollectionScopeLimit": "Опсег праћења може да садржи највише 32 бележница или докумената",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 90ce0ef788..5a31aef604 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "รูปแบบการจัดวางฟิลด์ฐานข้อมูล",
+ "databaseAttrLayoutTip": "กำหนดการจัดวางฟิลด์ในแผงฐานข้อมูลด้านบนเอกสารและแผงรายการแยก โดยใช้คอลัมน์เดียวโดยอัตโนมัติเมื่อพื้นที่ไม่เพียงพอ",
+ "databaseAttrLayoutSingle": "หนึ่งคอลัมน์",
+ "databaseAttrLayoutRow": "สองคอลัมน์ (เรียงตามแถว)",
+ "databaseAttrLayoutColumn": "สองคอลัมน์ (เรียงตามคอลัมน์)",
"mathDelimiterCompatibility": "รู้จำตัวคั่นสูตร LaTeX เมื่อวางและนำเข้า",
"mathDelimiterCompatibilityTip": "เมื่อเปิดใช้งาน ระบบจะรู้จำ \\(...\\) และ \\[...\\] ในเนื้อหาที่วางและนำเข้าเป็นสูตรในบรรทัดและสูตรแบบบล็อกตามลำดับโดยอัตโนมัติ",
"automationCollectionScopeLimit": "ขอบเขตการติดตามสามารถมีสมุดบันทึกหรือเอกสารรวมกันได้สูงสุด 32 รายการ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 82edd9bce0..3da25881f1 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Veritabanı alanı düzeni",
+ "databaseAttrLayoutTip": "Belgenin üstündeki veritabanı panelinde ve bağımsız öğe panelinde alan düzenini ayarlar; alan yetersiz olduğunda otomatik olarak tek sütun kullanılır",
+ "databaseAttrLayoutSingle": "Tek sütun",
+ "databaseAttrLayoutRow": "İki sütun (satır sırasıyla)",
+ "databaseAttrLayoutColumn": "İki sütun (sütun sırasıyla)",
"mathDelimiterCompatibility": "Yapıştırma ve içe aktarmada LaTeX formül sınırlayıcılarını tanı",
"mathDelimiterCompatibilityTip": "Etkinleştirildiğinde, yapıştırılan ve içe aktarılan içerikteki \\(...\\) ve \\[...\\] sırasıyla satır içi ve blok formüller olarak otomatik tanınır",
"automationCollectionScopeLimit": "İzleme kapsamı toplamda en fazla 32 not defteri veya belge içerebilir",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index ec4f2a4fac..d1c5bb82fa 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "Розташування полів бази даних",
+ "databaseAttrLayoutTip": "Задає розташування полів панелі бази даних угорі документа й окремої панелі запису; за браку місця автоматично використовується один стовпець",
+ "databaseAttrLayoutSingle": "Один стовпець",
+ "databaseAttrLayoutRow": "Два стовпці (за рядками)",
+ "databaseAttrLayoutColumn": "Два стовпці (за стовпцями)",
"mathDelimiterCompatibility": "Розпізнавати роздільники формул LaTeX під час вставлення та імпорту",
"mathDelimiterCompatibilityTip": "Якщо ввімкнено, \\(...\\) і \\[...\\] у вставленому та імпортованому вмісті автоматично розпізнаються як рядкові та блокові формули відповідно",
"automationCollectionScopeLimit": "Область відстеження може містити не більше 32 записників або документів",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 06cc5d5c68..555e0d285b 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "数据库字段布局",
+ "databaseAttrLayoutTip": "设置文档顶部数据库面板和独立条目面板中的字段布局,空间不足时自动使用单栏",
+ "databaseAttrLayoutSingle": "单栏",
+ "databaseAttrLayoutRow": "双栏(按行)",
+ "databaseAttrLayoutColumn": "双栏(按列)",
"mathDelimiterCompatibility": "粘贴和导入时兼容 LaTeX 公式分隔符",
"mathDelimiterCompatibilityTip": "启用后自动将粘贴和导入内容中的 \\(...\\)、\\[...\\] 分别识别为行级公式和块级公式",
"automationCollectionScopeLimit": "监听范围最多可包含 32 个笔记本或文档",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index b1c89c09c2..108c09b022 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,9 @@
{
+ "databaseAttrLayout": "資料庫欄位佈局",
+ "databaseAttrLayoutTip": "設定文件頂部資料庫面板和獨立項目面板中的欄位佈局,空間不足時自動使用單欄",
+ "databaseAttrLayoutSingle": "單欄",
+ "databaseAttrLayoutRow": "雙欄(按行)",
+ "databaseAttrLayoutColumn": "雙欄(按列)",
"mathDelimiterCompatibility": "貼上和匯入時相容 LaTeX 公式分隔符",
"mathDelimiterCompatibilityTip": "啟用後自動將貼上和匯入內容中的 \\(...\\)、\\[...\\] 分別識別為行內公式和區塊公式",
"automationCollectionScopeLimit": "監聽範圍最多可包含 32 個筆記本或文件",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
index 4621ae4819..c1cd0ef0a3 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
@@ -7,7 +7,7 @@
"id": "20240208172514-9dsv6na",
"title": "Database",
"type": "doc",
- "updated": "20261027120633"
+ "updated": "20261028110235"
},
"Children": [
{
@@ -3108,6 +3108,76 @@
}
]
},
+ {
+ "ID": "20261028100554-5uvtrxl",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261028100554-5uvtrxl",
+ "updated": "20261028110235"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Database panel layout and sorting"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-vymrc6v",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-vymrc6v",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "In "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Editor"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Database"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " choose One column, Two columns (by row), or Two columns (by column) under Database field layout. The default is Two columns (by row). This applies to the database panel at the top of a document and the standalone item panel. Panels automatically use one column when space is limited. Switching layouts preserves the field order."
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-o8rd07g",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-o8rd07g",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "The row layout reads from left to right, then top to bottom. Drag a field by its left handle to another field’s grid position to preview the resulting order, then drop to save it. The column layout reads down the left column, then down the right column; visible fields are split by count, with one extra field on the left when the count is odd. Editing field content does not move fields between columns. Column and single-column layouts use horizontal indicators for insertion above or below a field. Canceling a drag restores the original order; sorting supports undo and redo."
+ }
+ ]
+ },
{
"ID": "20260930175958-jgqkczm",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
index 2a63b8e0a3..cbdec82c51 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
@@ -7,7 +7,7 @@
"id": "20240208113259-nykkvaq",
"title": "数据库",
"type": "doc",
- "updated": "20261027120633"
+ "updated": "20261028110235"
},
"Children": [
{
@@ -3108,6 +3108,76 @@
}
]
},
+ {
+ "ID": "20261028100554-8qephai",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261028100554-8qephai",
+ "updated": "20261028110235"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "数据库面板布局与排序"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-4angel6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-4angel6",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "设置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "编辑器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "数据库"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中通过「数据库字段布局」选择「单栏」「双栏(按行)」或「双栏(按列)」,默认「双栏(按行)」。该设置同时作用于文档顶部数据库面板和独立条目面板,空间不足时自动使用单栏,切换布局不会改变字段顺序。"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-n4mrrtp",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-n4mrrtp",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "按行排列时,字段从左到右、从上到下显示。使用鼠标拖动字段左侧的手柄到目标字段所在的格位,可以实时预览新的排列,松手后保存排序。按列排列时,先从上到下显示左栏,再显示右栏;可见字段按数量均分,奇数时左栏多一个,编辑字段内容不会导致字段自动换栏。按列和单栏布局使用横向指示线提示上下插入位置。取消拖拽恢复原顺序,字段排序支持撤销和重做。"
+ }
+ ]
+ },
{
"ID": "20260930175958-maj1ve9",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
index 47099eb3dd..7c1098493f 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
@@ -7,7 +7,7 @@
"id": "20240208171522-y7dxcno",
"title": "資料庫",
"type": "doc",
- "updated": "20261027120633"
+ "updated": "20261028110235"
},
"Children": [
{
@@ -3108,6 +3108,76 @@
}
]
},
+ {
+ "ID": "20261028100554-7lm3pcm",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261028100554-7lm3pcm",
+ "updated": "20261028110235"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "資料庫面板佈局與排序"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-7r40o96",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-7r40o96",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "編輯器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "資料庫"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中透過「資料庫欄位佈局」選擇「單欄」「雙欄(按行)」或「雙欄(按列)」,預設為「雙欄(按行)」。此設定同時作用於文件頂部資料庫面板和獨立項目面板,空間不足時自動使用單欄,切換佈局不會改變欄位順序。"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-tchwmuu",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-tchwmuu",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "按行排列時,欄位由左到右、由上到下顯示。使用滑鼠拖曳欄位左側的把手至目標欄位所在的格位,可以即時預覽新的排列,放開後儲存排序。按列排列時,先由上到下顯示左欄,再顯示右欄;可見欄位依數量均分,奇數時左欄多一個,編輯欄位內容不會導致欄位自動換欄。按列和單欄佈局使用水平指示線提示上下插入位置。取消拖曳會恢復原順序,欄位排序支援復原與重做。"
+ }
+ ]
+ },
{
"ID": "20260930175958-lm4h64b",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
index 6921f10e86..52463f538e 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-3eaevtp",
"title": "データベース",
"type": "doc",
- "updated": "20261027120633"
+ "updated": "20261028110235"
},
"Children": [
{
@@ -3137,6 +3137,72 @@
}
]
},
+ {
+ "ID": "20261028100554-r4kl6qy",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261028100554-r4kl6qy",
+ "updated": "20261028110235"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "データベースパネルのレイアウトと並べ替え"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-n216b4x",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-n216b4x",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "エディター"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "データベース"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " の「データベースフィールドのレイアウト」で「1列」「2列(行順)」「2列(列順)」を選べます。デフォルトは「2列(行順)」です。ドキュメント上部のデータベースパネルと独立した項目パネルに適用され、スペースが不足する場合は自動的に1列になります。レイアウトを切り替えてもフィールドの順序は変わりません。"
+ }
+ ]
+ },
+ {
+ "ID": "20261028100554-oitbzhe",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261028100554-oitbzhe",
+ "updated": "20261028110235"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "行順では左から右、上から下へフィールドを表示します。マウスで左側のハンドルを移動先フィールドの位置へドラッグすると配置をプレビューし、ドロップすると順序を保存します。列順では左列を上から下へ表示してから右列を表示します。表示中のフィールドを個数で二等分し、奇数の場合は左列が一つ多くなります。内容を編集してもフィールドの列は変わりません。列順と1列では横の挿入線で上下の挿入位置を示します。ドラッグをキャンセルすると元の順序に戻り、並べ替えは元に戻す操作とやり直しに対応しています。"
+ }
+ ]
+ },
{
"ID": "20260930175958-ucbrk0m",
"Type": "NodeHeading",
diff --git a/app/src/assets/scss/business/_custom.scss b/app/src/assets/scss/business/_custom.scss
index c5ce72ad6b..209bca39c9 100644
--- a/app/src/assets/scss/business/_custom.scss
+++ b/app/src/assets/scss/business/_custom.scss
@@ -277,6 +277,11 @@
.av__row.dragover__top::after {
top: -1.5px;
}
+
+ .av__row[data-av-drag-preview="true"] {
+ outline: 2px solid var(--b3-theme-primary);
+ outline-offset: -2px;
+ }
}
.protyle-db-attr {
@@ -428,6 +433,28 @@
}
}
+@container (min-width: 900px) {
+ .protyle-db-attr__body > [data-av-id],
+ .protyle-db-row__body > [data-av-id] {
+ gap: 0 24px;
+ grid-template-columns: repeat(var(--b3-database-attr-columns, 2), minmax(0, 1fr));
+
+ > .av__row {
+ order: calc(var(--av-field-order, 0) * var(--b3-database-attr-column-flow, 0));
+ }
+
+ > .custom-attr__avheader {
+ order: -1;
+ }
+
+ > .fn__hr,
+ > .b3-button[data-type="addColumn"],
+ > .fn__hr--b {
+ order: 2147483647;
+ }
+ }
+}
+
.av__cell-action {
align-items: center;
background-color: var(--b3-theme-background);
diff --git a/app/src/config/tabs/editorTab.test.ts b/app/src/config/tabs/editorTab.test.ts
new file mode 100644
index 0000000000..c808b2d754
--- /dev/null
+++ b/app/src/config/tabs/editorTab.test.ts
@@ -0,0 +1,33 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {ScriptTarget, transpileModule} from "typescript";
+
+test("database field layout setting follows tabs and stays available when document panels are hidden", () => {
+ const source = readFileSync("src/config/tabs/editorTab.ts", "utf8");
+ const code = transpileModule(source.slice(source.indexOf("const bindDatabaseAttrSettingsVisibility ="),
+ source.indexOf("const registerEditorListsGroup =")) + source.slice(source.indexOf("const registerEditorDatabaseGroup ="),
+ source.indexOf("const registerEditorCodeGroup =")), {compilerOptions: {target: ScriptTarget.ES2022}}).outputText;
+ const register = new Function("window", "CSS", code + "\nreturn registerEditorDatabaseGroup;")(
+ {siyuan: {languages: new Proxy({}, {get: (_target, key) => key})}}, {escape: (value: string) => value});
+ const controls: {id: string, options?: {value: number}[], afterMount?: (root: unknown) => void}[] = [];
+ const group = new Proxy({}, {get: () => (id: string, options: object) => controls.push({id, ...options})});
+ register({group: (id: string) => {assert.equal(id, "database"); return group;}});
+ const index = controls.findIndex(item => item.id === "editor.databaseAttrLayout");
+ assert.equal(controls[index - 1].id, "editor.databaseAttrUseTabs");
+ assert.deepEqual(Array.from(controls[index].options, item => item.value), [0, 1, 2]);
+ const hidden = new Set<string>();
+ const listeners: (() => void)[] = [];
+ const show = {checked: false, addEventListener: (_event: string, listener: () => void) => listeners.push(listener)};
+ const root = {querySelector: (selector: string) => selector === "#editor.databaseAttrShow" ? show : {
+ closest: () => ({classList: {toggle: (_name: string, value: boolean) => {
+ if (value) hidden.add(selector); else hidden.delete(selector);
+ }}}),
+ }};
+ controls.find(item => item.id === "editor.databaseAttrShow").afterMount(root);
+ assert.equal(hidden.has("#editor.databaseAttrUseTabs"), true);
+ assert.equal(hidden.has("#editor.databaseAttrLayout"), false);
+ show.checked = true;
+ listeners[0]();
+ assert.equal(hidden.size, 0);
+});
diff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.ts
index 8e47dd4bb4..8e0099d3f0 100644
--- a/app/src/config/tabs/editorTab.ts
+++ b/app/src/config/tabs/editorTab.ts
@@ -296,6 +296,15 @@ const registerEditorDatabaseGroup = (tab: SettingTabBuilder) => {
title: window.siyuan.languages.databaseAttrUseTabs,
desc: window.siyuan.languages.databaseAttrUseTabsTip,
});
+ group.select("editor.databaseAttrLayout", {
+ title: window.siyuan.languages.databaseAttrLayout,
+ desc: window.siyuan.languages.databaseAttrLayoutTip,
+ options: [
+ {value: 0, label: window.siyuan.languages.databaseAttrLayoutSingle},
+ {value: 1, label: window.siyuan.languages.databaseAttrLayoutRow},
+ {value: 2, label: window.siyuan.languages.databaseAttrLayoutColumn},
+ ],
+ });
};
const registerEditorCodeGroup = (tab: SettingTabBuilder) => {
diff --git a/app/src/protyle/render/av/attributePanelDrag.test.ts b/app/src/protyle/render/av/attributePanelDrag.test.ts
new file mode 100644
index 0000000000..cdc64b8c62
--- /dev/null
+++ b/app/src/protyle/render/av/attributePanelDrag.test.ts
@@ -0,0 +1,303 @@
+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 {compileString} from "sass";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string, css: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ Object.assign(window, {siyuan: {config: {editor: {}}, languages: {database: "Database"}, dialogs: []}});
+ document.head.innerHTML = `<style>${css}
+ :root {--b3-theme-primary:#1565c0}
+ .av__row {display:flex; min-height:40px; position:relative} .fn__hr {height:8px}
+ .fn__none {display:none} .block__icon {width:20px} .custom-attr__avheader {height:30px}
+ </style>`;
+ const operations: IOperation[][][] = [];
+ const tables = ["first", "second"].map(avID => ({avID, avName: avID, blockIDs: ["carrier"],
+ keyValues: ["A", "B", "C", "D", "E", "F"].map(id => ({key: {id, name: id, type: "text"}, values: [{text: {content: id}}]}))}));
+ const render = new Function("fetchPost", "createEmptyAVValue", "getColIconByType", "cellValueIsEmpty", "genAVAttributeRowHTML",
+ "preserveAVBindingRange", "renderAVRichTextElements", "hasClosestBlock", "hasClosestByClassName", "transaction", "hasDataTransferFiles",
+ source + "\nreturn {renderAVAttribute, getAVAttributeDropTarget, getAVAttributeSort};")(
+ (url: string, _body: unknown, callback: (response: {data: unknown}) => void) =>
+ callback({data: url.endsWith("getAttributeViewKeys") ? tables : {total: 0}}),
+ () => ({}), () => "iconText", () => false,
+ ({keyID}: {keyID: string}) => `<div class="av__row block__icons" data-col-id="${keyID}" data-id="item">
+ <div class="block__icon" draggable="true">drag</div><div class="block__logo">${keyID}</div></div>`,
+ () => () => {}, () => {}, (element: HTMLElement) => element?.closest('[data-type="NodeAttributeView"]'),
+ (element: HTMLElement, className: string) => element?.closest("." + className),
+ (_protyle: unknown, forward: IOperation[], undo: IOperation[]) => operations.push([forward, undo]),
+ (types: string[]) => types.includes("Files"));
+ const fixture = (className = "protyle-db-attr__body", width = 1100) => {
+ document.body.innerHTML = "";
+ operations.length = 0;
+ const panel = document.createElement("div");
+ panel.className = "custom-attr " + className;
+ panel.style.width = width + "px";
+ document.body.append(panel);
+ const protyle = {disabled: false, options: {history: {}}};
+ render.renderAVAttribute(panel, "item", protyle);
+ const block = panel.querySelector<HTMLElement>('[data-av-id="first"]');
+ const row = (id: string) => block.querySelector<HTMLElement>(`.av__row[data-col-id="${id}"]`);
+ const order = () => Array.from(block.querySelectorAll<HTMLElement>(".av__row")).map(item => item.dataset.colId);
+ const transfer = new DataTransfer();
+ const event = (type: string, target: HTMLElement, x = 0, y = 0) => {
+ const e = new DragEvent(type, {bubbles: true, cancelable: true, clientX: x, clientY: y, dataTransfer: transfer});
+ target.dispatchEvent(e);
+ return e;
+ };
+ const begin = (id: string) => event("dragstart", row(id).firstElementChild as HTMLElement);
+ const at = (id: string, x: number, y = .5) => {
+ const rect = row(id).getBoundingClientRect();
+ return {x: rect.left + rect.width * x, y: rect.top + rect.height * y};
+ };
+ let lastPoint: {x: number, y: number};
+ const over = (id: string, x: number, y = .5) => {
+ lastPoint = at(id, x, y);
+ return event("dragover", row(id), lastPoint.x, lastPoint.y);
+ };
+ const drop = (id: string, x: number, y = .5) => {
+ const p = lastPoint || at(id, x, y);
+ return event("drop", document.elementFromPoint(p.x, p.y) as HTMLElement, p.x, p.y);
+ };
+ return {panel, block, protyle, row, order, event, begin, over, drop, at};
+ };
+ for (const className of ["protyle-db-attr__body", "protyle-db-row__body"]) {
+ for (const [source, destination, expected] of [
+ ["B", "D", ["A", "C", "D", "B", "E", "F"]],
+ ["F", "D", ["A", "B", "C", "F", "D", "E"]],
+ ["A", "C", ["B", "C", "A", "D", "E", "F"]],
+ ["E", "C", ["A", "B", "E", "C", "D", "F"]],
+ ] as const) {
+ for (const fraction of [.1, .5, .9]) {
+ for (const vertical of [.1, .5, .9]) {
+ const f = fixture(className);
+ const point = f.at(destination, fraction, vertical);
+ const slot = f.row(destination).getBoundingClientRect();
+ f.begin(source);
+ f.event("dragover", f.row(destination), point.x, point.y);
+ check.deepEqual(f.order(), expected, `${source} to ${destination} occupies the hovered slot`);
+ check.equal(f.row(source).getBoundingClientRect().left, slot.left, "vertical dragging keeps the hovered column");
+ check.equal(operations.length, 0);
+ f.event("drop", document.elementFromPoint(point.x, point.y) as HTMLElement, point.x, point.y);
+ check.deepEqual(f.order(), expected, "drop preserves the previewed slot");
+ check.equal(operations.length, 1);
+ }
+ }
+ }
+ }
+ const continuous = fixture();
+ continuous.begin("B");
+ for (const target of ["D", "F", "E"]) {
+ const point = continuous.at(target, .1);
+ const slot = continuous.row(target).getBoundingClientRect();
+ continuous.event("dragover", continuous.row(target), point.x, point.y);
+ check.equal(continuous.row("B").getBoundingClientRect().left, slot.left, "continuous vertical dragging keeps the hovered column");
+ check.equal(operations.length, 0, "intermediate previews do not create transactions");
+ }
+ const release = continuous.at("B", .1);
+ continuous.event("drop", continuous.row("B"), release.x, release.y);
+ check.equal(operations.length, 1);
+ check.equal(operations[0][1][0].previousID, "A", "undo uses the position at drag start");
+ for (const className of ["protyle-db-attr__body", "protyle-db-row__body"]) {
+ for (const columns of [2, 1]) {
+ document.documentElement.style.setProperty("--b3-database-attr-columns", String(columns));
+ const f = fixture(className);
+ const a = f.row("A").getBoundingClientRect(), b = f.row("B").getBoundingClientRect();
+ check.equal(a.top === b.top, columns === 2, className);
+ const expected = columns === 2 ? ["E", "A", "B", "C", "D", "F"] : ["A", "E", "B", "C", "D", "F"];
+ f.begin("E");
+ f.over("A", .9, .9);
+ if (columns === 2) {
+ check.deepEqual(f.order(), expected, "dragging previews the complete order");
+ check.equal(getComputedStyle(f.row("E")).outlineWidth, "2px");
+ check.equal(operations.length, 0, "preview does not save field order");
+ } else {
+ check.equal(f.row("A").classList.contains("dragover__bottom"), true);
+ check.deepEqual(f.order(), ["A", "B", "C", "D", "E", "F"]);
+ }
+ f.drop("A", .9, .9);
+ check.deepEqual(f.order(), expected);
+ check.deepEqual(operations[0], [[{action: "sortAttrViewKey", avID: "first", previousID: columns === 2 ? "" : "A", id: "E"}],
+ [{action: "sortAttrViewKey", avID: "first", previousID: "D", id: "E"}]]);
+ check.equal(f.panel.querySelector('[class*="dragover__"]'), null);
+ check.equal(window.siyuan.dragElement, undefined);
+ // 用实际撤销操作的字段 ID 和前驱重建顺序,再执行重做。
+ const undo = operations[0][1][0];
+ f.row(undo.previousID).after(f.row(undo.id));
+ check.deepEqual(f.order(), ["A", "B", "C", "D", "E", "F"]);
+ f.begin("E"); f.over("A", .9, .9); f.drop("A", .9, .9);
+ check.deepEqual(f.order(), expected);
+ }
+ document.documentElement.style.setProperty("--b3-database-attr-columns", "2");
+ const narrow = fixture(className, 800);
+ check.ok(narrow.row("B").getBoundingClientRect().top > narrow.row("A").getBoundingClientRect().top);
+ narrow.begin("F"); narrow.over("A", .9, .1); narrow.drop("A", .9, .1);
+ check.deepEqual(narrow.order(), ["F", "A", "B", "C", "D", "E"]);
+ check.equal(operations[0][0][0].previousID, "");
+ }
+ const f = fixture();
+ f.row("A").style.minHeight = "120px";
+ f.row("C").dataset.panelVisibility = "hide";
+ check.equal(f.row("C").getClientRects().length, 0);
+ f.begin("F"); f.over("D", .1);
+ check.deepEqual(f.order(), ["A", "B", "C", "F", "D", "E"], "preview preserves hidden fields in the full order");
+ f.drop("D", .1);
+ check.deepEqual(f.order(), ["A", "B", "C", "F", "D", "E"]);
+ const gap = fixture();
+ const left = gap.row("A").getBoundingClientRect(), right = gap.row("B").getBoundingClientRect();
+ gap.begin("F");
+ gap.event("dragover", gap.block, left.right + 2, left.top + 10);
+ check.deepEqual(gap.order(), ["A", "F", "B", "C", "D", "E"]);
+ gap.event("drop", gap.block, right.left - 2, right.top + 10);
+ check.deepEqual(gap.order(), ["A", "F", "B", "C", "D", "E"]);
+ const odd = fixture();
+ odd.row("F").remove();
+ odd.begin("A");
+ const last = odd.row("E").getBoundingClientRect(), bounds = odd.block.getBoundingClientRect();
+ odd.event("dragover", odd.block, bounds.right - 10, last.top + 10);
+ odd.event("drop", odd.block, bounds.right - 10, last.top + 10);
+ check.deepEqual(odd.order(), ["B", "C", "D", "E", "A"]);
+ for (const invalid of ["same", "self", "other", "footer", "readonly", "end", "leave", "removed"]) {
+ const h = fixture();
+ h.begin("E"); h.over(invalid === "self" ? "E" : "A", .9);
+ if (invalid === "same") {
+ h.event("dragend", h.row("E"));
+ h.begin("B"); h.over("A", .9); h.over("A", .9); h.drop("B", .9);
+ }
+ if (invalid === "self") { h.over("E", .9); h.drop("E", .9); }
+ if (invalid === "other") {
+ const target = h.panel.querySelector<HTMLElement>('[data-av-id="second"] .av__row');
+ const rect = target.getBoundingClientRect();
+ h.event("dragover", target, rect.left + 10, rect.top + 10);
+ h.event("drop", target, rect.left + 10, rect.top + 10);
+ }
+ if (invalid === "footer") h.event("drop", h.block, bounds.left + 20, h.block.getBoundingClientRect().bottom - 1);
+ if (invalid === "readonly") { h.protyle.disabled = true; h.drop("A", .9); }
+ if (invalid === "end") h.event("dragend", h.row("E"));
+ if (invalid === "leave") { h.event("dragleave", h.panel); }
+ if (invalid === "removed") {
+ const source = h.row("E").firstElementChild as HTMLElement;
+ h.block.remove(); h.event("dragend", source);
+ }
+ check.equal(operations.length, 0, invalid);
+ check.equal(h.panel.querySelector('[class*="dragover__"]'), null, invalid);
+ h.event("dragend", h.panel);
+ check.equal(window.siyuan.dragElement, undefined, invalid);
+ if (invalid !== "removed") check.deepEqual(h.order(), ["A", "B", "C", "D", "E", "F"], invalid + " restores the original order");
+ }
+ const handle = fixture();
+ handle.begin("F");
+ const handleRect = handle.row("A").firstElementChild.getBoundingClientRect();
+ const x = handleRect.left + handleRect.width / 2, y = handleRect.top + handleRect.height / 2;
+ handle.event("dragover", handle.row("A").firstElementChild as HTMLElement, x, y);
+ check.equal(handle.row("F").dataset.avDragPreview, "true", "the handle gutter remains a valid target");
+ handle.event("dragend", handle.panel);
+ check.deepEqual(handle.order(), ["A", "B", "C", "D", "E", "F"]);
+ const tall = fixture();
+ tall.row("A").style.minHeight = "140px";
+ const point = tall.at("D", .9);
+ tall.begin("A");
+ tall.event("dragover", tall.row("D"), point.x, point.y);
+ const preview = tall.order();
+ for (let i = 0; i < 5; i++) {
+ const target = document.elementFromPoint(point.x, point.y) as HTMLElement;
+ tall.event("dragover", target, point.x, point.y);
+ check.deepEqual(tall.order(), preview, "stationary dragging must not oscillate when row heights change");
+ }
+ tall.event("drop", document.elementFromPoint(point.x, point.y) as HTMLElement, point.x, point.y);
+ check.deepEqual(tall.order(), preview, "dropping commits exactly the visible preview");
+ check.equal(operations.length, 1);
+ const external = fixture();
+ const link = document.createElement("a");
+ link.draggable = true;
+ external.row("A").lastElementChild.append(link);
+ check.equal(external.event("dragstart", link).defaultPrevented, false, "non-field dragging remains available to other handlers");
+ check.equal(window.siyuan.dragElement, undefined);
+ for (const className of ["protyle-db-attr__body", "protyle-db-row__body"]) {
+ document.documentElement.style.setProperty("--b3-database-attr-column-flow", "1");
+ const col = fixture(className);
+ const rect = (id: string) => col.row(id).getBoundingClientRect();
+ check.equal(rect("A").left, rect("B").left);
+ check.equal(rect("A").left, rect("C").left);
+ check.ok(rect("D").left > rect("A").left);
+ check.equal(rect("A").top, rect("D").top);
+ check.ok(rect("B").top > rect("A").top);
+ check.ok(rect("C").top > rect("B").top);
+ check.deepEqual(col.order(), ["A", "B", "C", "D", "E", "F"], "column layout preserves the underlying field sequence");
+ check.ok(col.block.querySelector(".custom-attr__avheader").getBoundingClientRect().bottom <= rect("A").top);
+ check.ok(col.block.querySelector('[data-type="addColumn"]').getBoundingClientRect().top >= rect("C").bottom);
+ col.row("C").dataset.panelVisibility = "hide";
+ await Promise.resolve();
+ check.equal(rect("D").left, rect("A").left, "visible fields are split by count with the extra field on the left");
+ check.ok(rect("E").left > rect("A").left);
+ col.block.dataset.panelShowAll = "true";
+ await Promise.resolve();
+ check.ok(rect("D").left > rect("A").left, "revealing fields recalculates both columns");
+ col.block.dataset.panelShowAll = "false";
+ col.row("C").dataset.panelVisibility = "";
+ col.row("B").dataset.panelVisibility = "hide-empty";
+ col.row("B").dataset.empty = "true";
+ await Promise.resolve();
+ check.equal(rect("D").left, rect("A").left);
+ col.row("B").dataset.empty = "false";
+ await Promise.resolve();
+ check.ok(rect("D").left > rect("A").left, "value changes recalculate hidden-empty fields");
+ const rightColumn = rect("D").left;
+ col.row("A").style.minHeight = "160px";
+ check.equal(rect("D").left, rightColumn, "editing content height does not move fields between columns");
+ col.panel.style.width = "800px";
+ check.equal(rect("A").left, rect("D").left);
+ check.ok(rect("D").top > rect("C").top, "narrow column layout follows the complete single-column sequence");
+ col.panel.style.width = "1100px";
+ col.begin("B"); col.over("E", .1, .9);
+ check.equal(col.row("E").classList.contains("dragover__bottom"), true, "column layout uses vertical insertion");
+ check.equal(operations.length, 0);
+ col.drop("E", .1, .9);
+ check.deepEqual(col.order(), ["A", "C", "D", "E", "B", "F"]);
+ check.deepEqual(operations[0], [[{action: "sortAttrViewKey", avID: "first", previousID: "E", id: "B"}],
+ [{action: "sortAttrViewKey", avID: "first", previousID: "A", id: "B"}]]);
+ check.ok(rect("B").left > rect("A").left);
+ document.documentElement.style.setProperty("--b3-database-attr-column-flow", "0");
+ check.equal(rect("A").top, rect("C").top, "switching to row layout reuses the same data without reordering it");
+ check.deepEqual(col.order(), ["A", "C", "D", "E", "B", "F"]);
+ }
+ return "Database panel layout and drag cases passed";
+};
+
+test("database attribute panels render responsive columns with stable drag previews, cancellation and undo", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const source = ["attributePanelLayout.ts", "attributePanelDrag.ts", "blockAttr.ts"].map(file => transpileModule(readFileSync(path.join(__dirname, file), "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),
+ {compilerOptions: {target: ScriptTarget.ES2022}}).outputText).join("\n");
+ const css = compileString(readFileSync("src/assets/scss/business/_custom.scss", "utf8")).css;
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-panel-drag-test-"));
+ const script = path.join(temporary, "run.cjs");
+ const code = "const __name = value => value; (" + browserCases.toString() + ")(" + JSON.stringify(source) + "," + JSON.stringify(css) + ")";
+ 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, width: 1500, height: 1200, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ win.webContents.on("console-message", event => console.error(event.message));
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("try {" + code + "} catch (error) {console.error(error.stack); throw error;} ")}));
+ 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, /Database panel layout and drag cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) && path.basename(temporary).startsWith("siyuan-panel-drag-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/protyle/render/av/attributePanelDrag.ts b/app/src/protyle/render/av/attributePanelDrag.ts
new file mode 100644
index 0000000000..702c89326a
--- /dev/null
+++ b/app/src/protyle/render/av/attributePanelDrag.ts
@@ -0,0 +1,89 @@
+import {getAVAttributeRows} from "./attributePanelLayout";
+
+export interface IAVAttributeDropTarget {
+ element: HTMLElement;
+ before: boolean;
+ horizontal: boolean;
+}
+
+export const clearAVAttributeDropTarget = (element: HTMLElement) => {
+ element.querySelectorAll(".dragover__top, .dragover__bottom, .dragover__left, .dragover__right").forEach(item => {
+ item.classList.remove("dragover__top", "dragover__bottom", "dragover__left", "dragover__right");
+ });
+};
+
+export const getAVAttributeDropTarget = (block: HTMLElement, dragged: HTMLElement, x: number, y: number,
+ hitElement?: HTMLElement): IAVAttributeDropTarget | undefined => {
+ if (!block.isConnected || dragged.parentElement !== block) {
+ return;
+ }
+ const rows = getAVAttributeRows(block).filter(row => row.getClientRects().length > 0);
+ const candidates = rows.map(element => {
+ const rect = element.getBoundingClientRect();
+ const handle = element.querySelector<HTMLElement>('[draggable="true"]');
+ const left = handle?.getClientRects().length ? Math.min(rect.left, handle.getBoundingClientRect().left) : rect.left;
+ return {element, rect, left};
+ })
+ .filter(({rect}) => y >= rect.top && y <= rect.bottom);
+ if (candidates.length === 0) {
+ return;
+ }
+ const bounds = block.getBoundingClientRect();
+ if (x < Math.min(bounds.left, ...candidates.map(item => item.left)) || x > bounds.right) {
+ return;
+ }
+ const style = getComputedStyle(block);
+ const horizontal = style.display === "grid" && style.gridTemplateColumns.split(" ").length === 2 &&
+ style.getPropertyValue("--b3-database-attr-column-flow").trim() !== "1";
+ let closest: typeof candidates[number];
+ let distance = Infinity;
+ for (const candidate of candidates) {
+ const {rect} = candidate;
+ if (candidate.element === hitElement && x >= candidate.left && x <= rect.right) {
+ closest = candidate;
+ break;
+ }
+ const dx = Math.max(candidate.left - x, 0, x - rect.right);
+ const dy = Math.max(rect.top - y, 0, y - rect.bottom);
+ const current = dx * dx + dy * dy;
+ if (current < distance) {
+ closest = candidate;
+ distance = current;
+ }
+ }
+ if (!closest) {
+ return;
+ }
+ // 双栏中源字段移除后会让后续字段补位,向后移动时插在目标之后,才能占据目标原来的格位。
+ const before = horizontal ? rows.indexOf(dragged) > rows.indexOf(closest.element) :
+ y < closest.rect.top + closest.rect.height / 2;
+ return {element: closest.element, before, horizontal};
+};
+
+export const getAVAttributePreviousID = (element: HTMLElement) => {
+ const rows = getAVAttributeRows(element.parentElement);
+ return rows[rows.indexOf(element) - 1]?.dataset.colId || "";
+};
+
+export const getAVAttributeSort = (dragged: HTMLElement, target: IAVAttributeDropTarget) => {
+ const block = dragged.parentElement;
+ if (!block || target.element.parentElement !== block || target.element === dragged) {
+ return;
+ }
+ const rows = getAVAttributeRows(block);
+ const oldIndex = rows.indexOf(dragged);
+ if (oldIndex < 0) {
+ return;
+ }
+ const undoPreviousID = rows[oldIndex - 1]?.dataset.colId || "";
+ const remaining = rows.filter(row => row !== dragged);
+ const targetIndex = remaining.indexOf(target.element);
+ if (targetIndex < 0) {
+ return;
+ }
+ const previousID = remaining[targetIndex - (target.before ? 1 : 0)]?.dataset.colId || "";
+ if (previousID === undoPreviousID) {
+ return;
+ }
+ return {id: dragged.dataset.colId, previousID, undoPreviousID};
+};
diff --git a/app/src/protyle/render/av/attributePanelLayout.ts b/app/src/protyle/render/av/attributePanelLayout.ts
new file mode 100644
index 0000000000..9c180c19a9
--- /dev/null
+++ b/app/src/protyle/render/av/attributePanelLayout.ts
@@ -0,0 +1,41 @@
+const observedAttributeLayouts = new WeakSet<HTMLElement>();
+
+export const getAVAttributeRows = (block: HTMLElement) => Array.from(block.children).filter((element): element is HTMLElement =>
+ element instanceof HTMLElement && element.classList.contains("av__row") && !!element.dataset.colId);
+
+export const updateAVAttributeLayout = (element: HTMLElement) => {
+ const body = element.matches('[data-type="NodeAttributeView"]') ? element.parentElement : element;
+ if (!body?.matches(".protyle-db-attr__body, .protyle-db-row__body")) return;
+ const blocks = element.matches('[data-type="NodeAttributeView"]') ? [element] :
+ Array.from(element.querySelectorAll<HTMLElement>(":scope > [data-type=\"NodeAttributeView\"]"));
+ blocks.forEach(block => {
+ const rows = getAVAttributeRows(block);
+ const visible = rows.filter(row => getComputedStyle(row).display !== "none");
+ const split = Math.ceil(visible.length / 2);
+ const indices = new Map(visible.map((row, index) => [row, index]));
+ rows.forEach(row => {
+ const index = indices.get(row);
+ const order = index === undefined ? 0 : index < split ? index * 2 : (index - split) * 2 + 1;
+ if (row.style.getPropertyValue("--av-field-order") !== String(order)) {
+ row.style.setProperty("--av-field-order", String(order));
+ }
+ });
+ });
+};
+
+export const observeAVAttributeLayout = (element: HTMLElement) => {
+ if (!element.matches(".protyle-db-attr__body, .protyle-db-row__body")) return;
+ updateAVAttributeLayout(element);
+ if (observedAttributeLayouts.has(element)) return;
+ observedAttributeLayouts.add(element);
+ const observer = new MutationObserver(records => {
+ if (records.some(record => {
+ const target = record.target as HTMLElement;
+ return target === element || target.parentElement === element || target.classList?.contains("av__row");
+ })) updateAVAttributeLayout(element);
+ });
+ observer.observe(element, {
+ childList: true, subtree: true, attributes: true,
+ attributeFilter: ["class", "data-empty", "data-panel-visibility", "data-panel-show-all"],
+ });
+};
diff --git a/app/src/protyle/render/av/attributePanelVisibility.test.ts b/app/src/protyle/render/av/attributePanelVisibility.test.ts
index 784c42d3f6..36aeaa824d 100644
--- a/app/src/protyle/render/av/attributePanelVisibility.test.ts
+++ b/app/src/protyle/render/av/attributePanelVisibility.test.ts
@@ -406,7 +406,9 @@ test("attribute panel field rules preserve global defaults and reveal hidden fie
const columnSource = capabilitySource + transpileModule(readFileSync(path.resolve(__dirname, "col.ts"), "utf8")
.replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),
{compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
- const blockSource = capabilitySource + transpileModule(readFileSync(path.resolve(__dirname, "blockAttr.ts"), "utf8")
+ const layoutSource = transpileModule(readFileSync(path.resolve(__dirname, "attributePanelLayout.ts"), "utf8")
+ .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+ const blockSource = capabilitySource + layoutSource + transpileModule(readFileSync(path.resolve(__dirname, "blockAttr.ts"), "utf8")
.replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),
{compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
const menuSource = transpileModule(readFileSync("src/menus/Menu.ts", "utf8")
diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.ts
index 5f241fca49..49d84a3949 100644
--- a/app/src/protyle/render/av/blockAttr.ts
+++ b/app/src/protyle/render/av/blockAttr.ts
@@ -1,3 +1,5 @@
+import {clearAVAttributeDropTarget, getAVAttributeDropTarget, getAVAttributePreviousID, getAVAttributeSort, IAVAttributeDropTarget} from "./attributePanelDrag";
+import {observeAVAttributeLayout, updateAVAttributeLayout} from "./attributePanelLayout";
import {isAVTextType} from "./capabilities";
import {fetchPost} from "../../../util/fetch";
import {addCol, getColIconByType} from "./col";
@@ -195,16 +197,57 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
});
if (element.innerHTML === "") {
let dragBlockElement: HTMLElement;
+ let dropTarget: IAVAttributeDropTarget;
+ let draggedElement: HTMLElement;
+ let dragPreviousElement: Element;
+ let dragNextElement: Element;
+ let undoPreviousID: string;
let removeEditorRange: Range | undefined;
+ const finishDrag = (restore: boolean) => {
+ if (draggedElement) {
+ if (restore && dragBlockElement?.isConnected && draggedElement.parentElement === dragBlockElement) {
+ if (dragNextElement?.parentElement === dragBlockElement) {
+ dragNextElement.before(draggedElement);
+ } else if (dragPreviousElement?.parentElement === dragBlockElement) {
+ dragPreviousElement.after(draggedElement);
+ }
+ updateAVAttributeLayout(dragBlockElement);
+ }
+ draggedElement.style.opacity = "";
+ delete draggedElement.dataset.avDragPreview;
+ if (window.siyuan.dragElement === draggedElement) window.siyuan.dragElement = undefined;
+ }
+ draggedElement = undefined;
+ dragBlockElement = undefined;
+ dropTarget = undefined;
+ counter = 0;
+ clearAVAttributeDropTarget(element);
+ };
+ const insertDragged = (target: IAVAttributeDropTarget) => {
+ if (getAVAttributeSort(draggedElement, target)) {
+ if (target.before) target.element.before(draggedElement);
+ else target.element.after(draggedElement);
+ updateAVAttributeLayout(dragBlockElement);
+ }
+ };
element.addEventListener("dragstart", (event: DragEvent) => {
if (protyle.disabled) {
event.preventDefault();
return;
}
- const target = event.target as HTMLElement;
- window.siyuan.dragElement = target.parentElement;
- window.siyuan.dragElement.style.opacity = ".38";
- dragBlockElement = hasClosestBlock(window.siyuan.dragElement) as HTMLElement;
+ const target = (event.target as HTMLElement).closest<HTMLElement>('.av__row > [draggable="true"]');
+ if (!target || !element.contains(target)) {
+ return;
+ }
+ finishDrag(true);
+ draggedElement = target.parentElement;
+ window.siyuan.dragElement = draggedElement;
+ draggedElement.style.opacity = ".38";
+ dragBlockElement = hasClosestBlock(draggedElement) as HTMLElement;
+ dragPreviousElement = draggedElement.previousElementSibling;
+ dragNextElement = draggedElement.nextElementSibling;
+ undoPreviousID = getAVAttributePreviousID(draggedElement);
+ target.addEventListener("dragend", () => finishDrag(true), {once: true});
const ghostElement = document.createElement("div");
ghostElement.className = "block__icons";
@@ -218,35 +261,30 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
});
element.addEventListener("drop", (event) => {
counter = 0;
+ clearAVAttributeDropTarget(element);
if (protyle.disabled) {
+ finishDrag(true);
event.preventDefault();
event.stopPropagation();
return;
}
- const targetElement = element.querySelector(".dragover__bottom, .dragover__top") as HTMLElement;
- if (targetElement && dragBlockElement) {
- const isBottom = targetElement.classList.contains("dragover__bottom");
- const previousID = isBottom ? targetElement.dataset.colId : targetElement.previousElementSibling?.getAttribute("data-col-id");
- const undoPreviousID = window.siyuan.dragElement.previousElementSibling?.getAttribute("data-col-id");
- if (previousID !== undoPreviousID && previousID !== window.siyuan.dragElement.dataset.colId) {
+ dropTarget = dragBlockElement && draggedElement && hasClosestBlock(event.target as HTMLElement) === dragBlockElement ?
+ getAVAttributeDropTarget(dragBlockElement, draggedElement, event.clientX, event.clientY,
+ (event.target as HTMLElement).closest<HTMLElement>(".av__row")) : undefined;
+ if (dropTarget) {
+ insertDragged(dropTarget);
+ const previousID = getAVAttributePreviousID(draggedElement);
+ if (previousID !== undoPreviousID) {
+ const id = draggedElement.dataset.colId;
transaction(protyle, [{
- action: "sortAttrViewKey",
- avID: dragBlockElement.dataset.avId,
- previousID,
- id: window.siyuan.dragElement.dataset.colId,
+ action: "sortAttrViewKey", avID: dragBlockElement.dataset.avId, previousID, id,
}], [{
- action: "sortAttrViewKey",
- avID: dragBlockElement.dataset.avId,
- previousID: undoPreviousID,
- id,
+ action: "sortAttrViewKey", avID: dragBlockElement.dataset.avId, previousID: undoPreviousID, id,
}]);
- if (isBottom) {
- targetElement.after(window.siyuan.dragElement);
- } else {
- targetElement.before(window.siyuan.dragElement);
- }
}
- targetElement.classList.remove("dragover__bottom", "dragover__top");
+ finishDrag(false);
+ event.preventDefault();
+ event.stopPropagation();
} else if (!window.siyuan.dragElement && hasDataTransferFiles(event.dataTransfer.types)) {
const cellElement = element.querySelector(".custom-attr__avvalue--active") as HTMLElement;
if (cellElement) {
@@ -266,12 +304,11 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
}
}
}
- if (window.siyuan.dragElement) {
- window.siyuan.dragElement.style.opacity = "";
- window.siyuan.dragElement = undefined;
- }
+ finishDrag(true);
});
element.addEventListener("dragover", (event: DragEvent) => {
+ clearAVAttributeDropTarget(element);
+ dropTarget = undefined;
if (protyle.disabled) {
return;
}
@@ -288,47 +325,36 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
}
return;
}
- targetElement = hasClosestByClassName(target, "av__row");
- if (!targetElement) {
- targetElement = hasClosestByClassName(document.elementFromPoint(event.clientX, event.clientY - 1), "av__row");
- }
- if (!targetElement || targetElement === window.siyuan.dragElement || !dragBlockElement) {
+ if (!dragBlockElement || !draggedElement || hasClosestBlock(target) !== dragBlockElement) {
return;
}
- const targetBlockElement = hasClosestBlock(targetElement);
- if (!targetBlockElement || targetBlockElement !== dragBlockElement) {
+ dropTarget = getAVAttributeDropTarget(dragBlockElement, draggedElement, event.clientX, event.clientY,
+ target.closest<HTMLElement>(".av__row"));
+ if (!dropTarget) {
return;
}
event.preventDefault();
- const nodeRect = targetElement.getBoundingClientRect();
- element.querySelectorAll(".dragover__bottom, .dragover__top").forEach((item: HTMLElement) => {
- item.classList.remove("dragover__bottom", "dragover__top");
- });
- if (event.clientY > nodeRect.top + nodeRect.height / 2) {
- targetElement.classList.add("dragover__bottom");
- } else {
- targetElement.classList.add("dragover__top");
+ if (dropTarget.horizontal) {
+ insertDragged(dropTarget);
+ draggedElement.dataset.avDragPreview = "true";
+ } else if (getAVAttributeSort(draggedElement, dropTarget)) {
+ dropTarget.element.classList.add(dropTarget.before ? "dragover__top" : "dragover__bottom");
}
});
let counter = 0;
element.addEventListener("dragleave", () => {
counter--;
- if (counter === 0) {
- element.querySelectorAll(".dragover__bottom, .dragover__top").forEach((item: HTMLElement) => {
- item.classList.remove("dragover__bottom", "dragover__top");
- });
+ if (counter <= 0) {
+ counter = 0;
+ clearAVAttributeDropTarget(element);
+ dropTarget = undefined;
}
});
element.addEventListener("dragenter", (event) => {
event.preventDefault();
counter++;
});
- element.addEventListener("dragend", () => {
- if (window.siyuan.dragElement) {
- window.siyuan.dragElement.style.opacity = "";
- window.siyuan.dragElement = undefined;
- }
- });
+ element.addEventListener("dragend", () => finishDrag(true));
element.addEventListener("paste", (event) => {
if (protyle.disabled) {
return;
@@ -610,7 +636,11 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
}
});
}
- renderAttributeViewBacklinks(element, id, renderID, row, cb);
+ observeAVAttributeLayout(element);
+ renderAttributeViewBacklinks(element, id, renderID, row, rendered => {
+ cb?.(rendered);
+ updateAVAttributeLayout(element);
+ });
});
};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 3c02412cb7..ba69e6d7b4 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2004,7 +2004,7 @@ export type SetCriterionRequestInput = { "criterion": CriterionInput | null; };
export type SetDatabaseBlockViewRequestInput = { "avID": string; "id": string; "viewID": string; };
-export type SetEditorRequestInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoCloseRefBrackets"?: boolean | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockGutterMode"?: boolean | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "embedBlockBreadcrumbParentPath"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "mathDelimiterCompatibility"?: boolean | null; "onlySearchForDoc"?: boolean | null; "pageScrollButtons"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };
+export type SetEditorRequestInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoCloseRefBrackets"?: boolean | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockGutterMode"?: boolean | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrLayout"?: number | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "embedBlockBreadcrumbParentPath"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "mathDelimiterCompatibility"?: boolean | null; "onlySearchForDoc"?: boolean | null; "pageScrollButtons"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };
export type SetEntryVisibilityRequestInput = { "active"?: string | null; "profiles"?: Array<SettingEntryVisibilityProfileInput | null> | null; "version"?: number | null; };
@@ -2144,13 +2144,13 @@ export type SettingEditing = { "maxCompletionTokens": number; "maxHistoryMessage
export type SettingEditingInput = { "maxCompletionTokens"?: number | null; "maxHistoryMessages"?: number | null; "modelId"?: string | null; "temperature"?: number | null; };
-export type SettingEditor = { "allowHTMLBLockScript": boolean; "allowSVGScript": boolean; "assetOpen": SettingAssetOpen | null; "autoCloseRefBrackets": boolean; "autoDirection": boolean; "backlinkBlockSort": number; "backlinkContainChildren": boolean; "backlinkExpandCount": number; "backlinkGlobalSort": number; "backlinkHideReference": boolean; "backlinkMentionExclude": string; "backlinkShowBottom": boolean; "backlinkSort": number | null; "backmentionExpandCount": number; "backmentionSort": number | null; "blockGutterMode": boolean; "blockRefDynamicAnchorTextMaxLen": number; "checkBlockRef": boolean | null; "codeFontFamilies": Array<SettingEditorFont | null> | null; "codeLigatures": boolean; "codeLineWrap": boolean; "codeSyntaxHighlightLineNum": boolean; "codeTabSpaces": number; "cursorSurroundingLines": number; "databaseAttrClickMode": number; "databaseAttrHideEmpty": boolean; "databaseAttrShow": boolean | null; "databaseAttrUseTabs": boolean | null; "databaseAttrViewMode": number; "displayBookmarkIcon": boolean; "displayImgAlt": boolean; "displayImgName": boolean; "displayNetImgMark": boolean; "dragHTMLFileToIframe": boolean; "dynamicLoadBlocks": number; "embedBlockBreadcrumb": boolean; "embedBlockBreadcrumbParentPath": boolean | null; "emoji": Array<string> | null; "floatWindowDelay": number | null; "floatWindowMode": number; "fontFamilies": Array<SettingEditorFont | null> | null; "fontFamily": string; "fontFamilyDisplay": string; "fontSize": number; "fontSizeScrollZoom": boolean; "fontWeight": number; "fullWidth": boolean; "generateHistoryInterval": number; "hashTagSearch": boolean | null; "headingEmbedMode": number; "headingNumber": boolean; "headingNumberFormat": string; "historyRetentionDays": number; "justify": boolean; "katexMacros": string; "keepLoadedContent": boolean; "listItemDotNumberClickFocus": boolean; "listLogicalOutdent": boolean; "markdown": SettingMarkdown | null; "mathDelimiterCompatibility": boolean | null; "onlySearchForDoc": boolean; "pageScrollButtons": boolean; "pasteURLAutoConvert": boolean; "plantUMLServePath": string; "readOnly": boolean; "rtl": boolean; "spellcheck": boolean; "spellcheckLanguages": Array<string> | null; "virtualBlockRef": boolean; "virtualBlockRefExclude": string; "virtualBlockRefInclude": string; };
+export type SettingEditor = { "allowHTMLBLockScript": boolean; "allowSVGScript": boolean; "assetOpen": SettingAssetOpen | null; "autoCloseRefBrackets": boolean; "autoDirection": boolean; "backlinkBlockSort": number; "backlinkContainChildren": boolean; "backlinkExpandCount": number; "backlinkGlobalSort": number; "backlinkHideReference": boolean; "backlinkMentionExclude": string; "backlinkShowBottom": boolean; "backlinkSort": number | null; "backmentionExpandCount": number; "backmentionSort": number | null; "blockGutterMode": boolean; "blockRefDynamicAnchorTextMaxLen": number; "checkBlockRef": boolean | null; "codeFontFamilies": Array<SettingEditorFont | null> | null; "codeLigatures": boolean; "codeLineWrap": boolean; "codeSyntaxHighlightLineNum": boolean; "codeTabSpaces": number; "cursorSurroundingLines": number; "databaseAttrClickMode": number; "databaseAttrHideEmpty": boolean; "databaseAttrLayout": number | null; "databaseAttrShow": boolean | null; "databaseAttrUseTabs": boolean | null; "databaseAttrViewMode": number; "displayBookmarkIcon": boolean; "displayImgAlt": boolean; "displayImgName": boolean; "displayNetImgMark": boolean; "dragHTMLFileToIframe": boolean; "dynamicLoadBlocks": number; "embedBlockBreadcrumb": boolean; "embedBlockBreadcrumbParentPath": boolean | null; "emoji": Array<string> | null; "floatWindowDelay": number | null; "floatWindowMode": number; "fontFamilies": Array<SettingEditorFont | null> | null; "fontFamily": string; "fontFamilyDisplay": string; "fontSize": number; "fontSizeScrollZoom": boolean; "fontWeight": number; "fullWidth": boolean; "generateHistoryInterval": number; "hashTagSearch": boolean | null; "headingEmbedMode": number; "headingNumber": boolean; "headingNumberFormat": string; "historyRetentionDays": number; "justify": boolean; "katexMacros": string; "keepLoadedContent": boolean; "listItemDotNumberClickFocus": boolean; "listLogicalOutdent": boolean; "markdown": SettingMarkdown | null; "mathDelimiterCompatibility": boolean | null; "onlySearchForDoc": boolean; "pageScrollButtons": boolean; "pasteURLAutoConvert": boolean; "plantUMLServePath": string; "readOnly": boolean; "rtl": boolean; "spellcheck": boolean; "spellcheckLanguages": Array<string> | null; "virtualBlockRef": boolean; "virtualBlockRefExclude": string; "virtualBlockRefInclude": string; };
export type SettingEditorFont = { "displayName": string; "family": string; "weight": number; };
export type SettingEditorFontInput = { "displayName"?: string | null; "family"?: string | null; "weight"?: number | null; };
-export type SettingEditorInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoCloseRefBrackets"?: boolean | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockGutterMode"?: boolean | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "embedBlockBreadcrumbParentPath"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "mathDelimiterCompatibility"?: boolean | null; "onlySearchForDoc"?: boolean | null; "pageScrollButtons"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };
+export type SettingEditorInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoCloseRefBrackets"?: boolean | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockGutterMode"?: boolean | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrLayout"?: number | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "embedBlockBreadcrumbParentPath"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "mathDelimiterCompatibility"?: boolean | null; "onlySearchForDoc"?: boolean | null; "pageScrollButtons"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };
export type SettingEmbedding = { "apiKey": string; "baseURL": string; "batchSize": number; "concurrency": number; "dimensions": number; "enabled": boolean; "id": string; "name": string; "timeout": number; };
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 8a812714de..310e4d4674 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -688,6 +688,8 @@ declare namespace Config {
* Whether to use tabs for database attributes
*/
databaseAttrUseTabs: boolean;
+ /** 数据库字段布局:0 单栏,1 双栏按行(默认),2 双栏按列,空间不足时使用单栏 */
+ databaseAttrLayout: number;
/**
* Whether to retain dynamically loaded content blocks
*/
diff --git a/app/src/util/assets.test.ts b/app/src/util/assets.test.ts
index 58bcc7b49f..d37a7f3666 100644
--- a/app/src/util/assets.test.ts
+++ b/app/src/util/assets.test.ts
@@ -10,6 +10,31 @@ const source = ts.transpileModule(readFileSync(join(__dirname, "assets.ts"), "ut
compilerOptions: {module: ts.ModuleKind.CommonJS},
}).outputText;
+test("database field layout preference updates existing global styles and defaults to row-first two columns", async () => {
+ const api = {} as typeof import("./assets");
+ const editor: {fontSize: number, databaseAttrLayout?: number} = {fontSize: 16};
+ const style = {innerHTML: ""};
+ runInNewContext(source, {
+ exports: api,
+ window: {siyuan: {config: {editor}}},
+ document: {getElementById: () => style},
+ require: (id: string) => {
+ if (id === "../protyle/util/compatibility") return {
+ isMac: () => false, isIPad: () => false, isIPhone: () => false,
+ isWin11: async () => false, resolvePlatformClass: () => "body--windows",
+ };
+ if (id === "./hostCapabilities") return {getHostCapabilities: () => ({customAppearance: false})};
+ return new Proxy({}, {get: () => () => ""});
+ },
+ });
+ for (const value of [undefined, 0, 1, 2]) {
+ editor.databaseAttrLayout = value;
+ await api.setInlineStyle();
+ assert.match(style.innerHTML, new RegExp(`--b3-database-attr-columns: ${value === 0 ? 1 : 2}`));
+ assert.match(style.innerHTML, new RegExp(`--b3-database-attr-column-flow: ${value === 2 ? 1 : 0}`));
+ }
+});
+
for (const [name, platformClass, win11, apple] of [
["Windows 11", "body--windows", true, false],
["Windows fallback", "body--windows", false, false],
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index d877a684af..cdf829ee09 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -355,7 +355,7 @@ export const setInlineStyle = async (set = true, servePath = "../../../", export
`var(--b3-font-family-emoji-reset), ${codeFontFamilies}, var(--b3-font-family-code)` :
"var(--b3-font-family-code)";
const codeFontWeight = codeFonts[0]?.weight || 400;
- style += `\n:root { --b3-font-size-editor: ${window.siyuan.config.editor.fontSize}px; --b3-font-family-editor: ${editorFontFamilies || "var(--b3-font-family-protyle)"}; --b3-font-family-editor-code: ${codeFontFamily}; --b3-font-weight-editor-code: ${codeFontWeight} }
+ style += `\n:root { --b3-font-size-editor: ${window.siyuan.config.editor.fontSize}px; --b3-font-family-editor: ${editorFontFamilies || "var(--b3-font-family-protyle)"}; --b3-font-family-editor-code: ${codeFontFamily}; --b3-font-weight-editor-code: ${codeFontWeight}; --b3-database-attr-columns: ${window.siyuan.config.editor.databaseAttrLayout === 0 ? 1 : 2}; --b3-database-attr-column-flow: ${window.siyuan.config.editor.databaseAttrLayout === 2 ? 1 : 0} }
.b3-typography code:not(.hljs), .protyle-wysiwyg span[data-type~=code] { font-variant-ligatures: ${window.siyuan.config.editor.codeLigatures ? "normal" : "none"} }
.b3-typography:not(.b3-typography--default) code:not(.hljs), .protyle-wysiwyg span[data-type~=code] { font-family: var(--b3-font-family-editor-code); font-weight: var(--b3-font-weight-editor-code) }${window.siyuan.config.editor.justify ? "\n.protyle-wysiwyg [data-node-id] { text-align: justify }" : ""}`;
if (editorFontFamilies) {
diff --git a/kernel/api/contract_setting_database_layout_test.go b/kernel/api/contract_setting_database_layout_test.go
new file mode 100644
index 0000000000..de27676110
--- /dev/null
+++ b/kernel/api/contract_setting_database_layout_test.go
@@ -0,0 +1,65 @@
+// SiYuan - https://github.com/siyuan-note/siyuan
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package api
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractSettingDatabaseAttrLayout(t *testing.T) {
+ compareSettingConfig(t, apicontract.SetEditor, conf.NewEditor, []string{
+ `{}`, `{"databaseAttrLayout":0}`, `{"databaseAttrLayout":2}`,
+ `{"databaseAttrLayout":null}`, `{"DatabaseAttrLayout":2}`,
+ `{"databaseAttrLayout":"bad"}`, `{"databaseAttrLayout":true}`, `{"databaseAttrLayout":-1}`, `{"databaseAttrLayout":3}`,
+ })
+ previousConf, previousReadOnly, previousMarkdown := model.Conf, util.ReadOnly, util.MarkdownSettings.Load()
+ model.Conf = model.NewAppConf()
+ model.Conf.Editor.Store(conf.NewEditor())
+ util.ReadOnly = true
+ t.Cleanup(func() {
+ model.Conf = previousConf
+ util.ReadOnly = previousReadOnly
+ util.MarkdownSettings.Store(previousMarkdown)
+ })
+ for _, entry := range []struct {
+ body string
+ want int
+ }{
+ {`{}`, 1}, {`{"databaseAttrLayout":0}`, 0}, {`{}`, 0},
+ {`{"databaseAttrLayout":null}`, 1}, {`{"DatabaseAttrLayout":2}`, 2},
+ {`{"databaseAttrLayout":1}`, 1}, {`{"databaseAttrLayout":-1}`, 1},
+ {`{"databaseAttrLayout":3}`, 1},
+ } {
+ code, message, data := settingContractRequest(t, "setEditor", setEditor, entry.body)
+ var response apicontract.SettingEditor
+ if err := json.Unmarshal(data, &response); err != nil {
+ t.Fatal(err)
+ }
+ if code != 0 || response.DatabaseAttrLayout == nil || *response.DatabaseAttrLayout != entry.want ||
+ *model.Conf.Editor.Load().DatabaseAttrLayout != entry.want {
+ t.Fatalf("database layout update %s: code=%d message=%s data=%s", entry.body, code, message, data)
+ }
+ }
+ for _, entry := range []struct {
+ body string
+ want int
+ }{
+ {`{"editor":{"databaseAttrLayout":0}}`, 0},
+ {`{"editor":{"fontSize":18}}`, 0},
+ {`{"editor":{"databaseAttrLayout":2}}`, 2},
+ {`{"editor":{"databaseAttrLayout":null}}`, 1},
+ } {
+ code, message, _ := settingContractRequest(t, "patch", patchSetting, entry.body)
+ if code != 0 || *model.Conf.Editor.Load().DatabaseAttrLayout != entry.want {
+ t.Fatalf("database layout patch %s: code=%d message=%s", entry.body, code, message)
+ }
+ }
+}
diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.go
index a5983324d0..edc624d39f 100644
--- a/kernel/api/setting_contract.go
+++ b/kernel/api/setting_contract.go
@@ -383,6 +383,7 @@ func settingEditorPayload(value *conf.Editor) *apicontract.SettingEditor {
result.DatabaseAttrViewMode = value.DatabaseAttrViewMode
result.DatabaseAttrHideEmpty = value.DatabaseAttrHideEmpty
result.DatabaseAttrUseTabs = value.DatabaseAttrUseTabs
+ result.DatabaseAttrLayout = value.DatabaseAttrLayout
result.GenerateHistoryInterval = value.GenerateHistoryInterval
result.HistoryRetentionDays = value.HistoryRetentionDays
result.Emoji = value.Emoji
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 1eef46bdfa..205dc714a3 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -42451,6 +42451,16 @@
}
]
},
+ "databaseAttrLayout": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"databaseAttrShow": {
"anyOf": [
{
@@ -46736,6 +46746,16 @@
"databaseAttrHideEmpty": {
"type": "boolean"
},
+ "databaseAttrLayout": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"databaseAttrShow": {
"anyOf": [
{
@@ -46985,6 +47005,7 @@
"cursorSurroundingLines",
"databaseAttrClickMode",
"databaseAttrHideEmpty",
+ "databaseAttrLayout",
"databaseAttrShow",
"databaseAttrUseTabs",
"databaseAttrViewMode",
@@ -47362,6 +47383,16 @@
}
]
},
+ "databaseAttrLayout": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"databaseAttrShow": {
"anyOf": [
{
diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.go
index 3ac16fd15a..1e7f6d3117 100644
--- a/kernel/apicontract/setting.go
+++ b/kernel/apicontract/setting.go
@@ -293,6 +293,10 @@ type SettingEditor struct {
MathDelimiterCompatibility *bool `json:"mathDelimiterCompatibility" api:"optional,nullable"`
DragHTMLFileToIframe bool `json:"dragHTMLFileToIframe" api:"optional,nullable"`
Markdown *SettingMarkdown `json:"markdown" api:"optional,nullable"`
+
+ // 文档顶部与独立条目面板的字段布局:0 单栏,1 双栏按行(默认),2 双栏按列;空间不足时使用单栏。
+ // 省略保留当前值,null 或越界整数恢复默认,按列时按可见字段数量均分,奇数时左栏多一个。
+ DatabaseAttrLayout *int `json:"databaseAttrLayout" api:"optional,nullable"`
}
type SettingEditorFont struct {
diff --git a/kernel/conf/editor.go b/kernel/conf/editor.go
index 18f486e59a..90908ad2f3 100644
--- a/kernel/conf/editor.go
+++ b/kernel/conf/editor.go
@@ -56,6 +56,7 @@ type Editor struct {
DatabaseAttrViewMode int `json:"databaseAttrViewMode"` // 数据库属性默认展开状态,0:展开,1:折叠
DatabaseAttrHideEmpty bool `json:"databaseAttrHideEmpty"` // 是否隐藏数据库空属性
DatabaseAttrUseTabs *bool `json:"databaseAttrUseTabs"` // 数据库属性是否使用页签
+ DatabaseAttrLayout *int `json:"databaseAttrLayout"` // 数据库字段布局,0:单栏,1:双栏按行,2:双栏按列
GenerateHistoryInterval int `json:"generateHistoryInterval"` // 生成历史时间间隔,单位:分钟
HistoryRetentionDays int `json:"historyRetentionDays"` // 历史保留天数
Emoji []string `json:"emoji"` // 常用表情
@@ -206,6 +207,7 @@ func NewEditor() *Editor {
DatabaseAttrViewMode: 0,
DatabaseAttrHideEmpty: false,
DatabaseAttrUseTabs: new(true),
+ DatabaseAttrLayout: new(1),
GenerateHistoryInterval: 10,
HistoryRetentionDays: 30,
Emoji: []string{},
diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.go
index eb8bb4401d..29b5857bb8 100644
--- a/kernel/conf/settings_normalize.go
+++ b/kernel/conf/settings_normalize.go
@@ -85,6 +85,9 @@ func NormalizeEditor(editor *Editor) *Editor {
if editor.DatabaseAttrUseTabs == nil {
editor.DatabaseAttrUseTabs = defaults.DatabaseAttrUseTabs
}
+ if editor.DatabaseAttrLayout == nil || *editor.DatabaseAttrLayout < 0 || *editor.DatabaseAttrLayout > 2 {
+ editor.DatabaseAttrLayout = defaults.DatabaseAttrLayout
+ }
if editor.CheckBlockRef == nil {
editor.CheckBlockRef = defaults.CheckBlockRef
}
diff --git a/kernel/conf/settings_normalize_test.go b/kernel/conf/settings_normalize_test.go
index 7701bd14b8..467f42db50 100644
--- a/kernel/conf/settings_normalize_test.go
+++ b/kernel/conf/settings_normalize_test.go
@@ -34,6 +34,40 @@ func TestNormalizeSettingsEditorCompatibility(t *testing.T) {
}
}
+func TestNormalizeSettingsDatabaseAttrLayout(t *testing.T) {
+ for _, entry := range []struct {
+ input string
+ want int
+ }{
+ {`{}`, 1}, {`{"databaseAttrLayout":null}`, 1}, {`{"databaseAttrLayout":0}`, 0},
+ {`{"databaseAttrLayout":1}`, 1}, {`{"databaseAttrLayout":2}`, 2},
+ {`{"databaseAttrLayout":-1}`, 1}, {`{"databaseAttrLayout":3}`, 1},
+ } {
+ var editor Editor
+ if err := json.Unmarshal([]byte(entry.input), &editor); err != nil {
+ t.Fatal(err)
+ }
+ got := NormalizeEditor(&editor)
+ if got.DatabaseAttrLayout == nil || *got.DatabaseAttrLayout != entry.want {
+ t.Fatalf("%s: unexpected database field layout: %+v", entry.input, got)
+ }
+ encoded, err := json.Marshal(got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var saved Editor
+ if err = json.Unmarshal(encoded, &saved); err != nil {
+ t.Fatal(err)
+ }
+ if *NormalizeEditor(&saved).DatabaseAttrLayout != entry.want {
+ t.Fatal("normalization changed the saved preference")
+ }
+ }
+ if *NewEditor().DatabaseAttrLayout != 1 || *NormalizeEditor(nil).DatabaseAttrLayout != 1 {
+ t.Fatal("new and missing editor settings must use row-first two columns")
+ }
+}
+
func TestNormalizeSettingsFileTreeAndSearch(t *testing.T) {
fileTree := NormalizeFileTree(&FileTree{CloseTabsOnStart: true, ShorthandSavePath: "notes", MaxOpenTabCount: 99})
if *fileTree.TabStartupMode != 2 || !fileTree.CloseTabsOnStart || fileTree.ShorthandSavePath != "/notes" ||