Skip to content

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

:sparkles: Improve mobile table interactions https://github.com/siyuan-note/siyuan/issues/20635

Daniel591e6df612c0
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index d324dfa014..88e8c7257d 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "تحديد نطاق خلايا",
+ "tableSelectionDone": "تم",
"listMindmapConnectors": "خطوط التوصيل",
"listMindmapDefaultConnectorStyle": "نمط التوصيل الافتراضي للخرائط الجديدة",
"listMindmapConnectorStyle": "نمط خطوط الربط",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index a0ff45c79d..e35590b6f8 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Zellbereich auswählen",
+ "tableSelectionDone": "Fertig",
"listMindmapConnectors": "Verbindungslinien",
"listMindmapDefaultConnectorStyle": "Standard-Verbindungsstil für neue Mindmaps",
"listMindmapConnectorStyle": "Linienstil",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index fe36a6a17c..0f2ad963a1 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Select cell range",
+ "tableSelectionDone": "Done",
"listMindmapConnectors": "Connectors",
"listMindmapDefaultConnectorStyle": "Default connector style for new maps",
"listMindmapConnectorStyle": "Connector style",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index e433463677..b2002cdae8 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Seleccionar rango de celdas",
+ "tableSelectionDone": "Listo",
"listMindmapConnectors": "Conectores",
"listMindmapDefaultConnectorStyle": "Estilo de conexión predeterminado para mapas nuevos",
"listMindmapConnectorStyle": "Estilo de conexión",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 9bd398d4bf..f0b445bbd2 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Sélectionner une plage de cellules",
+ "tableSelectionDone": "Terminé",
"listMindmapConnectors": "Connecteurs",
"listMindmapDefaultConnectorStyle": "Style de connexion par défaut des nouvelles cartes",
"listMindmapConnectorStyle": "Style des connexions",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 0f04be1ff7..2930255fc1 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "בחירת טווח תאים",
+ "tableSelectionDone": "סיום",
"listMindmapConnectors": "קווי חיבור",
"listMindmapDefaultConnectorStyle": "סגנון חיבור ברירת מחדל למפות חדשות",
"listMindmapConnectorStyle": "סגנון קווי חיבור",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 72b3c67c46..284d3f106f 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "सेल श्रेणी चुनें",
+ "tableSelectionDone": "पूर्ण",
"listMindmapConnectors": "कनेक्टर",
"listMindmapDefaultConnectorStyle": "नए मानचित्रों के लिए डिफ़ॉल्ट कनेक्टर शैली",
"listMindmapConnectorStyle": "जोड़ने वाली रेखा की शैली",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 549b9c12b2..30a9848c12 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Pilih rentang sel",
+ "tableSelectionDone": "Selesai",
"listMindmapConnectors": "Penghubung",
"listMindmapDefaultConnectorStyle": "Gaya penghubung bawaan untuk peta baru",
"listMindmapConnectorStyle": "Gaya garis penghubung",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 46c4dbceca..f68826b4f8 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Seleziona intervallo di celle",
+ "tableSelectionDone": "Fine",
"listMindmapConnectors": "Collegamenti",
"listMindmapDefaultConnectorStyle": "Stile dei collegamenti predefinito per le nuove mappe",
"listMindmapConnectorStyle": "Stile dei collegamenti",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index eb8947ae6b..0c7de2c227 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "セル範囲を選択",
+ "tableSelectionDone": "完了",
"listMindmapConnectors": "接続線",
"listMindmapDefaultConnectorStyle": "新規マップの既定の接続線スタイル",
"listMindmapConnectorStyle": "接続線のスタイル",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 6f47111a2e..dffc0b7f36 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "셀 범위 선택",
+ "tableSelectionDone": "완료",
"listMindmapConnectors": "연결선",
"listMindmapDefaultConnectorStyle": "새 지도의 기본 연결선 스타일",
"listMindmapConnectorStyle": "연결선 스타일",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index ac4f5c79f8..efecd6e5ba 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Celbereik selecteren",
+ "tableSelectionDone": "Gereed",
"listMindmapConnectors": "Verbindingslijnen",
"listMindmapDefaultConnectorStyle": "Standaard verbindingsstijl voor nieuwe mindmaps",
"listMindmapConnectorStyle": "Verbindingsstijl",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 0f98320550..69ab61e0e6 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Wybierz zakres komórek",
+ "tableSelectionDone": "Gotowe",
"listMindmapConnectors": "Łączniki",
"listMindmapDefaultConnectorStyle": "Domyślny styl połączeń nowych map",
"listMindmapConnectorStyle": "Styl połączeń",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 5f76462683..7dc4b69891 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Selecionar intervalo de células",
+ "tableSelectionDone": "Concluído",
"listMindmapConnectors": "Conectores",
"listMindmapDefaultConnectorStyle": "Estilo de conexão padrão para novos mapas",
"listMindmapConnectorStyle": "Estilo das conexões",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 2930d3be3e..511aa8aa65 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Выбрать диапазон ячеек",
+ "tableSelectionDone": "Готово",
"listMindmapConnectors": "Соединительные линии",
"listMindmapDefaultConnectorStyle": "Стиль соединений по умолчанию для новых карт",
"listMindmapConnectorStyle": "Стиль соединительных линий",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 678620caa4..2ef344a284 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Vybrať rozsah buniek",
+ "tableSelectionDone": "Hotovo",
"listMindmapConnectors": "Spojnice",
"listMindmapDefaultConnectorStyle": "Predvolený štýl spojníc pre nové mapy",
"listMindmapConnectorStyle": "Štýl spojníc",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 1387d1fd00..78feac1693 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Изабери опсег ћелија",
+ "tableSelectionDone": "Готово",
"listMindmapConnectors": "Линије повезивања",
"listMindmapDefaultConnectorStyle": "Подразумевани стил веза за нове мапе",
"listMindmapConnectorStyle": "Стил спојних линија",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 489b61b3ed..33fce3f199 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "เลือกช่วงเซลล์",
+ "tableSelectionDone": "เสร็จสิ้น",
"listMindmapConnectors": "เส้นเชื่อม",
"listMindmapDefaultConnectorStyle": "รูปแบบเส้นเชื่อมเริ่มต้นสำหรับแผนผังใหม่",
"listMindmapConnectorStyle": "รูปแบบเส้นเชื่อม",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 7bd9cd1f31..9c0c8bc7ad 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Hücre aralığı seç",
+ "tableSelectionDone": "Bitti",
"listMindmapConnectors": "Bağlantı çizgileri",
"listMindmapDefaultConnectorStyle": "Yeni haritalar için varsayılan bağlantı stili",
"listMindmapConnectorStyle": "Bağlantı çizgisi stili",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index feb0346eba..23b985a1b9 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "Вибрати діапазон клітинок",
+ "tableSelectionDone": "Готово",
"listMindmapConnectors": "З’єднувальні лінії",
"listMindmapDefaultConnectorStyle": "Типовий стиль з’єднань для нових карт",
"listMindmapConnectorStyle": "Стиль сполучних ліній",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 5927d344a8..39f91c03a5 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "选择区域",
+ "tableSelectionDone": "完成",
"listMindmapConnectors": "连线",
"listMindmapDefaultConnectorStyle": "新建默认连线样式",
"listMindmapConnectorStyle": "连线样式",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 3c2dacbe3c..b76cbf5296 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "tableSelectRange": "選取區域",
+ "tableSelectionDone": "完成",
"listMindmapConnectors": "連線",
"listMindmapDefaultConnectorStyle": "新建預設連線樣式",
"listMindmapConnectorStyle": "連線樣式",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
index ed6ed60b2e..a87213ba3a 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
@@ -6,7 +6,7 @@
"id": "20200924101225-k254i8g",
"title": "Content Block Type",
"type": "doc",
- "updated": "20261016202856"
+ "updated": "20261017142635"
},
"Children": [
{
@@ -1938,6 +1938,48 @@
}
]
},
+ {
+ "ID": "20261017142635-7s38p0k",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-7s38p0k",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "On mobile, tap a cell to edit its text. Use the selection button beside the cell or the block menu in the keyboard toolbar to select a cell range. Drag either corner handle to expand or shrink the selection; dragging near the viewport edge scrolls the table. Swiping cell content still scrolls, and holding text still selects text."
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-d2uc99x",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-d2uc99x",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Tap a handle above a column or beside a row to select that column or row. Enable Multi-select in the bottom toolbar to add or remove nonadjacent cells, rows, or columns. Use More to merge cells, set styles and alignment, or operate on selected rows and columns. Tap Done to leave selection mode."
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-wrzqg7l",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-wrzqg7l",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Drag the column-width handle to change a column's width. Select columns and use More to auto-fit their widths or distribute them evenly. Tap the plus controls at the table edges to add rows or columns, or drag the edge controls to add several at once or remove trailing empty rows and columns. Shrinking preserves nonempty content and merged cells."
+ }
+ ]
+ },
{
"ID": "20250330191912-6gqtj5b",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
index dc48fadf35..ee9649173f 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
@@ -6,7 +6,7 @@
"id": "20200905090211-2vixtlf",
"title": "内容块类型",
"type": "doc",
- "updated": "20261016111305"
+ "updated": "20261017142635"
},
"Children": [
{
@@ -1978,6 +1978,48 @@
}
]
},
+ {
+ "ID": "20261017142635-4dbby6c",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-4dbby6c",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "移动端点击单元格可编辑文字,通过单元格旁的选择按钮或键盘工具栏的块菜单进入区域选择。拖动选区的两个角点手柄可扩大或缩小范围,拖到视口边缘可自动滚动表格。滑动单元格内容仍用于滚动,长按文字仍用于选字。"
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-bcg68ni",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-bcg68ni",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "点击列上方或行左侧的手柄可选中整列或整行。在底部工具栏开启「多选」后,可点选增减不连续的单元格、行或列。通过「更多」可合并单元格、设置样式和对齐,或批量操作所选行列;点击「完成」退出选择。"
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-oe1mo6v",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-oe1mo6v",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "拖动列宽手柄可调整列宽,选中列后可通过「更多」按内容自适应或均分列宽。点击表格边缘的加号可添加行列,拖动边缘控件可批量增加行列或移除末尾的空白行列。收缩表格时会保留非空内容和合并单元格。"
+ }
+ ]
+ },
{
"ID": "20250330183345-n3cc5zy",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
index 8a5a5b4239..16240a8871 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
@@ -6,7 +6,7 @@
"id": "20211226120147-ib6yy3i",
"title": "內容區塊類型",
"type": "doc",
- "updated": "20261016111305"
+ "updated": "20261017142635"
},
"Children": [
{
@@ -1965,6 +1965,48 @@
}
]
},
+ {
+ "ID": "20261017142635-6swexeg",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-6swexeg",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "行動端點選儲存格可編輯文字,透過儲存格旁的選取按鈕或鍵盤工具列的區塊選單進入區域選取。拖曳選取範圍的兩個角點控點可擴大或縮小範圍,拖到可視區域邊緣可自動捲動表格。滑動儲存格內容仍用於捲動,長按文字仍用於選字。"
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-qpn3xky",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-qpn3xky",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "點選欄上方或列左側的控點可選取整欄或整列。在底部工具列開啟「多選」後,可點選增減不連續的儲存格、列或欄。透過「更多」可合併儲存格、設定樣式和對齊,或批次操作所選列欄;點選「完成」退出選取。"
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-5ds55er",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-5ds55er",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "拖曳欄寬控點可調整欄寬,選取欄後可透過「更多」依內容自動調整或平均分配欄寬。點選表格邊緣的加號可新增列欄,拖曳邊緣控制項可批次新增列欄或移除末尾的空白列欄。縮小表格時會保留非空內容和合併儲存格。"
+ }
+ ]
+ },
{
"ID": "20250330183637-4bl34no",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
index 7d309be25d..79697afb7b 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-35bbvcx",
"title": "コンテンツブロックの種類",
"type": "doc",
- "updated": "20261016202856"
+ "updated": "20261017142635"
},
"Children": [
{
@@ -1996,6 +1996,48 @@
}
]
},
+ {
+ "ID": "20261017142635-kll3m6b",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-kll3m6b",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "モバイル端末ではセルをタップして文字を編集できます。セルの横にある選択ボタン、またはキーボードツールバーのブロックメニューからセル範囲の選択に入ります。選択範囲の両端のハンドルをドラッグして範囲を変更でき、画面の端までドラッグすると表が自動的にスクロールします。セル内をスワイプするとスクロールし、文字を長押しすると文字を選択できます。"
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-udb0p1z",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-udb0p1z",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "列の上または行の左にあるハンドルをタップすると、列全体または行全体を選択できます。下部ツールバーで複数選択を有効にすると、離れたセル、行、列をタップして選択に追加したり、選択から外したりできます。「詳細」からセルの結合、スタイルや配置の設定、選択した行や列の一括操作を行えます。「完了」をタップすると選択を終了します。"
+ }
+ ]
+ },
+ {
+ "ID": "20261017142635-99sm3ym",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261017142635-99sm3ym",
+ "updated": "20261017142635"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "列幅のハンドルをドラッグすると列幅を変更できます。列を選択して「詳細」を開くと、内容に合わせて列幅を自動調整したり、均等に配分したりできます。表の端のプラスボタンをタップすると行や列を追加できます。端のコントロールをドラッグすると複数の行や列を追加したり、末尾の空の行や列を削除したりできます。表を縮めても、内容のあるセルや結合セルは保持されます。"
+ }
+ ]
+ },
{
"ID": "20250330192102-eq3j7o6",
"Type": "NodeHeading",
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scss
index d90297ce12..7d934c3a29 100644
--- a/app/src/assets/scss/protyle/_protyle.scss
+++ b/app/src/assets/scss/protyle/_protyle.scss
@@ -1246,6 +1246,12 @@ table + .protyle-action__table {
}
}
+html[data-frontend="mobile"] .protyle-wysiwyg [data-type="NodeTable"] > div:first-child,
+html[data-frontend="browser-mobile"] .protyle-wysiwyg [data-type="NodeTable"] > div:first-child {
+ padding-top: 16px;
+ padding-left: 16px;
+}
+
.protyle-table-control {
position: fixed;
inset: 0;
@@ -1433,6 +1439,55 @@ table + .protyle-action__table {
background-color: var(--b3-theme-primary);
pointer-events: none;
}
+
+ &--touch {
+ > .protyle-table-control__handle,
+ > .protyle-table-control__add {
+ display: none;
+ }
+ }
+
+ &__touch-button,
+ &__endpoint {
+ position: fixed;
+ z-index: 3;
+ width: 28px;
+ height: 28px;
+ justify-content: center;
+ transform: translate(-50%, -50%);
+ pointer-events: auto;
+ touch-action: none;
+ }
+
+ &__endpoint {
+ z-index: 4;
+
+ &::before {
+ content: "";
+ width: 12px;
+ height: 12px;
+ background-color: var(--b3-theme-primary);
+ border: 2px solid var(--b3-theme-background);
+ border-radius: 50%;
+ }
+ }
+
+ &__toolbar {
+ position: fixed;
+ left: 8px;
+ right: 8px;
+ bottom: max(8px, env(safe-area-inset-bottom));
+ z-index: 5;
+ display: flex;
+ align-items: center;
+ justify-content: space-around;
+ gap: 4px;
+ padding: 8px;
+ background-color: var(--b3-theme-background);
+ border-radius: var(--b3-border-radius);
+ box-shadow: var(--b3-point-shadow);
+ pointer-events: auto;
+ }
}
.image-ocr {
display: flex;
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 9d907c00da..f20615befd 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -90,7 +90,7 @@ import {getFrequentSlashButtons, mountLiteSlashMenu, prependFrequentSlashButtons
import {getPluginSlashEntryKey, SLASH_MENU_ROOT_PATH} from "../../config/entryVisibility/catalog";
import {hintSlash} from "../../protyle/hint/extend";
import {getFrequentSlashItems} from "../../protyle/hint/frequentSlashStorage";
-import {getTableCellRichContext} from "../../protyle/util/tableCellRichContext";
+import {finishTableCellEditing, getTableCellRichContext, prepareTableCellMenuItems} from "../../protyle/util/tableCellRichContext";
import {insertEmptyBlock} from "../../block/util";
import {getIconByType} from "../../editor/getIcon";
import {MOBILE_TOOLBAR_ACTION_NAMES, MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS} from "./toolbarActions";
@@ -1376,6 +1376,7 @@ const updateVideoMaxHeight = () => {
};
export const initKeyboardToolbar = () => {
+ window.addEventListener("siyuan-mobile-table-action", () => activeBlur(true));
window.addEventListener("siyuan-mobile-toolbar-focus", renderKeyboardToolbar);
window.addEventListener("siyuan-mobile-toolbar-editor", (event: CustomEvent<IProtyle>) => {
if (event.detail) {
@@ -1940,14 +1941,38 @@ export const initKeyboardToolbar = () => {
keyboardPanelClosing = false;
hideKeyboardToolbarUtil();
if (!protyle.gutter && getTableCellRichContext(protyle)) {
- const {MenuItem} = await import("../../menus/Menu");
+ const [{MenuItem}, {tableMenu}] = await Promise.all([
+ import("../../menus/Menu"), import("../../menus/protyle"),
+ ]);
if (!session.isCurrent()) {
return;
}
if (!nodeElement.isConnected || protyle.disabled || !getTableCellRichContext(protyle)) {
return;
}
+ const context = getTableCellRichContext(protyle);
+ const table = context.cell.closest('[data-type="NodeTable"]');
+ const tableRange = document.createRange();
+ tableRange.selectNodeContents(context.cell);
+ tableRange.collapse(true);
+ const tableMenus = tableMenu(context.owner, table, context.cell, tableRange, true).menus;
+ prepareTableCellMenuItems(tableMenus, () => finishTableCellEditing(context.cell));
window.siyuan.menus.menu.remove();
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "tableSelectRange",
+ icon: "iconSelect",
+ label: window.siyuan.languages.tableSelectRange,
+ click: () => {
+ context.owner.wysiwyg.tableControl?.startTouchSelection(context.cell);
+ },
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "table",
+ icon: "iconTable",
+ label: window.siyuan.languages.table,
+ submenu: tableMenus,
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
window.siyuan.menus.menu.append(new MenuItem({
id: "insertBefore",
icon: "iconBefore",
diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.ts
index 35f7640cad..4514bc4ca4 100644
--- a/app/src/protyle/render/tableCellInput.test.ts
+++ b/app/src/protyle/render/tableCellInput.test.ts
@@ -355,7 +355,7 @@ const browserCases = async (source: string, queueSource: string, editorSource: s
owner.selectElement = document.createElement("div");
owner.toolbar.isMultiSelectMode = absent;
const selectedRanges: HTMLTableCellElement[][] = [];
- owner.wysiwyg.tableControl = {setHidden: noop, clear: noop, selectCellRange: (...cells: HTMLTableCellElement[]) => {
+ owner.wysiwyg.tableControl = {setHidden: noop, clear: noop, hasTouchSelection: absent, selectCellRange: (...cells: HTMLTableCellElement[]) => {
selectedRanges.push(cells);
return true;
}} as unknown as IProtyle["wysiwyg"]["tableControl"];
diff --git a/app/src/protyle/util/tableCellRichContext.ts b/app/src/protyle/util/tableCellRichContext.ts
index 3c6a3cd8ed..e9867f96cd 100644
--- a/app/src/protyle/util/tableCellRichContext.ts
+++ b/app/src/protyle/util/tableCellRichContext.ts
@@ -1,6 +1,7 @@
type TableCellContext = {owner: IProtyle, cell: HTMLTableCellElement, finish: () => void};
const contexts = new WeakMap<IProtyle, TableCellContext>();
+const cellContexts = new WeakMap<HTMLTableCellElement, TableCellContext>();
const forwardedEventTargets = new WeakMap<Event, HTMLElement>();
export const setTableCellRichEventTarget = (event: Event, host: HTMLElement) => {
@@ -22,6 +23,13 @@ export const getTableCellRichSelectionHost = (selection: Selection) => {
export const setTableCellRichContext = (protyle: IProtyle, context: TableCellContext) => {
contexts.set(protyle, context);
+ cellContexts.set(context.cell, context);
+};
+
+// 结构和选区操作必须先提交单元格;组合输入尚未结束时保留编辑器和原始内容。
+export const finishTableCellEditing = (cell: HTMLTableCellElement) => {
+ cellContexts.get(cell)?.finish();
+ return cell.isConnected && !cell.querySelector(".table__cell-editor");
};
export const getTableCellRichContext = (protyle: IProtyle) => {
@@ -30,12 +38,14 @@ export const getTableCellRichContext = (protyle: IProtyle) => {
};
// 菜单展示期间保留文字选区,执行表格操作前再提交单元格内容。
-export const prepareTableCellMenuItems = (items: IMenu[], prepare: () => void) => {
+export const prepareTableCellMenuItems = (items: IMenu[], prepare: () => boolean | void) => {
items.forEach(item => {
if (item.click) {
const click = item.click;
item.click = (...args) => {
- prepare();
+ if (prepare() === false) {
+ return;
+ }
return click(...args);
};
}
@@ -44,12 +54,18 @@ export const prepareTableCellMenuItems = (items: IMenu[], prepare: () => void) =
item.bind = element => {
element.addEventListener("click", event => {
if (!(event.target instanceof HTMLInputElement)) {
- prepare();
+ if (prepare() === false) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
}
}, {capture: true});
element.addEventListener("keydown", event => {
if (event.key === "Enter" && !event.isComposing) {
- prepare();
+ if (prepare() === false) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
}
}, {capture: true});
bind(element);
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
index b57e22df5b..1d0d0e5864 100644
--- a/app/src/protyle/util/tableControl.ts
+++ b/app/src/protyle/util/tableControl.ts
@@ -1,11 +1,11 @@
import {toggleMenu} from "../../menus/menuToggle";
import {MenuItem} from "../../menus/Menu";
import {getTableGridRect, TableGridCache} from "./tableGridCache";
-import {getVirtualTableGrid, setTableVirtualSelection, TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";
+import {getVirtualTableGrid, restoreTableVirtualizationDOM, setTableVirtualSelection, TABLE_VIRTUAL_ID, TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";
import {clearTableCellContent, getTableCellPlainText, mergeTableCellContents} from "./tableCellRich";
import {renderTableCellRichElements} from "../render/tableCellRich";
import {updateTransaction} from "../wysiwyg/transaction";
-import {copyPlainText, encodeBase64, isMac, readClipboard} from "./compatibility";
+import {copyPlainText, encodeBase64, isMac, readClipboard, writeClipboardData} from "./compatibility";
import {removeZWJ} from "./normalizeText";
import {paste} from "./paste";
import {getEditorRange, getUndoFocusContext} from "./selection";
@@ -47,6 +47,11 @@ import {
} from "../toolbar/inlineStyle";
import {escapeAttr} from "../../util/escape";
import {getTextWithoutSemanticMarkers} from "./inlineElementMarker";
+import {isMobile} from "../../util/functions";
+import {TableTouchControl, type ITableTouchState} from "./tableTouch";
+import {finishTableCellEditing} from "./tableCellRichContext";
+import {buildBlockDOMClipboardRichData} from "./blockDOMClipboard";
+import {showMessage} from "../../dialog/message";
type TableSelectionMode = "row" | "column" | "cell";
type TableAddControlType = "add-row" | "add-column" | "add-both";
@@ -360,6 +365,9 @@ export class TableControl {
private pinnedTableResizeObserver: ResizeObserver;
private pinnedTableActions = new Map<HTMLTableElement, HTMLElement>();
private abortController = new AbortController();
+ private touch: TableTouchControl;
+ private dragCleanup?: () => void;
+ private columnResizeCleanup?: () => void;
constructor(protyle: IProtyle, wysiwygElement: HTMLElement) {
this.protyle = protyle;
@@ -397,11 +405,38 @@ export class TableControl {
this.dropIndicator = this.element.querySelector(".protyle-table-control__drop");
protyle.element.append(this.element);
this.bindEvents();
+ if (isMobile()) {
+ this.touch = new TableTouchControl(wysiwygElement, this.element, () => protyle.contentElement || protyle.element, {
+ state: () => this.getTouchState(),
+ select: (cell, mode, toggle, extend) => this.startTouchSelection(cell, mode, toggle, extend),
+ range: (anchor, active) => this.selectCellRange(anchor, active),
+ drag: (event, cell, mode, handle) => this.startRowColumnDrag(event, mode, handle.getBoundingClientRect()),
+ resize: (event, cell, type) => {
+ if (protyle.disabled || !finishTableCellEditing(cell)) {
+ return;
+ }
+ this.blurTouchEditor();
+ this.hoverCell = cell;
+ this.startResize(event, type);
+ },
+ add: (cell, type) => {
+ if (!protyle.disabled && !this.suppressAddClick && finishTableCellEditing(cell)) {
+ this.hoverCell = cell;
+ this.addAtEnd(type);
+ }
+ },
+ width: (event, cell, column) => this.startColumnResize(event, cell, column),
+ menu: () => this.openMenu(0, 0),
+ copy: () => this.execClipboardCommand("copy"),
+ clear: () => this.clearCells(),
+ finish: () => this.clear(),
+ render: () => this.scheduleRender(),
+ });
+ }
this.pinnedTableResizeObserver = new ResizeObserver(() => this.scheduleRender());
this.observer = new MutationObserver(mutations => {
if (this.resizeState && !this.resizeState.node.isConnected) {
- this.resizeState = undefined;
- this.resizeLabel.classList.add("fn__none");
+ this.cancelResize();
}
if (this.selection && (!this.selection.node.isConnected || !this.selection.activeCell.isConnected)) {
this.clear();
@@ -447,6 +482,9 @@ export class TableControl {
}
public destroy() {
+ this.touch?.destroy();
+ this.dragCleanup?.();
+ this.columnResizeCleanup?.();
this.cancelResize();
this.abortController.abort();
this.observer.disconnect();
@@ -459,6 +497,9 @@ export class TableControl {
}
public clear() {
+ this.touch?.reset();
+ this.dragCleanup?.();
+ this.columnResizeCleanup?.();
if (this.selection) {
setTableVirtualSelection(this.selection.table);
}
@@ -476,6 +517,133 @@ export class TableControl {
this.scheduleRender();
}
+ public startTouchSelection(cell: HTMLTableCellElement, mode: TableSelectionMode = "cell", toggle = false,
+ extend = false) {
+ if (!this.touch || this.protyle.disabled || cell?.closest(".protyle-wysiwyg") !== this.wysiwygElement ||
+ !getTableNode(cell) || !finishTableCellEditing(cell)) {
+ return false;
+ }
+ restoreTableVirtualizationDOM(cell.closest("table"));
+ const entering = !this.selection;
+ this.caretCell = cell;
+ this.selectFromCell(mode, cell, toggle, extend);
+ if (entering) {
+ this.blurTouchEditor();
+ }
+ return true;
+ }
+
+ private blurTouchEditor() {
+ (document.activeElement as HTMLElement)?.blur();
+ window.dispatchEvent(new Event("siyuan-mobile-table-action"));
+ }
+
+ public hasTouchSelection() {
+ return !!this.touch && !!this.selection;
+ }
+
+ private getTouchState(): ITableTouchState | undefined {
+ const cell = this.selection?.activeCell || this.caretCell || this.hoverCell;
+ const node = getTableNode(cell);
+ if (this.protyle.disabled || !cell?.isConnected || !node || !this.wysiwygElement.contains(cell) ||
+ this.protyle.element.closest(".fn__none, [inert]")) {
+ return;
+ }
+ const table = cell.closest("table");
+ const viewport = this.getTableGridViewportRect(table);
+ const visualViewport = window.visualViewport;
+ viewport.left = Math.max(viewport.left, visualViewport?.offsetLeft || 0);
+ viewport.right = Math.min(viewport.right, window.innerWidth);
+ viewport.top = Math.max(viewport.top, visualViewport?.offsetTop || 0);
+ viewport.bottom = Math.min(viewport.bottom, (visualViewport?.height || window.innerHeight) +
+ (visualViewport?.offsetTop || 0), window.innerHeight - (this.selection ? 64 : 0));
+ return {cell, table, viewport, grid: this.selectionGrid || this.gridCache.get(table).grid,
+ selection: this.selection ? {
+ mode: this.selection.mode,
+ cells: this.getSelectedCells(),
+ indexes: this.selection.indexes,
+ rectangle: this.isRectangle(),
+ } : undefined};
+ }
+
+ private startColumnResize(event: PointerEvent, cell: HTMLTableCellElement, index: number) {
+ if (event.button !== 0 || this.protyle.disabled || !finishTableCellEditing(cell)) {
+ return;
+ }
+ const node = getTableNode(cell);
+ const table = cell.closest("table");
+ restoreTableVirtualizationDOM(table);
+ const column = table.querySelectorAll<HTMLTableColElement>(":scope > colgroup > col")[index];
+ if (!node || !column) {
+ return;
+ }
+ this.columnResizeCleanup?.();
+ const oldHTML = node.outerHTML;
+ const oldStyle = column.getAttribute("style");
+ const cells = buildTableGrid(table).cellInfos.filter(info => info.col === index)
+ .map(info => ({cell: info.cell, style: info.cell.getAttribute("style")}));
+ const width = this.getColumnRect(table, buildTableGrid(table), index)?.width || TABLE_DEFAULT_COLUMN_WIDTH;
+ const start = event.clientX;
+ this.blurTouchEditor();
+ const controller = new AbortController();
+ const restore = () => {
+ if (oldStyle === null) {
+ column.removeAttribute("style");
+ } else {
+ column.setAttribute("style", oldStyle);
+ }
+ cells.forEach(({cell: target, style}) => {
+ if (style === null) {
+ target.removeAttribute("style");
+ } else {
+ target.setAttribute("style", style);
+ }
+ });
+ };
+ const cleanup = () => {
+ controller.abort();
+ this.columnResizeCleanup = undefined;
+ this.resizeLabel.classList.add("fn__none");
+ };
+ this.columnResizeCleanup = () => {
+ restore();
+ cleanup();
+ };
+ document.addEventListener("pointermove", move => {
+ if (move.pointerId !== event.pointerId) {
+ return;
+ }
+ move.preventDefault();
+ const nextWidth = Math.max(TABLE_DEFAULT_COLUMN_WIDTH, Math.round(width + move.clientX - start));
+ column.style.width = `${nextWidth}px`;
+ column.style.removeProperty("min-width");
+ cells.forEach(({cell: target}) => target.style.removeProperty("width"));
+ this.resizeLabel.textContent = `${nextWidth}px`;
+ this.setPosition(this.resizeLabel, move.clientX + 12, move.clientY + 12);
+ this.resizeLabel.classList.remove("fn__none");
+ }, {signal: controller.signal, passive: false});
+ const end = (up: PointerEvent) => {
+ if (up.pointerId !== event.pointerId) {
+ return;
+ }
+ if (up.type === "pointercancel") {
+ restore();
+ } else if (node.outerHTML !== oldHTML) {
+ updateTransaction(this.protyle, node, oldHTML);
+ }
+ cleanup();
+ this.scheduleRender();
+ };
+ document.addEventListener("pointerup", end, {signal: controller.signal});
+ document.addEventListener("pointercancel", end, {signal: controller.signal});
+ window.addEventListener("blur", () => this.columnResizeCleanup?.(), {signal: controller.signal});
+ document.addEventListener("visibilitychange", () => {
+ if (document.hidden) {
+ this.columnResizeCleanup?.();
+ }
+ }, {signal: controller.signal});
+ }
+
public setHidden(hidden: boolean) {
this.element.classList.toggle("fn__none", hidden);
if (!hidden) {
@@ -540,6 +708,9 @@ export class TableControl {
this.scheduleRender();
}, {signal});
this.wysiwygElement.addEventListener("pointerdown", event => {
+ if (this.touch) {
+ return;
+ }
if (event.button === 0 && !(event.ctrlKey && isMac()) &&
!(event.target as Element).closest(".protyle-table-control")) {
this.clear();
@@ -670,8 +841,16 @@ export class TableControl {
top: event.deltaY,
});
}, {passive: false, signal});
- this.element.addEventListener("pointerdown", event => this.handlePointerDown(event), {signal});
- this.element.addEventListener("click", event => this.handleClick(event), {signal});
+ this.element.addEventListener("pointerdown", event => {
+ if (!this.touch) {
+ this.handlePointerDown(event);
+ }
+ }, {signal});
+ this.element.addEventListener("click", event => {
+ if (!this.touch) {
+ this.handleClick(event);
+ }
+ }, {signal});
this.element.addEventListener("contextmenu", event => {
const type = (event.target as Element).closest<HTMLElement>("[data-type]")?.dataset.type;
const cell = this.getControlCell(type);
@@ -760,7 +939,7 @@ export class TableControl {
}
private handleTablePointerMove(event: PointerEvent, fromControl: boolean) {
- if (event.buttons !== 0) {
+ if (this.touch || event.buttons !== 0) {
return;
}
const eventCell = getCell(event.target);
@@ -828,7 +1007,11 @@ export class TableControl {
return;
}
this.selectFromCell(type, cell, isPrimaryModifier(event), event.shiftKey);
- if (!this.selection) {
+ this.startRowColumnDrag(event, type, (type === "row" ? this.rowHandle : this.columnHandle).getBoundingClientRect());
+ }
+
+ private startRowColumnDrag(event: PointerEvent, type: "row" | "column", handleRect: DOMRect) {
+ if (this.protyle.disabled || !this.selection) {
return;
}
const grid = buildTableGrid(this.selection.table);
@@ -836,7 +1019,7 @@ export class TableControl {
(type === "row" && this.selection.indexes.size > 1 && this.selection.indexes.has(0))) {
return;
}
- const handleRect = (type === "row" ? this.rowHandle : this.columnHandle).getBoundingClientRect();
+ this.dragCleanup?.();
this.dragState = {
mode: type,
startX: event.clientX,
@@ -848,14 +1031,43 @@ export class TableControl {
handleSize: type === "row" ? handleRect.height : handleRect.width,
cellInfos: new Map(grid.cellInfos.map(info => [info.cell, info])),
};
- const move = (moveEvent: PointerEvent) => this.handleDragMove(moveEvent);
+ const move = (moveEvent: PointerEvent) => {
+ if (moveEvent.pointerId === event.pointerId) {
+ moveEvent.preventDefault();
+ this.handleDragMove(moveEvent);
+ }
+ };
const up = (upEvent: PointerEvent) => {
+ if (upEvent.pointerId !== event.pointerId) {
+ return;
+ }
+ this.dragCleanup?.();
+ if (upEvent.type === "pointercancel") {
+ this.dragState = undefined;
+ this.clearDragPreview();
+ this.dropIndicator.classList.add("fn__none");
+ } else {
+ this.handleDragEnd(upEvent);
+ }
+ this.scheduleRender();
+ };
+ const cancel = () => {
+ this.dragCleanup?.();
+ this.dragState = undefined;
+ this.clearDragPreview();
+ this.dropIndicator.classList.add("fn__none");
+ };
+ this.dragCleanup = () => {
document.removeEventListener("pointermove", move);
document.removeEventListener("pointerup", up);
- this.handleDragEnd(upEvent);
+ document.removeEventListener("pointercancel", up);
+ window.removeEventListener("blur", cancel);
+ this.dragCleanup = undefined;
};
- document.addEventListener("pointermove", move);
+ document.addEventListener("pointermove", move, {passive: false});
document.addEventListener("pointerup", up);
+ document.addEventListener("pointercancel", up);
+ window.addEventListener("blur", cancel);
}
private handleClick(event: MouseEvent) {
@@ -1340,6 +1552,7 @@ export class TableControl {
private render() {
this.renderPinnedTableFrames();
+ this.touch?.render();
if (this.resizeState?.dragging && this.resizeState.table.isConnected) {
this.renderResize();
return;
@@ -1357,8 +1570,10 @@ export class TableControl {
item.classList.add("fn__none");
item.classList.remove("protyle-table-control__add--active");
});
- this.resizeLabel.classList.add("fn__none");
- if (visible) {
+ if (!this.columnResizeCleanup) {
+ this.resizeLabel.classList.add("fn__none");
+ }
+ if (visible && !this.touch) {
const gridRect = getTableGridRect(table);
const addColumnEdge = gridRect.right;
const viewportRect = this.getTableGridViewportRect(table, gridRect);
@@ -1431,7 +1646,7 @@ export class TableControl {
rowControlCenter);
}
}
- if (!this.dragState && !this.selection && caretCell && getTableNode(caretCell) && !this.protyle.disabled) {
+ if (!this.touch && !this.dragState && !this.selection && caretCell && getTableNode(caretCell) && !this.protyle.disabled) {
const table = caretCell.closest("table") as HTMLTableElement;
const viewportRect = table ? this.getTableGridViewportRect(table) : undefined;
if (viewportRect) {
@@ -1492,7 +1707,7 @@ export class TableControl {
const bottom = Math.max(...rects.map(rect => rect.bottom));
const rect = {left, top, right, bottom, width: right - left, height: bottom - top};
this.appendSelectionRect(rect, selectionViewportRect, selectionGridRect);
- if (!this.dragState) {
+ if (!this.touch && !this.dragState) {
this.positionCellHandle(rect, selectionViewportRect);
}
}
@@ -1500,7 +1715,7 @@ export class TableControl {
this.getSelectedCells().forEach(item => {
this.appendSelectionRect(item.getBoundingClientRect(), selectionViewportRect, selectionGridRect);
});
- if (!this.dragState && this.selection.mode === "cell") {
+ if (!this.touch && !this.dragState && this.selection.mode === "cell") {
this.positionCellHandle(this.selection.activeCell.getBoundingClientRect(), selectionViewportRect);
}
}
@@ -1520,6 +1735,17 @@ export class TableControl {
const merged = buildTableGrid(this.selection.table).cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);
const mergedSelection = this.selection.mode !== "cell" && merged;
const rectangle = this.selection.mode !== "cell" || this.isRectangle();
+ if (this.touch) {
+ menu.append(new MenuItem({
+ id: "tableSelectAll",
+ icon: "iconSelectAll",
+ label: window.siyuan.languages.selectAll,
+ click: () => {
+ const grid = buildTableGrid(this.selection.table);
+ this.selectCellRange(grid.grid[0][0], grid.grid[grid.rowCount - 1][grid.columnCount - 1]);
+ },
+ }).element);
+ }
menu.append(new MenuItem({
icon: "iconCopy",
label: window.siyuan.languages.copy,
@@ -1643,7 +1869,7 @@ export class TableControl {
}).element);
}
}
- session.show(() => menu.popup({x, y}));
+ session.show(() => this.touch ? menu.fullscreen() : menu.popup({x, y}));
},
});
@@ -1813,6 +2039,10 @@ export class TableControl {
}
private execClipboardCommand(command: "copy" | "cut") {
+ if (this.touch) {
+ void this.writeTouchClipboard(command === "cut");
+ return;
+ }
if (!this.selection?.activeCell.isConnected) {
return;
}
@@ -1824,6 +2054,10 @@ export class TableControl {
}
private copySelectionAsRichText() {
+ if (this.touch) {
+ void this.writeTouchClipboard(false, true);
+ return;
+ }
const cells = this.getSelectedCells();
const first = cells[0];
const last = cells[cells.length - 1];
@@ -1848,15 +2082,25 @@ export class TableControl {
return;
}
const cell = this.getSelectedCells()[0] || this.selection.activeCell;
+ const selection = this.selection;
+ const cells = this.getSelectedCells();
+ const oldHTML = selection.node.outerHTML;
const range = getEditorRange(cell);
range.selectNodeContents(cell);
range.collapse(true);
focusByRange(range);
- if (document.queryCommandSupported("paste")) {
+ if (!this.touch && document.queryCommandSupported("paste")) {
document.execCommand("paste");
} else {
try {
const text = await readClipboard();
+ if (this.touch && (!cell.isConnected || this.protyle.disabled || this.selection !== selection ||
+ selection.node.outerHTML !== oldHTML || !this.hasSameSelectedCells(cells))) {
+ return;
+ }
+ if (this.touch) {
+ focusByRange(range);
+ }
paste(this.protyle, Object.assign(text, {target: cell}));
} catch (error) {
console.log(error);
@@ -1864,6 +2108,33 @@ export class TableControl {
}
}
+ private async writeTouchClipboard(cut = false, richText = false) {
+ const selection = this.selection;
+ const content = this.getSelectionClipboardContent();
+ if (!selection || !content || cut && (this.protyle.disabled || !this.canMutateSelection())) {
+ return;
+ }
+ const oldHTML = selection.node.outerHTML;
+ const cells = this.getSelectedCells();
+ const rich = buildBlockDOMClipboardRichData(this.protyle.lute, content.textSiyuan);
+ const result = await writeClipboardData({textPlain: content.text, textHTML: rich.textHTML,
+ textSiyuan: richText ? undefined : rich.textSiyuan}, {fallbackToPlainText: !cut});
+ if (result.status === "failed") {
+ showMessage(window.siyuan.languages.clipboardPermissionDenied, 7000, "error");
+ return;
+ }
+ // 等待剪贴板授权期间选区或内容可能变化,只有原始快照仍有效时才执行剪切。
+ if (cut && this.selection === selection && selection.node.isConnected &&
+ selection.node.outerHTML === oldHTML && !this.protyle.disabled && this.hasSameSelectedCells(cells)) {
+ this.deleteSelection(true);
+ }
+ }
+
+ private hasSameSelectedCells(cells: HTMLTableCellElement[]) {
+ const current = this.getSelectedCells();
+ return cells.length === current.length && cells.every((cell, index) => cell === current[index]);
+ }
+
private appendCellMenus(rectangle: boolean) {
const cells = this.getSelectedCells();
this.appendAlignmentMenu();
@@ -1932,7 +2203,7 @@ export class TableControl {
}
private setCellStyle(property: string, value: string) {
- if (!this.selection) {
+ if (this.protyle.disabled || !this.selection) {
return;
}
setTableCellStyle(this.protyle, this.selection.node, this.getSelectedCells(), property, value);
@@ -1940,7 +2211,7 @@ export class TableControl {
}
private setSelectedColumnWidth(minWidth?: number) {
- if (!this.selection || this.selection.mode !== "column") {
+ if (this.protyle.disabled || !this.selection || this.selection.mode !== "column") {
return;
}
const oldHTML = this.selection.node.outerHTML;
@@ -1962,7 +2233,7 @@ export class TableControl {
}
private distributeSelectedColumnWidths() {
- if (!this.selection || this.selection.mode !== "column") {
+ if (this.protyle.disabled || !this.selection || this.selection.mode !== "column") {
return;
}
const columns = this.getSelectedColumns();
@@ -1994,7 +2265,7 @@ export class TableControl {
}
private clearCells() {
- if (!this.selection) {
+ if (this.protyle.disabled || !this.selection) {
return;
}
const oldHTML = this.selection.node.outerHTML;
@@ -2029,7 +2300,7 @@ export class TableControl {
}
private deleteSelection(clearOnly: boolean) {
- if (!this.selection || (this.selection.mode === "cell" && !this.isRectangle())) {
+ if (this.protyle.disabled || !this.selection || (this.selection.mode === "cell" && !this.isRectangle())) {
return;
}
if (clearOnly && this.selection.mode === "cell") {
@@ -2058,7 +2329,7 @@ export class TableControl {
}
private duplicateRowsOrColumns() {
- if (!this.selection || this.selection.mode === "cell" || !this.canMutateSelection()) {
+ if (this.protyle.disabled || !this.selection || this.selection.mode === "cell" || !this.canMutateSelection()) {
return;
}
const selection = this.selection;
@@ -2135,7 +2406,7 @@ export class TableControl {
}
private mergeCells() {
- if (!this.selection || !this.isRectangle()) {
+ if (this.protyle.disabled || !this.selection || !this.isRectangle() || !this.isSelectionInOneSection()) {
return;
}
const grid = buildTableGrid(this.selection.table);
@@ -2166,7 +2437,8 @@ export class TableControl {
}
public splitCell(cell: HTMLTableCellElement) {
- if (!this.wysiwygElement.contains(cell) || !this.selectCellRange(cell, cell)) {
+ if (this.protyle.disabled || this.touch && !finishTableCellEditing(cell) ||
+ !this.wysiwygElement.contains(cell) || !this.selectCellRange(cell, cell)) {
return;
}
const grid = buildTableGrid(this.selection.table);
@@ -2303,10 +2575,13 @@ export class TableControl {
document.removeEventListener("pointermove", move);
document.removeEventListener("pointerup", up);
document.removeEventListener("pointercancel", cancel);
+ window.removeEventListener("blur", blur);
};
+ const blur = () => this.cancelResize();
document.addEventListener("pointermove", move);
document.addEventListener("pointerup", up);
document.addEventListener("pointercancel", cancel);
+ window.addEventListener("blur", blur);
}
private handleResizeMove(event: PointerEvent) {
diff --git a/app/src/protyle/util/tableTouch.test.ts b/app/src/protyle/util/tableTouch.test.ts
new file mode 100644
index 0000000000..f16307b61b
--- /dev/null
+++ b/app/src/protyle/util/tableTouch.test.ts
@@ -0,0 +1,394 @@
+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 {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (sources: Record<string, string>) => {
+ const check: typeof assert = require("node:assert/strict");
+ const nodePath: typeof path = require("node:path");
+ const noop = () => {};
+ const transactions: {before: string, after: string}[] = [];
+ const clipboard: {textPlain: string, textHTML?: string}[] = [];
+ const items: IMenu[] = [];
+ let mobile = true;
+ let clipboardFailure = false;
+ let clipboardWait: Promise<void> | undefined;
+ const menuElement = document.createElement("div");
+ menuElement.id = "commonMenu";
+ document.body.append(menuElement);
+ const menu = {element: menuElement, append: (element: HTMLElement) => menuElement.append(element),
+ remove: () => { items.length = 0; menuElement.replaceChildren(); }, fullscreen: noop, popup: noop};
+ const languages = new Proxy({}, {get: (_target, key: string) => key === "insertRowBefore" ||
+ key === "insertRowAfter" || key === "insertColumnLeft1" || key === "insertColumnRight1" ? "${x}" : key});
+ const hotkeys = new Proxy({}, {get: () => ({custom: ""})});
+ Object.assign(window, {Lute: {NewNodeID: () => "20261017120000-newnode", Caret: ""},
+ siyuan: {languages, menus: {menu}, config: {editor: {fontSize: 16},
+ keymap: {editor: {general: hotkeys, table: hotkeys, insert: hotkeys}}}}});
+ const focusByRange = (range: Range) => {
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ };
+ const getEditorRange = (element: HTMLElement) => {
+ const selection = getSelection();
+ if (selection.rangeCount && element.contains(selection.anchorNode)) {
+ return selection.getRangeAt(0);
+ }
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ range.collapse(true);
+ return range;
+ };
+ const constants = new Proxy<Record<string, string>>({ZWSP: "\u200b"}, {get: (target, key: string) => target[key] || key});
+ const stubs: Record<string, object | (() => object)> = {
+ "src/constants.ts": {Constants: constants},
+ "src/menus/menuToggle.ts": {toggleMenu: (options: {build: (menu: object, session: object) => void}) => {
+ menu.remove();
+ options.build(menu, {show: (show: () => void) => show()});
+ }},
+ "src/menus/Menu.ts": {MenuItem: class {
+ element = document.createElement("button");
+ constructor(item: IMenu) {
+ items.push(item);
+ this.element.innerHTML = item.label || "";
+ item.bind?.(this.element);
+ this.element.addEventListener("click", () => {
+ if (!item.disabled) {
+ item.click?.(this.element, undefined);
+ }
+ });
+ }
+ }},
+ "src/util/functions.ts": {isMobile: () => mobile},
+ "src/util/escape.ts": {escapeAttr: (text: string) => text, escapeHtmlTextAndAttr: (text: string) => text},
+ "src/protyle/wysiwyg/transaction.ts": {updateTransaction: (_protyle: object, node: HTMLElement, before: string) => {
+ transactions.push({before, after: node.outerHTML});
+ }},
+ "src/protyle/util/selection.ts": {getEditorRange, getUndoFocusContext: () => ({}), focusByWbr: (node: HTMLElement) => {
+ node.querySelector("wbr")?.remove();
+ }},
+ "src/protyle/util/selectionOffsets.ts": {focusByRange},
+ "src/protyle/util/compatibility.ts": {isMac: () => false, encodeBase64: (value: string) => Buffer.from(value, "utf8").toString("base64"),
+ copyPlainText: noop, readClipboard: async () => ({textPlain: "pasted"}),
+ writeClipboardData: async (value: {textPlain: string}) => {
+ await clipboardWait;
+ clipboard.push(value);
+ return {status: clipboardFailure ? "failed" : "rich"};
+ }},
+ "src/protyle/util/normalizeText.ts": {removeZWJ: (value: string) => value},
+ "src/protyle/util/inlineElementMarker.ts": {getTextWithoutSemanticMarkers: (node: Node) => node.textContent},
+ "src/protyle/toolbar/tableCell.ts": {getTableCellTextStyleMenus: (): IMenu[] => [], applyTableCellStyleHotkey: () => false},
+ "src/protyle/toolbar/inlineStyle.ts": {getInlineStylesCache: () => ({}), getVisibleOrderedStyleKeys: (): string[] => [],
+ getInlineStyleIDFromValue: () => ""},
+ "src/protyle/util/hotKey.ts": {matchHotKey: () => false},
+ "src/protyle/render/tableCellRich.ts": {renderTableCellRichElements: noop},
+ "src/protyle/util/blockDOMClipboard.ts": {buildBlockDOMClipboardRichData: (_lute: object, html: string) =>
+ ({textHTML: html, textSiyuan: html})},
+ "src/protyle/util/hasClosest.ts": {hasClosestByClassName: (node: Element, name: string) => node?.closest("." + name),
+ hasClosestBlock: (node: Element) => node?.closest("[data-node-id]")},
+ "src/dialog/message.ts": {showMessage: noop},
+ "dayjs": () => ({format: () => "20261017120000"}),
+ };
+ const cache: Record<string, {exports: object}> = {};
+ const load = (id: string): object => {
+ if (stubs[id]) {
+ return stubs[id];
+ }
+ if (cache[id]) {
+ return cache[id].exports;
+ }
+ if (!sources[id]) {
+ return {};
+ }
+ const module = {exports: {}};
+ cache[id] = module;
+ new Function("require", "module", "exports", sources[id])((name: string) => load(name.startsWith(".") ?
+ nodePath.posix.normalize(nodePath.posix.join(nodePath.posix.dirname(id), name + ".ts")) : name), module, module.exports);
+ return module.exports;
+ };
+ const {TableControl} = load("src/protyle/util/tableControl.ts") as typeof import("./tableControl");
+ const context = load("src/protyle/util/tableCellRichContext.ts") as typeof import("./tableCellRichContext");
+ const virtual = load("src/protyle/util/tableVirtualizationDOM.ts") as typeof import("./tableVirtualizationDOM");
+ const tick = () => new Promise(resolve => setTimeout(resolve, 30));
+ const pointer = (target: EventTarget, type: string, x = 0, y = 0, id = 1) => target.dispatchEvent(new PointerEvent(type,
+ {bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0, pointerId: id, pointerType: "touch"}));
+ const fixture = () => {
+ const root = document.createElement("div");
+ const editor = document.createElement("div");
+ root.style.cssText = "position:absolute;left:0;top:0;width:360px;height:500px;overflow:auto";
+ editor.className = "protyle-wysiwyg";
+ editor.innerHTML = '<div data-node-id="20261017120000-tableaa" data-type="NodeTable" class="table"><div style="overflow:auto">' +
+ '<table style="border-collapse:collapse;margin:40px 30px"><colgroup><col style="width:90px"><col style="width:90px"><col style="width:90px"></colgroup>' +
+ "<thead><tr><th>H1</th><th>H2</th><th>H3</th></tr></thead><tbody>" +
+ "<tr><td>A1</td><td>A2</td><td>A3</td></tr><tr><td>B1</td><td>B2</td><td>B3</td></tr>" +
+ '<tr><td></td><td></td><td></td></tr></tbody></table><div class="protyle-action__table"><div class="table__select"></div></div></div></div>';
+ root.append(editor);
+ document.body.append(root);
+ editor.querySelectorAll<HTMLElement>("td, th").forEach(cell => cell.style.height = "42px");
+ const owner = {element: root, contentElement: root, disabled: false, toolbar: {}, options: {},
+ wysiwyg: {element: editor}, lute: {}, block: {rootID: "root"}} as unknown as IProtyle;
+ const core = new TableControl(owner, editor);
+ owner.wysiwyg.tableControl = core;
+ const table = editor.querySelector("table");
+ const cell = (row: number, col: number) => table.rows[row].cells[col];
+ const render = () => Reflect.get(core, "render").call(core);
+ const invoke = (name: string, ...args: unknown[]) => Reflect.get(core, name).apply(core, args);
+ const touch = (selector: string) => root.querySelector<HTMLElement>(".protyle-table-control " + selector);
+ const dispose = () => { core.destroy(); root.remove(); getSelection().removeAllRanges(); };
+ return {root, editor, owner, core, table, cell, render, invoke, touch, dispose};
+ };
+ {
+ const f = fixture();
+ check.equal(f.core.startTouchSelection(f.cell(1, 0)), true);
+ f.render();
+ check.equal(f.touch("[data-action='done']").textContent, "tableSelectionDone");
+ const active = f.core.getSelectedCells()[0];
+ pointer(f.cell(2, 2), "pointerdown", 210, 150);
+ pointer(f.cell(2, 2), "pointermove", 200, 100);
+ pointer(f.cell(2, 2), "pointercancel", 200, 100);
+ check.equal(f.core.getSelectedCells()[0], active, "scroll gestures preserve the selection");
+ f.touch("[data-action='multi']").click();
+ f.cell(2, 2).click();
+ f.render();
+ check.equal(f.core.getSelectedCells().length, 2);
+ check.equal((f.touch("[data-action='copy']") as HTMLButtonElement).disabled, true, "nonrectangular copying stays disabled");
+ f.cell(2, 2).click();
+ check.equal(f.core.getSelectedCells().length, 1);
+ f.touch("[data-action='done']").click();
+ check.equal(f.core.hasTouchSelection(), false);
+ check.equal(f.table.rows.length, 4);
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ f.core.startTouchSelection(f.cell(1, 0));
+ f.render();
+ const endpoint = f.touch("[data-endpoint='end']");
+ const rect = f.cell(2, 1).getBoundingClientRect();
+ pointer(endpoint, "pointerdown", 120, 120);
+ pointer(document, "pointermove", rect.left + rect.width / 2, rect.top + rect.height / 2);
+ pointer(document, "pointerup");
+ check.equal(f.core.getSelectedCells().length, 4, "range endpoints expand a rectangular selection");
+ f.invoke("openMenu", 0, 0);
+ const merge = items.find(item => item.label === "mergeCell");
+ check.equal(merge.disabled, false);
+ merge.click(undefined, undefined);
+ check.equal(f.cell(1, 0).rowSpan, 2);
+ check.equal(f.cell(1, 0).colSpan, 2);
+ check.match(f.cell(1, 0).innerHTML, /A1.*A2.*B1.*B2/);
+ f.core.splitCell(f.cell(1, 0));
+ check.equal(f.cell(1, 0).rowSpan, 1);
+ check.equal(f.table.querySelectorAll(".fn__none").length, 0);
+ f.core.selectCellRange(f.cell(0, 0), f.cell(1, 0));
+ f.invoke("openMenu", 0, 0);
+ check.equal(items.find(item => item.label === "mergeCell").disabled, true, "header and body merging stays disabled");
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ f.core.startTouchSelection(f.cell(1, 0), "row");
+ f.core.startTouchSelection(f.cell(2, 0), "row", false, true);
+ check.equal(f.core.getSelectedCells().length, 6);
+ f.invoke("duplicateRowsOrColumns");
+ check.equal(f.table.rows.length, 6);
+ check.equal(f.table.rows[3].textContent, "A1A2A3");
+ check.equal(f.table.rows[4].textContent, "B1B2B3");
+ f.core.startTouchSelection(f.cell(1, 0), "column");
+ f.core.startTouchSelection(f.cell(1, 2), "column", true);
+ check.equal(f.core.getSelectedCells().length, 12);
+ f.invoke("setSelectedColumnWidth");
+ check.equal(f.table.querySelectorAll("col")[0].getAttribute("style"), null);
+ f.invoke("distributeSelectedColumnWidths");
+ check.equal((f.table.querySelectorAll("col")[0] as HTMLElement).style.width,
+ (f.table.querySelectorAll("col")[2] as HTMLElement).style.width);
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ f.core.startTouchSelection(f.cell(1, 0));
+ f.render();
+ const width = f.touch("[data-action='width']");
+ const before = f.table.querySelector("col").getAttribute("style");
+ const count = transactions.length;
+ pointer(width, "pointerdown", 120, 60);
+ pointer(document, "pointermove", 180, 60);
+ pointer(document, "pointercancel", 180, 60);
+ check.equal(f.table.querySelector("col").getAttribute("style"), before);
+ check.equal(transactions.length, count, "cancelled resizing creates no transaction");
+ f.render();
+ pointer(f.touch("[data-action='width']"), "pointerdown", 120, 60);
+ pointer(document, "pointermove", 180, 60);
+ pointer(document, "pointerup", 180, 60);
+ check.equal((f.table.querySelector("col") as HTMLElement).style.width, "150px");
+ check.equal(transactions.length, count + 1);
+ check.match(transactions.at(-1).before, /width:90px/);
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ f.core.startTouchSelection(f.cell(1, 0));
+ f.render();
+ const initial = f.table.rows.length;
+ const add = f.touch("[data-action='add-row']");
+ pointer(add, "pointerdown", 150, 220);
+ pointer(document, "pointerup", 150, 220);
+ add.click();
+ check.equal(f.table.rows.length, initial + 1);
+ f.core.startTouchSelection(f.cell(1, 0));
+ f.render();
+ pointer(f.touch("[data-action='add-row']"), "pointerdown", 150, 260);
+ pointer(document, "pointermove", 150, 70);
+ pointer(document, "pointerup", 150, 70);
+ check.equal(f.table.rows.length, 3, "shrinking preserves all nonempty rows");
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ f.core.startTouchSelection(f.cell(1, 0), "row");
+ f.render();
+ const handle = f.touch("[data-mode='row'][aria-pressed='true']");
+ const rect = handle.getBoundingClientRect();
+ pointer(handle, "pointerdown", rect.left + rect.width / 2, rect.top + rect.height / 2);
+ pointer(document, "pointermove", rect.left, 490);
+ pointer(document, "pointerup", rect.left, 490);
+ await tick();
+ check.equal(f.table.rows[3].textContent, "A1A2A3", "row drag uses the shared reorder transaction");
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ const cell = f.cell(1, 0);
+ const host = document.createElement("div");
+ host.className = "table__cell-editor";
+ cell.append(host);
+ let composing = true;
+ context.setTableCellRichContext({element: host} as unknown as IProtyle, {cell, owner: f.owner, finish: () => {
+ if (!composing) {
+ host.remove();
+ cell.innerHTML = "committed";
+ }
+ }});
+ check.equal(f.core.startTouchSelection(cell), false);
+ check.equal(cell.contains(host), true, "composition retains the live editor");
+ composing = false;
+ check.equal(f.core.startTouchSelection(cell), true);
+ await f.invoke("writeTouchClipboard");
+ await tick();
+ check.equal(clipboard.at(-1).textPlain, "committed");
+ clipboardFailure = true;
+ f.invoke("execClipboardCommand", "cut");
+ await tick();
+ check.equal(cell.textContent, "committed", "failed clipboard writes preserve source content");
+ clipboardFailure = false;
+ let release: () => void;
+ clipboardWait = new Promise(resolve => { release = resolve; });
+ f.invoke("execClipboardCommand", "cut");
+ cell.textContent = "newer content";
+ release();
+ await tick();
+ check.equal(cell.textContent, "newer content", "clipboard permission delays cannot cut newer content");
+ clipboardWait = undefined;
+ clipboardWait = new Promise(resolve => { release = resolve; });
+ f.invoke("execClipboardCommand", "cut");
+ f.core.startTouchSelection(f.cell(2, 2), "cell", true);
+ release();
+ await tick();
+ check.equal(cell.textContent, "newer content", "changing a selection in place cancels a pending cut");
+ check.equal(f.cell(2, 2).textContent, "B3");
+ clipboardWait = undefined;
+ f.owner.disabled = true;
+ check.equal(f.core.startTouchSelection(f.cell(2, 0)), false);
+ f.invoke("clearCells");
+ check.equal(f.cell(2, 2).textContent, "B3", "disabled editors reject stale toolbar actions");
+ f.dispose();
+ }
+ {
+ const f = fixture();
+ const detached = Array.from(f.table.tBodies[0].rows).slice(1);
+ const placeholder = document.createElement("tr");
+ detached[0].before(placeholder);
+ virtual.cacheTableVirtualizationRows(placeholder, detached);
+ detached.forEach(row => row.remove());
+ f.table.setAttribute(virtual.TABLE_VIRTUAL_ID, "test");
+ check.equal(f.table.rows.length, 3);
+ f.core.startTouchSelection(f.cell(1, 0), "column");
+ check.equal(f.core.getSelectedCells().length, 4, "column selection restores cached source rows");
+ check.equal(f.table.rows.length, 4);
+ check.equal(f.cell(2, 2).textContent, "B3");
+ f.dispose();
+ let ran = false;
+ const item: IMenu = {label: "blocked", click: () => { ran = true; }};
+ context.prepareTableCellMenuItems([item], () => false);
+ item.click(undefined, undefined);
+ check.equal(ran, false, "unfinished composition blocks structural menu actions");
+ }
+ mobile = false;
+ {
+ const f = fixture();
+ check.equal(f.touch(".protyle-table-control__toolbar"), null, "desktop retains its existing controls");
+ f.core.selectCellRange(f.cell(1, 0), f.cell(2, 1));
+ check.equal(f.core.getSelectedCells().length, 4);
+ f.invoke("selectFromCell", "row", f.cell(1, 0), false, false);
+ const before = f.table.textContent;
+ const event = new PointerEvent("pointerdown", {pointerId: 10, button: 0, clientX: 30, clientY: 110});
+ f.invoke("startRowColumnDrag", event, "row", new DOMRect(16, 100, 28, 28));
+ pointer(document, "pointermove", 30, 490, 10);
+ pointer(document, "pointercancel", 30, 490, 10);
+ check.equal(f.table.textContent, before, "desktop drag cancellation preserves row order");
+ f.invoke("startRowColumnDrag", event, "row", new DOMRect(16, 100, 28, 28));
+ pointer(document, "pointermove", 30, 490, 10);
+ pointer(document, "pointerup", 30, 490, 10);
+ await tick();
+ check.equal(f.table.rows[3].textContent, "A1A2A3", "desktop row dragging retains its existing behavior");
+ f.dispose();
+ }
+ menuElement.remove();
+ return "Mobile table interaction cases passed";
+};
+
+test("mobile table selection, editing handoff, operations and gesture cancellation", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const files = ["tableControl", "tableTouch", "table", "tableSelection", "tableResize", "tableColumnWidth", "tableGridCache",
+ "tableCellRich", "tableCellRichValue", "tableCellRichContext", "tableVirtualizationDOM"];
+ const sources = Object.fromEntries(files.map(file => ["src/protyle/util/" + file + ".ts", transpileModule(
+ readFileSync(path.join(__dirname, file + ".ts"), "utf8"),
+ {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022}}).outputText]));
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-touch-test-"));
+ const script = path.join(temporary, "run.cjs");
+ 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, width: 390, height: 640, webPreferences: {
+ nodeIntegration: true, contextIsolation: false, offscreen: true, backgroundThrottling: false,
+ }});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
+ browserCases.toString() + ")(" + JSON.stringify(sources) + ").catch(error => { throw new Error(error.stack || String(error)); })")}));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ 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, /Mobile table interaction cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-table-touch-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/protyle/util/tableTouch.ts b/app/src/protyle/util/tableTouch.ts
new file mode 100644
index 0000000000..71e0b6a600
--- /dev/null
+++ b/app/src/protyle/util/tableTouch.ts
@@ -0,0 +1,375 @@
+import type {ITableGrid} from "./table";
+import {escapeAttr} from "../../util/escape";
+import {TABLE_VIRTUAL_ROWS} from "./tableVirtualizationDOM";
+
+type SelectionMode = "cell" | "row" | "column";
+
+export interface ITableTouchState {
+ cell: HTMLTableCellElement;
+ table: HTMLTableElement;
+ grid: ITableGrid;
+ viewport: {left: number, top: number, right: number, bottom: number};
+ selection?: {
+ mode: SelectionMode;
+ cells: HTMLTableCellElement[];
+ indexes: Set<number>;
+ rectangle: boolean;
+ };
+}
+
+interface ITableTouchActions {
+ state: () => ITableTouchState | undefined;
+ select: (cell: HTMLTableCellElement, mode: SelectionMode, toggle: boolean, extend?: boolean) => boolean;
+ range: (anchor: HTMLTableCellElement, active: HTMLTableCellElement) => void;
+ drag: (event: PointerEvent, cell: HTMLTableCellElement, mode: "row" | "column", handle: HTMLElement) => void;
+ resize: (event: PointerEvent, cell: HTMLTableCellElement, type: "add-row" | "add-column" | "add-both") => void;
+ add: (cell: HTMLTableCellElement, type: "add-row" | "add-column" | "add-both") => void;
+ width: (event: PointerEvent, cell: HTMLTableCellElement, column: number) => void;
+ menu: () => void;
+ copy: () => void;
+ clear: () => void;
+ finish: () => void;
+ render: () => void;
+}
+
+// 触摸层只管理入口和手势,表格修改、合并边界与事务由共享控制器处理。
+export class TableTouchControl {
+ private controls = document.createElement("div");
+ private toolbar = document.createElement("div");
+ private endpoints: HTMLButtonElement[];
+ private multiSelect = false;
+ private controller = new AbortController();
+ private gesture?: AbortController;
+ private scrollFrame: number;
+ private dragging = false;
+
+ constructor(editor: HTMLElement, container: HTMLElement, private content: () => HTMLElement,
+ private actions: ITableTouchActions) {
+ container.classList.add("protyle-table-control--touch");
+ container.dataset.preventSwipe = "true";
+ this.controls.dataset.tableTouchControls = "true";
+ this.toolbar.className = "protyle-table-control__toolbar fn__none";
+ this.toolbar.innerHTML = `<button class="block__icon block__icon--show block__icon--touch" data-action="multi" aria-label="${escapeAttr(window.siyuan.languages.multiSelect)}"><svg><use xlink:href="#iconSelect"></use></svg></button>
+<button class="block__icon block__icon--show block__icon--touch" data-action="copy" aria-label="${escapeAttr(window.siyuan.languages.copy)}"><svg><use xlink:href="#iconCopy"></use></svg></button>
+<button class="block__icon block__icon--show block__icon--touch" data-action="clear" aria-label="${escapeAttr(window.siyuan.languages.clear)}"><svg><use xlink:href="#iconClear"></use></svg></button>
+<button class="block__icon block__icon--show block__icon--touch" data-action="more" aria-label="${escapeAttr(window.siyuan.languages.more)}"><svg><use xlink:href="#iconMore"></use></svg></button>
+<button class="b3-button b3-button--text" data-action="done">${window.siyuan.languages.tableSelectionDone}</button>`;
+ this.toolbar.setAttribute("role", "toolbar");
+ this.toolbar.setAttribute("aria-label", window.siyuan.languages.table);
+ this.endpoints = ["start", "end"].map(endpoint => {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "block__icon block__icon--show protyle-table-control__endpoint fn__none";
+ button.dataset.endpoint = endpoint;
+ button.setAttribute("aria-label", window.siyuan.languages.tableSelectRange);
+ return button;
+ });
+ container.append(this.controls, ...this.endpoints, this.toolbar);
+ const signal = this.controller.signal;
+ this.toolbar.addEventListener("pointerdown", event => event.preventDefault(), {signal});
+ this.toolbar.addEventListener("click", event => {
+ const action = (event.target as Element).closest<HTMLElement>("[data-action]")?.dataset.action;
+ if (action === "multi") {
+ this.multiSelect = !this.multiSelect;
+ this.actions.render();
+ } else if (action === "copy") {
+ this.actions.copy();
+ } else if (action === "clear") {
+ this.actions.clear();
+ } else if (action === "more") {
+ this.actions.menu();
+ } else if (action === "done") {
+ this.actions.finish();
+ }
+ }, {signal});
+ this.endpoints.forEach(button => button.addEventListener("pointerdown", event =>
+ this.startRangeDrag(event, button.dataset.endpoint === "start"), {signal}));
+ // 点击改变选区,滑动内容仍交给浏览器滚动,不在 pointerdown 阶段阻止默认行为。
+ editor.addEventListener("click", event => {
+ const state = this.actions.state();
+ const cell = (event.target as Element).closest<HTMLTableCellElement>("th, td");
+ if (!state?.selection || !cell || cell.closest("table") !== state.table) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ this.actions.select(cell, this.multiSelect ? state.selection.mode : "cell", this.multiSelect);
+ }, {capture: true, signal});
+ window.addEventListener("blur", () => this.cancelGesture(), {signal});
+ document.addEventListener("visibilitychange", () => {
+ if (document.hidden) {
+ this.cancelGesture();
+ }
+ }, {signal});
+ }
+
+ public reset() {
+ this.multiSelect = false;
+ this.cancelGesture();
+ }
+
+ public destroy() {
+ this.reset();
+ this.controller.abort();
+ this.controls.remove();
+ this.toolbar.remove();
+ this.endpoints.forEach(button => button.remove());
+ }
+
+ public render() {
+ const state = this.actions.state();
+ this.toolbar.classList.toggle("fn__none", !state?.selection);
+ const multi = this.toolbar.querySelector('[data-action="multi"]');
+ multi.setAttribute("aria-pressed", String(this.multiSelect));
+ multi.classList.toggle("block__icon--active", this.multiSelect);
+ const copy = this.toolbar.querySelector<HTMLButtonElement>('[data-action="copy"]');
+ copy.disabled = !!state?.selection && state.selection.mode === "cell" && !state.selection.rectangle;
+ if (this.dragging) {
+ this.renderEndpoints(state);
+ return;
+ }
+ this.endpoints.forEach(button => button.classList.add("fn__none"));
+ this.controls.replaceChildren();
+ if (!state || state.viewport.right <= state.viewport.left || state.viewport.bottom <= state.viewport.top) {
+ return;
+ }
+ const {viewport, grid, cell, table, selection} = state;
+ const visibleInfos = grid.cellInfos.filter(info => info.cell.isConnected &&
+ !info.cell.classList.contains("fn__none"));
+ const rows = new Set<number>();
+ const columns = new Set<number>();
+ visibleInfos.forEach(info => {
+ const rect = info.cell.getBoundingClientRect();
+ if (rect.bottom <= viewport.top || rect.top >= viewport.bottom ||
+ rect.right <= viewport.left || rect.left >= viewport.right) {
+ return;
+ }
+ if (!rows.has(info.row)) {
+ rows.add(info.row);
+ const row = this.button(window.siyuan.languages.row, "iconDrag", viewport.left - 14,
+ (Math.max(rect.top, viewport.top) + Math.min(rect.bottom, viewport.bottom)) / 2);
+ row.dataset.mode = "row";
+ row.setAttribute("aria-pressed", String(selection?.mode === "row" && selection.indexes.has(info.row)));
+ row.classList.toggle("block__icon--active", selection?.mode === "row" && selection.indexes.has(info.row));
+ row.addEventListener("pointerdown", event => this.selectHandle(event, info.cell, "row", row));
+ }
+ // 列控件只按逻辑列创建一次,支持没有表头的表格。
+ if (!columns.has(info.col)) {
+ columns.add(info.col);
+ const column = this.button(window.siyuan.languages.column, "iconDrag",
+ (Math.max(rect.left, viewport.left) + Math.min(rect.right, viewport.right)) / 2, viewport.top - 14);
+ column.dataset.mode = "column";
+ column.setAttribute("aria-pressed", String(selection?.mode === "column" && selection.indexes.has(info.col)));
+ column.classList.toggle("block__icon--active", selection?.mode === "column" && selection.indexes.has(info.col));
+ column.addEventListener("pointerdown", event => this.selectHandle(event, info.cell, "column", column));
+ }
+ });
+ if (!selection) {
+ const rect = cell.getBoundingClientRect();
+ if (rect.bottom > viewport.top && rect.top < viewport.bottom && rect.right > viewport.left && rect.left < viewport.right) {
+ const select = this.button(window.siyuan.languages.tableSelectRange, "iconSelect",
+ Math.min(rect.right, viewport.right) - 14, Math.min(rect.bottom, viewport.bottom) - 14);
+ select.dataset.action = "select";
+ select.addEventListener("pointerdown", event => event.preventDefault());
+ select.addEventListener("click", () => this.actions.select(cell, "cell", false));
+ }
+ }
+ const activeColumn = grid.cellInfos.find(info => info.cell === cell)?.col;
+ const column = typeof activeColumn === "number" ?
+ table.querySelectorAll<HTMLTableColElement>(":scope > colgroup > col")[activeColumn] : undefined;
+ const widthRect = column?.getBoundingClientRect() || cell.getBoundingClientRect();
+ if (typeof activeColumn === "number" && widthRect.right > viewport.left && widthRect.right <= viewport.right + 1) {
+ const width = this.button(window.siyuan.languages.width, "iconWidth", widthRect.right, viewport.top - 14);
+ width.dataset.action = "width";
+ width.addEventListener("pointerdown", event => {
+ event.preventDefault();
+ this.holdControls(event);
+ this.actions.width(event, cell, activeColumn);
+ });
+ }
+ const tableRect = table.getBoundingClientRect();
+ if (tableRect.bottom <= viewport.bottom + 1) {
+ this.addResize(cell, "add-row", viewport.left + (viewport.right - viewport.left) / 2, tableRect.bottom + 14);
+ }
+ if (tableRect.right <= viewport.right + 1) {
+ this.addResize(cell, "add-column", tableRect.right + 14, viewport.top + (viewport.bottom - viewport.top) / 2);
+ }
+ if (tableRect.bottom <= viewport.bottom + 1 && tableRect.right <= viewport.right + 1) {
+ this.addResize(cell, "add-both", tableRect.right + 14, tableRect.bottom + 14);
+ }
+ this.renderEndpoints(state);
+ }
+
+ private renderEndpoints(state?: ITableTouchState) {
+ this.endpoints.forEach(button => button.classList.add("fn__none"));
+ const selection = state?.selection;
+ if (selection?.cells.length && (selection.mode !== "cell" || selection.rectangle)) {
+ const {grid, viewport} = state;
+ const cells = new Set(selection.cells);
+ const infos = grid.cellInfos.filter(info => cells.has(info.cell));
+ if (!infos.length) {
+ return;
+ }
+ const first = infos.reduce((a, b) => a.row < b.row || a.row === b.row && a.col < b.col ? a : b);
+ const last = infos.reduce((a, b) => a.row + a.rowspan > b.row + b.rowspan ||
+ a.row + a.rowspan === b.row + b.rowspan && a.col + a.colspan > b.col + b.colspan ? a : b);
+ [first.cell.getBoundingClientRect(), last.cell.getBoundingClientRect()].forEach((rect, index) => {
+ const x = index === 0 ? rect.left : rect.right;
+ const y = index === 0 ? rect.top : rect.bottom;
+ if (x >= viewport.left - 1 && x <= viewport.right + 1 && y >= viewport.top - 1 && y <= viewport.bottom + 1) {
+ const button = this.endpoints[index];
+ button.style.left = `${x}px`;
+ button.style.top = `${y}px`;
+ button.classList.remove("fn__none");
+ }
+ });
+ }
+ }
+
+ private button(label: string, icon: string, left: number, top: number) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "block__icon block__icon--show protyle-table-control__touch-button";
+ button.setAttribute("aria-label", label);
+ button.innerHTML = `<svg><use xlink:href="#${icon}"></use></svg>`;
+ button.style.left = `${Math.max(16, Math.min(window.innerWidth - 16, left))}px`;
+ button.style.top = `${Math.max(16, Math.min(window.innerHeight - 72, top))}px`;
+ this.controls.append(button);
+ return button;
+ }
+
+ private selectHandle(event: PointerEvent, cell: HTMLTableCellElement, mode: "row" | "column", handle: HTMLElement) {
+ if (event.button !== 0) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ const state = this.actions.state();
+ // 拖动已选行列时保留整个选区,多选开关开启后点击手柄切换选中状态。
+ const selected = state?.selection?.mode === mode && state.selection.cells.includes(cell);
+ if ((!selected || this.multiSelect) && !this.actions.select(cell, mode, this.multiSelect)) {
+ return;
+ }
+ if (!this.multiSelect) {
+ this.holdControls(event);
+ this.actions.drag(event, cell, mode, handle);
+ }
+ }
+
+ private addResize(cell: HTMLTableCellElement, type: "add-row" | "add-column" | "add-both", x: number, y: number) {
+ const button = this.button(type === "add-column" ? window.siyuan.languages.tableAddColumnTip :
+ window.siyuan.languages.tableAddRowTip, type === "add-both" ? "iconMove" : "iconAdd", x, y);
+ button.dataset.action = type;
+ button.addEventListener("pointerdown", event => {
+ event.preventDefault();
+ this.holdControls(event);
+ this.actions.resize(event, cell, type);
+ });
+ button.addEventListener("click", () => this.actions.add(cell, type));
+ }
+
+ private holdControls(event: PointerEvent) {
+ this.cancelGesture();
+ this.dragging = true;
+ this.gesture = new AbortController();
+ const end = (up: PointerEvent) => {
+ if (up.pointerId === event.pointerId) {
+ this.cancelGesture();
+ this.actions.render();
+ }
+ };
+ document.addEventListener("pointerup", end, {signal: this.gesture.signal});
+ document.addEventListener("pointercancel", end, {signal: this.gesture.signal});
+ }
+
+ private startRangeDrag(event: PointerEvent, start: boolean) {
+ const state = this.actions.state();
+ if (event.button !== 0 || !state?.selection?.cells.length) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ this.cancelGesture();
+ const cells = new Set(state.selection.cells);
+ const infos = state.grid.cellInfos.filter(info => cells.has(info.cell));
+ const top = Math.min(...infos.map(info => info.row));
+ const left = Math.min(...infos.map(info => info.col));
+ const bottom = Math.max(...infos.map(info => info.row + info.rowspan - 1));
+ const right = Math.max(...infos.map(info => info.col + info.colspan - 1));
+ const anchor = state.grid.grid[start ? bottom : top]?.[start ? right : left];
+ if (!anchor) {
+ return;
+ }
+ this.dragging = true;
+ const controller = new AbortController();
+ this.gesture = controller;
+ const signal = controller.signal;
+ let point = {clientX: event.clientX, clientY: event.clientY};
+ const update = () => {
+ const current = this.actions.state();
+ if (!current?.selection) {
+ this.cancelGesture();
+ return;
+ }
+ const viewport = current.viewport;
+ const x = Math.min(Math.max(point.clientX, viewport.left + 2), viewport.right - 2);
+ const y = Math.min(Math.max(point.clientY, viewport.top + 2), viewport.bottom - 2);
+ const target = document.elementsFromPoint(x, y).map(element => element.closest<HTMLTableCellElement>("th, td"))
+ .find(candidate => candidate?.closest("table") === current.table);
+ if (target?.closest("table") === current.table && !target.closest(`tr[${TABLE_VIRTUAL_ROWS}]`)) {
+ if (state.selection.mode === "cell") {
+ this.actions.range(anchor, target);
+ } else {
+ this.actions.select(anchor, state.selection.mode, false);
+ this.actions.select(target, state.selection.mode, false, true);
+ }
+ }
+ };
+ document.addEventListener("pointermove", move => {
+ if (move.pointerId !== event.pointerId) {
+ return;
+ }
+ move.preventDefault();
+ point = move;
+ update();
+ }, {signal, passive: false});
+ const end = (up: PointerEvent) => {
+ if (up.pointerId === event.pointerId) {
+ this.cancelGesture();
+ this.actions.render();
+ }
+ };
+ document.addEventListener("pointerup", end, {signal});
+ document.addEventListener("pointercancel", end, {signal});
+ const scroll = () => {
+ const current = this.actions.state();
+ if (!this.gesture || !current?.selection) {
+ return;
+ }
+ const {viewport} = current;
+ const delta = (value: number, min: number, max: number) => value < min + 28 ? -10 : value > max - 28 ? 10 : 0;
+ const dx = delta(point.clientX, viewport.left, viewport.right);
+ const dy = delta(point.clientY, viewport.top, viewport.bottom);
+ if (dx || dy) {
+ current.table.parentElement.scrollLeft += dx;
+ const wrapper = current.table.parentElement;
+ const scrollTop = wrapper.scrollTop;
+ wrapper.scrollTop += dy;
+ if (wrapper.scrollTop === scrollTop) {
+ this.content().scrollTop += dy;
+ }
+ update();
+ this.actions.render();
+ }
+ this.scrollFrame = requestAnimationFrame(scroll);
+ };
+ this.scrollFrame = requestAnimationFrame(scroll);
+ }
+
+ private cancelGesture() {
+ this.gesture?.abort();
+ this.gesture = undefined;
+ this.dragging = false;
+ cancelAnimationFrame(this.scrollFrame);
+ }
+}
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index fd22cffce4..2f89e4969a 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -547,7 +547,7 @@ export class WYSIWYG {
if (window.siyuan.config.editor.displayBookmarkIcon) {
this.element.classList.add("protyle-wysiwyg--attr");
}
- if (!isMobile()) {
+ if (!isMobile() || !protyle.lite) {
this.tableControl = new TableControl(protyle, this.element);
}
this.bindCommonEvent(protyle);
@@ -1246,6 +1246,11 @@ export class WYSIWYG {
});
this.element.addEventListener("mousedown", (event: MouseEvent) => {
+ if (this.tableControl?.hasTouchSelection() && (event.target as Element).closest("td, th")) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
this.mouseDownTarget = event.target;
// 常规划选时排除属性占位,三击时恢复以保留浏览器的整段选择行为
this.element.classList.toggle("protyle-wysiwyg--select-attr", event.button === 0 && event.detail > 2);