An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Fix merged table cell copy and paste https://github.com/siyuan-note/siyuan/issues/18255
Daniel85478d9c89c6
diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.tsindex e74d7798ef..655111ea2e 100644--- a/app/src/protyle/util/insertHTML.ts+++ b/app/src/protyle/util/insertHTML.ts@@ -19,7 +19,7 @@ import {updateCellsValue} from "../render/av/cell";import {input} from "../wysiwyg/input";import {updateListOrder} from "../wysiwyg/list";import {fetchPost} from "../../util/fetch";-import {isIncludeCell} from "./table";+import {getTableRangeCells, isIncludeCell} from "./table";import {getFieldIdByCellElement, getRowHTML} from "../render/av/row";import {getAvBodyData} from "../render/av/virtualScroll";import {processClonePHElement} from "../render/util";@@ -265,37 +265,86 @@ const processAV = (range: Range, html: string, protyle: IProtyle, blockElement:});};-const processTable = (range: Range, html: string, protyle: IProtyle, blockElement: HTMLElement) => {+interface ITablePasteRange {+ table: HTMLTableElement;+ startCell: HTMLTableCellElement;+ endCell: HTMLTableCellElement;+}++const getTablePasteRange = (range: Range): ITablePasteRange | undefined => {+ if (range.collapsed) {+ return undefined;+ }+ const startCell = (hasClosestByTag(range.startContainer, "TD") ||+ hasClosestByTag(range.startContainer, "TH")) as HTMLTableCellElement;+ const endCell = (hasClosestByTag(range.endContainer, "TD") ||+ hasClosestByTag(range.endContainer, "TH")) as HTMLTableCellElement;+ if (!startCell || !endCell || startCell === endCell) {+ return undefined;+ }+ const table = startCell.closest("table");+ if (!table || table !== endCell.closest("table")) {+ return undefined;+ }+ return {table, startCell, endCell};+};++const processTable = (range: Range, html: string, protyle: IProtyle, blockElement: HTMLElement,+ pasteRange?: ITablePasteRange) => {const tempElement = document.createElement("template");tempElement.innerHTML = html;- const copyCellElements = tempElement.content.querySelectorAll("th, td");- if (copyCellElements.length === 0) {+ const copyTableElement = tempElement.content.querySelector("table") as HTMLTableElement;+ if (!copyTableElement) {+ return false;+ }+ const copyCells = getTableRangeCells(copyTableElement);+ if (copyCells.length === 0) {return false;}+ const tableElement = blockElement.querySelector("table") as HTMLTableElement;const scrollLeft = blockElement.firstElementChild.scrollLeft;- const scrollTop = blockElement.querySelector("table").scrollTop;+ const scrollTop = tableElement.scrollTop;const tableSelectElement = blockElement.querySelector(".table__select") as HTMLElement;- let index = 0;- const matchCellsElement: HTMLTableCellElement[] = [];- blockElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {- if (!item.classList.contains("fn__none") && copyCellElements.length > index &&- isIncludeCell({+ let startCell = pasteRange?.table === tableElement ? pasteRange.startCell : undefined;+ let endCell = pasteRange?.table === tableElement ? pasteRange.endCell : undefined;+ if (!startCell || !endCell) {+ tableElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {+ if (!item.classList.contains("fn__none") && isIncludeCell({tableSelectElement,scrollLeft,scrollTop,item,})) {- matchCellsElement.push(item);- index++;+ if (!startCell) {+ startCell = item;+ }+ endCell = item;+ }+ });+ }+ if (!startCell || !endCell) {+ return false;+ }+ const targetCells = getTableRangeCells(tableElement, startCell, endCell);+ // 按逻辑网格坐标匹配实际单元格,避免 colspan/rowspan 的 fn__none 占位导致内容错位。+ const copyCellMap = new Map(copyCells.map(item => [`${item.row}:${item.col}`, item.cell]));+ const matchedCells: { source: HTMLTableCellElement; target: HTMLTableCellElement }[] = [];+ targetCells.forEach(item => {+ const source = copyCellMap.get(`${item.row}:${item.col}`);+ if (source) {+ matchedCells.push({source, target: item.cell});}});+ if (matchedCells.length === 0) {+ return false;+ }tableSelectElement.removeAttribute("style");const oldHTML = blockElement.outerHTML;blockElement.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));- matchCellsElement.forEach((item, matchIndex) => {- item.innerHTML = copyCellElements[matchIndex].innerHTML;- if (matchIndex === matchCellsElement.length - 1) {- setLastNodeRange(item, range, false);+ matchedCells.forEach((item, index) => {+ item.target.innerHTML = item.source.innerHTML;+ if (index === matchedCells.length - 1) {+ setLastNodeRange(item.target, range, false);}});range.collapse(false);@@ -312,6 +361,7 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,return;}const range = useProtyleRange ? protyle.toolbar.range : getEditorRange(protyle.wysiwyg.element);+ const tablePasteRange = getTablePasteRange(range);fixTableRange(range);let unSpinHTML;if (hasClosestByAttribute(range.startContainer, "data-type", "NodeTable") && !isBlock) {@@ -343,8 +393,9 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,return;}}- if (blockElement.classList.contains("table") && blockElement.querySelector(".table__select").clientWidth > 0 &&- processTable(range, html, protyle, blockElement)) {+ if (blockElement.classList.contains("table") &&+ (tablePasteRange || blockElement.querySelector(".table__select").clientWidth > 0) &&+ processTable(range, html, protyle, blockElement, tablePasteRange)) {return;}diff --git a/app/src/protyle/util/table.ts b/app/src/protyle/util/table.tsindex ba22d3a7ad..7142dbcf5b 100644--- a/app/src/protyle/util/table.ts+++ b/app/src/protyle/util/table.ts@@ -887,23 +887,28 @@ export const updateTableTitle = (protyle: IProtyle, nodeElement: Element) => {inputElement.select();};-// getTableRangeHTML 根据起始单元格到结束单元格的矩形区域,重建一个合法的 <table> HTML。-// 用于表格内跨多单元格的文本选区复制/剪切:原 range.cloneContents()/extractContents() 会产出残缺片段。-// 算法:建立原表格的二维网格映射,确定选区的网格范围,枚举其中的物理单元格,-// 并根据每个单元格在新表格(选区)中的实际跨度重新计算 colspan/rowspan,避免维度错位。-export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElement, endCell: HTMLElement) => {- // 1. 建立二维网格映射,记录每个物理单元格的网格坐标、跨度及其所属行(用于保留 thead/tbody 划分)- // grid[r][c] = cell(每个单元格占据 rowspan×colspan 个网格位置)- type CellInfo = {- cell: HTMLTableCellElement;- row: number;- col: number;- rowspan: number;- colspan: number;- tr: HTMLTableRowElement- };- const cellInfos: CellInfo[] = [];- // sectionOfRow[r] = 该网格行对应的原始 section("thead" | "tbody"),用于输出时划分 thead/tbody+interface ITableCellInfo {+ cell: HTMLTableCellElement;+ row: number;+ col: number;+ rowspan: number;+ colspan: number;+}++interface ITableGrid {+ cellInfos: ITableCellInfo[];+ sectionOfRow: string[];+ rowCount: number;+}++export interface ITableRangeCell {+ cell: HTMLTableCellElement;+ row: number;+ col: number;+}++const buildTableGrid = (tableElement: HTMLElement): ITableGrid => {+ const cellInfos: ITableCellInfo[] = [];const sectionOfRow: string[] = [];const grid: (HTMLTableCellElement | null)[][] = [];const getCS = (cell: HTMLTableCellElement, attr: string) => {@@ -937,7 +942,7 @@ export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElemwhile (grid[rowIdx][colIdx]) {colIdx++;}- cellInfos.push({cell, row: rowIdx, col: colIdx, rowspan, colspan, tr: tr as HTMLTableRowElement});+ cellInfos.push({cell, row: rowIdx, col: colIdx, rowspan, colspan});// 占据网格for (let dr = 0; dr < rowspan; dr++) {ensureRow(rowIdx + dr);@@ -949,18 +954,68 @@ export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElem});});- // 2. 确定 startCell/endCell 的网格坐标+ return {cellInfos, sectionOfRow, rowCount: trElements.length};+};++const getTableRangeBounds = (cellInfos: ITableCellInfo[], rowCount: number, startCell: HTMLElement, endCell: HTMLElement) => {const startInfo = cellInfos.find(info => info.cell === startCell);const endInfo = cellInfos.find(info => info.cell === endCell);if (!startInfo || !endInfo) {+ return undefined;+ }+ return {+ rowStart: Math.min(startInfo.row, endInfo.row),+ // 历史数据可能存在超出表格末行的 rowspan,复制时不能为其生成仅含 fn__none 的虚拟尾行。+ rowEnd: Math.min(rowCount - 1,+ Math.max(startInfo.row + startInfo.rowspan - 1, endInfo.row + endInfo.rowspan - 1)),+ colStart: Math.min(startInfo.col, endInfo.col),+ colEnd: Math.max(startInfo.col + startInfo.colspan - 1, endInfo.col + endInfo.colspan - 1),+ };+};++// 返回选区内实际可编辑的单元格及其相对网格坐标,合并单元格占位不会进入结果。+export const getTableRangeCells = (tableElement: HTMLElement, startCell?: HTMLElement, endCell?: HTMLElement) => {+ const {cellInfos, rowCount} = buildTableGrid(tableElement);+ if (!startCell || !endCell) {+ return cellInfos.map(info => ({cell: info.cell, row: info.row, col: info.col}));+ }+ const bounds = getTableRangeBounds(cellInfos, rowCount, startCell, endCell);+ if (!bounds) {+ return [];+ }+ const ret: ITableRangeCell[] = [];+ cellInfos.forEach(info => {+ const row = Math.max(info.row, bounds.rowStart);+ const rowEnd = Math.min(info.row + info.rowspan - 1, bounds.rowEnd);+ const col = Math.max(info.col, bounds.colStart);+ const colEnd = Math.min(info.col + info.colspan - 1, bounds.colEnd);+ if (row <= rowEnd && col <= colEnd) {+ ret.push({cell: info.cell, row: row - bounds.rowStart, col: col - bounds.colStart});+ }+ });+ return ret;+};++// getTableRangeHTML 根据起始单元格到结束单元格的矩形区域,重建一个合法的 <table> HTML。+// 用于表格内跨多单元格的文本选区复制/剪切:原 range.cloneContents()/extractContents() 会产出残缺片段。+// 算法:建立原表格的二维网格映射,确定选区的网格范围,枚举其中的物理单元格,+// 并根据每个单元格在新表格(选区)中的实际跨度重新计算 colspan/rowspan,避免维度错位。+export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElement, endCell: HTMLElement) => {+ // 1. 建立二维网格映射,记录每个物理单元格的网格坐标、跨度及其所属行(用于保留 thead/tbody 划分)+ // grid[r][c] = cell(每个单元格占据 rowspan×colspan 个网格位置)+ const {cellInfos, sectionOfRow, rowCount} = buildTableGrid(tableElement);++ // 2. 确定 startCell/endCell 的网格坐标+ const bounds = getTableRangeBounds(cellInfos, rowCount, startCell, endCell);+ if (!bounds) {return "";}// 3. 计算选区网格范围(包含 startCell/endCell 各自的合并跨度)- const selRowStart = Math.min(startInfo.row, endInfo.row);- const selRowEnd = Math.max(startInfo.row + startInfo.rowspan - 1, endInfo.row + endInfo.rowspan - 1);- const selColStart = Math.min(startInfo.col, endInfo.col);- const selColEnd = Math.max(startInfo.col + startInfo.colspan - 1, endInfo.col + endInfo.colspan - 1);+ const selRowStart = bounds.rowStart;+ const selRowEnd = bounds.rowEnd;+ const selColStart = bounds.colStart;+ const selColEnd = bounds.colEnd;// 4. 枚举与选区有交集的单元格,计算在新表格中的行号、列号和跨度type OutCell = {@@ -1004,24 +1059,24 @@ export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElem// 5. 按新行列号输出。需建立输出网格以正确处理 rowspan 占位:// 当某单元格 newRowspan > 1 跨多行时,后续行对应列要插入 class="fn__none" 占位单元格//(与思源内部合并单元格规范一致),否则行列对应关系会错乱。- // 占位单元格的 th/td 类型、所属 section(thead/tbody)均跟随原表格对应位置,保留表头划分。+ // 输出时会根据规范化后的 thead/tbody 选择 th/td,保证结果可直接解析为独立表格块。if (outCells.length === 0) {return "";}const maxOutRow = outCells.reduce((m, oc) => Math.max(m, oc.newRow + oc.newRowspan - 1), 0);const maxOutCol = outCells.reduce((m, oc) => Math.max(m, oc.newCol + oc.newColspan - 1), 0);- // coveredTag[r][c] = 原表格中该网格位置对应的占位单元格标签名("th" 或 "td")- const coveredTag: string[][] = [];+ // coveredSlots[r][c] = 该网格位置被合并单元格覆盖+ const coveredSlots: boolean[][] = [];const outGrid: (OutCell | null)[][] = [];for (let r = 0; r <= maxOutRow; r++) {outGrid.push(new Array(maxOutCol + 1).fill(null));- coveredTag.push(new Array(maxOutCol + 1).fill(""));+ coveredSlots.push(new Array(maxOutCol + 1).fill(false));}// 按 newRow, newCol 排序后填充,确保起始格先于其占位被处理outCells.sort((a, b) => a.newRow - b.newRow || a.newCol - b.newCol);outCells.forEach(oc => {outGrid[oc.newRow][oc.newCol] = oc;- // 标记被 rowspan/colspan 覆盖的位置,并记录原始占位的标签名+ // 标记被 rowspan/colspan 覆盖的位置for (let dr = 0; dr < oc.newRowspan; dr++) {for (let dc = 0; dc < oc.newColspan; dc++) {if (dr === 0 && dc === 0) {@@ -1030,24 +1085,44 @@ export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElemconst rr = oc.newRow + dr;const cc = oc.newCol + dc;if (rr <= maxOutRow && cc <= maxOutCol) {- // 查原表格该位置的占位单元格类型- const origRow = selRowStart + rr;- const origCol = selColStart + cc;- const origCell = (origRow < grid.length && origCol < grid[origRow].length) ? grid[origRow][origCol] : null;- coveredTag[rr][cc] = origCell ? origCell.tagName.toLowerCase() : "td";+ coveredSlots[rr][cc] = true;}}}});- // 计算每个输出行所属的原始 section+ // 计算每个输出行所属的 section。独立表格必须包含 thead;从 tbody 开始复制时,将首行及其 rowspan+ // 覆盖的行提升为表头,避免合并单元格跨越 thead/tbody。const outSection = (outRow: number) => {const origRow = selRowStart + outRow;return (origRow < sectionOfRow.length && sectionOfRow[origRow]) ? sectionOfRow[origRow] : "tbody";};+ let originalHeadRows = 0;+ while (originalHeadRows <= maxOutRow && outSection(originalHeadRows) === "thead") {+ originalHeadRows++;+ }+ const mergedHeadRows = outCells.reduce((max, item) => {+ return item.newRow === 0 ? Math.max(max, item.newRowspan) : max;+ }, 1);+ const headRows = Math.min(maxOutRow + 1, Math.max(originalHeadRows, mergedHeadRows));+ const getOutputSection = (outRow: number) => {+ return outRow < headRows ? "thead" : "tbody";+ };+ const getCellHTML = (cell: HTMLTableCellElement, section: string) => {+ const tagName = section === "thead" ? "th" : "td";+ if (cell.tagName.toLowerCase() === tagName) {+ return cell.outerHTML;+ }+ const outputCell = document.createElement(tagName);+ Array.from(cell.attributes).forEach(attribute => {+ outputCell.setAttribute(attribute.name, attribute.value);+ });+ outputCell.innerHTML = cell.innerHTML;+ return outputCell.outerHTML;+ };let html = "<table>";let curSection = "";for (let r = 0; r <= maxOutRow; r++) {- const section = outSection(r);+ const section = getOutputSection(r);if (section !== curSection) {if (curSection) {html += `</${curSection}>`;@@ -1059,13 +1134,14 @@ export const getTableRangeHTML = (tableElement: HTMLElement, startCell: HTMLElemfor (let c = 0; c <= maxOutCol; c++) {const slot = outGrid[r][c];if (slot) {- html += slot.newCell.outerHTML;- } else if (coveredTag[r][c]) {- // 被 rowspan/colspan 覆盖的占位,保留原始 th/td 标签- html += `<${coveredTag[r][c]} class="fn__none"></${coveredTag[r][c]}>`;+ html += getCellHTML(slot.newCell, section);+ } else if (coveredSlots[r][c]) {+ // 被 rowspan/colspan 覆盖的占位使用当前 section 对应的单元格标签。+ const tagName = section === "thead" ? "th" : "td";+ html += `<${tagName} class="fn__none"></${tagName}>`;} else {- // 选区内空洞(理论上不应发生),补空 td- html += "<td></td>";+ // 选区内空洞(理论上不应发生),补齐当前 section 的空单元格。+ html += section === "thead" ? "<th></th>" : "<td></td>";}}html += "</tr>";