Skip to content

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

:sparkles: Support multiple table row, column, and cell selection https://github.com/siyuan-note/siyuan/issues/4785

Daniel0bf4467d9262
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 6e892621c9..37beb4cd33 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "يتطلب تحديدًا مستطيلاً",
"updateChannel": "قناة التحديث",
"updateChannelTip": "تتلقى قناة Beta الإصدارات المستقرة وRC وBeta، بينما تتلقى قناة Alpha جميع الإصدارات. تتطلب قنوات الاختبار إمكانية الوصول إلى GitHub",
"updateChannelStable": "مستقر",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index d82aa05b11..f448a3283a 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Erfordert eine rechteckige Auswahl",
"updateChannel": "Aktualisierungskanal",
"updateChannelTip": "Der Beta-Kanal erhält stabile, RC- und Beta-Versionen; der Alpha-Kanal erhält alle Versionen. Testkanäle erfordern Zugriff auf GitHub",
"updateChannelStable": "Stabil",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index a5cd284f6f..ac457de47c 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Requires a rectangular selection",
"updateChannel": "Update channel",
"updateChannelTip": "Beta receives stable, RC, and Beta releases; Alpha receives all releases. Test channels require access to GitHub",
"updateChannelStable": "Stable",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index eb2e5eab08..5d4fa0288f 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Requiere una selección rectangular",
"updateChannel": "Canal de actualización",
"updateChannelTip": "El canal Beta recibe versiones estables, RC y Beta; el canal Alpha recibe todas las versiones. Los canales de prueba requieren acceso a GitHub",
"updateChannelStable": "Estable",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 3a3c2d4988..a2b8765fa1 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Nécessite une sélection rectangulaire",
"updateChannel": "Canal de mise à jour",
"updateChannelTip": "Le canal Beta reçoit les versions stables, RC et bêta ; le canal Alpha reçoit toutes les versions. Les canaux de test nécessitent un accès à GitHub",
"updateChannelStable": "Stable",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 8066c76483..7302bb6f2f 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "נדרשת בחירה מלבנית",
"updateChannel": "ערוץ עדכונים",
"updateChannelTip": "ערוץ Beta מקבל גרסאות יציבות, RC ו-Beta; ערוץ Alpha מקבל את כל הגרסאות. ערוצי הבדיקה דורשים גישה ל-GitHub",
"updateChannelStable": "יציב",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 990959d427..e3120a0521 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "आयताकार चयन आवश्यक है",
"updateChannel": "अपडेट चैनल",
"updateChannelTip": "Beta चैनल को स्थिर, RC और Beta रिलीज़ मिलते हैं; Alpha चैनल को सभी रिलीज़ मिलते हैं। परीक्षण चैनलों के लिए GitHub तक पहुंच आवश्यक है",
"updateChannelStable": "स्थिर",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 8deb33e2c9..ed1a2f713c 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Memerlukan pilihan persegi panjang",
"updateChannel": "Saluran pembaruan",
"updateChannelTip": "Kanal Beta menerima rilis stabil, RC, dan Beta; kanal Alpha menerima semua rilis. Kanal pengujian memerlukan akses ke GitHub",
"updateChannelStable": "Stabil",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 96e284f2de..4f27a6d055 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Richiede una selezione rettangolare",
"updateChannel": "Canale di aggiornamento",
"updateChannelTip": "Il canale Beta riceve le versioni stabili, RC e Beta; il canale Alpha riceve tutte le versioni. I canali di test richiedono l'accesso a GitHub",
"updateChannelStable": "Stabile",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index ffba2bbdf8..402a45b036 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "矩形範囲の選択が必要です",
"updateChannel": "更新チャンネル",
"updateChannelTip": "Beta チャンネルでは正式版、RC、Beta 版を受信し、Alpha チャンネルではすべての版を受信します。テストチャンネルの利用には GitHub へのアクセスが必要です",
"updateChannelStable": "正式版",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 5a509c51f4..e96f0c1f61 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "직사각형 선택 영역이 필요합니다",
"updateChannel": "업데이트 채널",
"updateChannelTip": "Beta 채널은 정식, RC 및 Beta 릴리스를 받고 Alpha 채널은 모든 릴리스를 받습니다. 테스트 채널을 사용하려면 GitHub에 접근할 수 있어야 합니다",
"updateChannelStable": "정식",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 792bb46f3c..42ff0ca54a 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Vereist een rechthoekige selectie",
"updateChannel": "Updatekanaal",
"updateChannelTip": "Het Beta-kanaal ontvangt stabiele, RC- en Beta-versies; het Alpha-kanaal ontvangt alle versies. Testkanalen vereisen toegang tot GitHub",
"updateChannelStable": "Stabiel",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index caf2ce8b71..05624e09e4 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Wymaga prostokątnego zaznaczenia",
"updateChannel": "Kanał aktualizacji",
"updateChannelTip": "Kanał Beta otrzymuje wydania stabilne, RC i Beta, a kanał Alpha wszystkie wydania. Kanały testowe wymagają dostępu do GitHub",
"updateChannelStable": "Stabilny",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 7cc83ec190..f10bbee9ba 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Requer uma seleção retangular",
"updateChannel": "Canal de atualização",
"updateChannelTip": "O canal Beta recebe versões estáveis, RC e Beta; o canal Alpha recebe todas as versões. Os canais de teste exigem acesso ao GitHub",
"updateChannelStable": "Estável",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 03e57f3768..bd26f3a123 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Требуется прямоугольное выделение",
"updateChannel": "Канал обновлений",
"updateChannelTip": "Канал Beta получает стабильные, RC- и Beta-версии, а канал Alpha — все версии. Для тестовых каналов требуется доступ к GitHub",
"updateChannelStable": "Стабильный",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index aa0ae3c253..716e057646 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Vyžaduje obdĺžnikový výber",
"updateChannel": "Aktualizačný kanál",
"updateChannelTip": "Kanál Beta prijíma stabilné vydania, RC a Beta; kanál Alpha prijíma všetky vydania. Testovacie kanály vyžadujú prístup ku GitHubu",
"updateChannelStable": "Stabilný",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 87a7e52ba4..06f09b79ae 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "ต้องเลือกเป็นรูปสี่เหลี่ยมผืนผ้า",
"updateChannel": "ช่องทางการอัปเดต",
"updateChannelTip": "ช่อง Beta จะได้รับรุ่นเสถียร รุ่น RC และรุ่น Beta ส่วนช่อง Alpha จะได้รับทุกรุ่น ช่องทดสอบจำเป็นต้องเข้าถึง GitHub",
"updateChannelStable": "เสถียร",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index bf42d4912e..13f362a18a 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Dikdörtgen bir seçim gerektirir",
"updateChannel": "Güncelleme kanalı",
"updateChannelTip": "Beta kanalı kararlı, RC ve Beta sürümlerini; Alpha kanalı ise tüm sürümleri alır. Test kanalları GitHub erişimi gerektirir",
"updateChannelStable": "Kararlı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index fe913dd5f8..a5233aacd7 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "Потрібне прямокутне виділення",
"updateChannel": "Канал оновлень",
"updateChannelTip": "Канал Beta отримує стабільні, RC- та Beta-версії, а канал Alpha — усі версії. Для тестових каналів потрібен доступ до GitHub",
"updateChannelStable": "Стабільний",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 9943f51710..24e9b8064e 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "需要矩形选区",
"updateChannel": "更新通道",
"updateChannelTip": "Beta 通道接收正式版、RC 和 Beta,Alpha 通道接收全部版本。测试通道需要能够访问 GitHub",
"updateChannelStable": "正式版",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index a16c27e982..42af98caf7 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "tableRectangleSelectionRequired": "需要矩形選區",
"updateChannel": "更新通道",
"updateChannelTip": "Beta 通道接收正式版、RC 和 Beta,Alpha 通道接收所有版本。測試通道需要能夠存取 GitHub",
"updateChannelStable": "正式版",
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scss
index a9f0267ebb..493cf5c78b 100644
--- a/app/src/assets/scss/protyle/_protyle.scss
+++ b/app/src/assets/scss/protyle/_protyle.scss
@@ -685,3 +685,94 @@ table + .protyle-action__table {
z-index: 3;
}
}
+
+.protyle-table-control {
+ position: fixed;
+ inset: 0;
+ z-index: 4;
+ pointer-events: none;
+
+ &__handle,
+ &__add {
+ position: fixed;
+ z-index: 2;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ padding: 0;
+ color: var(--b3-theme-on-surface);
+ background-color: var(--b3-theme-background);
+ border: 1px solid var(--b3-border-color);
+ border-radius: var(--b3-border-radius);
+ box-shadow: var(--b3-point-shadow);
+ cursor: pointer;
+ pointer-events: auto;
+ transform: translate(-50%, -50%);
+
+ svg {
+ width: 14px;
+ height: 14px;
+ }
+
+ &:hover {
+ color: var(--b3-theme-primary);
+ background-color: var(--b3-list-hover);
+ }
+ }
+
+ &__handle {
+ width: 24px;
+ height: 24px;
+
+ &--row,
+ &--column {
+ cursor: grab;
+ }
+
+ &--column {
+ transform: translate(-50%, -50%) rotate(90deg);
+
+ svg {
+ transform: rotate(-90deg);
+ }
+ }
+
+ &--cell {
+ width: 20px;
+ height: 20px;
+ }
+ }
+
+ &__add {
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ }
+
+ &__selection {
+ position: fixed;
+ z-index: 1;
+ box-sizing: border-box;
+ background-color: var(--b3-theme-primary-lightest);
+ border: 1px solid var(--b3-theme-primary);
+ pointer-events: none;
+ }
+
+ &__drop {
+ position: fixed;
+ z-index: 3;
+ background-color: var(--b3-theme-primary);
+ pointer-events: none;
+ }
+
+ &__color {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin-right: 8px;
+ vertical-align: middle;
+ border: 1px solid var(--b3-border-color);
+ border-radius: 50%;
+ }
+}
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.ts
index 60ab103ef3..b3ab4e9303 100644
--- a/app/src/protyle/util/destroy.ts
+++ b/app/src/protyle/util/destroy.ts
@@ -18,6 +18,7 @@ export const destroy = (protyle: IProtyle) => {
protyle.element.classList.remove("protyle");
protyle.element.removeAttribute("style");
if (protyle.wysiwyg) {
+ protyle.wysiwyg.tableControl?.destroy();
protyle.wysiwyg.lastHTMLs = {};
}
if (protyle.undo) {
diff --git a/app/src/protyle/util/table.ts b/app/src/protyle/util/table.ts
index d6a10e3a93..d2d4b2853b 100644
--- a/app/src/protyle/util/table.ts
+++ b/app/src/protyle/util/table.ts
@@ -887,7 +887,7 @@ export const updateTableTitle = (protyle: IProtyle, nodeElement: Element) => {
inputElement.select();
};
-interface ITableCellInfo {
+export interface ITableCellInfo {
cell: HTMLTableCellElement;
row: number;
col: number;
@@ -895,10 +895,12 @@ interface ITableCellInfo {
colspan: number;
}
-interface ITableGrid {
+export interface ITableGrid {
cellInfos: ITableCellInfo[];
sectionOfRow: string[];
rowCount: number;
+ columnCount: number;
+ grid: (HTMLTableCellElement | null)[][];
}
export interface ITableRangeCell {
@@ -907,7 +909,7 @@ export interface ITableRangeCell {
col: number;
}
-const buildTableGrid = (tableElement: HTMLElement): ITableGrid => {
+export const buildTableGrid = (tableElement: HTMLElement): ITableGrid => {
const cellInfos: ITableCellInfo[] = [];
const sectionOfRow: string[] = [];
const grid: (HTMLTableCellElement | null)[][] = [];
@@ -954,7 +956,13 @@ const buildTableGrid = (tableElement: HTMLElement): ITableGrid => {
});
});
- return {cellInfos, sectionOfRow, rowCount: trElements.length};
+ return {
+ cellInfos,
+ sectionOfRow,
+ rowCount: trElements.length,
+ columnCount: grid.reduce((count, row) => Math.max(count, row.length), 0),
+ grid,
+ };
};
const getTableRangeBounds = (cellInfos: ITableCellInfo[], rowCount: number, startCell: HTMLElement, endCell: HTMLElement) => {
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
new file mode 100644
index 0000000000..76f259383a
--- /dev/null
+++ b/app/src/protyle/util/tableControl.ts
@@ -0,0 +1,1163 @@
+import {MenuItem} from "../../menus/Menu";
+import {removeBlock} from "../wysiwyg/remove";
+import {updateTransaction} from "../wysiwyg/transaction";
+import {isMac} from "./compatibility";
+import {focusByRange, getEditorRange} from "./selection";
+import {
+ buildTableGrid,
+ getTableRangeHTML,
+ insertColumn,
+ insertRow,
+ insertRowAbove,
+ ITableCellInfo,
+} from "./table";
+
+type TableSelectionMode = "row" | "column" | "cell";
+
+interface ITableSelection {
+ node: HTMLElement;
+ table: HTMLTableElement;
+ mode: TableSelectionMode;
+ indexes: Set<number>;
+ cells: Set<HTMLTableCellElement>;
+ anchor: number | HTMLTableCellElement;
+ activeCell: HTMLTableCellElement;
+}
+
+interface IDragState {
+ mode: "row" | "column";
+ startX: number;
+ startY: number;
+ target: number;
+ dragging: boolean;
+}
+
+const getCell = (target: EventTarget) => {
+ return (target as Element)?.closest?.("th, td") as HTMLTableCellElement;
+};
+
+const getTableNode = (cell: HTMLTableCellElement) => {
+ return cell?.closest<HTMLElement>('[data-type="NodeTable"]');
+};
+
+const isPrimaryModifier = (event: MouseEvent | KeyboardEvent) => isMac() ? event.metaKey : event.ctrlKey;
+
+const getRangeIndexes = (start: number, end: number) => {
+ const indexes: number[] = [];
+ for (let index = Math.min(start, end); index <= Math.max(start, end); index++) {
+ indexes.push(index);
+ }
+ return indexes;
+};
+
+const replaceCellTag = (cell: HTMLTableCellElement, tag: "th" | "td") => {
+ if (cell.tagName.toLowerCase() === tag) {
+ return cell;
+ }
+ const newCell = document.createElement(tag);
+ Array.from(cell.attributes).forEach(attribute => {
+ newCell.setAttribute(attribute.name, attribute.value);
+ });
+ while (cell.firstChild) {
+ newCell.append(cell.firstChild);
+ }
+ cell.replaceWith(newCell);
+ return newCell;
+};
+
+const getCellText = (cell: HTMLTableCellElement) => cell.innerText.replace(/\n+$/g, "");
+
+export class TableControl {
+ private protyle: IProtyle;
+ private wysiwygElement: HTMLElement;
+ private element: HTMLElement;
+ private rowHandle: HTMLButtonElement;
+ private columnHandle: HTMLButtonElement;
+ private cellHandle: HTMLButtonElement;
+ private addRowButton: HTMLButtonElement;
+ private addColumnButton: HTMLButtonElement;
+ private dropIndicator: HTMLElement;
+ private selection: ITableSelection;
+ private hoverCell: HTMLTableCellElement;
+ private selectionElements: HTMLElement[] = [];
+ private selectedCells: HTMLTableCellElement[] = [];
+ private frame: number;
+ private dragState: IDragState;
+ private observer: MutationObserver;
+ private abortController = new AbortController();
+
+ constructor(protyle: IProtyle, wysiwygElement: HTMLElement) {
+ this.protyle = protyle;
+ this.wysiwygElement = wysiwygElement;
+ this.element = document.createElement("div");
+ this.element.className = "protyle-table-control";
+ this.element.setAttribute("contenteditable", "false");
+ this.element.innerHTML = `<button class="protyle-table-control__handle protyle-table-control__handle--row fn__none" data-type="row" aria-label="${window.siyuan.languages.row}">
+ <svg><use xlink:href="#iconDrag"></use></svg>
+</button>
+<button class="protyle-table-control__handle protyle-table-control__handle--column fn__none" data-type="column" aria-label="${window.siyuan.languages.column}">
+ <svg><use xlink:href="#iconDrag"></use></svg>
+</button>
+<button class="protyle-table-control__handle protyle-table-control__handle--cell fn__none" data-type="cell" aria-label="${window.siyuan.languages.more}">
+ <svg><use xlink:href="#iconMore"></use></svg>
+</button>
+<button class="protyle-table-control__add protyle-table-control__add--row fn__none" data-type="add-row" aria-label="${window.siyuan.languages.insertRowBelow}">
+ <svg><use xlink:href="#iconAdd"></use></svg>
+</button>
+<button class="protyle-table-control__add protyle-table-control__add--column fn__none" data-type="add-column" aria-label="${window.siyuan.languages.insertColumnRight}">
+ <svg><use xlink:href="#iconAdd"></use></svg>
+</button>
+<div class="protyle-table-control__drop fn__none"></div>`;
+ this.rowHandle = this.element.querySelector('[data-type="row"]');
+ this.columnHandle = this.element.querySelector('[data-type="column"]');
+ this.cellHandle = this.element.querySelector('[data-type="cell"]');
+ this.addRowButton = this.element.querySelector('[data-type="add-row"]');
+ this.addColumnButton = this.element.querySelector('[data-type="add-column"]');
+ this.dropIndicator = this.element.querySelector(".protyle-table-control__drop");
+ protyle.element.append(this.element);
+ this.bindEvents();
+ this.observer = new MutationObserver(() => {
+ if (this.selection && !this.selection.node.isConnected) {
+ this.clear();
+ } else if (this.hoverCell && !this.hoverCell.isConnected) {
+ this.hoverCell = undefined;
+ this.scheduleRender();
+ }
+ });
+ this.observer.observe(this.wysiwygElement, {childList: true, subtree: true});
+ }
+
+ public destroy() {
+ this.abortController.abort();
+ this.observer.disconnect();
+ cancelAnimationFrame(this.frame);
+ this.element.remove();
+ }
+
+ public clear() {
+ this.selection = undefined;
+ this.selectedCells = [];
+ this.selectionElements.forEach(item => item.remove());
+ this.selectionElements = [];
+ this.dropIndicator.classList.add("fn__none");
+ this.scheduleRender();
+ }
+
+ private bindEvents() {
+ const signal = this.abortController.signal;
+ this.wysiwygElement.addEventListener("pointermove", event => {
+ const cell = getCell(event.target);
+ if (cell && getTableNode(cell) && !this.protyle.disabled) {
+ if (cell === this.hoverCell) {
+ return;
+ }
+ this.hoverCell = cell;
+ this.scheduleRender();
+ } else if (this.hoverCell) {
+ this.hoverCell = undefined;
+ this.scheduleRender();
+ }
+ }, {signal});
+ this.wysiwygElement.addEventListener("pointerleave", event => {
+ if (this.element.contains(event.relatedTarget as Node)) {
+ return;
+ }
+ this.hoverCell = undefined;
+ this.scheduleRender();
+ }, {signal});
+ this.wysiwygElement.addEventListener("pointerdown", event => {
+ if (event.button === 0 && !(event.ctrlKey && isMac()) &&
+ !(event.target as Element).closest(".protyle-table-control")) {
+ this.clear();
+ }
+ }, {capture: true, signal});
+ this.wysiwygElement.addEventListener("contextmenu", event => {
+ if (!this.selection) {
+ return;
+ }
+ const cell = getCell(event.target);
+ if (!cell || getTableNode(cell) !== this.selection.node) {
+ this.clear();
+ return;
+ }
+ if (!this.isCellInSelection(cell)) {
+ this.selectFromCell(this.selection.mode, cell, false, false);
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ this.openMenu(event.clientX, event.clientY);
+ }, {capture: true, signal});
+ document.addEventListener("keydown", event => {
+ if (event.key === "Escape" && this.selection) {
+ this.clear();
+ }
+ }, {signal});
+ document.addEventListener("pointerdown", event => {
+ if (!this.selection) {
+ return;
+ }
+ const target = event.target as Node;
+ if (this.element.contains(target) || this.selection.node.contains(target) ||
+ document.getElementById("commonMenu")?.contains(target)) {
+ return;
+ }
+ this.clear();
+ }, {capture: true, signal});
+ document.addEventListener("copy", event => {
+ if (!this.selection) {
+ return;
+ }
+ this.writeClipboard(event);
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }, {capture: true, signal});
+ document.addEventListener("cut", event => {
+ if (!this.selection) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ if (this.protyle.disabled || !this.canMutateSelection()) {
+ return;
+ }
+ if (this.writeClipboard(event)) {
+ this.deleteSelection(true);
+ }
+ }, {capture: true, signal});
+ this.protyle.element.addEventListener("scroll", () => this.scheduleRender(), {capture: true, signal});
+ window.addEventListener("resize", () => this.scheduleRender(), {signal});
+ this.element.addEventListener("pointerdown", event => this.handlePointerDown(event), {signal});
+ this.element.addEventListener("click", event => this.handleClick(event), {signal});
+ this.element.addEventListener("contextmenu", event => {
+ const type = (event.target as Element).closest<HTMLElement>("[data-type]")?.dataset.type;
+ if (!this.hoverCell || (type !== "row" && type !== "column" && type !== "cell")) {
+ return;
+ }
+ if (!this.selection || this.selection.mode !== type || !this.isCellInSelection(this.hoverCell)) {
+ this.selectFromCell(type, this.hoverCell, false, false);
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ this.openMenu(event.clientX, event.clientY);
+ }, {signal});
+ this.element.addEventListener("pointerleave", event => {
+ if (this.wysiwygElement.contains(event.relatedTarget as Node)) {
+ return;
+ }
+ this.hoverCell = undefined;
+ this.scheduleRender();
+ }, {signal});
+ }
+
+ private handlePointerDown(event: PointerEvent) {
+ const type = (event.target as Element).closest<HTMLElement>("[data-type]")?.dataset.type;
+ if (!type || !this.hoverCell) {
+ return;
+ }
+ if (event.button !== 0) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ if (type !== "row" && type !== "column") {
+ return;
+ }
+ this.selectFromCell(type, this.hoverCell, isPrimaryModifier(event), event.shiftKey);
+ const grid = buildTableGrid(this.selection.table);
+ if (grid.cellInfos.some(info => info.rowspan > 1 || info.colspan > 1) ||
+ (type === "row" && this.selection.indexes.size > 1 && this.selection.indexes.has(0))) {
+ return;
+ }
+ this.dragState = {
+ mode: type,
+ startX: event.clientX,
+ startY: event.clientY,
+ target: -1,
+ dragging: false,
+ };
+ const move = (moveEvent: PointerEvent) => this.handleDragMove(moveEvent);
+ const up = (upEvent: PointerEvent) => {
+ document.removeEventListener("pointermove", move);
+ document.removeEventListener("pointerup", up);
+ this.handleDragEnd(upEvent);
+ };
+ document.addEventListener("pointermove", move);
+ document.addEventListener("pointerup", up);
+ }
+
+ private handleClick(event: MouseEvent) {
+ const type = (event.target as Element).closest<HTMLElement>("[data-type]")?.dataset.type;
+ if (!type || !this.hoverCell) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ if (type === "add-row" || type === "add-column") {
+ this.addAtEnd(type);
+ return;
+ }
+ if (type !== "row" && type !== "column" && type !== "cell") {
+ return;
+ }
+ if (type === "row" || type === "column") {
+ if (this.dragState?.dragging) {
+ this.dragState = undefined;
+ return;
+ }
+ if (!isPrimaryModifier(event) && !event.shiftKey) {
+ const handle = type === "row" ? this.rowHandle : this.columnHandle;
+ const rect = handle.getBoundingClientRect();
+ this.openMenu(rect.right, rect.bottom);
+ }
+ return;
+ }
+ this.selectFromCell(type, this.hoverCell, isPrimaryModifier(event), event.shiftKey);
+ if (!isPrimaryModifier(event) && !event.shiftKey) {
+ const rect = this.cellHandle.getBoundingClientRect();
+ this.openMenu(rect.right, rect.bottom);
+ }
+ }
+
+ private selectFromCell(mode: TableSelectionMode, cell: HTMLTableCellElement, toggle: boolean, extend: boolean) {
+ const node = getTableNode(cell);
+ const table = cell.closest("table") as HTMLTableElement;
+ if (!node || !table) {
+ return;
+ }
+ node.querySelector(".table__select")?.removeAttribute("style");
+ this.wysiwygElement.querySelectorAll(".protyle-wysiwyg--select").forEach(item => {
+ item.classList.remove("protyle-wysiwyg--select");
+ });
+ const grid = buildTableGrid(table);
+ const info = grid.cellInfos.find(item => item.cell === cell);
+ if (!info) {
+ return;
+ }
+ const sameSelection = this.selection?.node === node && this.selection.mode === mode;
+ if (!sameSelection) {
+ this.selection = {
+ node,
+ table,
+ mode,
+ indexes: new Set(),
+ cells: new Set(),
+ anchor: mode === "cell" ? cell : mode === "row" ? info.row : info.col,
+ activeCell: cell,
+ };
+ }
+ this.selection.activeCell = cell;
+ if (mode === "cell") {
+ if (extend && this.selection.anchor instanceof HTMLTableCellElement) {
+ const anchorInfo = grid.cellInfos.find(item => item.cell === this.selection.anchor);
+ const selected = this.getCellsInRectangle(grid.cellInfos, anchorInfo, info);
+ if (!toggle) {
+ this.selection.cells.clear();
+ }
+ selected.forEach(item => this.selection.cells.add(item));
+ } else if (toggle) {
+ if (this.selection.cells.has(cell)) {
+ this.selection.cells.delete(cell);
+ } else {
+ this.selection.cells.add(cell);
+ }
+ this.selection.anchor = cell;
+ } else {
+ this.selection.cells = new Set([cell]);
+ this.selection.anchor = cell;
+ }
+ } else {
+ const index = mode === "row" ? info.row : info.col;
+ if (extend && typeof this.selection.anchor === "number") {
+ if (!toggle) {
+ this.selection.indexes.clear();
+ }
+ getRangeIndexes(this.selection.anchor, index).forEach(item => this.selection.indexes.add(item));
+ } else if (toggle) {
+ if (this.selection.indexes.has(index)) {
+ this.selection.indexes.delete(index);
+ } else {
+ this.selection.indexes.add(index);
+ }
+ this.selection.anchor = index;
+ } else {
+ this.selection.indexes = new Set([index]);
+ this.selection.anchor = index;
+ }
+ this.expandMergedIndexes(grid.cellInfos);
+ }
+ if (this.selection.indexes.size === 0 && this.selection.cells.size === 0) {
+ this.clear();
+ return;
+ }
+ this.updateSelectedCells();
+ getSelection()?.removeAllRanges();
+ this.scheduleRender();
+ }
+
+ private expandMergedIndexes(cellInfos: ITableCellInfo[]) {
+ if (!this.selection || this.selection.mode === "cell") {
+ return;
+ }
+ let changed = true;
+ while (changed) {
+ changed = false;
+ cellInfos.forEach(info => {
+ const start = this.selection.mode === "row" ? info.row : info.col;
+ const span = this.selection.mode === "row" ? info.rowspan : info.colspan;
+ const indexes = getRangeIndexes(start, start + span - 1);
+ if (indexes.some(index => this.selection.indexes.has(index))) {
+ indexes.forEach(index => {
+ if (!this.selection.indexes.has(index)) {
+ this.selection.indexes.add(index);
+ changed = true;
+ }
+ });
+ }
+ });
+ }
+ }
+
+ private getCellsInRectangle(cellInfos: ITableCellInfo[], start: ITableCellInfo, end: ITableCellInfo) {
+ if (!start || !end) {
+ return [];
+ }
+ let rowStart = Math.min(start.row, end.row);
+ let rowEnd = Math.max(start.row + start.rowspan - 1, end.row + end.rowspan - 1);
+ let colStart = Math.min(start.col, end.col);
+ let colEnd = Math.max(start.col + start.colspan - 1, end.col + end.colspan - 1);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ cellInfos.forEach(info => {
+ if (info.row <= rowEnd && info.row + info.rowspan - 1 >= rowStart &&
+ info.col <= colEnd && info.col + info.colspan - 1 >= colStart) {
+ const nextRowStart = Math.min(rowStart, info.row);
+ const nextRowEnd = Math.max(rowEnd, info.row + info.rowspan - 1);
+ const nextColStart = Math.min(colStart, info.col);
+ const nextColEnd = Math.max(colEnd, info.col + info.colspan - 1);
+ changed = nextRowStart !== rowStart || nextRowEnd !== rowEnd ||
+ nextColStart !== colStart || nextColEnd !== colEnd;
+ rowStart = nextRowStart;
+ rowEnd = nextRowEnd;
+ colStart = nextColStart;
+ colEnd = nextColEnd;
+ }
+ });
+ }
+ return cellInfos.filter(info => info.row <= rowEnd && info.row + info.rowspan - 1 >= rowStart &&
+ info.col <= colEnd && info.col + info.colspan - 1 >= colStart).map(info => info.cell);
+ }
+
+ private isCellInSelection(cell: HTMLTableCellElement) {
+ if (!this.selection) {
+ return false;
+ }
+ const info = buildTableGrid(this.selection.table).cellInfos.find(item => item.cell === cell);
+ if (!info) {
+ return false;
+ }
+ if (this.selection.mode === "cell") {
+ return this.selection.cells.has(cell);
+ }
+ const start = this.selection.mode === "row" ? info.row : info.col;
+ const span = this.selection.mode === "row" ? info.rowspan : info.colspan;
+ return getRangeIndexes(start, start + span - 1).some(index => this.selection.indexes.has(index));
+ }
+
+ private getSelectedCells() {
+ return this.selectedCells.filter(cell => cell.isConnected);
+ }
+
+ private updateSelectedCells() {
+ if (!this.selection) {
+ this.selectedCells = [];
+ return;
+ }
+ if (this.selection.mode === "cell") {
+ this.selectedCells = Array.from(this.selection.cells);
+ return;
+ }
+ const grid = buildTableGrid(this.selection.table);
+ this.selectedCells = grid.cellInfos.filter(info => {
+ const start = this.selection.mode === "row" ? info.row : info.col;
+ const span = this.selection.mode === "row" ? info.rowspan : info.colspan;
+ return getRangeIndexes(start, start + span - 1).some(index => this.selection.indexes.has(index));
+ }).map(info => info.cell);
+ }
+
+ private isRectangle() {
+ if (!this.selection || this.selection.mode !== "cell" || this.selection.cells.size === 0) {
+ return false;
+ }
+ const infos = buildTableGrid(this.selection.table).cellInfos.filter(info => this.selection.cells.has(info.cell));
+ const rowStart = Math.min(...infos.map(info => info.row));
+ const rowEnd = Math.max(...infos.map(info => info.row + info.rowspan - 1));
+ const colStart = Math.min(...infos.map(info => info.col));
+ const colEnd = Math.max(...infos.map(info => info.col + info.colspan - 1));
+ const slots = new Set<string>();
+ infos.forEach(info => {
+ for (let row = info.row; row < info.row + info.rowspan; row++) {
+ for (let col = info.col; col < info.col + info.colspan; col++) {
+ slots.add(`${row}:${col}`);
+ }
+ }
+ });
+ return slots.size === (rowEnd - rowStart + 1) * (colEnd - colStart + 1);
+ }
+
+ private scheduleRender() {
+ cancelAnimationFrame(this.frame);
+ this.frame = requestAnimationFrame(() => this.render());
+ }
+
+ private setPosition(element: HTMLElement, left: number, top: number) {
+ element.style.left = `${Math.round(left)}px`;
+ element.style.top = `${Math.round(top)}px`;
+ }
+
+ private render() {
+ const cell = this.hoverCell?.isConnected ? this.hoverCell : this.selection?.activeCell;
+ const node = getTableNode(cell);
+ const table = cell?.closest("table") as HTMLTableElement;
+ const visible = !!cell && !!node && !!table && !this.protyle.disabled;
+ [this.rowHandle, this.columnHandle, this.cellHandle, this.addRowButton, this.addColumnButton].forEach(item => {
+ item.classList.toggle("fn__none", !visible);
+ });
+ if (visible) {
+ const cellRect = cell.getBoundingClientRect();
+ const rowRect = cell.parentElement.getBoundingClientRect();
+ const tableRect = table.getBoundingClientRect();
+ this.setPosition(this.rowHandle, tableRect.left - 18, rowRect.top + rowRect.height / 2);
+ this.setPosition(this.columnHandle, cellRect.left + cellRect.width / 2, tableRect.top - 18);
+ this.setPosition(this.cellHandle, cellRect.right - 5, cellRect.top + 5);
+ this.setPosition(this.addRowButton, tableRect.left + tableRect.width / 2, tableRect.bottom + 7);
+ this.setPosition(this.addColumnButton, tableRect.right + 7, tableRect.top + tableRect.height / 2);
+ }
+ this.selectionElements.forEach(item => item.remove());
+ this.selectionElements = [];
+ if (!this.selection?.node.isConnected) {
+ this.selection = undefined;
+ return;
+ }
+ this.getSelectedCells().forEach(cellElement => {
+ const rect = cellElement.getBoundingClientRect();
+ if (rect.width === 0 || rect.height === 0) {
+ return;
+ }
+ const selectionElement = document.createElement("div");
+ selectionElement.className = "protyle-table-control__selection";
+ selectionElement.style.left = `${rect.left}px`;
+ selectionElement.style.top = `${rect.top}px`;
+ selectionElement.style.width = `${rect.width}px`;
+ selectionElement.style.height = `${rect.height}px`;
+ this.element.append(selectionElement);
+ this.selectionElements.push(selectionElement);
+ });
+ }
+
+ private openMenu(x: number, y: number) {
+ if (!this.selection) {
+ return;
+ }
+ const menu = window.siyuan.menus.menu;
+ menu.remove();
+ const merged = buildTableGrid(this.selection.table).cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);
+ const rectangle = this.selection.mode !== "cell" || this.isRectangle();
+ menu.append(new MenuItem({
+ icon: "iconCopy",
+ label: window.siyuan.languages.copy,
+ disabled: !rectangle,
+ accelerator: rectangle ? undefined : window.siyuan.languages.tableRectangleSelectionRequired,
+ click: () => this.execClipboardCommand("copy"),
+ }).element);
+ menu.append(new MenuItem({
+ icon: "iconCut",
+ label: window.siyuan.languages.cut,
+ disabled: this.protyle.disabled || !rectangle || (this.selection.mode !== "cell" && merged),
+ accelerator: !rectangle ? window.siyuan.languages.tableRectangleSelectionRequired :
+ this.selection.mode !== "cell" && merged ? window.siyuan.languages.cancelMerged : undefined,
+ click: () => this.execClipboardCommand("cut"),
+ }).element);
+ menu.append(new MenuItem({type: "separator"}).element);
+ if (!this.protyle.disabled) {
+ this.appendInsertMenus();
+ if (this.selection.mode !== "cell") {
+ menu.append(new MenuItem({
+ icon: "iconCopy",
+ label: window.siyuan.languages.duplicate,
+ disabled: merged,
+ click: () => this.duplicateRowsOrColumns(),
+ }).element);
+ }
+ menu.append(new MenuItem({
+ icon: "iconClear",
+ label: window.siyuan.languages.clear,
+ click: () => this.clearCells(),
+ }).element);
+ menu.append(new MenuItem({
+ icon: "iconTheme",
+ label: window.siyuan.languages.colorPrimary,
+ submenu: this.getBackgroundMenus(),
+ }).element);
+ if (this.selection.mode === "cell") {
+ this.appendCellMenus(rectangle);
+ } else {
+ if (this.selection.mode === "column") {
+ this.appendAlignmentMenus();
+ }
+ menu.append(new MenuItem({
+ icon: this.selection.mode === "row" ? "iconTrashcan" : "iconTrashcan",
+ label: this.selection.mode === "row" ? window.siyuan.languages["delete-row"] :
+ window.siyuan.languages["delete-column"],
+ disabled: merged,
+ click: () => this.deleteSelection(false),
+ }).element);
+ }
+ }
+ menu.popup({x, y});
+ }
+
+ private appendInsertMenus() {
+ const cell = this.selection.activeCell;
+ const range = getEditorRange(cell);
+ if (this.selection.mode === "row") {
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAdd",
+ label: window.siyuan.languages.insertRowAbove,
+ click: () => {
+ insertRowAbove(this.protyle, range, cell, this.selection.node);
+ this.clear();
+ },
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAdd",
+ label: window.siyuan.languages.insertRowBelow,
+ click: () => {
+ insertRow(this.protyle, range, cell, this.selection.node);
+ this.clear();
+ },
+ }).element);
+ } else if (this.selection.mode === "column") {
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAdd",
+ label: window.siyuan.languages.insertColumnLeft,
+ click: () => {
+ insertColumn(this.protyle, this.selection.node, cell, "beforebegin", range);
+ this.clear();
+ },
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAdd",
+ label: window.siyuan.languages.insertColumnRight,
+ click: () => {
+ insertColumn(this.protyle, this.selection.node, cell, "afterend", range);
+ this.clear();
+ },
+ }).element);
+ }
+ }
+
+ private execClipboardCommand(command: "copy" | "cut") {
+ if (!this.selection?.activeCell.isConnected) {
+ return;
+ }
+ const range = getEditorRange(this.selection.activeCell);
+ range.selectNodeContents(this.selection.activeCell);
+ range.collapse(true);
+ focusByRange(range);
+ document.execCommand(command);
+ }
+
+ private appendCellMenus(rectangle: boolean) {
+ this.appendAlignmentMenus();
+ window.siyuan.menus.menu.append(new MenuItem({
+ label: `${window.siyuan.languages.alignment} ↑`,
+ click: () => this.setCellStyle("vertical-align", "top"),
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ label: `${window.siyuan.languages.alignment} ↕`,
+ click: () => this.setCellStyle("vertical-align", "middle"),
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ label: `${window.siyuan.languages.alignment} ↓`,
+ click: () => this.setCellStyle("vertical-align", "bottom"),
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ label: `${window.siyuan.languages.useDefaultAlign} ↕`,
+ click: () => this.setCellStyle("vertical-align", ""),
+ }).element);
+ const cells = this.getSelectedCells();
+ const mergedCell = cells.length === 1 && (cells[0].rowSpan > 1 || cells[0].colSpan > 1);
+ window.siyuan.menus.menu.append(new MenuItem({
+ label: mergedCell ? window.siyuan.languages.cancelMerged : window.siyuan.languages.mergeCell,
+ disabled: !mergedCell && (!rectangle || cells.length < 2 || !this.isSelectionInOneSection()),
+ accelerator: !mergedCell && !rectangle ? window.siyuan.languages.tableRectangleSelectionRequired : undefined,
+ click: () => mergedCell ? this.splitCell(cells[0]) : this.mergeCells(),
+ }).element);
+ }
+
+ private appendAlignmentMenus() {
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAlignLeft",
+ label: window.siyuan.languages.alignLeft,
+ click: () => this.setCellStyle("text-align", "left"),
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAlignCenter",
+ label: window.siyuan.languages.alignCenter,
+ click: () => this.setCellStyle("text-align", "center"),
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconAlignRight",
+ label: window.siyuan.languages.alignRight,
+ click: () => this.setCellStyle("text-align", "right"),
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ label: window.siyuan.languages.useDefaultAlign,
+ click: () => this.setCellStyle("text-align", ""),
+ }).element);
+ }
+
+ private isSelectionInOneSection() {
+ const sections = new Set(this.getSelectedCells().map(cell => cell.parentElement.parentElement.tagName));
+ return sections.size === 1;
+ }
+
+ private getBackgroundMenus(): IMenu[] {
+ const colors = ["", ...Array.from({length: 13}, (_, index) => `var(--b3-font-background${index + 1})`)];
+ return colors.map((color, index) => ({
+ label: index === 0 ? window.siyuan.languages.default : `${window.siyuan.languages.colorPrimary} ${index}`,
+ iconHTML: `<span class="protyle-table-control__color" style="${color ? `background-color: ${color}` : ""}"></span>`,
+ click: () => this.setCellStyle("background-color", color),
+ }));
+ }
+
+ private setCellStyle(property: string, value: string) {
+ if (!this.selection) {
+ return;
+ }
+ const oldHTML = this.selection.node.outerHTML;
+ this.getSelectedCells().forEach(cell => {
+ if (value) {
+ cell.style.setProperty(property, value);
+ } else {
+ cell.style.removeProperty(property);
+ if (!cell.getAttribute("style")) {
+ cell.removeAttribute("style");
+ }
+ }
+ });
+ updateTransaction(this.protyle, this.selection.node, oldHTML);
+ this.scheduleRender();
+ }
+
+ private clearCells() {
+ if (!this.selection) {
+ return;
+ }
+ const oldHTML = this.selection.node.outerHTML;
+ this.getSelectedCells().forEach(cell => cell.innerHTML = "");
+ updateTransaction(this.protyle, this.selection.node, oldHTML);
+ this.scheduleRender();
+ }
+
+ private canMutateSelection() {
+ if (!this.selection) {
+ return false;
+ }
+ if (this.selection.mode === "cell") {
+ return this.isRectangle();
+ }
+ return !buildTableGrid(this.selection.table).cellInfos.some(info => info.rowspan > 1 || info.colspan > 1);
+ }
+
+ private deleteSelection(clearOnly: boolean) {
+ if (!this.selection || !this.canMutateSelection()) {
+ return;
+ }
+ if (clearOnly && this.selection.mode === "cell") {
+ this.clearCells();
+ return;
+ }
+ if (clearOnly && this.selection.mode !== "cell") {
+ this.deleteRowsOrColumns();
+ return;
+ }
+ if (this.selection.mode === "cell") {
+ this.clearCells();
+ } else {
+ this.deleteRowsOrColumns();
+ }
+ }
+
+ private deleteRowsOrColumns() {
+ const selection = this.selection;
+ const grid = buildTableGrid(selection.table);
+ const total = selection.mode === "row" ? grid.rowCount : grid.columnCount;
+ if (selection.indexes.size >= total) {
+ const range = getEditorRange(selection.node);
+ selection.node.classList.add("protyle-wysiwyg--select");
+ removeBlock(this.protyle, selection.node, range, "remove");
+ this.clear();
+ return;
+ }
+ const oldHTML = selection.node.outerHTML;
+ const indexes = Array.from(selection.indexes).sort((a, b) => b - a);
+ if (selection.mode === "row") {
+ const rows = Array.from(selection.table.rows);
+ indexes.forEach(index => rows[index]?.remove());
+ this.normalizeTableSections(selection.table);
+ } else {
+ Array.from(selection.table.rows).forEach(row => {
+ indexes.forEach(index => row.cells[index]?.remove());
+ });
+ const columns = Array.from(selection.table.querySelectorAll("col"));
+ indexes.forEach(index => columns[index]?.remove());
+ }
+ updateTransaction(this.protyle, selection.node, oldHTML);
+ this.clear();
+ }
+
+ private duplicateRowsOrColumns() {
+ if (!this.selection || this.selection.mode === "cell" || !this.canMutateSelection()) {
+ return;
+ }
+ const selection = this.selection;
+ const selected = Array.from(selection.indexes).sort((a, b) => a - b);
+ const oldHTML = selection.node.outerHTML;
+ if (selection.mode === "row") {
+ const rows = Array.from(selection.table.rows);
+ const clones = selected.map(index => rows[index]?.cloneNode(true) as HTMLTableRowElement).filter(Boolean);
+ clones.forEach(row => Array.from(row.cells).forEach(cell => replaceCellTag(cell, "td")));
+ const lastIndex = selected[selected.length - 1];
+ if (lastIndex === 0) {
+ clones.slice().reverse().forEach(row => {
+ selection.table.tBodies[0].insertAdjacentElement("afterbegin", row);
+ });
+ selection.indexes = new Set(getRangeIndexes(1, clones.length));
+ } else {
+ let lastRow = rows[lastIndex];
+ clones.forEach(row => {
+ lastRow.insertAdjacentElement("afterend", row);
+ lastRow = row;
+ });
+ selection.indexes = new Set(getRangeIndexes(lastIndex + 1, lastIndex + clones.length));
+ }
+ } else {
+ Array.from(selection.table.rows).forEach(row => {
+ const cells = Array.from(row.cells);
+ let lastCell = cells[selected[selected.length - 1]];
+ selected.map(index => cells[index]?.cloneNode(true) as HTMLTableCellElement).filter(Boolean)
+ .forEach(cell => {
+ lastCell.insertAdjacentElement("afterend", cell);
+ lastCell = cell;
+ });
+ });
+ const columns = Array.from(selection.table.querySelectorAll("col"));
+ if (columns.length > 0) {
+ let lastColumn = columns[selected[selected.length - 1]];
+ selected.map(index => columns[index]?.cloneNode(true) as HTMLTableColElement).filter(Boolean)
+ .forEach(column => {
+ lastColumn.insertAdjacentElement("afterend", column);
+ lastColumn = column;
+ });
+ }
+ const start = selected[selected.length - 1] + 1;
+ selection.indexes = new Set(getRangeIndexes(start, start + selected.length - 1));
+ }
+ updateTransaction(this.protyle, selection.node, oldHTML);
+ this.updateSelectedCells();
+ this.scheduleRender();
+ }
+
+ private normalizeTableSections(table: HTMLTableElement) {
+ const rows = Array.from(table.rows);
+ let head = table.tHead;
+ let body = table.tBodies[0];
+ if (!head) {
+ head = table.createTHead();
+ }
+ if (!body) {
+ body = table.createTBody();
+ }
+ head.innerHTML = "";
+ body.innerHTML = "";
+ rows.forEach((row, index) => {
+ Array.from(row.cells).forEach(cell => replaceCellTag(cell, index === 0 ? "th" : "td"));
+ (index === 0 ? head : body).append(row);
+ });
+ Array.from(table.tBodies).slice(1).forEach(item => item.remove());
+ }
+
+ private mergeCells() {
+ if (!this.selection || !this.isRectangle()) {
+ return;
+ }
+ const grid = buildTableGrid(this.selection.table);
+ const infos = grid.cellInfos.filter(info => this.selection.cells.has(info.cell))
+ .sort((a, b) => a.row - b.row || a.col - b.col);
+ if (infos.length < 2) {
+ return;
+ }
+ const rowStart = Math.min(...infos.map(info => info.row));
+ const rowEnd = Math.max(...infos.map(info => info.row + info.rowspan - 1));
+ const colStart = Math.min(...infos.map(info => info.col));
+ const colEnd = Math.max(...infos.map(info => info.col + info.colspan - 1));
+ const oldHTML = this.selection.node.outerHTML;
+ const first = infos[0].cell;
+ const contents = infos.map(info => info.cell.innerHTML.trim().replace(/<br>$/, "")).filter(Boolean);
+ infos.slice(1).forEach(info => {
+ info.cell.innerHTML = "";
+ info.cell.classList.add("fn__none");
+ });
+ first.innerHTML = contents.join("<br>");
+ first.rowSpan = rowEnd - rowStart + 1;
+ first.colSpan = colEnd - colStart + 1;
+ updateTransaction(this.protyle, this.selection.node, oldHTML);
+ this.selection.cells = new Set([first]);
+ this.selectedCells = [first];
+ this.selection.activeCell = first;
+ this.scheduleRender();
+ }
+
+ private splitCell(cell: HTMLTableCellElement) {
+ if (!this.selection) {
+ return;
+ }
+ const grid = buildTableGrid(this.selection.table);
+ const info = grid.cellInfos.find(item => item.cell === cell);
+ if (!info) {
+ return;
+ }
+ const oldHTML = this.selection.node.outerHTML;
+ const rows = Array.from(this.selection.table.rows);
+ for (let row = info.row; row < info.row + info.rowspan; row++) {
+ for (let col = info.col; col < info.col + info.colspan; col++) {
+ const current = rows[row]?.cells[col];
+ if (current && current !== cell) {
+ current.classList.remove("fn__none");
+ current.removeAttribute("rowspan");
+ current.removeAttribute("colspan");
+ }
+ }
+ }
+ cell.removeAttribute("rowspan");
+ cell.removeAttribute("colspan");
+ if (cell.tagName === "TH") {
+ const head = this.selection.table.tHead;
+ const body = this.selection.table.tBodies[0] || this.selection.table.createTBody();
+ const pureRow = Array.from(head?.rows || []).find(row =>
+ Array.from(row.cells).every(item => item.rowSpan === 1 && item.colSpan === 1 &&
+ !item.classList.contains("fn__none")));
+ while (pureRow && head.lastElementChild !== pureRow) {
+ const row = head.lastElementChild as HTMLTableRowElement;
+ Array.from(row.cells).forEach(item => replaceCellTag(item, "td"));
+ body.insertAdjacentElement("afterbegin", row);
+ }
+ }
+ updateTransaction(this.protyle, this.selection.node, oldHTML);
+ this.updateSelectedCells();
+ this.scheduleRender();
+ }
+
+ private addAtEnd(type: string) {
+ const node = getTableNode(this.hoverCell);
+ if (!node) {
+ return;
+ }
+ const table = node.querySelector("table") as HTMLTableElement;
+ const range = getEditorRange(this.hoverCell);
+ if (type === "add-row") {
+ const cell = table.rows[table.rows.length - 1].cells[0] as HTMLTableCellElement;
+ insertRow(this.protyle, range, cell, node);
+ } else {
+ const cell = table.rows[0].cells[table.rows[0].cells.length - 1] as HTMLTableCellElement;
+ insertColumn(this.protyle, node, cell, "afterend", range);
+ }
+ this.clear();
+ }
+
+ private handleDragMove(event: PointerEvent) {
+ if (!this.dragState || !this.selection) {
+ return;
+ }
+ if (!this.dragState.dragging &&
+ Math.hypot(event.clientX - this.dragState.startX, event.clientY - this.dragState.startY) < 4) {
+ return;
+ }
+ this.dragState.dragging = true;
+ const cell = getCell(document.elementFromPoint(event.clientX, event.clientY));
+ if (!cell || getTableNode(cell) !== this.selection.node) {
+ this.dragState.target = -1;
+ this.dropIndicator.classList.add("fn__none");
+ return;
+ }
+ const info = buildTableGrid(this.selection.table).cellInfos.find(item => item.cell === cell);
+ if (!info) {
+ return;
+ }
+ const rect = this.dragState.mode === "row" ? cell.parentElement.getBoundingClientRect() : cell.getBoundingClientRect();
+ const after = this.dragState.mode === "row" ? event.clientY > rect.top + rect.height / 2 :
+ event.clientX > rect.left + rect.width / 2;
+ this.dragState.target = (this.dragState.mode === "row" ? info.row : info.col) + (after ? 1 : 0);
+ this.dropIndicator.classList.remove("fn__none");
+ if (this.dragState.mode === "row") {
+ this.dropIndicator.classList.add("protyle-table-control__drop--row");
+ this.dropIndicator.classList.remove("protyle-table-control__drop--column");
+ this.dropIndicator.style.left = `${rect.left}px`;
+ this.dropIndicator.style.top = `${after ? rect.bottom : rect.top}px`;
+ this.dropIndicator.style.width = `${rect.width}px`;
+ this.dropIndicator.style.height = "2px";
+ } else {
+ const tableRect = this.selection.table.getBoundingClientRect();
+ this.dropIndicator.classList.add("protyle-table-control__drop--column");
+ this.dropIndicator.classList.remove("protyle-table-control__drop--row");
+ this.dropIndicator.style.left = `${after ? rect.right : rect.left}px`;
+ this.dropIndicator.style.top = `${tableRect.top}px`;
+ this.dropIndicator.style.width = "2px";
+ this.dropIndicator.style.height = `${tableRect.height}px`;
+ }
+ }
+
+ private handleDragEnd(event: PointerEvent) {
+ if (!this.dragState) {
+ return;
+ }
+ const state = this.dragState;
+ this.dropIndicator.classList.add("fn__none");
+ if (state.dragging && state.target >= 0) {
+ this.moveSelection(state.target);
+ event.preventDefault();
+ }
+ setTimeout(() => {
+ this.dragState = undefined;
+ });
+ }
+
+ private moveSelection(target: number) {
+ if (!this.selection || this.selection.mode === "cell") {
+ return;
+ }
+ const selected = Array.from(this.selection.indexes).sort((a, b) => a - b);
+ if (this.selection.mode === "row" && selected.length > 1 && (selected.includes(0) || target === 0)) {
+ return;
+ }
+ const adjustedTarget = target - selected.filter(index => index < target).length;
+ const oldHTML = this.selection.node.outerHTML;
+ if (this.selection.mode === "row") {
+ const rows = Array.from(this.selection.table.rows);
+ const moving = selected.map(index => rows[index]).filter(Boolean);
+ const remaining = rows.filter((row, index) => !selected.includes(index));
+ remaining.splice(Math.max(0, adjustedTarget), 0, ...moving);
+ const head = this.selection.table.tHead || this.selection.table.createTHead();
+ const body = this.selection.table.tBodies[0] || this.selection.table.createTBody();
+ head.innerHTML = "";
+ body.innerHTML = "";
+ remaining.forEach((row, index) => {
+ Array.from(row.cells).forEach(cell => replaceCellTag(cell, index === 0 ? "th" : "td"));
+ (index === 0 ? head : body).append(row);
+ });
+ const start = Math.max(0, adjustedTarget);
+ this.selection.indexes = new Set(getRangeIndexes(start, start + moving.length - 1));
+ this.selection.activeCell = remaining[start].cells[0];
+ this.hoverCell = this.selection.activeCell;
+ } else {
+ Array.from(this.selection.table.rows).forEach(row => {
+ const cells = Array.from(row.cells);
+ const moving = selected.map(index => cells[index]).filter(Boolean);
+ const remaining = cells.filter((cell, index) => !selected.includes(index));
+ remaining.splice(Math.max(0, adjustedTarget), 0, ...moving);
+ remaining.forEach(cell => row.append(cell));
+ });
+ const columns = Array.from(this.selection.table.querySelectorAll("col"));
+ if (columns.length > 0) {
+ const moving = selected.map(index => columns[index]).filter(Boolean);
+ const remaining = columns.filter((column, index) => !selected.includes(index));
+ remaining.splice(Math.max(0, adjustedTarget), 0, ...moving);
+ remaining.forEach(column => column.parentElement.append(column));
+ }
+ this.selection.indexes = new Set(getRangeIndexes(adjustedTarget, adjustedTarget + selected.length - 1));
+ }
+ updateTransaction(this.protyle, this.selection.node, oldHTML);
+ this.updateSelectedCells();
+ this.scheduleRender();
+ }
+
+ private writeClipboard(event: ClipboardEvent) {
+ if (!this.selection || !event.clipboardData) {
+ return false;
+ }
+ let html = "";
+ if (this.selection.mode === "cell") {
+ if (!this.isRectangle()) {
+ return false;
+ }
+ const grid = buildTableGrid(this.selection.table);
+ const infos = grid.cellInfos.filter(info => this.selection.cells.has(info.cell));
+ const rowStart = Math.min(...infos.map(info => info.row));
+ const rowEnd = Math.max(...infos.map(info => info.row + info.rowspan - 1));
+ const colStart = Math.min(...infos.map(info => info.col));
+ const colEnd = Math.max(...infos.map(info => info.col + info.colspan - 1));
+ html = getTableRangeHTML(this.selection.table, grid.grid[rowStart][colStart], grid.grid[rowEnd][colEnd]);
+ } else {
+ html = this.getCompressedTableHTML();
+ }
+ if (!html) {
+ return false;
+ }
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ const rows = Array.from(container.querySelectorAll("tr"));
+ const text = rows.map(row => Array.from(row.querySelectorAll("th, td")).filter(cell =>
+ !cell.classList.contains("fn__none")).map(cell => getCellText(cell as HTMLTableCellElement)).join("\t")).join("\n");
+ event.clipboardData.setData("text/plain", text);
+ event.clipboardData.setData("text/html", html);
+ return true;
+ }
+
+ private getCompressedTableHTML() {
+ const selection = this.selection;
+ const grid = buildTableGrid(selection.table);
+ const rows = selection.mode === "row" ? Array.from(selection.indexes).sort((a, b) => a - b) :
+ getRangeIndexes(0, grid.rowCount - 1);
+ const columns = selection.mode === "column" ? Array.from(selection.indexes).sort((a, b) => a - b) :
+ getRangeIndexes(0, grid.columnCount - 1);
+ const rowMap = new Map(rows.map((row, index) => [row, index]));
+ const columnMap = new Map(columns.map((column, index) => [column, index]));
+ const output: HTMLTableCellElement[][] = rows.map(() => []);
+ grid.cellInfos.forEach(info => {
+ const selectedRows = rows.filter(row => row >= info.row && row < info.row + info.rowspan);
+ const selectedColumns = columns.filter(column => column >= info.col && column < info.col + info.colspan);
+ if (selectedRows.length === 0 || selectedColumns.length === 0) {
+ return;
+ }
+ const row = rowMap.get(selectedRows[0]);
+ const column = columnMap.get(selectedColumns[0]);
+ const cell = info.cell.cloneNode(true) as HTMLTableCellElement;
+ cell.classList.remove("fn__none");
+ cell.rowSpan = selectedRows.length;
+ cell.colSpan = selectedColumns.length;
+ cell.dataset.tableControlColumn = String(column);
+ output[row].push(cell);
+ });
+ const table = document.createElement("table");
+ const head = table.createTHead();
+ const body = table.createTBody();
+ let headRowCount = Math.max(1, rows.filter(row => grid.sectionOfRow[row] === "thead").length);
+ for (let rowIndex = 0; rowIndex < headRowCount; rowIndex++) {
+ output[rowIndex]?.forEach(cell => {
+ headRowCount = Math.max(headRowCount, rowIndex + cell.rowSpan);
+ });
+ }
+ output.forEach((cells, rowIndex) => {
+ const row = document.createElement("tr");
+ cells.sort((a, b) => Number(a.dataset.tableControlColumn) - Number(b.dataset.tableControlColumn));
+ cells.forEach(cell => {
+ delete cell.dataset.tableControlColumn;
+ row.append(replaceCellTag(cell, rowIndex < headRowCount ? "th" : "td"));
+ });
+ (rowIndex < headRowCount ? head : body).append(row);
+ });
+ return table.outerHTML;
+ }
+}
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index fe0b998403..cf360c3382 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -75,6 +75,7 @@ import {MenuItem} from "../../menus/Menu";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {onGet} from "../util/onGet";
import {clearTableCell, getTableRangeHTML, isIncludeCell, setTableAlign, updateTableTitle} from "../util/table";
+import {TableControl} from "../util/tableControl";
import {countBlockWord, countSelectWord} from "../../layout/status";
import {showMessage} from "../../dialog/message";
import {getBacklinkHeadingMore, loadBreadcrumb} from "./renderBacklink";
@@ -228,6 +229,7 @@ export class WYSIWYG {
private preventInput: boolean;
private inputTimeout: number;
private pendingInputTimeouts = new Map<number, () => void>();
+ public tableControl: TableControl;
private scheduleInput(callback: () => void, delay = 0, replace = true) {
if (replace && this.inputTimeout) {
@@ -269,6 +271,9 @@ export class WYSIWYG {
if (window.siyuan.config.editor.displayBookmarkIcon) {
this.element.classList.add("protyle-wysiwyg--attr");
}
+ if (!isMobile()) {
+ this.tableControl = new TableControl(protyle, this.element);
+ }
this.bindCommonEvent(protyle);
this.bindEvent(protyle);
if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {