Skip to content

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

:sparkles: Add slash commands for current list conversion https://github.com/siyuan-note/siyuan/issues/20804

Danielf5070154de97
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 8abb344f36..17d4dcc715 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "تحويل القائمة الحالية إلى ${name}",
+ "cancelCurrentList": "إلغاء القائمة الحالية",
+ "createList": "إنشاء ${name}",
+ "insertChildList": "إدراج قائمة فرعية: ${name}",
"backlinkDatabaseFields": "حقول قاعدة البيانات",
"listMindmapPaletteOcean": "محيط",
"listMindmapPaletteSunset": "غروب",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index dff9371420..4da0ba240b 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Aktuelle Liste umwandeln in: ${name}",
+ "cancelCurrentList": "Aktuelle Liste aufheben",
+ "createList": "${name} erstellen",
+ "insertChildList": "Unterliste einfügen: ${name}",
"backlinkDatabaseFields": "Datenbankfelder",
"listMindmapPaletteOcean": "Ozean",
"listMindmapPaletteSunset": "Sonnenuntergang",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 99f5905175..642e97055d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Convert current list to ${name}",
+ "cancelCurrentList": "Cancel current list",
+ "createList": "Create ${name}",
+ "insertChildList": "Insert sublist: ${name}",
"backlinkDatabaseFields": "Database fields",
"listMindmapPaletteOcean": "Ocean",
"listMindmapPaletteSunset": "Sunset",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index f4b44896d8..f931519b69 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Convertir la lista actual en: ${name}",
+ "cancelCurrentList": "Quitar la lista actual",
+ "createList": "Crear ${name}",
+ "insertChildList": "Insertar sublista: ${name}",
"backlinkDatabaseFields": "Campos de la base de datos",
"listMindmapPaletteOcean": "Océano",
"listMindmapPaletteSunset": "Atardecer",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 8d7f74fb7f..83261f17e5 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Convertir la liste actuelle en : ${name}",
+ "cancelCurrentList": "Supprimer la structure de la liste actuelle",
+ "createList": "Créer : ${name}",
+ "insertChildList": "Insérer une sous-liste : ${name}",
"backlinkDatabaseFields": "Champs de la base de données",
"listMindmapPaletteOcean": "Océan",
"listMindmapPaletteSunset": "Coucher de soleil",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 3acc114d12..c9e9e2a710 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "המרת הרשימה הנוכחית ל־${name}",
+ "cancelCurrentList": "ביטול הרשימה הנוכחית",
+ "createList": "יצירת ${name}",
+ "insertChildList": "הוספת תת־רשימה: ${name}",
"backlinkDatabaseFields": "שדות מסד נתונים",
"listMindmapPaletteOcean": "אוקיינוס",
"listMindmapPaletteSunset": "שקיעה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 0f332b9e1e..9db11ead1b 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "वर्तमान सूची को ${name} में बदलें",
+ "cancelCurrentList": "वर्तमान सूची का प्रारूप हटाएँ",
+ "createList": "${name} बनाएँ",
+ "insertChildList": "उपसूची डालें: ${name}",
"backlinkDatabaseFields": "डेटाबेस फ़ील्ड",
"listMindmapPaletteOcean": "महासागर",
"listMindmapPaletteSunset": "सूर्यास्त",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 84d414daf5..5968b2bbc9 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Ubah daftar saat ini menjadi ${name}",
+ "cancelCurrentList": "Hapus format daftar saat ini",
+ "createList": "Buat ${name}",
+ "insertChildList": "Sisipkan subdaftar: ${name}",
"backlinkDatabaseFields": "Bidang basis data",
"listMindmapPaletteOcean": "Samudra",
"listMindmapPaletteSunset": "Senja",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 077e35725b..34c73e0b92 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Converti l’elenco corrente in: ${name}",
+ "cancelCurrentList": "Rimuovi la struttura dell’elenco corrente",
+ "createList": "Crea ${name}",
+ "insertChildList": "Inserisci sottoelenco: ${name}",
"backlinkDatabaseFields": "Campi del database",
"listMindmapPaletteOcean": "Oceano",
"listMindmapPaletteSunset": "Tramonto",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index c327619b27..df1cfd72a3 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "現在のリストを${name}に変換",
+ "cancelCurrentList": "現在のリストを解除",
+ "createList": "${name}を作成",
+ "insertChildList": "子リストを挿入:${name}",
"backlinkDatabaseFields": "データベースのフィールド",
"listMindmapPaletteOcean": "海",
"listMindmapPaletteSunset": "夕日",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index dba78ba507..814f0660fc 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "현재 목록을 ${name}(으)로 변환",
+ "cancelCurrentList": "현재 목록 해제",
+ "createList": "${name} 만들기",
+ "insertChildList": "하위 목록 삽입: ${name}",
"backlinkDatabaseFields": "데이터베이스 필드",
"listMindmapPaletteOcean": "바다",
"listMindmapPaletteSunset": "일몰",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index aeb8fd66fc..3fe39772dc 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Huidige lijst omzetten naar: ${name}",
+ "cancelCurrentList": "Huidige lijststructuur opheffen",
+ "createList": "${name} maken",
+ "insertChildList": "Sublijst invoegen: ${name}",
"backlinkDatabaseFields": "Databasevelden",
"listMindmapPaletteOcean": "Oceaan",
"listMindmapPaletteSunset": "Zonsondergang",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 684e453cb3..6d7845f502 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Przekształć bieżącą listę w: ${name}",
+ "cancelCurrentList": "Usuń format bieżącej listy",
+ "createList": "Utwórz: ${name}",
+ "insertChildList": "Wstaw podlistę: ${name}",
"backlinkDatabaseFields": "Pola bazy danych",
"listMindmapPaletteOcean": "Ocean",
"listMindmapPaletteSunset": "Zachód słońca",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index aae1e9ed07..32b8f92012 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Converter a lista atual em: ${name}",
+ "cancelCurrentList": "Remover a formatação da lista atual",
+ "createList": "Criar ${name}",
+ "insertChildList": "Inserir sublista: ${name}",
"backlinkDatabaseFields": "Campos do banco de dados",
"listMindmapPaletteOcean": "Oceano",
"listMindmapPaletteSunset": "Pôr do sol",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 6264452d57..6dbb8ae439 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Преобразовать текущий список в: ${name}",
+ "cancelCurrentList": "Убрать формат текущего списка",
+ "createList": "Создать: ${name}",
+ "insertChildList": "Вставить вложенный список: ${name}",
"backlinkDatabaseFields": "Поля базы данных",
"listMindmapPaletteOcean": "Океан",
"listMindmapPaletteSunset": "Закат",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 0f4cf0f086..9c81893f5d 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Zmeniť aktuálny zoznam na: ${name}",
+ "cancelCurrentList": "Zrušiť formát aktuálneho zoznamu",
+ "createList": "Vytvoriť: ${name}",
+ "insertChildList": "Vložiť vnorený zoznam: ${name}",
"backlinkDatabaseFields": "Polia databázy",
"listMindmapPaletteOcean": "Oceán",
"listMindmapPaletteSunset": "Západ slnka",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 8123509a35..7462dcc3ea 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Претвори тренутну листу у: ${name}",
+ "cancelCurrentList": "Уклони формат тренутне листе",
+ "createList": "Направи: ${name}",
+ "insertChildList": "Уметни подлисту: ${name}",
"backlinkDatabaseFields": "Поља базе података",
"listMindmapPaletteOcean": "Океан",
"listMindmapPaletteSunset": "Залазак сунца",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 2bd2ee0aec..28347ae89d 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "แปลงรายการปัจจุบันเป็น ${name}",
+ "cancelCurrentList": "ยกเลิกรูปแบบรายการปัจจุบัน",
+ "createList": "สร้าง${name}",
+ "insertChildList": "แทรกรายการย่อย: ${name}",
"backlinkDatabaseFields": "ฟิลด์ฐานข้อมูล",
"listMindmapPaletteOcean": "มหาสมุทร",
"listMindmapPaletteSunset": "พระอาทิตย์ตก",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index bd77260917..b59370f691 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Geçerli listeyi dönüştür: ${name}",
+ "cancelCurrentList": "Geçerli liste biçimini kaldır",
+ "createList": "${name} oluştur",
+ "insertChildList": "Alt liste ekle: ${name}",
"backlinkDatabaseFields": "Veritabanı alanları",
"listMindmapPaletteOcean": "Okyanus",
"listMindmapPaletteSunset": "Gün batımı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index f7e7339c2f..0c83c3083f 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "Перетворити поточний список на: ${name}",
+ "cancelCurrentList": "Прибрати формат поточного списку",
+ "createList": "Створити: ${name}",
+ "insertChildList": "Вставити вкладений список: ${name}",
"backlinkDatabaseFields": "Поля бази даних",
"listMindmapPaletteOcean": "Океан",
"listMindmapPaletteSunset": "Захід сонця",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 978a170ae4..71c47f2a71 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "将当前列表转换为${name}",
+ "cancelCurrentList": "取消当前列表",
+ "createList": "创建${name}",
+ "insertChildList": "插入子列表:${name}",
"backlinkDatabaseFields": "数据库字段",
"listMindmapPaletteOcean": "海洋",
"listMindmapPaletteSunset": "日落",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index df46dfd693..1fbe800bcf 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,8 @@
{
+ "convertCurrentList": "將目前列表轉換為${name}",
+ "cancelCurrentList": "取消目前列表",
+ "createList": "建立${name}",
+ "insertChildList": "插入子列表:${name}",
"backlinkDatabaseFields": "資料庫欄位",
"listMindmapPaletteOcean": "海洋",
"listMindmapPaletteSunset": "日落",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
index 54c557a94f..a238a49348 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
@@ -7,7 +7,7 @@
"id": "20200924100950-9op5xi1",
"title": "Shortcuts",
"type": "doc",
- "updated": "20261022134112"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -4365,7 +4365,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210106154056-koo4wdj",
- "updated": "20261020181700"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12660,7 +12660,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20210106154319-ans1gna",
- "updated": "20260923083553"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12673,6 +12673,20 @@
}
]
},
+ {
+ "ID": "20261022181833-rojpzqb",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022181833-rojpzqb",
+ "updated": "20261022181833"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "In a list item, type / and choose a command to convert the current list to an ordered, unordered, or task list, or to cancel the current list. The command affects all sibling items in the nearest list; nested list types remain unchanged. The list creation commands insert a sublist inside a list item. Conversion commands are unavailable when zooming into a single list item without its parent list."
+ }
+ ]
+ },
{
"ID": "20210106154319-4oe7doq",
"Type": "NodeTable",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
index 675c1146a7..9ebbe84ab5 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
@@ -7,7 +7,7 @@
"id": "20200813004551-gm0pbn1",
"title": "快捷键",
"type": "doc",
- "updated": "20261022134112"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -4363,7 +4363,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20201227133317-rkh4bji",
- "updated": "20261020181700"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12640,7 +12640,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20201227133317-x02vhoh",
- "updated": "20260923083553"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12649,6 +12649,20 @@
}
]
},
+ {
+ "ID": "20261022181833-hss43q2",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022181833-hss43q2",
+ "updated": "20261022181833"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在列表项内输入 /,可选择将当前列表转换为有序、无序或任务列表,也可取消当前列表。命令作用于光标所在最近一层列表中的全部同级项,子列表类型保持不变。创建列表的命令在列表项内会插入子列表。聚焦单个列表项且未显示父列表时,不提供转换命令。"
+ }
+ ]
+ },
{
"ID": "20201227133317-yv5msrs",
"Type": "NodeTable",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
index c66cad1444..9e09009bac 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
@@ -7,7 +7,7 @@
"id": "20211226122549-jktxego",
"title": "快捷鍵",
"type": "doc",
- "updated": "20261022134112"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -4357,7 +4357,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226122652-htptsmh",
- "updated": "20261020181700"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12652,7 +12652,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20211226122652-td76oes",
- "updated": "20260923083553"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12661,6 +12661,20 @@
}
]
},
+ {
+ "ID": "20261022181833-kib791u",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022181833-kib791u",
+ "updated": "20261022181833"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在列表項內輸入 /,可選擇將目前列表轉換為有序、無序或任務列表,也可取消目前列表。命令作用於游標所在最近一層列表中的全部同級項,子列表類型保持不變。建立列表的命令在列表項內會插入子列表。聚焦單一列表項且未顯示父列表時,不提供轉換命令。"
+ }
+ ]
+ },
{
"ID": "20211226122652-qj1o02k",
"Type": "NodeTable",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
index 641f9a5b5c..ebdaf41c05 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
@@ -9,7 +9,7 @@
"id": "20240530101000-xsbxokr",
"title": "ショートカット",
"type": "doc",
- "updated": "20261022134112"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -4311,7 +4311,7 @@
"Properties": {
"ID": "20240530101000-twmuxke",
"id": "20240530101000-675gu9g",
- "updated": "20261018200107"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12588,7 +12588,7 @@
"Properties": {
"ID": "20240530101000-uaq4ub6",
"id": "20240530101000-yl0e0sq",
- "updated": "20260923083553"
+ "updated": "20261022181833"
},
"Children": [
{
@@ -12607,6 +12607,20 @@
}
]
},
+ {
+ "ID": "20261022181833-l8vygno",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022181833-l8vygno",
+ "updated": "20261022181833"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "リスト項目内で / を入力すると、現在のリストを順序付き・順序なし・タスクリストに変換したり、リストを解除したりできます。対象はカーソルに最も近いリストの同階層の全項目で、入れ子のリストの種類は変わりません。リスト作成コマンドは、リスト項目内では子リストを挿入します。単一のリスト項目にズームインし、親リストが表示されていない場合、変換コマンドは表示されません。"
+ }
+ ]
+ },
{
"ID": "20240530101000-wqr5cs1",
"Type": "NodeTable",
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 816ab8a065..86dfa10669 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -44,6 +44,7 @@ import {
TOP_BAR_ROOT_PATH,
} from "./catalog";
import {getBuiltinProfileEntryVisibility} from "./profile";
+import {isValidEntryOrder, mergeEntryOrderPreservingUnknown} from "./order";
test("image OCR actions retain their configurable paths and order", t => {
const descriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
@@ -139,6 +140,10 @@ const slashMenuBuiltinOrder = [
"list",
"orderedList",
"check",
+ "convertCurrentListUL",
+ "convertCurrentListOL",
+ "convertCurrentListTL",
+ "cancelCurrentList",
"quote",
"horizontalSuperBlock",
"verticalSuperBlock",
@@ -578,7 +583,7 @@ test("slash menu catalog follows the built-in hint order", () => {
assert.deepEqual(section?.children.map((item) => item.key), ["menu"]);
const children = getEntryCatalogChildren(SLASH_MENU_ROOT_PATH);
assert.deepEqual(children.map((item) => item.key), ["frequent", ...slashMenuBuiltinOrder]);
- assert.equal(children.filter((item) => item.type === "entry").length, 70);
+ assert.equal(children.filter((item) => item.type === "entry").length, 74);
assert.equal(children.filter((item) => item.type === "separator").length, 5);
assert.equal(children.filter(item => item.key !== "frequent").every((item) => item.simple), true);
});
@@ -606,6 +611,24 @@ test("slash menu entries are indexed below their total switch", () => {
]);
});
+test("list conversion commands merge into saved slash order without losing plugin slots", () => {
+ const commands = ["convertCurrentListUL", "convertCurrentListOL", "convertCurrentListTL", "cancelCurrentList"];
+ const children = getEntryCatalogChildren(SLASH_MENU_ROOT_PATH);
+ const defaults = children.map(item => item.key);
+ const saved = defaults.filter(key => !commands.includes(key));
+ saved.splice(saved.indexOf("check"), 0, "plugin:unavailable:entry");
+ const separators = new Set(children.filter(item => item.type === "separator").map(item => item.key));
+ const merged = mergeEntryOrderPreservingUnknown(defaults, saved, undefined, separators);
+ assert.deepEqual(merged.filter(key => !commands.includes(key)), saved);
+ assert.deepEqual(merged.slice(merged.indexOf("check") + 1, merged.indexOf("check") + 5), commands);
+ assert.ok(isValidEntryOrder(merged, separators));
+ commands.forEach(key => {
+ const entry = getEntryCatalogNode(getSlashMenuEntryPath(key));
+ assert.equal(entry.type, "entry");
+ assert.equal(entry.simple, true);
+ });
+});
+
test("plugin slash keys encode dotted names and IDs without ambiguity", () => {
const dottedPlugin = getPluginSlashEntryKey("plugin.name", "entry");
const dottedEntry = getPluginSlashEntryKey("plugin", "name.entry");
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 51e946ecda..a4a5227427 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -559,6 +559,10 @@ const slashMenuBuiltinChildren = [
node("list", lang("list")),
node("orderedList", lang("ordered-list")),
node("check", lang("check")),
+ node("convertCurrentListUL", () => lang("convertCurrentList")().replace("${name}", lang("list")())),
+ node("convertCurrentListOL", () => lang("convertCurrentList")().replace("${name}", lang("ordered-list")())),
+ node("convertCurrentListTL", () => lang("convertCurrentList")().replace("${name}", lang("check")())),
+ node("cancelCurrentList", lang("cancelCurrentList")),
node("quote", lang("quote")),
node("horizontalSuperBlock", lang("horizontalSuperBlock")),
node("verticalSuperBlock", lang("verticalSuperBlock")),
diff --git a/app/src/mobile/util/frequentSlashMenu.test.ts b/app/src/mobile/util/frequentSlashMenu.test.ts
index 859b09718e..d7d2d75b42 100644
--- a/app/src/mobile/util/frequentSlashMenu.test.ts
+++ b/app/src/mobile/util/frequentSlashMenu.test.ts
@@ -120,6 +120,8 @@ for (const iosPhotos of [false, true]) {
canPickIOSPhotos: () => iosPhotos,
isBuiltinInlineStyleVisible: () => false,
getSuperBlockCommand: (layout: string) => layout,
+ getListInsertLabel: (_protyle: unknown, name: string) => name,
+ getBuiltinSlashMenuItems: () => [{id: "convertCurrentListOL", value: "convert-current-list:o", filter: ["Convert current list"]}],
escapeHtml: (value: string) => value,
getFrequentSlashButtons,
getFrequentSlashItems: (buttons: HTMLButtonElement[], getKey: (button: HTMLButtonElement) => string) =>
@@ -149,6 +151,7 @@ for (const iosPhotos of [false, true]) {
assert.equal(util.innerHTML.includes('data-native-photos="true"'), iosPhotos);
assert.equal((util.innerHTML.match(/data-slash-entry-key="insertHTMLFile"/g) || []).length, 0);
assert.equal(boundUploads, 1);
+ assert.equal((util.innerHTML.match(/data-slash-entry-key="convertCurrentListOL"/g) || []).length, 1);
assert.equal(protyle.hint.splitChar, "/");
assert.equal(protyle.hint.lastIndex, -1);
protyle.lite = true;
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index c161664833..9c08afcfb4 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -90,7 +90,8 @@ import {restoreGutterBySelection} from "../../protyle/gutter/restore";
import {isGutterTouchDragging} from "../../protyle/ui/gutterVisibility";
import {getFrequentSlashButtons, mountLiteSlashMenu, prependFrequentSlashButtons} from "./liteSlashMenu";
import {getPluginSlashEntryKey, SLASH_MENU_ROOT_PATH} from "../../config/entryVisibility/catalog";
-import {hintSlash} from "../../protyle/hint/extend";
+import {getBuiltinSlashMenuItems, hintSlash} from "../../protyle/hint/extend";
+import {getListInsertLabel} from "../../protyle/hint/listCommands";
import {getFrequentSlashItems} from "../../protyle/hint/frequentSlashStorage";
import {finishTableCellEditing, getTableCellRichContext, prepareTableCellMenuItems} from "../../protyle/util/tableCellRichContext";
import {insertEmptyBlock} from "../../block/util";
@@ -795,9 +796,11 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {
${getSlashItem("heading4", "#### " + Lute.Caret, "iconH4", window.siyuan.languages.heading4, "true")}
${getSlashItem("heading5", "##### " + Lute.Caret, "iconH5", window.siyuan.languages.heading5, "true")}
${getSlashItem("heading6", "###### " + Lute.Caret, "iconH6", window.siyuan.languages.heading6, "true")}
- ${getSlashItem("list", "- " + Lute.Caret, "iconList", window.siyuan.languages.list, "true")}
- ${getSlashItem("orderedList", "1. " + Lute.Caret, "iconOrderedList", window.siyuan.languages["ordered-list"], "true")}
- ${getSlashItem("check", "- [ ] " + Lute.Caret, "iconCheck", window.siyuan.languages.check, "true")}
+ ${getSlashItem("list", "- " + Lute.Caret, "iconList", getListInsertLabel(protyle, window.siyuan.languages.list), "true")}
+ ${getSlashItem("orderedList", "1. " + Lute.Caret, "iconOrderedList", getListInsertLabel(protyle, window.siyuan.languages["ordered-list"]), "true")}
+ ${getSlashItem("check", "- [ ] " + Lute.Caret, "iconCheck", getListInsertLabel(protyle, window.siyuan.languages.check), "true")}
+ ${getBuiltinSlashMenuItems(protyle).filter(item => item.value.startsWith("convert-current-list:")).map(item =>
+ getSlashItem(item.id, item.value, item.id === "cancelCurrentList" ? "iconParagraph" : "iconList", item.filter[0], "true")).join("")}
${getSlashItem("quote", "> " + Lute.Caret, "iconQuote", window.siyuan.languages.quote, "true")}
${getSlashItem("horizontalSuperBlock", getSuperBlockCommand("col"), "iconSuper", window.siyuan.languages.horizontalSuperBlock, "true")}
${getSlashItem("verticalSuperBlock", getSuperBlockCommand("row"), "iconSuper", window.siyuan.languages.verticalSuperBlock, "true")}
diff --git a/app/src/protyle/hint/convertListCommand.dom.test.ts b/app/src/protyle/hint/convertListCommand.dom.test.ts
new file mode 100644
index 0000000000..8b1e130d9c
--- /dev/null
+++ b/app/src/protyle/hint/convertListCommand.dom.test.ts
@@ -0,0 +1,295 @@
+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 {createSourceFile, isClassDeclaration, isImportDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string, lutePath: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ require(lutePath);
+ const lute = Lute.New();
+ lute.SetProtyleWYSIWYG(true);
+ lute.SetKramdownIAL(true);
+ lute.SetTextMark(true);
+ const editor = document.createElement("div");
+ editor.className = "protyle-wysiwyg";
+ document.body.append(editor);
+ const operations: {doOperations: IOperation[], undoOperations: IOperation[]}[] = [];
+ let removedList: Element;
+ const normalize = (html: string) => {
+ const holder = document.createElement("div");
+ holder.innerHTML = html;
+ holder.querySelectorAll("[data-node-index]").forEach(item => item.removeAttribute("data-node-index"));
+ holder.querySelectorAll(".protyle-attr--av").forEach(item => item.remove());
+ return holder.innerHTML;
+ };
+ let fragment = false;
+ const focusByWbr = () => {
+ const marker = editor.querySelector("wbr");
+ if (marker) {
+ const range = document.createRange();
+ range.setStartBefore(marker);
+ range.collapse(true);
+ marker.remove();
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ }
+ };
+ const dependencies = {
+ Constants: {CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap", BLOCK_HINT_KEYS: [] as string[], INLINE_TYPE: [] as string[], ZWSP: "\u200b"},
+ isProtyleListItemFragment: () => fragment,
+ getContenteditableElement: (element: Element) => element.querySelector('[contenteditable="true"]'),
+ unfoldListHeadings: async () => [] as IOperation[],
+ isListMindmapListConversion: () => false,
+ getPreviousBlockSibling: (element: Element) => element.previousElementSibling,
+ getEmbedChildOperationParentID: (): undefined => undefined,
+ getParentBlock: () => editor,
+ isTabsListConversion: () => false,
+ convertListMindmapToList: (): undefined => undefined,
+ cleanListMindmapHTML: (html: string) => html,
+ disposeCustomBlocksInElement() {},
+ transaction: (_protyle: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) =>
+ operations.push({doOperations, undoOperations}),
+ updateTransaction: (_protyle: IProtyle, element: Element, oldHTML: string, context: IOperation["context"]) => {
+ operations.push({doOperations: [{action: "update", id: element.getAttribute("data-node-id"), data: element.outerHTML}],
+ undoOperations: [{action: "update", id: element.getAttribute("data-node-id"), data: oldHTML, context}]});
+ },
+ removeListStructure: async (_protyle: IProtyle, elements: Element[], recursively: boolean, focus: Record<string, string>) => {
+ check.equal(operations.length, 1);
+ check.equal(recursively, false);
+ check.ok(focus);
+ check.equal(elements.length, 1);
+ removedList = elements[0];
+ },
+ focusByWbr,
+ getEditorRange: () => getSelection().rangeCount ? getSelection().getRangeAt(0) : document.createRange(),
+ blockRender() {}, processRender() {}, highlightRender() {}, avRender() {},
+ hideElements() {}, isOnlyMeta: () => false,
+ shouldCaptureHintUndoFocus: () => true,
+ getUndoFocusContext: () => ({undoFocusStart: "15", undoFocusEnd: "15"}),
+ focusByRange: (range: Range) => {
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ },
+ getHostCapabilities: () => ({widgets: false, remoteKernel: true}),
+ isDisabledFeature: () => true, canPickIOSPhotos: () => false,
+ getSuperBlockCommand: () => "", getBuiltinStyleCSS: () => "",
+ updateHotkeyTip: (key: string) => key,
+ };
+ const api = new Function(...Object.keys(dependencies), source +
+ "return {convertListCommand, getSlashListContext, getListCommandType, getListInsertLabel, getListCommandLabel, getBuiltinSlashMenuItems, Hint};")(
+ ...Object.values(dependencies)) as typeof import("./convertListCommand") & typeof import("./listCommands") &
+ Pick<typeof import("./extend"), "getBuiltinSlashMenuItems"> & {Hint: new () => import("./index").Hint};
+ const bindings = new Proxy({}, {get: () => ({custom: ""})});
+ window.siyuan = {config: {keymap: {editor: {insert: bindings, heading: bindings}}}, languages: {list: "Unordered list", "ordered-list": "Ordered list", check: "Task list",
+ convertCurrentList: "Convert current list to ${name}", cancelCurrentList: "Cancel current list",
+ createList: "Create ${name}", insertChildList: "Insert sublist: ${name}"}} as any;
+ const make = (subtype: string, nested = false) => {
+ const marker = subtype === "u" ? "-" : subtype === "o" ? "1." : "- [x]";
+ editor.innerHTML = lute.Md2BlockDOM(`${marker} first\n${marker} command\n - child\n 1. grandchild\n${marker} last`);
+ const paragraph = Array.from(editor.querySelectorAll<HTMLElement>(".p")).find(item =>
+ item.firstElementChild.textContent.trim() === (nested ? "child" : "command"));
+ check.ok(paragraph, editor.innerHTML);
+ paragraph.firstElementChild.textContent = "before /convert after";
+ paragraph.setAttribute("custom-avs", "database-id");
+ const range = document.createRange();
+ range.setStart(paragraph.firstElementChild.firstChild, 7);
+ range.setEnd(paragraph.firstElementChild.firstChild, 15);
+ const protyle = {wysiwyg: {element: editor}, toolbar: {range}, lute, options: {upload: {}}, block: {parentID: "document"}} as IProtyle;
+ return {protyle, range, paragraph};
+ };
+ const apply = (items: IOperation[]) => {
+ for (const item of items) {
+ const element = editor.querySelector(`[data-node-id="${item.id}"]`);
+ check.ok(item.action === "update");
+ element.outerHTML = item.data;
+ }
+ editor.querySelectorAll("wbr").forEach(item => item.remove());
+ };
+ for (const subtype of ["u", "o", "t"]) {
+ for (const target of ["u", "o", "t"]) {
+ if (subtype === target) {
+ continue;
+ }
+ for (const nested of [false, true]) {
+ const {protyle, range, paragraph} = make(subtype, nested);
+ const context = api.getSlashListContext(protyle);
+ if (nested && context.subtype === target) {
+ continue;
+ }
+ const listID = context.listElement.dataset.nodeId;
+ const paragraphID = paragraph.dataset.nodeId;
+ const child = context.listElement.querySelector<HTMLElement>(".list");
+ const childID = child.dataset.nodeId;
+ const childHTML = child.outerHTML;
+ const outerType = editor.firstElementChild.getAttribute("data-subtype");
+ const originalHTML = editor.innerHTML;
+ const undoContext = {undoFocusId: paragraphID, undoFocusStart: "15", undoFocusEnd: "15"};
+ operations.length = 0;
+ await api.convertListCommand(protyle, `convert-current-list:${target}`, range, undoContext);
+ check.equal(operations.length, 1);
+ check.equal(editor.querySelector(`[data-node-id="${paragraphID}"]`).textContent.replace(/\u200b/g, ""), "before after");
+ check.equal(normalize(editor.querySelector(`[data-node-id="${childID}"]`).outerHTML), normalize(childHTML));
+ check.ok(operations[0].undoOperations.some(operation => operation.context === undoContext));
+ const converted = editor.querySelector(`[data-node-id="${listID}"]`);
+ check.equal(converted.getAttribute("data-subtype"), target);
+ check.ok(Array.from(converted.children).filter(item => item.classList.contains("li"))
+ .every(item => item.getAttribute("data-subtype") === target));
+ if (nested) {
+ check.equal(editor.firstElementChild.getAttribute("data-subtype"), outerType);
+ }
+ const convertedHTML = editor.innerHTML;
+ apply(operations[0].undoOperations);
+ check.equal(normalize(editor.innerHTML), normalize(originalHTML), `${subtype}/${target}/${nested}: undo`);
+ apply(operations[0].doOperations);
+ check.equal(normalize(editor.innerHTML), normalize(convertedHTML), `${subtype}/${target}/${nested}: redo`);
+ }
+ }
+ }
+ for (const nested of [false, true]) {
+ const {protyle: current, range, paragraph} = make("u", nested);
+ const list = api.getSlashListContext(current).listElement;
+ const original = paragraph.outerHTML;
+ operations.length = 0;
+ removedList = undefined;
+ await api.convertListCommand(current, "convert-current-list:remove", range);
+ check.equal(removedList, list);
+ check.equal(operations[0].undoOperations[0].data, original);
+ const cleanup = operations[0].doOperations[0];
+ check.ok(cleanup.action === "update");
+ check.ok(!cleanup.data.includes("/convert"));
+ }
+ for (const scenario of ["same", "invalid", "disabled", "readonly", "publish", "lite", "fragment", "embed", "table", "zoom", "outside", "cross-block"]) {
+ const {protyle, range, paragraph} = make("u");
+ let value = "convert-current-list:o";
+ if (scenario === "same") { value = "convert-current-list:u"; }
+ if (scenario === "invalid") { value = "convert-current-list:bad"; }
+ if (scenario === "disabled") { protyle.disabled = true; }
+ if (scenario === "readonly") { window.siyuan.config.readonly = true; }
+ if (scenario === "publish") { window.siyuan.isPublish = true; }
+ if (scenario === "lite") { protyle.lite = true; }
+ if (scenario === "fragment") { fragment = true; }
+ if (scenario === "embed") { paragraph.classList.add("protyle-wysiwyg__embed"); }
+ if (scenario === "table") {
+ const cell = document.createElement("td");
+ paragraph.before(cell);
+ cell.append(paragraph);
+ }
+ if (scenario === "zoom") { editor.replaceChildren(paragraph.parentElement); }
+ if (scenario === "outside") { document.body.append(paragraph); }
+ if (scenario === "cross-block") {
+ range.setEnd(editor.querySelector(".li:last-of-type .p") || editor.lastElementChild, 0);
+ }
+ const originalHTML = editor.innerHTML;
+ operations.length = 0;
+ await api.convertListCommand(protyle, value, range);
+ check.equal(operations.length, 0, scenario);
+ check.equal(editor.innerHTML, originalHTML, scenario);
+ fragment = false;
+ window.siyuan.config.readonly = false;
+ window.siyuan.isPublish = false;
+ }
+ const {protyle} = make("u");
+ check.equal(api.getListInsertLabel(protyle, "Ordered list"), "Insert sublist: Ordered list");
+ check.equal(api.getListCommandLabel("o"), "Convert current list to Ordered list");
+ const menu = api.getBuiltinSlashMenuItems(protyle);
+ check.deepEqual(menu.filter(item => item.value.startsWith("convert-current-list:")).map(item => item.id),
+ ["convertCurrentListOL", "convertCurrentListTL", "cancelCurrentList"]);
+ check.ok(menu.find(item => item.id === "orderedList").html.includes("Insert sublist: Ordered list"));
+ protyle.disabled = true;
+ check.equal(api.getBuiltinSlashMenuItems(protyle).filter(item => item.value.startsWith("convert-current-list:")).length, 0);
+ for (const mobile of [false, true]) {
+ const {protyle: current, range, paragraph} = make("u");
+ const hint = new api.Hint();
+ Object.assign(hint, {source: "hint", splitChar: "/", lastIndex: 7});
+ range.collapse(false);
+ dependencies.focusByRange(range);
+ operations.length = 0;
+ if (mobile) {
+ hint.fillCommand("convert-current-list:o", current, false);
+ } else {
+ hint.element = document.createElement("div");
+ hint.element.innerHTML = '<button class="b3-list-item--focus" data-value="convert-current-list%3Ao">Convert</button>';
+ const event = new KeyboardEvent("keydown", {key: "Enter", cancelable: true});
+ hint.select(event, current);
+ check.ok(event.defaultPrevented);
+ }
+ await new Promise(resolve => setTimeout(resolve, 0));
+ check.equal(operations.length, 1);
+ const changed = editor.querySelector(`[data-node-id="${paragraph.dataset.nodeId}"]`);
+ check.equal(changed.firstElementChild.textContent, mobile ? "before /convert after" : "before after");
+ check.equal(changed.closest(".list").getAttribute("data-subtype"), "o");
+ }
+ for (const index of [0, 1, 2]) {
+ for (const text of ["/", "prefix / tail"]) {
+ const {protyle: current} = make("u");
+ const paragraph = editor.querySelectorAll<HTMLElement>(":scope > .list > .li > .p")[index];
+ paragraph.firstElementChild.textContent = text;
+ const range = document.createRange();
+ range.setStart(paragraph.firstElementChild.firstChild, text.indexOf("/"));
+ range.setEnd(paragraph.firstElementChild.firstChild, text.indexOf("/") + 1);
+ current.toolbar.range = range;
+ operations.length = 0;
+ await api.convertListCommand(current, "convert-current-list:t", range);
+ check.equal(operations.length, 1);
+ check.equal(editor.firstElementChild.getAttribute("data-subtype"), "t");
+ check.equal(editor.querySelector(`[data-node-id="${paragraph.dataset.nodeId}"]`).firstElementChild.textContent,
+ text.replace("/", ""));
+ }
+ }
+ return "List command DOM cases passed";
+};
+
+test("slash list conversion preserves sibling scope, nested lists, command text and undo/redo", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const extract = (filename: string, names?: string[]) => {
+ const full = path.join(__dirname, filename);
+ const parsed = createSourceFile(full, readFileSync(full, "utf8"), ScriptTarget.Latest, true);
+ return parsed.statements.filter(statement => !isImportDeclaration(statement) && (!names ||
+ isVariableStatement(statement) && statement.declarationList.declarations.some(item => names.includes(item.name.getText(parsed)))))
+ .map(statement => statement.getText(parsed).replace(/^export /, "")).join("\n");
+ };
+ const source = transpileModule([
+ extract("../util/hasClosest.ts"), extract("../wysiwyg/listContext.ts"), extract("listCommands.ts"),
+ extract("../wysiwyg/transaction.ts", ["turnsOneInto"]),
+ extract("convertListCommand.ts"),
+ extract("extend.ts", ["getHotkeyAccelerator", "getHotkeyOrMarker", "genSlashMenuEntryHTML", "getBuiltinSlashMenuItems"]),
+ (() => {
+ const parsed = createSourceFile("index.ts", readFileSync(path.join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest, true);
+ const declaration = parsed.statements.find(isClassDeclaration);
+ return `class Hint {${declaration.members.filter(member =>
+ ["fillCommand", "fill", "select", "consumeRefBracketClose"].includes(member.name?.getText(parsed)))
+ .map(member => member.getText(parsed)).join("\n")}}`;
+ })(),
+ ].join("\n"), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-list-command-test-"));
+ const script = path.join(temporary, "run.cjs");
+ const expression = `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(path.resolve("stage/protyle/js/lute/lute.min.js"))})`;
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("about:blank");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(expression)}));
+ 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, timeout: 40000, windowsHide: true});
+ assert.match(result.stdout, /List command DOM cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));
+ assert.ok(path.basename(temporary).startsWith("siyuan-list-command-test-"));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/protyle/hint/convertListCommand.ts b/app/src/protyle/hint/convertListCommand.ts
new file mode 100644
index 0000000000..a981e84a16
--- /dev/null
+++ b/app/src/protyle/hint/convertListCommand.ts
@@ -0,0 +1,37 @@
+import {getListCommandType, getSlashListContext} from "./listCommands";
+import {hasClosestBlock} from "../util/hasClosest";
+import {removeListStructure, turnsOneInto, updateTransaction} from "../wysiwyg/transaction";
+import {getUndoFocusContext} from "../util/selection";
+
+export const convertListCommand = async (protyle: IProtyle, value: string, range: Range,
+ undoContext?: Record<string, string>) => {
+ const context = getSlashListContext(protyle, range);
+ const type = context && getListCommandType(context.subtype, value);
+ if (!type) {
+ return;
+ }
+ const node = hasClosestBlock(range.startContainer);
+ if (!node) {
+ return;
+ }
+ const id = node.getAttribute("data-node-id");
+ const html = node.outerHTML;
+ range.deleteContents();
+ range.insertNode(document.createElement("wbr"));
+ if (type === "CancelList") {
+ const focusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
+ // 先保存命令清理,再由内核读取完整列表并校验属性和数据库关联。
+ updateTransaction(protyle, node, html, undoContext);
+ await removeListStructure(protyle, [context.listElement], false, focusContext);
+ return;
+ }
+ // 命令清理与列表转换共用一个事务,撤销同时恢复命令文本及原光标位置。
+ await turnsOneInto({
+ protyle,
+ nodeElement: context.listElement,
+ id: context.listElement.dataset.nodeId,
+ type,
+ undoElement: {id, html},
+ undoContext,
+ });
+};
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index c9b3f6041e..8bbc806648 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -59,6 +59,7 @@ import {
import {countBlockWord} from "../../layout/status";
import {genTemplateDocTreePlanHTML} from "../../template/docTree";
import {getDailyNoteHints} from "./dailyNote";
+import {getListCommandLabel, getListCommandType, getListInsertLabel, getSlashListContext} from "./listCommands";
const slashBuiltinStyleIDs: Partial<Record<string, TBuiltinInlineStyleID>> = {
infoStyle: "info",
@@ -209,26 +210,46 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {
hotkey: window.siyuan.config.keymap.editor.heading.heading6.custom,
marker: "###### ",
}, {
- filter: [window.siyuan.languages.list, "unordered list", "无序列表", "wuxvliebiao", "wuxuliebiao", "wxlb"],
+ filter: [getListInsertLabel(protyle, window.siyuan.languages.list), window.siyuan.languages.list, "unordered list", "无序列表", "wuxvliebiao", "wuxuliebiao", "wxlb"],
id: "list",
value: "- " + Lute.Caret,
icon: "iconList",
hotkey: window.siyuan.config.keymap.editor.insert.list.custom,
marker: "- ",
}, {
- filter: [window.siyuan.languages["ordered-list"], "order list", "ordered list", "有序列表", "youxvliebiao", "youxuliebiao", "yxlb"],
+ filter: [getListInsertLabel(protyle, window.siyuan.languages["ordered-list"]), window.siyuan.languages["ordered-list"], "order list", "ordered list", "有序列表", "youxvliebiao", "youxuliebiao", "yxlb"],
id: "orderedList",
value: "1. " + Lute.Caret,
icon: "iconOrderedList",
hotkey: window.siyuan.config.keymap.editor.insert["ordered-list"].custom,
marker: "1. ",
}, {
- filter: [window.siyuan.languages.check, "task list", "todo list", "任务列表", "renwuliebiao", "rwlb"],
+ filter: [getListInsertLabel(protyle, window.siyuan.languages.check), window.siyuan.languages.check, "task list", "todo list", "任务列表", "renwuliebiao", "rwlb"],
id: "check",
value: "- [ ] " + Lute.Caret,
icon: "iconCheck",
hotkey: window.siyuan.config.keymap.editor.insert.check.custom,
marker: "[]",
+ }, {
+ filter: [getListCommandLabel("u"), "convert list", "转换列表", "zhuanhuanliebiao", "zhlb"],
+ id: "convertCurrentListUL",
+ value: "convert-current-list:u",
+ icon: "iconList",
+ }, {
+ filter: [getListCommandLabel("o"), "convert list", "转换列表", "zhuanhuanliebiao", "zhlb"],
+ id: "convertCurrentListOL",
+ value: "convert-current-list:o",
+ icon: "iconOrderedList",
+ }, {
+ filter: [getListCommandLabel("t"), "convert list", "转换列表", "zhuanhuanliebiao", "zhlb"],
+ id: "convertCurrentListTL",
+ value: "convert-current-list:t",
+ icon: "iconCheck",
+ }, {
+ filter: [getListCommandLabel("remove"), "remove list", "cancel list", "取消列表", "quxiaoliebiao", "qxlb"],
+ id: "cancelCurrentList",
+ value: "convert-current-list:remove",
+ icon: "iconParagraph",
}, {
filter: [window.siyuan.languages.quote, "blockquote", "bq", "引述", "yinshu", "ys"],
id: "quote",
@@ -560,7 +581,9 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {
id: "separator_6",
html: "separator",
}];
- return items.map((item) => "html" in item ? item : {
+ const listContext = getSlashListContext(protyle);
+ return items.filter(item => !item.value.startsWith("convert-current-list:") ||
+ listContext && getListCommandType(listContext.subtype, item.value)).map((item) => "html" in item ? item : {
filter: item.filter,
id: item.id,
value: item.value,
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index a4ebdd5d5d..c2bb480af2 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -21,6 +21,7 @@ import {focusByRange, getSelectionOffset} from "../util/selectionOffsets";
import {genHintItemHTML, hintEmbed, hintRef, hintSlash, hintTag} from "./extend";
import {searchRef} from "./searchRef";
import {getSlashEntryKey, TSlashMenuItem} from "./slashMenu";
+import {convertListCommand} from "./convertListCommand";
import {getFrequentSlashItems, recordSlashExecution} from "./frequentSlashStorage";
import {escapeAttr} from "../../util/escape";
import {createDailyNoteReference} from "./dailyNote";
@@ -1316,6 +1317,9 @@ ${genHintItemHTML(item)}
this.enableExtend = true;
this.render(protyle);
}
+ } else if (value.startsWith("convert-current-list:")) {
+ void convertListCommand(protyle, value, range, undoContext);
+ return;
} else if (value === "((" || value === "{{") {
this.enableExtend = true;
if (value === "((") {
diff --git a/app/src/protyle/hint/listCommands.ts b/app/src/protyle/hint/listCommands.ts
new file mode 100644
index 0000000000..8f9a231e10
--- /dev/null
+++ b/app/src/protyle/hint/listCommands.ts
@@ -0,0 +1,50 @@
+import {hasClosestBlock} from "../util/hasClosest";
+import {getListContext, getListConversionType, TListSubtype} from "../wysiwyg/listContext";
+import {isProtyleListItemFragment} from "../runtimeCapabilities";
+import {Constants} from "../../constants";
+
+export const LIST_COMMAND_PREFIX = "convert-current-list:";
+
+export const getSlashListContext = (protyle: IProtyle, range = protyle.toolbar.range) => {
+ if (!range || protyle.disabled || protyle.lite || window.siyuan.config.readonly || window.siyuan.isPublish ||
+ isProtyleListItemFragment(protyle)) {
+ return;
+ }
+ const node = hasClosestBlock(range.startContainer) as HTMLElement;
+ if (!node || !node.isConnected || hasClosestBlock(range.endContainer) !== node ||
+ node.closest(".protyle-wysiwyg") !== protyle.wysiwyg.element ||
+ node.closest(".protyle-wysiwyg__embed, td, th")) {
+ return;
+ }
+ const context = getListContext(node, protyle.wysiwyg.element);
+ if (context?.listElement &&
+ context.listElement.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) !== "1" &&
+ context.listElement.contains(range.endContainer)) {
+ return context;
+ }
+};
+
+export const getListCommandType = (subtype: TListSubtype, value: string) => {
+ const target = value.substring(LIST_COMMAND_PREFIX.length);
+ if (!value.startsWith(LIST_COMMAND_PREFIX)) {
+ return;
+ }
+ if (target === "remove") {
+ return "CancelList";
+ }
+ if (target === "u" || target === "o" || target === "t") {
+ return getListConversionType(subtype, target);
+ }
+};
+
+export const getListCommandLabel = (type: "u" | "o" | "t" | "remove") => {
+ const lang = window.siyuan.languages;
+ return type === "remove" ? lang.cancelCurrentList :
+ lang.convertCurrentList.replace("${name}", lang[type === "u" ? "list" : type === "o" ? "ordered-list" : "check"]);
+};
+
+export const getListInsertLabel = (protyle: IProtyle, name: string) => {
+ const node = protyle.toolbar.range && hasClosestBlock(protyle.toolbar.range.startContainer);
+ const inList = node && getListContext(node as HTMLElement, protyle.wysiwyg.element);
+ return window.siyuan.languages[inList ? "insertChildList" : "createList"].replace("${name}", name);
+};
diff --git a/app/src/protyle/wysiwyg/listConversion.test.ts b/app/src/protyle/wysiwyg/listConversion.test.ts
index 1257e2e989..4ff61d6ce0 100644
--- a/app/src/protyle/wysiwyg/listConversion.test.ts
+++ b/app/src/protyle/wysiwyg/listConversion.test.ts
@@ -108,3 +108,20 @@ test("conversion refresh repairs deleted zoom targets and leaves other views unf
refresh(protyle, {rootIDs: ["document"], removedIDs: [], focusID: "paragraph"});
assert.deepEqual(calls, ["reload"]);
});
+
+test("slash list removal restores the command caret after reload and falls back when it is unavailable", () => {
+ for (const restored of [false, true]) {
+ const calls: string[] = [];
+ const context = {undoFocusId: "paragraph", undoFocusStart: "7", undoFocusEnd: "7"};
+ const protyle = {block: {rootID: "document"}, wysiwyg: {element: {querySelector: () => "paragraph"}}} as unknown as IProtyle;
+ const refresh = new Function("reloadProtyle", "focusBlock", "restoreFocusContext", extract("refreshListConversion") + "\nreturn refreshListConversion;")(
+ (_protyle: IProtyle, _focus: boolean, _readonly: boolean, callback: () => void) => callback(),
+ () => calls.push("fallback"), (_protyle: IProtyle, value: unknown) => {
+ assert.equal(value, context);
+ calls.push("restore");
+ return restored;
+ });
+ refresh(protyle, {rootIDs: ["document"], removedIDs: [], focusID: "paragraph"}, true, context);
+ assert.deepEqual(calls, restored ? ["restore"] : ["restore", "fallback"]);
+ }
+});
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 58e6d430de..f45443ec72 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -9,6 +9,7 @@ import {
focusSideBlock,
getEditorRange,
getUndoFocusContext,
+ restoreFocusContext,
restoreUndoFocus
} from "../util/selection";
import {
@@ -2172,10 +2173,12 @@ const unfoldListHeadings = async (protyle: IProtyle, nodeElements: Element[]) =>
return foldOperations.reverse();
};
-export const removeListStructure = (protyle: IProtyle, nodeElements: Element[], recursively = false) =>
- turnListBlocksInto({protyle, recursively}, nodeElements.filter(isListHeadingContainer));
+export const removeListStructure = (protyle: IProtyle, nodeElements: Element[], recursively = false,
+ focusContext?: Record<string, string>) =>
+ turnListBlocksInto({protyle, recursively, focusContext}, nodeElements.filter(isListHeadingContainer));
-const refreshListConversion = (protyle: IProtyle, result: TransactionListConversionResult, focus = false) => {
+const refreshListConversion = (protyle: IProtyle, result: TransactionListConversionResult, focus = false,
+ focusContext?: Record<string, string>) => {
if (!result?.rootIDs?.length) {
return;
}
@@ -2187,6 +2190,9 @@ const refreshListConversion = (protyle: IProtyle, result: TransactionListConvers
protyle.block.parentID = protyle.block.rootID;
}
reloadProtyle(protyle, false, undefined, () => {
+ if (focus && focusContext && restoreFocusContext(protyle, focusContext)) {
+ return;
+ }
if (focus && result.focusID) {
const element = protyle.wysiwyg.element.querySelector(`[data-node-id="${result.focusID}"]`);
if (element) {
@@ -2209,6 +2215,7 @@ const turnListBlocksInto = async (options: {
range?: Range,
unfocus?: boolean,
recursively?: boolean,
+ focusContext?: Record<string, string>,
}, elements: Element[]) => {
const protyle = options.protyle;
const selected = elements.filter(element => !elements.some(parent => parent !== element && parent.contains(element)));
@@ -2239,7 +2246,7 @@ const turnListBlocksInto = async (options: {
operation.retData.rootIDs.forEach(rootID => markMirror(rootID, {canUndo: true, canRedo: false}));
protyle.updated = true;
hideElements(["select", "gutter"], protyle);
- refreshListConversion(protyle, operation.retData, !options.unfocus);
+ refreshListConversion(protyle, operation.retData, !options.unfocus, options.focusContext);
refreshUndoButtons(protyle);
});
};
@@ -2340,6 +2347,7 @@ export const turnsOneInto = async (options: {
id: string,
html: string,
},
+ undoContext?: Record<string, string>,
additionalOperations?: {
doOperations: IOperation[],
undoOperations: IOperation[],
@@ -2491,7 +2499,7 @@ export const turnsOneInto = async (options: {
const undoFoldOperations = foldOperations.map((operation) => ({...operation}));
transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));
} else {
- updateTransaction(options.protyle, options.nodeElement, oldHTML);
+ updateTransaction(options.protyle, options.nodeElement, oldHTML, options.undoContext);
}
focusByWbr(options.protyle.wysiwyg.element, getEditorRange(options.protyle.wysiwyg.element));
options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {