Skip to content

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

:sparkles: Support database range selection https://github.com/siyuan-note/siyuan/issues/11975

Daniele8db98604000
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index 5acab973e5..dc4b88b696 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -17,7 +17,13 @@ import {
} from "./cell";
import {addCol, getColIconByType, getColNameByType, showColMenu} from "./col";
import {deleteRow, duplicateRows, insertRows, selectRow, setPageSize, updateHeader} from "./row";
-import {getAVPrimaryCell, getAVSelectedItems, resetAVRowSelect, updateAVRowSelect} from "./virtualScroll";
+import {
+ getAVPrimaryCell,
+ getAVSelectedItemInfos,
+ getAVSelectedItems,
+ resetAVRowSelect,
+ updateAVRowSelect
+} from "./virtualScroll";
import {emitOpenMenu} from "../../../plugin/EventBus";
import {openMenuPanel} from "./openMenuPanel";
import {hintRef} from "../../hint/extend";
@@ -30,6 +36,7 @@ import {openCalcMenu} from "./calc";
import {avRender, getGroupFoldTip} from "./render";
import {addView, openViewMenu} from "./view";
import {isOnlyMeta, writeText} from "../../util/compatibility";
+import {selectAVItemRange, setAVItemAnchor} from "./rangeSelect";
import {openSearchAV} from "./relation";
import {Constants} from "../../../constants";
import {hideElements} from "../../ui/hideElements";
@@ -57,8 +64,8 @@ const isDetachedDatabaseCell = (cellElement: HTMLElement) => {
return cellElement.dataset.detached === "true" || !cellElement.querySelector(".av__celltext--ref");
};
-const getPrimaryRowInfo = (blockElement: HTMLElement, rowElement: HTMLElement) => {
- const cellElement = rowElement.querySelector('.av__cell[data-dtype="block"]') as HTMLElement;
+const getPrimaryRowInfo = (blockElement: HTMLElement, rowElement?: HTMLElement, itemID = rowElement?.dataset.id) => {
+ const cellElement = rowElement?.querySelector('.av__cell[data-dtype="block"]') as HTMLElement;
if (cellElement) {
const value = genCellValueByElement("block", cellElement);
return {
@@ -71,7 +78,7 @@ const getPrimaryRowInfo = (blockElement: HTMLElement, rowElement: HTMLElement) =
isDetached: isDetachedDatabaseCell(cellElement),
};
}
- const cell = getAVPrimaryCell(blockElement, rowElement.dataset.id);
+ const cell = getAVPrimaryCell(blockElement, itemID);
if (!cell?.value) {
return;
}
@@ -360,7 +367,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
return;
}
if (cellType === "updated" || cellType === "created" || cellType === "lineNumber") {
- selectRow(rowElement.querySelector(".av__firstcol"), "toggle");
+ clearSelect(["row"], blockElement);
} else {
scrollElement.querySelectorAll(".av__row--select").forEach(item => {
item.querySelector(".av__firstcol use").setAttribute("xlink:href", "#iconUncheck");
@@ -495,7 +502,13 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
return true;
} else if (target.classList.contains("av__firstcol")) {
window.siyuan.menus.menu.remove();
- selectRow(target, "toggle");
+ const rowElement = hasClosestByClassName(target, "av__row") as HTMLElement;
+ if (event.shiftKey) {
+ selectAVItemRange(blockElement, rowElement);
+ } else {
+ selectRow(target, "toggle");
+ setAVItemAnchor(blockElement, rowElement);
+ }
event.preventDefault();
event.stopPropagation();
return true;
@@ -538,7 +551,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
event.stopPropagation();
return true;
} else if (target.classList.contains("av__row") && event.shiftKey && !target.classList.contains("av__row--header")) {
- selectRow(target.querySelector(".av__firstcol"), "toggle");
+ selectAVItemRange(blockElement, target);
event.preventDefault();
event.stopPropagation();
return true;
@@ -609,17 +622,21 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
}
updateHeader(rowElement);
}
+ setAVItemAnchor(blockElement as HTMLElement, rowElement);
const menu = new Menu();
const rowElements = blockElement.querySelectorAll(".av__row--select:not(.av__row--header), .av__gallery-item--select");
+ const selectedItemInfos = getAVSelectedItemInfos(blockElement);
const selectedItems = getAVSelectedItems(blockElement);
- const primaryRows = Array.from(rowElements)
- .map(item => getPrimaryRowInfo(blockElement, item as HTMLElement))
+ const primaryRows = selectedItemInfos
+ .map(item => getPrimaryRowInfo(blockElement,
+ blockElement.querySelector(`.av__row[data-id="${item.itemID}"], .av__gallery-item[data-id="${item.itemID}"]`) as HTMLElement,
+ item.itemID))
.filter((item): item is NonNullable<ReturnType<typeof getPrimaryRowInfo>> => Boolean(item));
- if (primaryRows.length !== rowElements.length) {
+ if (primaryRows.length !== selectedItemInfos.length) {
return false;
}
const ids = primaryRows.map(item => item.blockID);
- if (rowElements.length === 1 && !primaryRows[0].isDetached) {
+ if (selectedItemInfos.length === 1 && !primaryRows[0].isDetached) {
/// #if !MOBILE
const blockId = ids[0];
const openSubmenus = openEditorTab(protyle.app, [blockId], undefined, undefined, true);
@@ -655,7 +672,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
click() {
let text = "";
primaryRows.forEach((item, i) => {
- if (rowElements.length > 1) {
+ if (selectedItemInfos.length > 1) {
text += "- ";
}
text += item.content.trim();
@@ -673,14 +690,13 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
const databaseBlockID = blockElement.dataset.nodeId;
const viewID = blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW) ||
blockElement.querySelector(".layout-tab-bar .item--focus")?.getAttribute("data-id") || "";
- const links = Array.from(rowElements).map((item: HTMLElement) => {
+ const links = selectedItemInfos.map(item => {
const params = new URLSearchParams({
avViewID: viewID,
- avItemID: item.dataset.id,
+ avItemID: item.itemID,
});
- const groupID = (hasClosestByClassName(item, "av__body") as HTMLElement)?.dataset.groupId;
- if (groupID) {
- params.set("avGroupID", groupID);
+ if (item.groupID) {
+ params.set("avGroupID", item.groupID);
}
return `siyuan://blocks/${databaseBlockID}?${params.toString()}`;
});
@@ -842,7 +858,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
iconHTML: "",
label: window.siyuan.languages.duplicate,
click: () => {
- duplicateRows(blockElement, protyle, rowElements);
+ duplicateRows(blockElement, protyle, selectedItemInfos.map(item => item.itemID));
}
});
@@ -890,11 +906,10 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
label: window.siyuan.languages.addToDatabase,
icon: "iconDatabase",
click() {
- openSearchAV(blockElement.getAttribute("data-av-id"), rowElements[0] as HTMLElement, (listItemElement) => {
+ openSearchAV(blockElement.getAttribute("data-av-id"), rowElement, (listItemElement) => {
const srcs: IOperationSrcs[] = [];
const sourceIds: string[] = [];
- rowElements.forEach((item, index) => {
- const rowId = item.getAttribute("data-id");
+ selectedItemInfos.forEach((item, index) => {
const primaryInfo = primaryRows[index];
srcs.push({
itemID: Lute.NewNodeID(),
@@ -902,7 +917,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
id: primaryInfo.blockID,
isDetached: primaryInfo.isDetached,
});
- sourceIds.push(rowId);
+ sourceIds.push(item.itemID);
});
const avID = listItemElement.dataset.avId;
const viewID = listItemElement.dataset.viewId;
@@ -927,7 +942,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
}, true, blockElement.getAttribute("data-node-id"));
}
});
- if (rowElements.length === 1) {
+ if (selectedItemInfos.length === 1) {
if (!primaryRows[0].isDetached) {
menu.addSeparator({id: "separator_1"});
}
@@ -947,8 +962,8 @@ ${window.siyuan.languages[avType === "table" ? "insertRowBefore" : "insertItemBe
blockElement,
protyle,
count: parseInt(inputElement.value),
- previousID: rowElements[0].previousElementSibling?.getAttribute("data-id"),
- groupID: rowElements[0].parentElement.getAttribute("data-group-id")
+ previousID: selectedItemInfos[0].previousID,
+ groupID: selectedItemInfos[0].groupID
});
menu.close();
});
@@ -958,8 +973,8 @@ ${window.siyuan.languages[avType === "table" ? "insertRowBefore" : "insertItemBe
blockElement,
protyle,
count: parseInt(inputElement.value),
- previousID: rowElements[0].previousElementSibling?.getAttribute("data-id"),
- groupID: rowElements[0].parentElement.getAttribute("data-group-id")
+ previousID: selectedItemInfos[0].previousID,
+ groupID: selectedItemInfos[0].groupID
});
menu.close();
}
@@ -982,8 +997,8 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
blockElement,
protyle,
count: parseInt(inputElement.value),
- previousID: rowElements[0].getAttribute("data-id"),
- groupID: rowElements[0].parentElement.getAttribute("data-group-id")
+ previousID: selectedItemInfos[0].itemID,
+ groupID: selectedItemInfos[0].groupID
});
menu.close();
});
@@ -993,8 +1008,8 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
blockElement,
protyle,
count: parseInt(inputElement.value),
- previousID: rowElements[0].getAttribute("data-id"),
- groupID: rowElements[0].parentElement.getAttribute("data-group-id")
+ previousID: selectedItemInfos[0].itemID,
+ groupID: selectedItemInfos[0].groupID
});
menu.close();
}
@@ -1011,7 +1026,7 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
unbindDatabaseRow(
protyle,
blockElement,
- rowElements[0] as HTMLElement,
+ rowElement,
primaryRows[0]
);
}
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index be31f4e4d9..3b413ffac2 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -28,6 +28,7 @@ import {
getConvertedEmptyAVCellValue,
} from "./cellValue";
import {setPosition} from "../../../util/setPosition";
+import {getAVSelectedCells, IAVSelectedCell, updateAVSelectedCellValue} from "./selectionState";
export {cellValueIsEmpty} from "./cellValue";
@@ -749,12 +750,16 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
const id = nodeElement.dataset.nodeId;
let text = "";
const json: IAVCellValue[][] = [];
- let cellElements: Element[];
+ let cellElements: Element[] = [];
+ let selectedCells: IAVSelectedCell[] = [];
if (cElements?.length > 0) {
cellElements = cElements;
} else {
- cellElements = Array.from(nodeElement.querySelectorAll(".av__cell--active, .av__cell--select"));
- if (cellElements.length === 0) {
+ selectedCells = getAVSelectedCells(nodeElement);
+ if (selectedCells.length === 0) {
+ cellElements = Array.from(nodeElement.querySelectorAll(".av__cell--active, .av__cell--select"));
+ }
+ if (cellElements.length === 0 && selectedCells.length === 0) {
nodeElement.querySelectorAll(".av__row--select:not(.av__row--header)").forEach(rowElement => {
rowElement.querySelectorAll(".av__cell").forEach(cellElement => {
cellElements.push(cellElement);
@@ -762,40 +767,65 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
});
}
}
- const isCustomAttr = hasClosestByClassName(cellElements[0], "custom-attr");
+ const sources: Array<{ element?: HTMLElement, selectedCell?: IAVSelectedCell }> = selectedCells.length > 0 ?
+ selectedCells.map(selectedCell => ({selectedCell})) :
+ cellElements.map((element: HTMLElement) => ({element}));
+ if (sources.length === 0) {
+ return {text: "", json};
+ }
+ const isCustomAttr = sources[0].element ?
+ Boolean(hasClosestByClassName(sources[0].element, "custom-attr")) : false;
const viewType = nodeElement.getAttribute("data-av-type") as TAVView;
- for (let elementIndex = 0; elementIndex < cellElements.length; elementIndex++) {
- let item = cellElements[elementIndex] as HTMLElement;
- const rowID = getFieldIdByCellElement(item, viewType);
+ for (let elementIndex = 0; elementIndex < sources.length; elementIndex++) {
+ const source = sources[elementIndex];
+ let item = source.element;
+ const rowID = source.selectedCell?.rowID || (item ? getFieldIdByCellElement(item, viewType) : "");
if (!rowID) {
- break;
+ continue;
}
- if (!nodeElement.contains(item)) {
+ if (item && !nodeElement.contains(item)) {
if (viewType === "table") {
- item = cellElements[elementIndex] = (nodeElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${item.dataset.colId}"]`) ||
+ item = source.element = (nodeElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${item.dataset.colId}"]`) ||
nodeElement.querySelector(`.fn__flex-1[data-col-id="${item.dataset.colId}"]`)) as HTMLElement;
} else {
- item = cellElements[elementIndex] = (nodeElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`)) as HTMLElement;
+ item = source.element = nodeElement.querySelector(
+ `.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`) as HTMLElement;
}
}
-
- if (!item) {
+ if (!item && !source.selectedCell) {
// 兼容新增行后台隐藏
- break;
+ continue;
}
- const type = item.dataset.dtype as TAVCol || getTypeByCellElement(item) || item.dataset.type as TAVCol;
- if (["created", "updated", "template", "rollup"].includes(type)) {
- break;
+ const type = source.selectedCell?.column.type ||
+ (item ? item.dataset.dtype as TAVCol || getTypeByCellElement(item) || item.dataset.type as TAVCol : undefined);
+ if (!type) {
+ continue;
}
- const cellId = item.dataset.id; // 刚创建时无 id,更新需和 oldValue 保持一致
- const colId = getColId(item, viewType);
-
- text += getCellText(item) + ((cellElements[elementIndex + 1] && item.nextElementSibling && item.nextElementSibling === cellElements[elementIndex + 1]) ? "\t" : "\n\n");
- const oldValue = genCellValueByElement(type, item);
- if (elementIndex === 0 || cellElements[elementIndex - 1] !== item.previousElementSibling) {
+ const readonly = ["created", "updated", "template", "rollup", "lineNumber"].includes(type);
+ const cellId = source.selectedCell?.cell.id || item?.dataset.id;
+ const colId = source.selectedCell?.colID || (item ? getColId(item, viewType) : "");
+ const oldValue = source.selectedCell?.cell.value || (item ? genCellValueByElement(type, item) : undefined);
+ if (!colId || !oldValue) {
+ continue;
+ }
+ const nextSource = sources[elementIndex + 1];
+ const sameNextRow = nextSource && (source.selectedCell ?
+ nextSource.selectedCell?.rowID === rowID :
+ Boolean(item?.nextElementSibling && item.nextElementSibling === nextSource.element));
+ const cellText = item ? getCellText(item) :
+ getCellValueText(oldValue, source.selectedCell?.column, source.selectedCell?.rowIndex);
+ text += cellText + (sameNextRow ? "\t" : "\n\n");
+ const previousSource = sources[elementIndex - 1];
+ const samePreviousRow = previousSource && (source.selectedCell ?
+ previousSource.selectedCell?.rowID === rowID :
+ previousSource.element === item?.previousElementSibling);
+ if (!samePreviousRow) {
json.push([]);
}
json[json.length - 1].push(oldValue);
+ if (readonly || !cellId) {
+ continue;
+ }
let newValue = value;
// relation 为全部更新,以下类型为添加
if (type === "mAsset") {
@@ -891,7 +921,7 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
newValue.icon = oldValue.block.icon;
}
}
- let column = columns?.find(columnItem => columnItem.id === colId);
+ let column = source.selectedCell?.column || columns?.find(columnItem => columnItem.id === colId);
if (type === "date" && !column) {
const response = await fetchSyncPost("/api/av/getAttributeViewKeysByID", {avID, keyIDs: [colId]});
column = response.data?.[0];
@@ -938,13 +968,14 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
rowID,
data: oldValue
});
- if (isCustomAttr) {
+ if (isCustomAttr && item) {
item.innerHTML = genAVValueHTML(cellValue, column?.dateFormat);
item.parentElement.dataset.empty = cellValueIsEmpty(cellValue).toString();
- } else {
+ } else if (item) {
updateAttrViewCellAnimation(item, cellValue);
}
updateAttrViewCellInOtherElements(protyle, avID, rowID, colId, cellValue, item);
+ updateAVSelectedCellValue(nodeElement, rowID, colId, cellValue);
}
}
if (getOperations) {
@@ -1147,6 +1178,30 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru
return text;
};
+const getCellValueText = (value: IAVCellValue, column?: IAVColumn, rowIndex = 0) => {
+ const cellElement = document.createElement("div");
+ cellElement.innerHTML = renderCell(value, rowIndex, true, "table", column?.options, column?.dateFormat);
+ return getCellText(cellElement);
+};
+
+export const getAVSelectedCellData = (blockElement: HTMLElement) => {
+ const selectedCells = getAVSelectedCells(blockElement);
+ const json: IAVCellValue[][] = [];
+ let text = "";
+ selectedCells.forEach((item, index) => {
+ if (index === 0 || selectedCells[index - 1].rowID !== item.rowID) {
+ json.push([]);
+ }
+ json[json.length - 1].push(item.cell.value);
+ text += getCellValueText(item.cell.value, item.column, item.rowIndex);
+ text += index === selectedCells.length - 1 || selectedCells[index + 1].rowID !== item.rowID ? "\n" : "\t";
+ });
+ return {
+ json,
+ text: text.substring(0, text.length - 1),
+ };
+};
+
const renderRollup = (cellValue: IAVCellValue, showIcon: boolean) => {
let text = "";
if (["text"].includes(cellValue.type)) {
diff --git a/app/src/protyle/render/av/keydown.ts b/app/src/protyle/render/av/keydown.ts
index ec88596881..9bab687419 100644
--- a/app/src/protyle/render/av/keydown.ts
+++ b/app/src/protyle/render/av/keydown.ts
@@ -1,5 +1,5 @@
import {matchHotKey} from "../../util/hotKey";
-import {deleteRow, insertRows, selectRow} from "./row";
+import {deleteRow, insertRows} from "./row";
import {addDragFill, cellScrollIntoView, popTextCell, updateCellsValue} from "./cell";
import {avContextmenu} from "./action";
import {hasClosestByClassName} from "../../util/hasClosest";
@@ -8,6 +8,14 @@ import {upDownHint} from "../../../util/upDownHint";
import {clearSelect} from "../../util/clear";
import {getAVSelectedItems} from "./virtualScroll";
import {createAttributeViewItemDocs} from "./newItemTemplate";
+import {
+ moveAVCellRange,
+ moveAVItemRange,
+ selectAVItemRange,
+ setAVCellAnchor,
+ setAVItemAnchor,
+} from "./rangeSelect";
+import {getAVCellSelection, getAVItemSelection} from "./selectionState";
export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyle: IProtyle) => {
if (!nodeElement.classList.contains("av") || !window.siyuan.menus.menu.element.classList.contains("fn__none")) {
@@ -53,7 +61,35 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
event.stopPropagation();
return true;
}
- const selectCellElement = nodeElement.querySelector(".av__cell--select") as HTMLElement;
+ const cellSelection = getAVCellSelection(nodeElement);
+ const selectCellElement = (cellSelection ?
+ nodeElement.querySelector(`.av__row[data-id="${cellSelection.focus.rowID}"] .av__cell[data-col-id="${cellSelection.focus.colID}"]`) :
+ nodeElement.querySelector(".av__cell--select")) as HTMLElement;
+ if (!selectCellElement && cellSelection && event.key === "Escape") {
+ clearSelect(["cell"], nodeElement);
+ event.preventDefault();
+ return true;
+ }
+ if (!selectCellElement && cellSelection && (event.key === "Backspace" || event.key === "Delete")) {
+ updateCellsValue(protyle, nodeElement);
+ event.preventDefault();
+ return true;
+ }
+ if (!selectCellElement && cellSelection && event.shiftKey &&
+ ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
+ const previousFocus = `${cellSelection.focus.rowID}:${cellSelection.focus.colID}`;
+ const targetElement = moveAVCellRange(nodeElement,
+ event.key.replace("Arrow", "").toLowerCase() as "left" | "right" | "up" | "down");
+ if (targetElement) {
+ cellScrollIntoView(nodeElement, targetElement, ["ArrowUp", "ArrowDown"].includes(event.key));
+ } else if ((event.key === "ArrowUp" || event.key === "ArrowDown") &&
+ previousFocus !== `${getAVCellSelection(nodeElement)?.focus.rowID}:${getAVCellSelection(nodeElement)?.focus.colID}`) {
+ protyle.contentElement.scrollBy({top: event.key === "ArrowUp" ? -48 : 48});
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ }
if (selectCellElement) {
const rowElement = hasClosestByClassName(selectCellElement, "av__row");
if (!rowElement || rowElement.dataset.type === "ghost") {
@@ -71,13 +107,12 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
}
// 需在 avPanelElement 之后,否则点击资源单元格后删除,资源面板不会更新
if (event.key === "Backspace" || event.key === "Delete") {
- updateCellsValue(protyle, nodeElement, undefined, Array.from(nodeElement.querySelectorAll(".av__cell--active, .av__cell--select")));
+ updateCellsValue(protyle, nodeElement);
event.preventDefault();
return true;
}
if (event.key === "Escape") {
clearSelect(["cell"], nodeElement);
- selectRow(rowElement.querySelector(".av__firstcol"), "select");
event.preventDefault();
return true;
}
@@ -86,6 +121,23 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
event.preventDefault();
return true;
}
+ if (event.shiftKey && ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
+ if (!getAVCellSelection(nodeElement)) {
+ setAVCellAnchor(nodeElement, selectCellElement);
+ }
+ const previousFocus = getAVCellSelection(nodeElement)?.focus;
+ const newCellElement = moveAVCellRange(nodeElement,
+ event.key.replace("Arrow", "").toLowerCase() as "left" | "right" | "up" | "down");
+ if (newCellElement) {
+ cellScrollIntoView(nodeElement, newCellElement, ["ArrowUp", "ArrowDown"].includes(event.key));
+ } else if ((event.key === "ArrowUp" || event.key === "ArrowDown") &&
+ previousFocus?.rowID !== getAVCellSelection(nodeElement)?.focus.rowID) {
+ protyle.contentElement.scrollBy({top: event.key === "ArrowUp" ? -48 : 48});
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ }
let newCellElement;
if (event.key === "ArrowLeft" || matchHotKey("⇧⇥", event)) {
const previousRowElement = rowElement.previousElementSibling;
@@ -181,7 +233,34 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
return true;
}
}
- const selectRowElements = nodeElement.querySelectorAll(".av__row--select:not(.av__row--header)");
+ const selectRowElements = nodeElement.querySelectorAll(
+ ".av__row--select:not(.av__row--header), .av__gallery-item--select");
+ const itemSelection = getAVItemSelection(nodeElement);
+ if (selectRowElements.length === 0 && itemSelection && event.shiftKey &&
+ (event.key === "ArrowUp" || event.key === "ArrowDown")) {
+ const previousFocusID = itemSelection.focusID;
+ const targetElement = moveAVItemRange(nodeElement, event.key === "ArrowUp" ? "up" : "down");
+ if (targetElement) {
+ cellScrollIntoView(nodeElement, targetElement);
+ } else if (previousFocusID !== getAVItemSelection(nodeElement)?.focusID) {
+ protyle.contentElement.scrollBy({top: event.key === "ArrowUp" ? -48 : 48});
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ }
+ if (selectRowElements.length === 0 && getAVSelectedItems(nodeElement).length > 0) {
+ if (event.key === "Escape") {
+ clearSelect(["row", "galleryItem"], nodeElement);
+ event.preventDefault();
+ return true;
+ }
+ if (event.key === "Backspace") {
+ deleteRow(nodeElement, protyle);
+ event.preventDefault();
+ return true;
+ }
+ }
if (selectRowElements.length > 0) {
if (matchHotKey("⌘/", event)) {
event.stopPropagation();
@@ -194,7 +273,7 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
}
if (event.key === "Escape") {
event.preventDefault();
- selectRow(selectRowElements[0].querySelector(".av__firstcol"), "unselectAll");
+ clearSelect(["row", "galleryItem"], nodeElement);
return true;
}
if (event.key === "Backspace") {
@@ -203,17 +282,33 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
return true;
}
if (event.key === "Enter") {
- selectRow(selectRowElements[0].querySelector(".av__firstcol"), "unselectAll");
+ clearSelect(["row", "galleryItem"], nodeElement);
popTextCell(protyle, [selectRowElements[0].querySelector(".av__cell")]);
event.preventDefault();
return true;
}
- // TODO event.shiftKey
+ if (event.shiftKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
+ if (!getAVItemSelection(nodeElement)) {
+ setAVItemAnchor(nodeElement, selectRowElements[event.key === "ArrowUp" ? 0 :
+ selectRowElements.length - 1] as HTMLElement);
+ }
+ const previousFocusID = getAVItemSelection(nodeElement)?.focusID;
+ const targetElement = moveAVItemRange(nodeElement, event.key === "ArrowUp" ? "up" : "down");
+ if (targetElement) {
+ cellScrollIntoView(nodeElement, targetElement);
+ } else if (previousFocusID !== getAVItemSelection(nodeElement)?.focusID) {
+ protyle.contentElement.scrollBy({top: event.key === "ArrowUp" ? -48 : 48});
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ }
if (event.key === "ArrowUp") {
- const previousRowElement = selectRowElements[0].previousElementSibling;
- selectRow(selectRowElements[0].querySelector(".av__firstcol"), "unselectAll");
- if (previousRowElement && !previousRowElement.classList.contains("av__row--header")) {
- selectRow(previousRowElement.querySelector(".av__firstcol"), "select");
+ const previousRowElement = selectRowElements[0].previousElementSibling as HTMLElement;
+ clearSelect(["row", "galleryItem"], nodeElement);
+ if (previousRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]")) {
+ setAVItemAnchor(nodeElement, previousRowElement as HTMLElement);
+ selectAVItemRange(nodeElement, previousRowElement);
cellScrollIntoView(nodeElement, previousRowElement);
} else {
nodeElement.classList.add("protyle-wysiwyg--select");
@@ -222,10 +317,11 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
return true;
}
if (event.key === "ArrowDown") {
- const nextRowElement = selectRowElements[selectRowElements.length - 1].nextElementSibling;
- selectRow(selectRowElements[0].querySelector(".av__firstcol"), "unselectAll");
- if (nextRowElement && !nextRowElement.classList.contains("av__row--util")) {
- selectRow(nextRowElement.querySelector(".av__firstcol"), "select");
+ const nextRowElement = selectRowElements[selectRowElements.length - 1].nextElementSibling as HTMLElement;
+ clearSelect(["row", "galleryItem"], nodeElement);
+ if (nextRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]")) {
+ setAVItemAnchor(nodeElement, nextRowElement as HTMLElement);
+ selectAVItemRange(nodeElement, nextRowElement);
cellScrollIntoView(nodeElement, nextRowElement);
} else {
nodeElement.classList.add("protyle-wysiwyg--select");
diff --git a/app/src/protyle/render/av/rangeSelect.ts b/app/src/protyle/render/av/rangeSelect.ts
new file mode 100644
index 0000000000..d9355593a0
--- /dev/null
+++ b/app/src/protyle/render/av/rangeSelect.ts
@@ -0,0 +1,320 @@
+import {hasClosestByClassName} from "../../util/hasClosest";
+import {
+ getAVData,
+ getAVLoadedItemInfos,
+ getAVSelectedItemIDs,
+ IAVItemInfo,
+ resetAVRowSelect,
+} from "./virtualScroll";
+import {updateAVSelectionStatus} from "./row";
+import {
+ clearAVCellSelectionState,
+ clearAVItemSelectionState,
+ getAVCellSelection,
+ getAVItemSelection,
+ IAVCellPoint,
+ IAVSelectedCell,
+ restoreAVCellSelection,
+ setAVCellSelection,
+ setAVItemAnchorState,
+ setAVItemSelectionState,
+} from "./selectionState";
+
+const getGroupID = (element: Element) => {
+ return (hasClosestByClassName(element, "av__body") as HTMLElement)?.dataset.groupId || "";
+};
+
+const getGroupView = (view: IAVView, groupID: string): IAVView | undefined => {
+ if (!groupID) {
+ return view.groups?.length > 0 ? undefined : view;
+ }
+ if (view.id === groupID) {
+ return view;
+ }
+ for (const group of view.groups || []) {
+ const result = getGroupView(group, groupID);
+ if (result) {
+ return result;
+ }
+ }
+};
+
+const getCellPoint = (cellElement: HTMLElement): IAVCellPoint | undefined => {
+ const rowElement = hasClosestByClassName(cellElement, "av__row") as HTMLElement;
+ if (!rowElement?.dataset.id || !cellElement.dataset.colId) {
+ return;
+ }
+ return {
+ groupID: getGroupID(rowElement),
+ rowID: rowElement.dataset.id,
+ colID: cellElement.dataset.colId,
+ };
+};
+
+const buildCellSelection = (blockElement: HTMLElement, anchor: IAVCellPoint,
+ focus: IAVCellPoint): IAVSelectedCell[] => {
+ if (anchor.groupID !== focus.groupID) {
+ return [];
+ }
+ const data = getAVData(blockElement);
+ const view = data && getGroupView(data.view, anchor.groupID) as IAVTable;
+ if (!view?.rows || !view.columns) {
+ return [];
+ }
+ const visibleColumns = view.columns.filter(column => !column.hidden);
+ const anchorRowIndex = view.rows.findIndex(row => row.id === anchor.rowID);
+ const focusRowIndex = view.rows.findIndex(row => row.id === focus.rowID);
+ const anchorColIndex = visibleColumns.findIndex(column => column.id === anchor.colID);
+ const focusColIndex = visibleColumns.findIndex(column => column.id === focus.colID);
+ if ([anchorRowIndex, focusRowIndex, anchorColIndex, focusColIndex].some(index => index < 0)) {
+ return [];
+ }
+ const rowStart = Math.min(anchorRowIndex, focusRowIndex);
+ const rowEnd = Math.max(anchorRowIndex, focusRowIndex);
+ const colStart = Math.min(anchorColIndex, focusColIndex);
+ const colEnd = Math.max(anchorColIndex, focusColIndex);
+ const selectedCells: IAVSelectedCell[] = [];
+ for (let rowIndex = rowStart; rowIndex <= rowEnd; rowIndex++) {
+ const row = view.rows[rowIndex];
+ for (let colIndex = colStart; colIndex <= colEnd; colIndex++) {
+ const column = visibleColumns[colIndex];
+ const sourceColIndex = view.columns.findIndex(item => item.id === column.id);
+ const cell = row.cells[sourceColIndex];
+ if (cell) {
+ selectedCells.push({
+ groupID: anchor.groupID,
+ rowID: row.id,
+ colID: column.id,
+ rowIndex,
+ colIndex,
+ cell,
+ column,
+ });
+ }
+ }
+ }
+ return selectedCells;
+};
+
+const clearCellDOM = (blockElement: HTMLElement) => {
+ blockElement.querySelectorAll<HTMLElement>(".av__cell--active, .av__cell--select").forEach(item => {
+ item.classList.remove("av__cell--active", "av__cell--select");
+ item.querySelector(".av__drag-fill")?.remove();
+ });
+};
+
+export const clearAVCellRange = (blockElement: HTMLElement) => {
+ clearCellDOM(blockElement);
+ clearAVCellSelectionState(blockElement);
+};
+
+const applyCellRange = (blockElement: HTMLElement, anchor: IAVCellPoint, focus: IAVCellPoint) => {
+ const cells = buildCellSelection(blockElement, anchor, focus);
+ if (cells.length === 0) {
+ return false;
+ }
+ clearAVItemSelection(blockElement, true);
+ setAVCellSelection(blockElement, {anchor, focus, cells});
+ restoreAVCellSelection(blockElement);
+ return true;
+};
+
+export const setAVCellAnchor = (blockElement: HTMLElement, cellElement: HTMLElement) => {
+ const point = getCellPoint(cellElement);
+ if (!point) {
+ return false;
+ }
+ return applyCellRange(blockElement, point, point);
+};
+
+export const selectAVCellRange = (blockElement: HTMLElement, cellElement: HTMLElement) => {
+ const focus = getCellPoint(cellElement);
+ if (!focus) {
+ return false;
+ }
+ const anchor = getAVCellSelection(blockElement)?.anchor;
+ if (!anchor || anchor.groupID !== focus.groupID) {
+ return applyCellRange(blockElement, focus, focus);
+ }
+ return applyCellRange(blockElement, anchor, focus);
+};
+
+const getRenderedCell = (blockElement: HTMLElement, point: IAVCellPoint) => {
+ const groupSelector = point.groupID ? `[data-group-id="${point.groupID}"]` : "";
+ return blockElement.querySelector<HTMLElement>(
+ `.av__body${groupSelector} .av__row[data-id="${point.rowID}"] .av__cell[data-col-id="${point.colID}"]`);
+};
+
+export const moveAVCellRange = (blockElement: HTMLElement, direction: "up" | "down" | "left" | "right") => {
+ const selection = getAVCellSelection(blockElement);
+ if (!selection) {
+ return;
+ }
+ const data = getAVData(blockElement);
+ const view = data && getGroupView(data.view, selection.focus.groupID) as IAVTable;
+ if (!view?.rows || !view.columns) {
+ return;
+ }
+ const columns = view.columns.filter(column => !column.hidden);
+ let rowIndex = view.rows.findIndex(row => row.id === selection.focus.rowID);
+ let colIndex = columns.findIndex(column => column.id === selection.focus.colID);
+ if (rowIndex < 0 || colIndex < 0) {
+ return;
+ }
+ if (direction === "up") {
+ rowIndex--;
+ } else if (direction === "down") {
+ rowIndex++;
+ } else if (direction === "left") {
+ colIndex--;
+ } else {
+ colIndex++;
+ }
+ if (!view.rows[rowIndex] || !columns[colIndex]) {
+ return;
+ }
+ const focus = {
+ groupID: selection.focus.groupID,
+ rowID: view.rows[rowIndex].id,
+ colID: columns[colIndex].id,
+ };
+ if (!applyCellRange(blockElement, selection.anchor, focus)) {
+ return;
+ }
+ return getRenderedCell(blockElement, focus);
+};
+
+const getItemElement = (blockElement: HTMLElement, item: Pick<IAVItemInfo, "itemID" | "groupID">) => {
+ const groupSelector = item.groupID ? `[data-group-id="${item.groupID}"]` : "";
+ return blockElement.querySelector<HTMLElement>(
+ `.av__body${groupSelector} .av__row[data-id="${item.itemID}"], ` +
+ `.av__body${groupSelector} .av__gallery-item[data-id="${item.itemID}"]`);
+};
+
+const syncItemSelectionDOM = (blockElement: HTMLElement, selectedIDs: Set<string>) => {
+ const isTable = blockElement.dataset.avType === "table";
+ blockElement.querySelectorAll<HTMLElement>(".av__row[data-id], .av__gallery-item[data-id]").forEach(item => {
+ if (item.closest(".av") !== blockElement) {
+ return;
+ }
+ const selected = selectedIDs.has(item.dataset.id);
+ item.classList.toggle(isTable ? "av__row--select" : "av__gallery-item--select", selected);
+ if (isTable) {
+ item.querySelector(".av__firstcol use")?.setAttribute("xlink:href",
+ selected ? "#iconCheck" : "#iconUncheck");
+ }
+ });
+};
+
+export const clearAVItemSelection = (blockElement: HTMLElement, clearAnchor = false) => {
+ blockElement.querySelectorAll<HTMLElement>(".av__body").forEach(bodyElement => {
+ if (bodyElement.closest(".av") === blockElement) {
+ resetAVRowSelect(bodyElement, []);
+ }
+ });
+ syncItemSelectionDOM(blockElement, new Set());
+ updateAVSelectionStatus(blockElement);
+ if (clearAnchor) {
+ clearAVItemSelectionState(blockElement);
+ }
+};
+
+export const setAVItemAnchor = (blockElement: HTMLElement, itemElement: HTMLElement) => {
+ if (!itemElement?.dataset.id) {
+ return;
+ }
+ const groupID = getGroupID(itemElement);
+ setAVItemSelectionState(blockElement, {
+ anchorID: itemElement.dataset.id,
+ anchorGroupID: groupID,
+ focusID: itemElement.dataset.id,
+ focusGroupID: groupID,
+ selectedIDs: getAVSelectedItemIDs(blockElement),
+ });
+};
+
+const applyItemRange = (blockElement: HTMLElement, target: IAVItemInfo) => {
+ const viewType = blockElement.dataset.avType as TAVView;
+ const allItems = getAVLoadedItemInfos(blockElement, true);
+ const scopeItems = viewType === "kanban" ?
+ allItems.filter(item => item.groupID === target.groupID) : allItems;
+ let itemSelection = getAVItemSelection(blockElement);
+ let anchorIndex = scopeItems.findIndex(item =>
+ item.itemID === itemSelection?.anchorID &&
+ (viewType !== "kanban" || item.groupID === itemSelection?.anchorGroupID));
+ const targetIndex = scopeItems.findIndex(item =>
+ item.itemID === target.itemID && item.groupID === target.groupID);
+ if (targetIndex < 0) {
+ return false;
+ }
+ if (anchorIndex < 0) {
+ setAVItemAnchorState(blockElement, target.itemID, target.groupID);
+ itemSelection = getAVItemSelection(blockElement);
+ anchorIndex = targetIndex;
+ }
+ const selectedItems = scopeItems.slice(Math.min(anchorIndex, targetIndex), Math.max(anchorIndex, targetIndex) + 1);
+ const selectedIDs = new Set(selectedItems.map(item => item.itemID));
+ blockElement.querySelectorAll<HTMLElement>(".av__body").forEach(bodyElement => {
+ if (bodyElement.closest(".av") !== blockElement) {
+ return;
+ }
+ const groupID = bodyElement.dataset.groupId || "";
+ resetAVRowSelect(bodyElement, selectedItems.filter(item => item.groupID === groupID).map(item => item.itemID));
+ });
+ clearAVCellRange(blockElement);
+ syncItemSelectionDOM(blockElement, selectedIDs);
+ updateAVSelectionStatus(blockElement);
+ setAVItemSelectionState(blockElement, {
+ anchorID: itemSelection.anchorID,
+ anchorGroupID: itemSelection.anchorGroupID,
+ focusID: target.itemID,
+ focusGroupID: target.groupID,
+ selectedIDs: Array.from(selectedIDs),
+ });
+ return true;
+};
+
+export const selectAVItemRange = (blockElement: HTMLElement, itemElement: HTMLElement) => {
+ if (!itemElement?.dataset.id) {
+ return false;
+ }
+ const groupID = getGroupID(itemElement);
+ const target = getAVLoadedItemInfos(blockElement, true).find(item =>
+ item.itemID === itemElement.dataset.id && item.groupID === groupID);
+ return target ? applyItemRange(blockElement, target) : false;
+};
+
+export const moveAVItemRange = (blockElement: HTMLElement, direction: "up" | "down") => {
+ const selection = getAVItemSelection(blockElement);
+ if (!selection) {
+ return;
+ }
+ const viewType = blockElement.dataset.avType as TAVView;
+ const allItems = getAVLoadedItemInfos(blockElement, true);
+ const scopeItems = viewType === "kanban" ?
+ allItems.filter(item => item.groupID === selection.focusGroupID) : allItems;
+ const focusIndex = scopeItems.findIndex(item =>
+ item.itemID === selection.focusID &&
+ (viewType !== "kanban" || item.groupID === selection.focusGroupID));
+ const target = scopeItems[focusIndex + (direction === "up" ? -1 : 1)];
+ if (!target || !applyItemRange(blockElement, target)) {
+ return;
+ }
+ return getItemElement(blockElement, target);
+};
+
+export const setAVDragItemAnchor = (blockElement: HTMLElement) => {
+ const selectedIDs = new Set(getAVSelectedItemIDs(blockElement));
+ const selectedItems = getAVLoadedItemInfos(blockElement, true).filter(item => selectedIDs.has(item.itemID));
+ if (selectedItems.length > 0) {
+ const firstSelected = selectedItems[0];
+ const lastSelected = selectedItems[selectedItems.length - 1];
+ setAVItemSelectionState(blockElement, {
+ anchorID: firstSelected.itemID,
+ anchorGroupID: firstSelected.groupID,
+ focusID: lastSelected.itemID,
+ focusGroupID: lastSelected.groupID,
+ selectedIDs: selectedItems.map(item => item.itemID),
+ });
+ }
+};
diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.ts
index 11af419d86..abe55f3fc6 100644
--- a/app/src/protyle/render/av/render.ts
+++ b/app/src/protyle/render/av/render.ts
@@ -24,6 +24,7 @@ import {beginAVRender, finishAVLocate, getAVLocateParams, isCurrentAVRender, pre
import {setGroupFoldedStates, updateGroupFoldedStates} from "./groupFold";
import {updateHotkeyTip} from "../../util/compatibility";
import {inspectAVInsertedItem} from "./filteredTip";
+import {refreshAVCellSelection, restoreAVCellSelection} from "./selectionState";
interface IIds {
groupId: string,
@@ -300,6 +301,7 @@ const renderGroupTable = (options: ITableOptions) => {
const afterRenderTable = (options: ITableOptions) => {
setAVData(options.blockElement, options.data);
+ refreshAVCellSelection(options.blockElement, options.data);
if (options.blockElement.getAttribute("data-need-focus") === "true") {
focusBlock(options.blockElement);
options.blockElement.removeAttribute("data-need-focus");
@@ -387,6 +389,7 @@ const afterRenderTable = (options: ITableOptions) => {
}
activeCellElement?.classList.add("av__cell--active");
});
+ restoreAVCellSelection(options.blockElement);
if (getSelection().rangeCount > 0) {
// 修改表头后光标重新定位
const range = getSelection().getRangeAt(0);
diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.ts
index dcccf1d653..09e1ea2f41 100644
--- a/app/src/protyle/render/av/row.ts
+++ b/app/src/protyle/render/av/row.ts
@@ -5,7 +5,6 @@ import {transaction} from "../../wysiwyg/transaction";
import {
cellValueIsEmpty,
genCellValue,
- genCellValueByElement,
getTypeByCellElement,
renderCell,
renderCellAttr
@@ -21,8 +20,8 @@ import {unicode2Emoji} from "../../../emoji";
import {escapeAttr} from "../../../util/escape";
import {getCompressURL} from "../../../util/image";
import {
- getAVPrimaryCell,
getAVSelectStat,
+ getAVSelectedItemInfos,
getAvBodyData,
resetAVRowSelect,
updateAVRowSelect
@@ -838,25 +837,19 @@ export const setPageSize = (options: {
};
export const deleteRow = (blockElement: HTMLElement, protyle: IProtyle) => {
- const rowElements = blockElement.querySelectorAll(".av__row--select:not(.av__row--header), .av__gallery-item--select");
- if (rowElements.length === 0) {
+ const selectedItems = getAVSelectedItemInfos(blockElement);
+ if (selectedItems.length === 0) {
return;
}
- const primaryValues = Array.from(rowElements).map((item: HTMLElement) => {
- const cellElement = item.querySelector('.av__cell[data-dtype="block"]') as HTMLElement;
- return cellElement ? genCellValueByElement("block", cellElement) :
- getAVPrimaryCell(blockElement, item.dataset.id)?.value;
- });
+ const primaryValues = selectedItems.map(item => item.primaryCell?.value);
if (primaryValues.some(value => !value)) {
return;
}
const avID = blockElement.getAttribute("data-av-id");
const undoOperations: IOperation[] = [];
const blockIds: string[] = [];
- rowElements.forEach(item => {
- blockIds.push(item.getAttribute("data-id"));
- });
- rowElements.forEach((item, index) => {
+ selectedItems.forEach(item => blockIds.push(item.itemID));
+ selectedItems.forEach((item, index) => {
const blockValue = primaryValues[index];
const itemID = Lute.NewNodeID();
// 撤销会使用新的条目 ID 恢复该行,重做时需要同时删除这个新条目。
@@ -864,15 +857,15 @@ export const deleteRow = (blockElement: HTMLElement, protyle: IProtyle) => {
undoOperations.push({
action: "insertAttrViewBlock",
avID,
- previousID: item.previousElementSibling?.getAttribute("data-id") || "",
+ previousID: item.previousID,
srcs: [{
itemID,
- id: item.getAttribute("data-id"),
+ id: item.itemID,
isDetached: blockValue.isDetached,
content: blockValue.block.content
}],
blockID: blockElement.dataset.nodeId,
- groupID: item.parentElement.getAttribute("data-group-id")
+ groupID: item.groupID
});
});
const newUpdated = dayjs().format("YYYYMMDDHHmmss");
@@ -890,9 +883,13 @@ export const deleteRow = (blockElement: HTMLElement, protyle: IProtyle) => {
id: blockElement.dataset.nodeId,
data: newUpdated,
}], undoOperations);
- rowElements.forEach(item => {
- item.remove();
+ const selectedIDs = new Set(selectedItems.map(item => item.itemID));
+ blockElement.querySelectorAll<HTMLElement>(".av__row[data-id], .av__gallery-item[data-id]").forEach(item => {
+ if (selectedIDs.has(item.dataset.id)) {
+ item.remove();
+ }
});
+ clearSelect(["row", "galleryItem"], blockElement);
stickyRow(blockElement, protyle.contentElement, "all");
updateHeader(blockElement.querySelector(".av__row"));
blockElement.setAttribute("updated", newUpdated);
@@ -962,18 +959,20 @@ export const insertRows = (options: {
options.blockElement.setAttribute("updated", newUpdated);
};
-export const duplicateRows = (blockElement: HTMLElement, protyle: IProtyle, rowElements: NodeListOf<Element>) => {
+export const duplicateRows = (blockElement: HTMLElement, protyle: IProtyle, rowIDs: string[]) => {
+ if (rowIDs.length === 0) {
+ return;
+ }
const avID = blockElement.getAttribute("data-av-id");
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
const newRowIDs: string[] = [];
// 副本统一插入到最后选中的条目之后,按源序排列
- const anchorID = rowElements[rowElements.length - 1].getAttribute("data-id");
+ const anchorID = rowIDs[rowIDs.length - 1];
let previousID = anchorID;
- rowElements.forEach(rowElement => {
+ rowIDs.forEach(srcRowID => {
const newRowID = Lute.NewNodeID();
newRowIDs.push(newRowID);
- const srcRowID = rowElement.getAttribute("data-id");
doOperations.push({
action: "duplicateAttrViewRow",
avID,
diff --git a/app/src/protyle/render/av/selectionState.ts b/app/src/protyle/render/av/selectionState.ts
new file mode 100644
index 0000000000..3c78c60931
--- /dev/null
+++ b/app/src/protyle/render/av/selectionState.ts
@@ -0,0 +1,177 @@
+export interface IAVCellPoint {
+ groupID: string;
+ rowID: string;
+ colID: string;
+}
+
+export interface IAVSelectedCell {
+ groupID: string;
+ rowID: string;
+ colID: string;
+ rowIndex: number;
+ colIndex: number;
+ cell: IAVCell;
+ column: IAVColumn;
+}
+
+interface IAVCellSelection {
+ anchor: IAVCellPoint;
+ focus: IAVCellPoint;
+ cells: IAVSelectedCell[];
+}
+
+interface IAVItemSelection {
+ anchorID: string;
+ anchorGroupID: string;
+ focusID: string;
+ focusGroupID: string;
+ selectedIDs: string[];
+}
+
+interface IAVSelectionState {
+ cell?: IAVCellSelection;
+ item?: IAVItemSelection;
+}
+
+const selectionStates = new WeakMap<HTMLElement, IAVSelectionState>();
+
+const getState = (blockElement: HTMLElement) => {
+ let state = selectionStates.get(blockElement);
+ if (!state) {
+ state = {};
+ selectionStates.set(blockElement, state);
+ }
+ return state;
+};
+
+export const getAVCellSelection = (blockElement: HTMLElement) => {
+ return selectionStates.get(blockElement)?.cell;
+};
+
+export const setAVCellSelection = (blockElement: HTMLElement, selection: IAVCellSelection) => {
+ getState(blockElement).cell = selection;
+};
+
+export const clearAVCellSelectionState = (blockElement: HTMLElement) => {
+ const state = selectionStates.get(blockElement);
+ if (state) {
+ delete state.cell;
+ }
+};
+
+export const getAVSelectedCells = (blockElement: HTMLElement) => {
+ return selectionStates.get(blockElement)?.cell?.cells || [];
+};
+
+export const updateAVSelectedCellValue = (blockElement: HTMLElement, rowID: string, colID: string,
+ value: IAVCellValue) => {
+ const selectedCell = getAVSelectedCells(blockElement).find(item =>
+ item.rowID === rowID && item.colID === colID);
+ if (selectedCell) {
+ selectedCell.cell.id = value.id || "";
+ selectedCell.cell.value = value;
+ selectedCell.cell.valueType = value.type;
+ }
+};
+
+export const getAVItemSelection = (blockElement: HTMLElement) => {
+ return selectionStates.get(blockElement)?.item;
+};
+
+export const setAVItemAnchorState = (blockElement: HTMLElement, itemID: string, groupID: string) => {
+ const state = getState(blockElement);
+ state.item = {
+ anchorID: itemID,
+ anchorGroupID: groupID,
+ focusID: itemID,
+ focusGroupID: groupID,
+ selectedIDs: state.item?.selectedIDs || [],
+ };
+};
+
+export const setAVItemSelectionState = (blockElement: HTMLElement, selection: IAVItemSelection) => {
+ getState(blockElement).item = selection;
+};
+
+export const clearAVItemSelectionState = (blockElement: HTMLElement) => {
+ const state = selectionStates.get(blockElement);
+ if (state) {
+ delete state.item;
+ }
+};
+
+export const refreshAVCellSelection = (blockElement: HTMLElement, data: IAV) => {
+ const selection = getAVCellSelection(blockElement);
+ if (!selection) {
+ return;
+ }
+ const findView = (view: IAVView): IAVView | undefined => {
+ if ((!selection.anchor.groupID && !view.groups?.length) || view.id === selection.anchor.groupID) {
+ return view;
+ }
+ for (const group of view.groups || []) {
+ const result = findView(group);
+ if (result) {
+ return result;
+ }
+ }
+ };
+ const view = findView(data.view) as IAVTable;
+ if (!view?.rows || !view.columns) {
+ clearAVCellSelectionState(blockElement);
+ return;
+ }
+ const columns = view.columns.filter(column => !column.hidden);
+ const cells: IAVSelectedCell[] = [];
+ selection.cells.forEach(selectedCell => {
+ const rowIndex = view.rows.findIndex(row => row.id === selectedCell.rowID);
+ const colIndex = columns.findIndex(column => column.id === selectedCell.colID);
+ const sourceColIndex = view.columns.findIndex(column => column.id === selectedCell.colID);
+ const cell = view.rows[rowIndex]?.cells[sourceColIndex];
+ if (cell && colIndex >= 0) {
+ cells.push({
+ groupID: selection.anchor.groupID,
+ rowID: selectedCell.rowID,
+ colID: selectedCell.colID,
+ rowIndex,
+ colIndex,
+ cell,
+ column: columns[colIndex],
+ });
+ }
+ });
+ if (cells.length !== selection.cells.length) {
+ clearAVCellSelectionState(blockElement);
+ return;
+ }
+ selection.cells = cells;
+};
+
+export const restoreAVCellSelection = (blockElement: HTMLElement) => {
+ const selection = getAVCellSelection(blockElement);
+ if (!selection) {
+ return;
+ }
+ const selectedKeys = new Set(selection.cells.map(item => `${item.rowID}:${item.colID}`));
+ blockElement.querySelectorAll<HTMLElement>(".av__cell--active, .av__cell--select").forEach(item => {
+ item.classList.remove("av__cell--active", "av__cell--select");
+ item.querySelector(".av__drag-fill")?.remove();
+ });
+ blockElement.querySelectorAll<HTMLElement>(".av__row[data-id] .av__cell[data-col-id]").forEach(cellElement => {
+ const rowElement = cellElement.closest<HTMLElement>(".av__row[data-id]");
+ if (!rowElement || !selectedKeys.has(`${rowElement.dataset.id}:${cellElement.dataset.colId}`)) {
+ return;
+ }
+ cellElement.classList.add("av__cell--active");
+ if (rowElement.dataset.id === selection.anchor.rowID &&
+ cellElement.dataset.colId === selection.anchor.colID) {
+ cellElement.classList.add("av__cell--select");
+ }
+ if (rowElement.dataset.id === selection.focus.rowID &&
+ cellElement.dataset.colId === selection.focus.colID &&
+ !["template", "rollup", "lineNumber", "created", "updated"].includes(cellElement.dataset.dtype)) {
+ cellElement.insertAdjacentHTML("beforeend",
+ `<div aria-label="${window.siyuan.languages.dragFill}" class="av__drag-fill ariaLabel"></div>`);
+ }
+ });
+};
diff --git a/app/src/protyle/render/av/virtualScroll.ts b/app/src/protyle/render/av/virtualScroll.ts
index 3f3145ad10..82d11ed3f3 100644
--- a/app/src/protyle/render/av/virtualScroll.ts
+++ b/app/src/protyle/render/av/virtualScroll.ts
@@ -1,5 +1,6 @@
import {Constants} from "../../../constants";
import {getRowHTML} from "./row";
+import {getAVItemSelection, restoreAVCellSelection} from "./selectionState";
const BUFFER_RATIO = 1;
@@ -117,18 +118,20 @@ const doTrim = (blockElement: HTMLElement, elementRect: DOMRect): void => {
}
// 给回填的行恢复选中态:遍历 body 内现存数据行,命中 selectedRowIds 的补回高亮类与选中图标。
const restoreSelect = () => {
- if (state.selectedRowIds.size === 0) {
- return;
- }
- bodyEl.querySelectorAll(type === "table" ? ".av__row[data-id]" : ".av__gallery-item[data-id]").forEach((row: HTMLElement) => {
- if (state.selectedRowIds.has(row.getAttribute("data-id"))) {
- row.classList.add(type === "table" ? "av__row--select" : "av__gallery-item--select");
- const use = row.querySelector(".av__firstcol use") as SVGUseElement;
- if (use) {
- use.setAttribute("xlink:href", "#iconCheck");
+ if (state.selectedRowIds.size > 0) {
+ bodyEl.querySelectorAll(type === "table" ? ".av__row[data-id]" : ".av__gallery-item[data-id]").forEach((row: HTMLElement) => {
+ if (state.selectedRowIds.has(row.getAttribute("data-id"))) {
+ row.classList.add(type === "table" ? "av__row--select" : "av__gallery-item--select");
+ const use = row.querySelector(".av__firstcol use") as SVGUseElement;
+ if (use) {
+ use.setAttribute("xlink:href", "#iconCheck");
+ }
}
- }
- });
+ });
+ }
+ if (type === "table") {
+ restoreAVCellSelection(blockElement);
+ }
};
let firstVisibleIndex: number;
let lastVisibleIndex: number;
@@ -498,28 +501,61 @@ export const getAVData = (blockElement: HTMLElement) => {
return blockDataStore.get(blockElement);
};
-export const getAVPrimaryCell = (blockElement: HTMLElement, itemID: string) => {
+export interface IAVItemInfo {
+ itemID: string;
+ groupID: string;
+ previousID: string;
+ item: IAVRow | IAVGalleryItem;
+ primaryCell?: IAVCell;
+}
+
+export const getAVLoadedItemInfos = (blockElement: HTMLElement, visibleOnly = false): IAVItemInfo[] => {
const data = blockDataStore.get(blockElement);
- if (!data || !itemID) {
- return;
+ if (!data) {
+ return [];
}
- let primaryCell: IAVCell;
- const findPrimaryCell = (view: IAVView) => {
+ const infos: IAVItemInfo[] = [];
+ const collect = (view: IAVView, groupID = "") => {
if (view.groups?.length > 0) {
- return view.groups.some(findPrimaryCell);
+ view.groups.forEach(group => {
+ if (visibleOnly) {
+ const bodyElement = blockElement.querySelector<HTMLElement>(
+ `.av__body[data-group-id="${group.id}"]`);
+ if (!bodyElement || bodyElement.classList.contains("fn__none")) {
+ return;
+ }
+ } else if (group.groupHidden !== 0) {
+ return;
+ }
+ collect(group, group.id);
+ });
+ return;
}
const items: Array<IAVRow | IAVGalleryItem> =
(view as IAVTable).rows || (view as IAVGallery).cards || [];
- const item = items.find((row: IAVRow | IAVGalleryItem) => row.id === itemID);
- if (!item) {
- return false;
- }
- const cells = "cells" in item ? item.cells : item.values;
- primaryCell = cells.find((cell: IAVCell) => cell.valueType === "block" || cell.value?.type === "block");
- return true;
+ items.forEach((item, index) => {
+ const cells = "cells" in item ? item.cells : item.values;
+ infos.push({
+ itemID: item.id,
+ groupID,
+ previousID: items[index - 1]?.id || "",
+ item,
+ primaryCell: cells.find(cell =>
+ cell.valueType === "block" || cell.value?.type === "block"),
+ });
+ });
};
- findPrimaryCell(data.view);
- return primaryCell;
+ collect(data.view);
+ return infos;
+};
+
+export const getAVSelectedItemInfos = (blockElement: HTMLElement) => {
+ const selectedIDs = new Set(getAVSelectedItemIDs(blockElement));
+ return getAVLoadedItemInfos(blockElement).filter(item => selectedIDs.has(item.itemID));
+};
+
+export const getAVPrimaryCell = (blockElement: HTMLElement, itemID: string) => {
+ return getAVLoadedItemInfos(blockElement).find(item => item.itemID === itemID)?.primaryCell;
};
export const setAVData = (blockElement: HTMLElement, data: IAV) => {
@@ -588,6 +624,7 @@ export const initVirtualScroll = (options: {
data: IAV,
}): void => {
setAVData(options.blockElement, options.data);
+ const itemSelection = getAVItemSelection(options.blockElement);
if (options.blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) !== "true") {
return;
}
@@ -611,6 +648,23 @@ export const initVirtualScroll = (options: {
selectedRowIds.add(id);
}
});
+ const viewItems = (view as IAVTable).rows || (view as IAVGallery).cards || [];
+ itemSelection?.selectedIDs.forEach(itemID => {
+ if (viewItems.some(item => item.id === itemID)) {
+ selectedRowIds.add(itemID);
+ }
+ });
+ item.querySelectorAll<HTMLElement>(".av__row[data-id], .av__gallery-item[data-id]").forEach(row => {
+ if (!selectedRowIds.has(row.dataset.id)) {
+ return;
+ }
+ if (options.data.viewType === "table") {
+ row.classList.add("av__row--select");
+ row.querySelector(".av__firstcol use")?.setAttribute("xlink:href", "#iconCheck");
+ } else {
+ row.classList.add("av__gallery-item--select");
+ }
+ });
if (options.data.viewType === "table") {
const firstRow = item.querySelector(".av__row[data-id]") as HTMLElement;
let lastRow = item.querySelector(".av__row--util")?.previousElementSibling as HTMLElement;
diff --git a/app/src/protyle/util/clear.ts b/app/src/protyle/util/clear.ts
index af43641cf7..f7764b8476 100644
--- a/app/src/protyle/util/clear.ts
+++ b/app/src/protyle/util/clear.ts
@@ -2,6 +2,16 @@ import {updateHeader} from "../render/av/row";
import {resetAVRowSelect} from "../render/av/virtualScroll";
import {hasClosestByClassName} from "./hasClosest";
import {Constants} from "../../constants";
+import {clearAVCellSelectionState, clearAVItemSelectionState} from "../render/av/selectionState";
+
+const getAVElements = (element: Element) => {
+ const elements: HTMLElement[] = [];
+ if (element.classList.contains("av")) {
+ elements.push(element as HTMLElement);
+ }
+ element.querySelectorAll<HTMLElement>(".av").forEach(item => elements.push(item));
+ return elements;
+};
export const clearBlockElement = (element: Element, keepRefcount = false) => {
element.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--hl");
@@ -25,6 +35,7 @@ export const clearSelect = (types: ("av" | "img" | "cell" | "row" | "galleryItem
item.querySelector(".av__drag-fill")?.remove();
item.classList.remove("av__cell--select", "av__cell--active");
});
+ getAVElements(element).forEach(clearAVCellSelectionState);
}
if (types.includes("row")) {
const clearedBodies = new Set<HTMLElement>();
@@ -40,6 +51,7 @@ export const clearSelect = (types: ("av" | "img" | "cell" | "row" | "galleryItem
updateHeader(item);
});
resetAVBodySelect(element, "table");
+ getAVElements(element).forEach(clearAVItemSelectionState);
}
if (types.includes("galleryItem")) {
const clearedBodies = new Set<HTMLElement>();
@@ -47,6 +59,7 @@ export const clearSelect = (types: ("av" | "img" | "cell" | "row" | "galleryItem
clearGalleryItem(item, clearedBodies);
});
resetAVBodySelect(element, "gallery");
+ getAVElements(element).forEach(clearAVItemSelectionState);
}
if (types.includes("av")) {
const clearedBodies = new Set<HTMLElement>();
@@ -68,6 +81,10 @@ export const clearSelect = (types: ("av" | "img" | "cell" | "row" | "galleryItem
}
});
resetAVBodySelect(element, "all");
+ getAVElements(element).forEach(avElement => {
+ clearAVCellSelectionState(avElement);
+ clearAVItemSelectionState(avElement);
+ });
}
if (types.includes("img")) {
element.querySelectorAll(".img--select").forEach((item: HTMLElement) => {
diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.ts
index 8dd2446a36..bdfb75677d 100644
--- a/app/src/protyle/util/insertHTML.ts
+++ b/app/src/protyle/util/insertHTML.ts
@@ -47,6 +47,7 @@ import {Dialog} from "../../dialog";
import {isMobile} from "../../util/functions";
import {getCrossBlockMergeRemoveElement} from "../wysiwyg/removeRange";
import {getAVFilteredTipContext} from "../render/av/filteredTip";
+import {getAVSelectedCells, IAVSelectedCell} from "../render/av/selectionState";
// 粘贴时临时插入的占位行标记,遍历结束后统一移除,避免污染虚拟滚动的 renderedStart/renderedEnd/spacer 状态
const PLACEHOLDER_ROW_CLASS = "av__row--placeholder";
@@ -274,18 +275,24 @@ const pasteAVMatrix = async (options: {
values: TAVPasteValue[][],
protyle: IProtyle,
blockElement: HTMLElement,
- startCell: HTMLElement,
+ startCell?: HTMLElement,
+ start?: IAVSelectedCell,
columns: IAVColumn[],
html: string,
cellHTML?: string[][],
header?: string[],
}) => {
- const startRowElement = hasClosestByClassName(options.startCell, "av__row") as HTMLElement;
+ const startRowElement = options.startCell ?
+ hasClosestByClassName(options.startCell, "av__row") as HTMLElement : undefined;
const sourceWidth = getAVPasteMatrixWidth(options.values, options.header);
- if (!startRowElement || sourceWidth === 0) {
+ const startItemID = options.start?.rowID || startRowElement?.dataset.id;
+ const startColID = options.start?.colID || options.startCell?.dataset.colId;
+ if (!startItemID || !startColID || sourceWidth === 0) {
return;
}
- const bodyElement = hasClosestByClassName(startRowElement, "av__body") as HTMLElement;
+ const bodyElement = (startRowElement ? hasClosestByClassName(startRowElement, "av__body") :
+ Array.from(options.blockElement.querySelectorAll<HTMLElement>(".av__body")).find(item =>
+ (item.dataset.groupId || "") === (options.start?.groupID || ""))) as HTMLElement;
if (!bodyElement) {
return;
}
@@ -297,7 +304,7 @@ const pasteAVMatrix = async (options: {
viewID: options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW) || "",
groupID,
query: options.blockElement.querySelector('[data-type="av-search"]')?.textContent || "",
- startItemID: startRowElement.dataset.id,
+ startItemID,
count: Math.max(options.values.length, 1),
});
const view = response.data?.view as IAVTable;
@@ -322,7 +329,7 @@ const pasteAVMatrix = async (options: {
const newColumnUndoOperations: IOperation[] = [];
const inferableKeyIDs = new Set<string>(response.data?.inferableKeyIDs || []);
const visibleColumns = view.columns.filter(column => !column.hidden);
- const startColumnIndex = visibleColumns.findIndex(column => column.id === options.startCell.dataset.colId);
+ const startColumnIndex = visibleColumns.findIndex(column => column.id === startColID);
if (startColumnIndex < 0) {
return;
}
@@ -425,7 +432,7 @@ const pasteAVMatrix = async (options: {
const existingRows = rows.slice(0, options.values.length);
const rowElements: HTMLElement[] = [];
const pasteRows: IAVRow[] = [];
- const startIndex = parseInt(startRowElement.dataset.index || "0");
+ const startIndex = options.start?.rowIndex ?? parseInt(startRowElement?.dataset.index || "0");
const cellPlaceholders: IAVPasteCellPlaceholder[] = [];
existingRows.forEach((row, index) => {
let rowElement = bodyElement.querySelector(`.av__row[data-id="${row.id}"]`) as HTMLElement;
@@ -594,6 +601,7 @@ const processAV = (range: Range, html: string, protyle: IProtyle, blockElement:
const avID = blockElement.dataset.avId;
fetchPost("/api/av/getAttributeViewKeysByAvID", {avID}, async (response) => {
const columns: IAVColumn[] = response.data;
+ const selectedCells = getAVSelectedCells(blockElement);
const cellElements: HTMLElement[] = Array.from(blockElement.querySelectorAll(".av__cell--active, .av__cell--select")) || [];
if (values && Array.isArray(values) && values.length > 0) {
if (cellElements.length === 0) {
@@ -603,10 +611,10 @@ const processAV = (range: Range, html: string, protyle: IProtyle, blockElement:
});
});
}
- if (cellElements.length === 0) {
+ if (cellElements.length === 0 && selectedCells.length === 0) {
cellElements.push(blockElement.querySelector(".av__row:not(.av__row--header) .av__cell"));
}
- if (cellElements[0]) {
+ if (cellElements[0] || selectedCells[0]) {
const useHeader = headerCandidate ? await confirmAVPasteHeader() : false;
const header = useHeader ?
values[0].map(value => typeof value === "string" ? value : "") : undefined;
@@ -615,6 +623,7 @@ const processAV = (range: Range, html: string, protyle: IProtyle, blockElement:
protyle,
blockElement,
startCell: cellElements[0],
+ start: selectedCells[0],
columns,
html,
cellHTML: useHeader ? cellHTML.slice(1) : cellHTML,
@@ -674,13 +683,29 @@ const processAV = (range: Range, html: string, protyle: IProtyle, blockElement:
}
if (cellElements.length > 0) {
if (textJSON.length === 1 && textJSON[0].length === 1) {
- updateCellsValue(protyle, blockElement as HTMLElement, normalizedText, cellElements, columns, html);
+ updateCellsValue(protyle, blockElement as HTMLElement, normalizedText,
+ selectedCells.length > 0 ? undefined : cellElements, columns, html);
} else {
await pasteAVMatrix({
values: textJSON,
protyle,
blockElement,
startCell: cellElements[0],
+ start: selectedCells[0],
+ columns,
+ html,
+ });
+ }
+ document.querySelector(".av__panel")?.remove();
+ } else if (selectedCells.length > 0) {
+ if (textJSON.length === 1 && textJSON[0].length === 1) {
+ updateCellsValue(protyle, blockElement as HTMLElement, normalizedText, undefined, columns, html);
+ } else {
+ await pasteAVMatrix({
+ values: textJSON,
+ protyle,
+ blockElement,
+ start: selectedCells[0],
columns,
html,
});
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index ae06b4074f..8749a72f9b 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -90,12 +90,14 @@ import {checkFold} from "../../util/noRelyPCFunction";
import {
addDragFill,
dragFillCellsValue,
+ getAVSelectedCellData,
genCellValueByElement,
getCellText,
getPositionByCellElement,
getTypeByCellElement,
updateCellsValue
} from "../render/av/cell";
+import {getAVSelectedCells} from "../render/av/selectionState";
import {openEmojiPanel, unicode2Emoji} from "../../emoji";
import {openLink} from "../../editor/openLink";
import {mathRender} from "../render/mathRender";
@@ -120,6 +122,13 @@ import {addSpellcheckMenuItems, requestSpellcheckContext} from "../../menus/spel
import {getAVTemplateInteractiveElement, isAVTemplateLink} from "../render/av/attributeValue";
import {focusAVByArrow} from "../render/av/focus";
import {applyAVDragSelection, clearAVDragSelection, isAVDragSelectSupported} from "../render/av/dragSelect";
+import {
+ selectAVCellRange,
+ selectAVItemRange,
+ setAVCellAnchor,
+ setAVDragItemAnchor,
+ setAVItemAnchor,
+} from "../render/av/rangeSelect";
interface IShiftClickBlockPoint {
blockElement: HTMLElement;
@@ -423,7 +432,8 @@ export class WYSIWYG {
return;
}
const selectImgElement = nodeElement.querySelector(".img--select");
- const selectAVElement = nodeElement.querySelector(".av__row--select, .av__cell--select");
+ const selectAVElement = nodeElement.querySelector(".av__row--select, .av__cell--select") ||
+ (getAVSelectedCells(nodeElement).length > 0 ? nodeElement : null);
const selectTableElement = nodeElement.querySelector(".table__select")?.clientWidth > 0;
// 表格内跨多单元格的文本选区:range.cloneContents() 会产出残缺的 td/tr 片段,需要重建合法 table
let selectTableRange = false;
@@ -515,7 +525,13 @@ export class WYSIWYG {
selectElements[0].removeAttribute("data-reftext");
}
} else if (selectAVElement) {
- const cellElements: Element[] = Array.from(nodeElement.querySelectorAll(".av__cell--active, .av__cell--select")) || [];
+ const selectedCellData = getAVSelectedCellData(nodeElement);
+ const cellElements: Element[] = selectedCellData.json.length > 0 ? [] :
+ Array.from(nodeElement.querySelectorAll(".av__cell--active, .av__cell--select"));
+ if (selectedCellData.json.length > 0) {
+ html = JSON.stringify(selectedCellData.json);
+ textPlain = selectedCellData.text;
+ }
if (cellElements.length === 0) {
nodeElement.querySelectorAll(".av__row--select:not(.av__row--header)").forEach(rowElement => {
rowElement.querySelectorAll(".av__cell").forEach(cellElement => {
@@ -523,7 +539,7 @@ export class WYSIWYG {
});
});
}
- if (cellElements.length > 0) {
+ if (cellElements.length > 0 && selectedCellData.json.length === 0) {
html = "[";
cellElements.forEach((item: HTMLElement, index) => {
const cellText = getCellText(item);
@@ -739,6 +755,7 @@ export class WYSIWYG {
let nodeElement = hasClosestBlock(target) as HTMLElement;
const hasSelectClassElement = this.element.querySelector(".protyle-wysiwyg--select");
const galleryItemElement = hasClosestByClassName(target, "av__gallery-item");
+ const avCellElement = hasClosestByClassName(target, "av__cell") as HTMLElement;
const wysiwygRect = protyle.wysiwyg.element.getBoundingClientRect();
const wysiwygStyle = window.getComputedStyle(protyle.wysiwyg.element);
const mostLeft = wysiwygRect.left + (parseInt(wysiwygStyle.paddingLeft) || 24) + 1;
@@ -752,6 +769,22 @@ export class WYSIWYG {
const baseDragSelectElements = new Set(isToggleBlockDrag ?
Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select")) : []);
if (event.shiftKey) {
+ if (!protyle.disabled && nodeElement?.dataset.avType === "table" && avCellElement?.dataset.id &&
+ selectAVCellRange(nodeElement, avCellElement)) {
+ focusBlock(nodeElement);
+ this.preventClick = true;
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ if (!hasSelectClassElement && galleryItemElement &&
+ selectAVItemRange(nodeElement, galleryItemElement as HTMLElement)) {
+ focusBlock(nodeElement);
+ this.preventClick = true;
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
let startElement;
let endElement = nodeElement;
let shiftClickBlockPoint: IShiftClickBlockPoint | undefined;
@@ -767,49 +800,7 @@ export class WYSIWYG {
endElement = shiftClickBlockPoint?.blockElement;
}
// shift 多选
- if (!hasSelectClassElement && galleryItemElement) {
- galleryItemElement.classList.add("av__gallery-item--select");
- let sideElement = galleryItemElement.previousElementSibling;
- let previousList: Element[] = [];
- while (sideElement) {
- if (sideElement.classList.contains("av__gallery-item--select")) {
- break;
- } else {
- previousList.push(sideElement);
- }
- sideElement = sideElement.previousElementSibling;
- if (!sideElement) {
- previousList = [];
- break;
- }
- }
- sideElement = galleryItemElement.nextElementSibling;
- let nextList: Element[] = [];
- while (sideElement) {
- if (sideElement.classList.contains("av__gallery-item--select")) {
- break;
- } else {
- nextList.push(sideElement);
- }
- sideElement = sideElement.nextElementSibling as HTMLElement;
- if (!sideElement || sideElement.classList.contains("av__gallery-add")) {
- nextList = [];
- break;
- }
- }
- // 锚点卡片及范围内卡片统一选中并同步虚拟滚动选中快照
- const shiftSelectItems = [galleryItemElement].concat(previousList as HTMLElement[]).concat(nextList as HTMLElement[]);
- shiftSelectItems.forEach(item => {
- item.classList.add("av__gallery-item--select");
- const galleryBodyElement = hasClosestByClassName(item, "av__body") as HTMLElement;
- const galleryRowId = item.getAttribute("data-id");
- if (galleryBodyElement && galleryRowId) {
- updateAVRowSelect(galleryBodyElement, galleryRowId, true);
- }
- });
- updateHeader(galleryItemElement);
- event.preventDefault();
- } else if (startElement && endElement && startElement !== endElement) {
+ if (startElement && endElement && startElement !== endElement) {
let toDown = true;
const startRect = startElement.getBoundingClientRect();
const endRect = endElement.getBoundingClientRect();
@@ -923,8 +914,10 @@ export class WYSIWYG {
galleryItemElement.classList.toggle("av__gallery-item--select"));
}
updateHeader(galleryItemElement);
+ setAVItemAnchor(nodeElement, galleryItemElement as HTMLElement);
} else if (rowElement) {
selectRow(rowElement.querySelector(".av__firstcol"), "toggle");
+ setAVItemAnchor(nodeElement, rowElement as HTMLElement);
}
} else if (ctrlElement) {
clearSelect(["row", "galleryItem"], this.element);
@@ -969,6 +962,7 @@ export class WYSIWYG {
documentSelf.onselectstart = null;
documentSelf.onselect = null;
clearSelect(["galleryItem"], protyle.wysiwyg.element);
+ setAVItemAnchor(nodeElement, galleryItemElement as HTMLElement);
return false;
};
return;
@@ -1333,19 +1327,13 @@ export class WYSIWYG {
return false;
}
// av cell select
- const avCellElement = hasClosestByClassName(target, "av__cell");
if (!protyle.disabled && avCellElement && avCellElement.dataset.id && !isInEmbedBlock(avCellElement)) {
if (!nodeElement || nodeElement.dataset.avType !== "table") {
return;
}
- nodeElement.querySelectorAll(".av__cell--select").forEach(item => {
- item.classList.remove("av__cell--select");
- });
- nodeElement.querySelectorAll(".av__drag-fill").forEach(item => {
- item.remove();
- });
- avCellElement.classList.add("av__cell--select");
- const originIndex = getPositionByCellElement(avCellElement);
+ if (!setAVCellAnchor(nodeElement, avCellElement)) {
+ return;
+ }
let moveSelectCellElement: HTMLElement;
let lastCellElement: HTMLElement;
const nodeRect = nodeElement.getBoundingClientRect();
@@ -1370,20 +1358,8 @@ export class WYSIWYG {
return;
}
if (tempCellElement && tempCellElement.dataset.id && (event.clientX !== moveEvent.clientX || event.clientY !== moveEvent.clientY)) {
- const newIndex = getPositionByCellElement(tempCellElement);
- nodeElement.querySelectorAll(".av__cell--active").forEach((item: HTMLElement) => {
- item.classList.remove("av__cell--active");
- });
- bodyElement.querySelectorAll(".av__row").forEach((rowElement: HTMLElement, index: number) => {
- if (index >= Math.min(originIndex.rowIndex, newIndex.rowIndex) && index <= Math.max(originIndex.rowIndex, newIndex.rowIndex)) {
- rowElement.querySelectorAll(".av__cell").forEach((cellElement: HTMLElement, cellIndex: number) => {
- if (cellIndex >= Math.min(originIndex.celIndex, newIndex.celIndex) && cellIndex <= Math.max(originIndex.celIndex, newIndex.celIndex)) {
- cellElement.classList.add("av__cell--active");
- lastCellElement = cellElement;
- }
- });
- }
- });
+ selectAVCellRange(nodeElement, tempCellElement);
+ lastCellElement = tempCellElement;
moveSelectCellElement = tempCellElement;
}
};
@@ -2338,6 +2314,7 @@ export class WYSIWYG {
const selectElement = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");
if (avDragSelectMode === "items" && avDragSelectElement) {
+ setAVDragItemAnchor(avDragSelectElement);
countBlockWord([]);
focusBlock(avDragSelectElement);
} else {
@@ -2475,7 +2452,8 @@ export class WYSIWYG {
event.stopPropagation();
event.preventDefault();
const selectImgElement = nodeElement.querySelector(".img--select");
- const selectAVElement = nodeElement.querySelector(".av__row--select, .av__cell--select");
+ const selectAVElement = nodeElement.querySelector(".av__row--select, .av__cell--select") ||
+ (getAVSelectedCells(nodeElement).length > 0 ? nodeElement : null);
const selectTableElement = nodeElement.querySelector(".table__select")?.clientWidth > 0;
// 表格内跨多单元格的文本选区:range.cloneContents() 会产出残缺的 td/tr 片段,需要重建合法 table
let selectTableRange = false;