Skip to content

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

:sparkles: Support a database multi-selection editing toolbar https://github.com/siyuan-note/siyuan/issues/11742

Daniel7b4f474d71a5
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index cde9d37d0c..7c7d79bccb 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -19,6 +19,13 @@
.av__row--footer .av__calc {
opacity: 1;
}
+
+ .av__selection-toolbar {
+ [data-type="av-selection-edit"],
+ [data-type="av-selection-delete"] {
+ display: none;
+ }
+ }
}
&__cursor {
@@ -192,44 +199,33 @@
}
}
- &__counter {
- position: absolute;
- bottom: 0;
- height: 26px;
- padding: 0 5px;
- background-color: var(--b3-parent-background);
+ &__selection-toolbar {
+ align-items: center;
+ display: none;
+ flex: 1;
+ gap: 4px;
+ height: 32px;
+ min-width: 0;
font-size: 87.5%;
- &--sticky {
- align-items: center;
- bottom: auto;
- display: none;
- flex-shrink: 0;
- position: static;
- white-space: nowrap;
+ .block__icon {
+ opacity: 1;
}
}
- &__views--fixed > &__counter--sticky {
- display: flex;
+ &__selection-count {
+ flex-shrink: 0;
+ padding: 0 5px;
+ white-space: nowrap;
}
- &__header:has(> .av__title.fn__none + .av__counter:not(.fn__none)) {
- display: flex;
- align-items: center;
-
- .av__views {
- min-width: 0;
- flex: 1;
- order: 2;
+ &__views--selection {
+ > :not(.av__selection-toolbar) {
+ display: none;
}
- > .av__counter {
- position: static;
+ > .av__selection-toolbar {
display: flex;
- align-items: center;
- flex-shrink: 0;
- order: 1;
}
}
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index 48735ea409..2d1bf4ca08 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -58,7 +58,7 @@ import {
resetCardCoverPosition,
startCardCoverPosition
} from "./coverPosition";
-import {getEditableAVFields, openAVFieldEditor} from "./batchEdit";
+import {getEditableAVFields, openAVFieldEditor, updateAVFieldValue} from "./batchEdit";
import {getAVTemplateInteractiveElement, isAVTemplateLink} from "./attributeValue";
import {isMobile} from "../../../util/functions";
@@ -94,7 +94,7 @@ const getPrimaryRowInfo = (blockElement: HTMLElement, rowElement?: HTMLElement,
};
};
-const unbindDatabaseRow = (protyle: IProtyle, blockElement: HTMLElement, rowElement: HTMLElement,
+const unbindDatabaseRow = (protyle: IProtyle, blockElement: HTMLElement, rowID: string,
primaryInfo: NonNullable<ReturnType<typeof getPrimaryRowInfo>>) => {
if (primaryInfo.cellElement) {
updateCellsValue(protyle, blockElement, {content: primaryInfo.content}, [primaryInfo.cellElement]);
@@ -117,7 +117,7 @@ const unbindDatabaseRow = (protyle: IProtyle, blockElement: HTMLElement, rowElem
id: primaryInfo.valueID,
avID: blockElement.dataset.avId,
keyID: primaryInfo.fieldID,
- rowID: rowElement.dataset.id,
+ rowID,
data: value,
}, {
action: "doUpdateUpdated",
@@ -128,7 +128,7 @@ const unbindDatabaseRow = (protyle: IProtyle, blockElement: HTMLElement, rowElem
id: primaryInfo.valueID,
avID: blockElement.dataset.avId,
keyID: primaryInfo.fieldID,
- rowID: rowElement.dataset.id,
+ rowID,
data: primaryInfo.value,
}, {
action: "doUpdateUpdated",
@@ -179,6 +179,85 @@ const setGroupFolded = (foldElement: HTMLElement, folded: boolean) => {
foldElement.setAttribute("aria-label", getGroupFoldTip(folded));
};
+const getAVEditFieldMenuItems = (protyle: IProtyle, blockElement: HTMLElement): IMenu[] => {
+ return getEditableAVFields(blockElement).map(field => {
+ const item: IMenu = {
+ iconHTML: field.icon ? unicode2Emoji(field.icon, "b3-menu__icon", true) :
+ `<svg class="b3-menu__icon"><use xlink:href="#${getColIconByType(field.type)}"></use></svg>`,
+ label: escapeHtml(field.name || getColNameByType(field.type)),
+ };
+ if (field.type === "checkbox") {
+ item.type = "submenu";
+ item.submenu = [{
+ iconHTML: "",
+ label: window.siyuan.languages.checked,
+ click(element) {
+ updateAVFieldValue({
+ protyle,
+ blockElement,
+ field,
+ anchorElement: element,
+ value: {checked: true},
+ });
+ }
+ }, {
+ iconHTML: "",
+ label: window.siyuan.languages.unchecked,
+ click(element) {
+ updateAVFieldValue({
+ protyle,
+ blockElement,
+ field,
+ anchorElement: element,
+ value: {checked: false},
+ });
+ }
+ }];
+ } else if (["mSelect", "mAsset", "relation"].includes(field.type)) {
+ item.type = "submenu";
+ item.submenu = [{
+ iconHTML: "",
+ label: window.siyuan.languages.addAttr,
+ click(element) {
+ openAVFieldEditor({protyle, blockElement, field, anchorElement: element, mode: "add"});
+ return true;
+ }
+ }, {
+ iconHTML: "",
+ label: window.siyuan.languages.remove,
+ click(element) {
+ openAVFieldEditor({protyle, blockElement, field, anchorElement: element, mode: "remove"});
+ return true;
+ }
+ }, {
+ iconHTML: "",
+ label: window.siyuan.languages.replace,
+ click(element) {
+ openAVFieldEditor({protyle, blockElement, field, anchorElement: element, mode: "replace"});
+ return true;
+ }
+ }];
+ } else {
+ item.click = (element) => {
+ openAVFieldEditor({protyle, blockElement, field, anchorElement: element});
+ return true;
+ };
+ }
+ return item;
+ });
+};
+
+const openAVEditFieldMenu = (protyle: IProtyle, blockElement: HTMLElement, anchorElement: HTMLElement) => {
+ const menu = new Menu();
+ getAVEditFieldMenuItems(protyle, blockElement).forEach(item => menu.addItem(item));
+ if (isMobile()) {
+ menu.fullscreen();
+ } else {
+ const rect = anchorElement.getBoundingClientRect();
+ menu.open({x: rect.left, y: rect.bottom, w: rect.width, h: rect.height});
+ }
+};
+
let foldTimeout: number;
export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLElement }) => {
const templateInteractiveElement = getAVTemplateInteractiveElement(event.target);
@@ -201,7 +280,31 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
let target = event.target;
while (target && !target.isEqualNode(blockElement)) {
const type = target.getAttribute("data-type");
- if (type === "av-header-add" && !protyle.disabled) {
+ if (type === "av-selection-edit" && !protyle.disabled) {
+ openAVEditFieldMenu(protyle, blockElement as HTMLElement, target);
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ } else if (type === "av-selection-delete" && !protyle.disabled) {
+ deleteRow(blockElement as HTMLElement, protyle);
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ } else if (type === "av-selection-more") {
+ const rect = target.getBoundingClientRect();
+ avContextmenu(protyle, undefined, {
+ x: rect.left,
+ y: rect.bottom,
+ w: rect.width,
+ h: rect.height,
+ }, {
+ blockElement: blockElement as HTMLElement,
+ anchorElement: target,
+ });
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ } else if (type === "av-header-add" && !protyle.disabled) {
const addMenu = addCol(protyle, blockElement);
const addRect = target.getBoundingClientRect();
addMenu.open({
@@ -522,6 +625,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
if (target.classList.contains("item--focus")) {
openViewMenu({protyle, blockElement, element: target});
} else if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {
+ clearSelect(["row", "galleryItem"], blockElement);
blockElement.setAttribute(Constants.CUSTOM_SY_AV_VIEW, target.dataset.id);
blockElement.removeAttribute("data-render");
if (target.dataset.page) {
@@ -531,6 +635,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
}
avRender(blockElement, protyle);
} else {
+ clearSelect(["row", "galleryItem"], blockElement);
transaction(protyle, [{
action: "setAttrViewBlockView",
blockID: blockElement.getAttribute("data-node-id"),
@@ -597,17 +702,20 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
return false;
};
-export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, position: IPosition) => {
+export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement | undefined, position: IPosition, options?: {
+ blockElement?: HTMLElement;
+ anchorElement?: HTMLElement;
+}) => {
hideElements(["hint"], protyle);
- if (rowElement.classList.contains("av__row--header")) {
+ if (rowElement?.classList.contains("av__row--header")) {
return false;
}
- const blockElement = hasClosestBlock(rowElement);
+ const blockElement = options?.blockElement || (rowElement ? hasClosestBlock(rowElement) : undefined);
if (!blockElement) {
return false;
}
const avType = blockElement.getAttribute("data-av-type") as TAVView;
- if (avType === "table") {
+ if (rowElement && avType === "table") {
if (!rowElement.classList.contains("av__row--select")) {
clearSelect(["row"], blockElement);
}
@@ -620,7 +728,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
updateAVRowSelect(bodyElement, rowId, true);
}
updateHeader(rowElement);
- } else {
+ } else if (rowElement) {
if (!rowElement.classList.contains("av__gallery-item--select")) {
clearSelect(["galleryItem"], blockElement);
}
@@ -632,7 +740,13 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
}
updateHeader(rowElement);
}
- setAVItemAnchor(blockElement as HTMLElement, rowElement);
+ if (rowElement) {
+ setAVItemAnchor(blockElement as HTMLElement, rowElement);
+ }
+ const anchorElement = options?.anchorElement || rowElement;
+ if (!anchorElement) {
+ return false;
+ }
const menu = new Menu();
const rowElements = blockElement.querySelectorAll(".av__row--select:not(.av__row--header), .av__gallery-item--select");
const selectedItemInfos = getAVSelectedItemInfos(blockElement);
@@ -918,7 +1032,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
click() {
openSearchAV({
avID: blockElement.getAttribute("data-av-id"),
- target: rowElement,
+ target: anchorElement,
purpose: "addToDatabase",
blockID: blockElement.getAttribute("data-node-id"),
callback: (listItemElement) => {
@@ -944,7 +1058,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positi
srcs,
context: {ignoreTip: "true"},
blockID: listItemElement.dataset.blockId,
- groupID: rowElement.parentElement.getAttribute("data-group-id")
+ groupID: selectedItemInfos[0].groupID
}, {
action: "doUpdateUpdated",
id: listItemElement.dataset.blockId,
@@ -1042,7 +1156,7 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
unbindDatabaseRow(
protyle,
blockElement,
- rowElement,
+ selectedItemInfos[0].itemID,
primaryRows[0]
);
}
@@ -1057,29 +1171,12 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
deleteRow(blockElement, protyle);
}
});
- const editAttrSubmenu: IMenu[] = [];
- getEditableAVFields(blockElement).forEach((field) => {
- editAttrSubmenu.push({
- iconHTML: field.icon ? unicode2Emoji(field.icon, "b3-menu__icon", true) :
- `<svg class="b3-menu__icon"><use xlink:href="#${getColIconByType(field.type)}"></use></svg>`,
- label: escapeHtml(field.name || getColNameByType(field.type)),
- click(element) {
- openAVFieldEditor({
- protyle,
- blockElement,
- field,
- anchorElement: element,
- });
- return true;
- }
- });
- });
menu.addItem({
id: "fields",
icon: "iconAttr",
label: window.siyuan.languages.editFields,
type: "submenu",
- submenu: editAttrSubmenu
+ submenu: getAVEditFieldMenuItems(protyle, blockElement)
});
}
if (protyle?.app?.plugins) {
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index 916eb9e067..6a243b0f5c 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -9,6 +9,7 @@ import {openMenu} from "../../../menus/commonMenuItem";
import {MenuItem} from "../../../menus/Menu";
import {copyPNGByLink, exportAsset, writeAssetToClipboard} from "../../../menus/util";
import {setPosition} from "../../../util/setPosition";
+import {getAVBatchEditMode, getAVBatchSourceValue} from "./batchValue";
import {previewAttrViewImages} from "../../preview/image";
import {genAVValueHTML} from "./attributeValue";
import {hideMessage, showMessage} from "../../../dialog/message";
@@ -57,9 +58,28 @@ export const bindAssetEvent = (options: {
});
};
+const getVisibleAssetValues = (cellElements: HTMLElement[]) => {
+ const batchMode = getAVBatchEditMode(cellElements[0]);
+ if (batchMode === "add") {
+ return [];
+ }
+ if (batchMode === "remove") {
+ const assets = new Map<string, IAVCellAssetValue>();
+ cellElements.forEach(item => {
+ const renderedValue = genCellValueByElement("mAsset", item);
+ getAVBatchSourceValue(item, renderedValue).mAsset?.forEach(asset => {
+ assets.set(`${asset.type}:${asset.content}:${asset.name}`, asset);
+ });
+ });
+ return Array.from(assets.values());
+ }
+ return genCellValueByElement("mAsset", cellElements[0]).mAsset || [];
+};
+
export const getAssetHTML = (cellElements: HTMLElement[]) => {
let html = "";
- genCellValueByElement("mAsset", cellElements[0]).mAsset.forEach((item, index) => {
+ const batchMode = getAVBatchEditMode(cellElements[0]);
+ getVisibleAssetValues(cellElements).forEach((item, index) => {
let contentHTML;
if (item.type === "image") {
contentHTML = `<span data-type="openAssetItem" class="fn__flex-1 ariaLabel" aria-label="${escapeAriaLabel(item.content)}">
@@ -72,7 +92,7 @@ export const getAssetHTML = (cellElements: HTMLElement[]) => {
html += `<button class="b3-menu__item" draggable="true" data-index="${index}" data-name="${escapeAttr(item.name)}" data-type="${item.type}" data-content="${escapeAttr(item.content)}">
<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
${contentHTML}
-<svg class="b3-menu__action" data-type="editAssetItem"><use xlink:href="#iconEdit"></use></svg>
+${batchMode === "replace" ? '<svg class="b3-menu__action" data-type="editAssetItem"><use xlink:href="#iconEdit"></use></svg>' : ""}
</button>`;
});
const ids: string[] = [];
@@ -111,6 +131,9 @@ export const updateAssetCell = (options: {
const cellDoOperations: IOperation[] = [];
const cellUndoOperations: IOperation[] = [];
let mAssetValue: IAVCellAssetValue[];
+ const batchMode = getAVBatchEditMode(options.cellElements[0]);
+ const batchTarget = typeof options.removeIndex === "number" ?
+ getVisibleAssetValues(options.cellElements)[options.removeIndex] : undefined;
options.cellElements.forEach((item, elementIndex) => {
const rowID = getFieldIdByCellElement(item, viewType);
if (!options.blockElement.contains(item)) {
@@ -121,9 +144,19 @@ export const updateAssetCell = (options: {
item = options.cellElements[elementIndex] = (options.blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`)) as HTMLElement;
}
}
- const cellValue = genCellValueByElement(getTypeByCellElement(item) || item.dataset.type as TAVCol, item);
+ const renderedValue = genCellValueByElement(getTypeByCellElement(item) || item.dataset.type as TAVCol, item);
+ const cellValue = batchMode === "replace" ? renderedValue : getAVBatchSourceValue(item, renderedValue);
const oldValue = JSON.parse(JSON.stringify(cellValue));
- if (elementIndex === 0) {
+ if (batchMode === "add" && options.addValue?.length > 0) {
+ const existing = new Set((cellValue.mAsset || []).map(asset =>
+ `${asset.type}:${asset.content}:${asset.name}`));
+ cellValue.mAsset = (cellValue.mAsset || []).concat(options.addValue.filter(asset =>
+ !existing.has(`${asset.type}:${asset.content}:${asset.name}`)));
+ } else if (batchMode === "remove" && batchTarget) {
+ cellValue.mAsset = (cellValue.mAsset || []).filter(asset =>
+ asset.type !== batchTarget.type || asset.content !== batchTarget.content ||
+ asset.name !== batchTarget.name);
+ } else if (elementIndex === 0) {
if (typeof options.removeIndex === "number") {
cellValue.mAsset.splice(options.removeIndex, 1);
} else if (options.addValue?.length > 0) {
diff --git a/app/src/protyle/render/av/batchEdit.ts b/app/src/protyle/render/av/batchEdit.ts
index 24a8563f72..0b8df32f44 100644
--- a/app/src/protyle/render/av/batchEdit.ts
+++ b/app/src/protyle/render/av/batchEdit.ts
@@ -1,7 +1,8 @@
import {createEmptyAVValue} from "./attributeValue";
-import {popTextCell, renderCell} from "./cell";
+import {popTextCell, renderCell, updateCellsValue} from "./cell";
import {getAVData, getAVSelectedItemIDs} from "./virtualScroll";
import {getFieldsByData} from "./view";
+import {TAVBatchEditMode} from "./batchValue";
const EDITABLE_FIELD_TYPES: TAVCol[] = [
"block",
@@ -53,18 +54,62 @@ const getItemCell = (data: IAV, itemID: string, fieldID: string) => {
return findItemCell(data.view, data.viewType, itemID, fieldIndex);
};
+const cloneValue = <T>(value: T) => JSON.parse(JSON.stringify(value)) as T;
+
+const getCollectionDisplayValue = (field: IAVColumn, values: IAVCellValue[], mode: TAVBatchEditMode) => {
+ const displayValue = cloneValue(values[0]);
+ if (mode === "replace") {
+ return displayValue;
+ }
+ if (field.type === "mSelect") {
+ displayValue.mSelect = [];
+ if (mode === "remove") {
+ const options = new Map<string, IAVCellSelectValue>();
+ values.forEach(value => value.mSelect?.forEach(item => options.set(item.content, item)));
+ displayValue.mSelect = Array.from(options.values()).map(item => ({...item}));
+ }
+ } else if (field.type === "mAsset") {
+ displayValue.mAsset = [];
+ if (mode === "remove") {
+ const assets = new Map<string, IAVCellAssetValue>();
+ values.forEach(value => value.mAsset?.forEach(item => {
+ assets.set(`${item.type}:${item.content}:${item.name}`, item);
+ }));
+ displayValue.mAsset = Array.from(assets.values()).map(item => ({...item}));
+ }
+ } else if (field.type === "relation") {
+ displayValue.relation = {blockIDs: [], contents: []};
+ if (mode === "remove") {
+ const relations = new Map<string, IAVCellValue>();
+ values.forEach(value => value.relation?.blockIDs?.forEach((itemID, index) => {
+ relations.set(itemID, value.relation.contents[index]);
+ }));
+ relations.forEach((content, itemID) => {
+ displayValue.relation.blockIDs.push(itemID);
+ displayValue.relation.contents.push(cloneValue(content));
+ });
+ }
+ }
+ return displayValue;
+};
+
const createEditProxy = (options: {
data: IAV;
field: IAVColumn;
itemID: string;
+ value: IAVCellValue;
+ displayValue: IAVCellValue;
+ mode: TAVBatchEditMode;
}) => {
const cell = getItemCell(options.data, options.itemID, options.field.id);
- const value = cell?.value ?
- JSON.parse(JSON.stringify(cell.value)) as IAVCellValue :
- createEmptyAVValue(options.field.id, options.field.type, options.itemID);
+ const value = cloneValue(options.value);
value.id = value.id || cell?.id;
value.keyID = options.field.id;
value.blockID = options.itemID;
+ const displayValue = cloneValue(options.displayValue);
+ displayValue.id = value.id;
+ displayValue.keyID = options.field.id;
+ displayValue.blockID = options.itemID;
const cellElement = document.createElement("div");
cellElement.className = "custom-attr__avvalue";
@@ -73,7 +118,10 @@ const createEditProxy = (options: {
cellElement.dataset.rowId = options.itemID;
cellElement.dataset.type = options.field.type;
cellElement.dataset.dtype = options.field.type;
- cellElement.dataset.cellValue = encodeURIComponent(JSON.stringify(value));
+ cellElement.dataset.cellValue = encodeURIComponent(JSON.stringify(displayValue));
+ cellElement.dataset.avBatchMode = options.mode;
+ cellElement.dataset.avBatchOriginalValue = encodeURIComponent(JSON.stringify(value));
+ cellElement.dataset.avBatchDisplayValue = encodeURIComponent(JSON.stringify(displayValue));
cellElement.dataset.options = JSON.stringify(options.field.options || []);
if (value.id) {
cellElement.dataset.id = value.id;
@@ -83,22 +131,35 @@ const createEditProxy = (options: {
}
cellElement.dataset.dateFormat = options.field.dateFormat || "";
cellElement.style.cssText = "position:absolute;inset:0;";
- cellElement.innerHTML = renderCell(value, 0, options.data.view.showIcon, "table", options.field.options,
+ cellElement.innerHTML = renderCell(displayValue, 0, options.data.view.showIcon, "table", options.field.options,
options.field.dateFormat);
return cellElement;
};
-export const openAVFieldEditor = (options: {
+const createBatchEditContext = (options: {
protyle: IProtyle;
blockElement: HTMLElement;
field: IAVColumn;
anchorElement: HTMLElement;
+ mode?: TAVBatchEditMode;
}) => {
const data = getAVData(options.blockElement);
const itemIDs = getAVSelectedItemIDs(options.blockElement);
if (!data || itemIDs.length === 0) {
return;
}
+ const mode = options.mode || "replace";
+ const values = itemIDs.map(itemID => {
+ const cell = getItemCell(data, itemID, options.field.id);
+ const value = cell?.value ?
+ cloneValue(cell.value) :
+ createEmptyAVValue(options.field.id, options.field.type, itemID);
+ value.id = value.id || cell?.id;
+ value.keyID = options.field.id;
+ value.blockID = itemID;
+ return value;
+ });
+ const displayValue = getCollectionDisplayValue(options.field, values, mode);
const anchorRect = options.anchorElement.getBoundingClientRect();
const proxyElement = document.createElement("div");
@@ -106,10 +167,13 @@ export const openAVFieldEditor = (options: {
proxyElement.style.cssText = `position:fixed;left:${anchorRect.left}px;top:${anchorRect.top}px;` +
`width:${Math.max(anchorRect.width, 25)}px;height:${Math.max(anchorRect.height, 25)}px;` +
"opacity:0;pointer-events:none;";
- const cellElements = itemIDs.map((itemID) => createEditProxy({
+ const cellElements = itemIDs.map((itemID, index) => createEditProxy({
data,
field: options.field,
itemID,
+ value: values[index],
+ displayValue: mode === "replace" ? values[index] : displayValue,
+ mode,
}));
cellElements.forEach((cellElement) => proxyElement.append(cellElement));
options.blockElement.append(proxyElement);
@@ -125,17 +189,50 @@ export const openAVFieldEditor = (options: {
if (!cell || !cellElement.dataset.cellValue) {
return;
}
- const value = JSON.parse(decodeURIComponent(cellElement.dataset.cellValue)) as IAVCellValue;
+ const encodedValue = cellElement.dataset.avBatchChanged === "true" ?
+ cellElement.dataset.cellValue :
+ cellElement.dataset.avBatchOriginalValue;
+ const value = JSON.parse(decodeURIComponent(encodedValue)) as IAVCellValue;
cell.id = value.id || "";
cell.value = value;
cell.valueType = value.type;
});
proxyElement.remove();
};
- popTextCell(options.protyle, cellElements, options.field.type, {
+ return {data, cellElements, destroy};
+};
+
+export const updateAVFieldValue = async (options: {
+ protyle: IProtyle;
+ blockElement: HTMLElement;
+ field: IAVColumn;
+ anchorElement: HTMLElement;
+ value: unknown;
+}) => {
+ const context = createBatchEditContext(options);
+ if (!context) {
+ return;
+ }
+ await updateCellsValue(options.protyle, options.blockElement, options.value, context.cellElements,
+ getFieldsByData(context.data));
+ context.destroy();
+};
+
+export const openAVFieldEditor = (options: {
+ protyle: IProtyle;
+ blockElement: HTMLElement;
+ field: IAVColumn;
+ anchorElement: HTMLElement;
+ mode?: TAVBatchEditMode;
+}) => {
+ const context = createBatchEditContext(options);
+ if (!context) {
+ return;
+ }
+ popTextCell(options.protyle, context.cellElements, options.field.type, {
scrollIntoView: false,
- data,
- destroyCallback: destroy,
+ data: context.data,
+ destroyCallback: context.destroy,
keepMenuOpen: true,
positionByMenu: true,
requireExplicitChange: true,
diff --git a/app/src/protyle/render/av/batchValue.ts b/app/src/protyle/render/av/batchValue.ts
new file mode 100644
index 0000000000..249f25f954
--- /dev/null
+++ b/app/src/protyle/render/av/batchValue.ts
@@ -0,0 +1,60 @@
+export type TAVBatchEditMode = "replace" | "add" | "remove";
+
+const decodeCellValue = (value?: string): IAVCellValue | undefined => {
+ if (!value) {
+ return;
+ }
+ return JSON.parse(decodeURIComponent(value)) as IAVCellValue;
+};
+
+export const getAVBatchEditMode = (cellElement?: HTMLElement): TAVBatchEditMode => {
+ return cellElement?.dataset.avBatchMode as TAVBatchEditMode || "replace";
+};
+
+export const getAVBatchSourceValue = (cellElement: HTMLElement, fallback: IAVCellValue): IAVCellValue => {
+ if (getAVBatchEditMode(cellElement) === "replace") {
+ return fallback;
+ }
+ const value = cellElement.dataset.avBatchChanged === "true" ?
+ decodeCellValue(cellElement.dataset.cellValue) :
+ decodeCellValue(cellElement.dataset.avBatchOriginalValue);
+ return value || fallback;
+};
+
+export const getAVBatchDisplayValue = (cellElement: HTMLElement, fallback: IAVCellValue): IAVCellValue => {
+ return decodeCellValue(cellElement.dataset.avBatchDisplayValue) || fallback;
+};
+
+export const setAVBatchDisplayValue = (cellElements: HTMLElement[], value: IAVCellValue) => {
+ const encodedValue = encodeURIComponent(JSON.stringify(value));
+ cellElements.forEach(item => {
+ item.dataset.avBatchDisplayValue = encodedValue;
+ });
+};
+
+export const mergeAVBatchRelationValue = (
+ original: IAVCellRelationValue,
+ previousDisplay: IAVCellRelationValue,
+ nextDisplay: IAVCellRelationValue,
+ mode: Exclude<TAVBatchEditMode, "replace">
+): IAVCellRelationValue => {
+ const relations = new Map<string, IAVCellValue>();
+ (original.blockIDs || []).forEach((itemID, index) => relations.set(itemID, original.contents[index]));
+ if (mode === "add") {
+ (nextDisplay.blockIDs || []).forEach((itemID, index) => {
+ if (!previousDisplay.blockIDs?.includes(itemID)) {
+ relations.set(itemID, nextDisplay.contents[index]);
+ }
+ });
+ } else {
+ (previousDisplay.blockIDs || []).forEach(itemID => {
+ if (!nextDisplay.blockIDs?.includes(itemID)) {
+ relations.delete(itemID);
+ }
+ });
+ }
+ return {
+ blockIDs: Array.from(relations.keys()),
+ contents: Array.from(relations.values())
+ };
+};
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index 28759e9a12..59c02ec58a 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -29,6 +29,13 @@ import {
} from "./cellValue";
import {setPosition} from "../../../util/setPosition";
import {getAVSelectedCells, IAVSelectedCell, updateAVSelectedCellValue} from "./selectionState";
+import {
+ getAVBatchDisplayValue,
+ getAVBatchEditMode,
+ getAVBatchSourceValue,
+ mergeAVBatchRelationValue,
+ setAVBatchDisplayValue
+} from "./batchValue";
export {cellValueIsEmpty} from "./cellValue";
@@ -777,6 +784,8 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
const isCustomAttr = sources[0].element ?
Boolean(hasClosestByClassName(sources[0].element, "custom-attr")) : false;
const viewType = nodeElement.getAttribute("data-av-type") as TAVView;
+ let batchDisplayValue: IAVCellValue;
+ let nextBatchDisplayValue: IAVCellValue;
for (let elementIndex = 0; elementIndex < sources.length; elementIndex++) {
const source = sources[elementIndex];
let item = source.element;
@@ -805,10 +814,16 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
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);
+ const renderedOldValue = source.selectedCell?.cell.value ||
+ (item ? genCellValueByElement(type, item) : undefined);
+ const oldValue = item && renderedOldValue ? getAVBatchSourceValue(item, renderedOldValue) : renderedOldValue;
if (!colId || !oldValue) {
continue;
}
+ const batchMode = getAVBatchEditMode(item);
+ if (elementIndex === 0 && item && batchMode !== "replace") {
+ batchDisplayValue = getAVBatchDisplayValue(item, renderedOldValue);
+ }
const nextSource = sources[elementIndex + 1];
const sameNextRow = nextSource && (source.selectedCell ?
nextSource.selectedCell?.rowID === rowID :
@@ -913,6 +928,10 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
});
newValue = oldSelectValues.concat(newMSelectValue);
}
+ } else if (type === "relation" && batchMode !== "replace" && batchDisplayValue?.relation &&
+ value?.blockIDs && value?.contents) {
+ newValue = mergeAVBatchRelationValue(oldValue.relation, batchDisplayValue.relation, value, batchMode);
+ nextBatchDisplayValue = genCellValue("relation", value);
} else if (type === "block" && typeof value === "string" && oldValue.block.id) {
newValue = {
content: value,
@@ -979,6 +998,9 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
updateAVSelectedCellValue(nodeElement, rowID, colId, cellValue);
}
}
+ if (nextBatchDisplayValue) {
+ setAVBatchDisplayValue(cellElements as HTMLElement[], nextBatchDisplayValue);
+ }
if (getOperations) {
return {doOperations, undoOperations};
}
@@ -1001,6 +1023,9 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
export const updateAttrViewCellInOtherElements = (protyle: IProtyle, avID: string, rowID: string, colID: string,
value: IAVCellValue, sourceElement?: HTMLElement) => {
const updateCustomAttr = (cellElement: HTMLElement) => {
+ if (cellElement.dataset.avBatchOriginalValue) {
+ cellElement.dataset.avBatchChanged = "true";
+ }
if (value.id) {
cellElement.dataset.id = value.id;
} else {
diff --git a/app/src/protyle/render/av/locate.ts b/app/src/protyle/render/av/locate.ts
index f741a1e16f..ee1c5d557d 100644
--- a/app/src/protyle/render/av/locate.ts
+++ b/app/src/protyle/render/av/locate.ts
@@ -258,6 +258,9 @@ export const prepareAVLocate = (blockElement: HTMLElement, data: IAV, resetData:
}
return;
}
+ if (request.viewID && request.previousViewID !== undefined && request.viewID !== request.previousViewID) {
+ clearSelect(["row", "galleryItem"], blockElement);
+ }
const key = data.target.groupID || "all";
if (request.persistView === false && request.viewID) {
blockElement.setAttribute(Constants.CUSTOM_SY_AV_VIEW, request.viewID);
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index 96e76abd95..6e35bb159d 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -76,6 +76,7 @@ import {
setGroupMethod
} from "./groups";
import {openFieldVisibilityPanel} from "./fieldVisibility";
+import {clearSelect} from "../../util/clear";
export const openMenuPanel = (options: {
protyle: IProtyle,
@@ -1806,6 +1807,7 @@ export const openMenuPanel = (options: {
break;
} else if (type === "av-view-switch") {
if (!target.parentElement.classList.contains("b3-menu__item--current")) {
+ clearSelect(["row", "galleryItem"], options.blockElement);
avPanelElement.querySelector(".b3-menu__item--current")?.classList.remove("b3-menu__item--current");
target.parentElement.classList.add("b3-menu__item--current");
transaction(options.protyle, [{
@@ -1831,6 +1833,7 @@ export const openMenuPanel = (options: {
element: target.parentElement
});
} else {
+ clearSelect(["row", "galleryItem"], options.blockElement);
avPanelElement.querySelector(".b3-menu__item--current")?.classList.remove("b3-menu__item--current");
target.parentElement.classList.add("b3-menu__item--current");
transaction(options.protyle, [{
diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.ts
index e257842573..2ea718fe7b 100644
--- a/app/src/protyle/render/av/render.ts
+++ b/app/src/protyle/render/av/render.ts
@@ -94,7 +94,18 @@ export const genTabHeaderHTML = (data: IAV, showSearch: boolean, editable: boole
defaultTemplate.primaryKeyTemplate || Object.keys(defaultTemplate.fieldValues || {}).length) ? defaultTemplate.id : "";
return `<div class="av__header" data-default-template-id="${defaultTemplateID}">
<div class="fn__flex av__views${showSearch ? " av__views--show" : ""}">
- <div class="av__counter av__counter--sticky fn__none"></div>
+ <div class="av__selection-toolbar">
+ <span class="av__selection-count"></span>
+ ${editable ? `<button data-type="av-selection-edit" class="block__icon block__icon--show ariaLabel" data-position="8south" aria-label="${window.siyuan.languages.editFields}">
+ <svg><use xlink:href="#iconAttr"></use></svg>
+ </button>
+ <button data-type="av-selection-delete" class="block__icon block__icon--show ariaLabel" data-position="8south" aria-label="${window.siyuan.languages.delete}">
+ <svg><use xlink:href="#iconTrashcan"></use></svg>
+ </button>` : ""}
+ <button data-type="av-selection-more" class="block__icon block__icon--show ariaLabel" data-position="8south" aria-label="${window.siyuan.languages.more}">
+ <svg><use xlink:href="#iconMore"></use></svg>
+ </button>
+ </div>
<div class="layout-tab-bar fn__flex">
${tabHTML}
</div>
@@ -138,7 +149,6 @@ export const genTabHeaderHTML = (data: IAV, showSearch: boolean, editable: boole
</div>` : ""}
</div>
<div contenteditable="${editable}" spellcheck="${window.siyuan.config.editor.spellcheck.toString()}" class="av__title${viewData.hideAttrViewName ? " fn__none" : ""}" data-title="${Lute.EscapeHTMLStr(data.name || "")}" data-tip="${window.siyuan.languages._kernel[267]}">${Lute.EscapeHTMLStr(data.name || "")}</div>
- <div class="av__counter fn__none"></div>
</div>`;
};
diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.ts
index 3e32536ce2..d95a9f8ec5 100644
--- a/app/src/protyle/render/av/row.ts
+++ b/app/src/protyle/render/av/row.ts
@@ -355,20 +355,20 @@ export const updateAVSelectionStatus = (blockElement: HTMLElement) => {
});
}
- const counterElements = Array.from(blockElement.querySelectorAll<HTMLElement>(".av__counter")).filter(
+ const viewsElement = Array.from(blockElement.querySelectorAll<HTMLElement>(".av__views")).find(
item => hasClosestByClassName(item, "av") === blockElement
);
- if (counterElements.length === 0) {
+ const countElement = viewsElement?.querySelector<HTMLElement>(".av__selection-count");
+ if (!viewsElement || !countElement) {
return;
}
if (selectCount === 0) {
- counterElements.forEach(item => item.classList.add("fn__none"));
+ viewsElement.classList.remove("av__views--selection");
+ countElement.textContent = "";
return;
}
- counterElements.forEach(item => {
- item.classList.remove("fn__none");
- item.textContent = `${selectCount} ${window.siyuan.languages.selected}`;
- });
+ viewsElement.classList.add("av__views--selection");
+ countElement.textContent = `${selectCount} ${window.siyuan.languages.selected}`;
};
export const setPage = (blockElement: Element) => {
diff --git a/app/src/protyle/render/av/select.ts b/app/src/protyle/render/av/select.ts
index b30f9f26f4..0dd25e9d85 100644
--- a/app/src/protyle/render/av/select.ts
+++ b/app/src/protyle/render/av/select.ts
@@ -14,6 +14,7 @@ import {getFieldsByData} from "./view";
import {getFieldIdByCellElement} from "./row";
import {Constants} from "../../../constants";
import {setPosition} from "../../../util/setPosition";
+import {getAVBatchEditMode, getAVBatchSourceValue} from "./batchValue";
let cellValues: IAVCellValue[];
@@ -80,6 +81,7 @@ export const removeCellOption = (protyle: IProtyle, cellElements: HTMLElement[],
const undoOperations: IOperation[] = [];
let mSelectValue: IAVCellSelectValue[];
const avID = blockElement.getAttribute("data-av-id");
+ const batchMode = getAVBatchEditMode(cellElements[0]);
cellElements.forEach((item, elementIndex) => {
const rowID = getFieldIdByCellElement(item, viewType);
if (!rowID) {
@@ -93,9 +95,13 @@ export const removeCellOption = (protyle: IProtyle, cellElements: HTMLElement[],
item = cellElements[elementIndex] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`)) as HTMLElement;
}
}
- const cellValue: IAVCellValue = cellValues[elementIndex];
+ const cellValue: IAVCellValue = batchMode === "replace" ?
+ cellValues[elementIndex] :
+ getAVBatchSourceValue(item, cellValues[elementIndex]);
const oldValue = JSON.parse(JSON.stringify(cellValue));
- if (elementIndex === 0) {
+ if (batchMode !== "replace") {
+ cellValue.mSelect = cellValue.mSelect?.filter(option => option.content !== target.dataset.content) || [];
+ } else if (elementIndex === 0) {
cellValue.mSelect?.find((item, index) => {
if (item.content === target.dataset.content) {
cellValue.mSelect.splice(index, 1);
@@ -106,6 +112,7 @@ export const removeCellOption = (protyle: IProtyle, cellElements: HTMLElement[],
} else {
cellValue.mSelect = mSelectValue;
}
+ cellValues[elementIndex] = cellValue;
doOperations.push({
action: "updateAttrViewCell",
id: cellValue.id,
@@ -577,14 +584,30 @@ export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: H
const cellDoOperations: IOperation[] = [];
const cellUndoOperations: IOperation[] = [];
let mSelectValue: IAVCellSelectValue[];
+ const batchMode = getAVBatchEditMode(cellElements[0]);
cellElements.forEach((item, index) => {
const rowID = getFieldIdByCellElement(item, data.viewType);
if (!rowID) {
return;
}
- const cellValue: IAVCellValue = cellValues[index];
+ const cellValue: IAVCellValue = batchMode === "replace" ?
+ cellValues[index] :
+ getAVBatchSourceValue(item, cellValues[index]);
const oldValue = JSON.parse(JSON.stringify(cellValue));
- if (index === 0) {
+ if (batchMode === "remove") {
+ cellValue.mSelect = cellValue.mSelect?.filter(option =>
+ option.content !== currentElement.dataset.name) || [];
+ } else if (batchMode === "add") {
+ if (!cellValue.mSelect?.some(option => option.content === currentElement.dataset.name)) {
+ if (!cellValue.mSelect) {
+ cellValue.mSelect = [];
+ }
+ cellValue.mSelect.push({
+ color: currentElement.dataset.color,
+ content: currentElement.dataset.name
+ });
+ }
+ } else if (index === 0) {
if (colData.type === "mSelect") {
let hasOption = false;
cellValue.mSelect.find((item) => {
@@ -609,6 +632,7 @@ export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: H
} else {
cellValue.mSelect = mSelectValue;
}
+ cellValues[index] = cellValue;
cellDoOperations.push({
action: "updateAttrViewCell",
id: cellValue.id,
@@ -698,8 +722,10 @@ export const getSelectHTML = (fields: IAVColumn[], cellElements: HTMLElement[],
});
let selectedHTML = "";
const selected: string[] = [];
- const canSort = colData.type === "mSelect" && cellValues[0].mSelect?.length > 1;
- cellValues[0].mSelect?.forEach((item) => {
+ const batchMode = getAVBatchEditMode(cellElements[0]);
+ const visibleValues = batchMode === "replace" ? cellValues[0].mSelect : [];
+ const canSort = colData.type === "mSelect" && visibleValues?.length > 1;
+ visibleValues?.forEach((item) => {
const option = colData.options?.find((colOption) => colOption.name === item.content);
selected.push(item.content);
selectedHTML += `<div class="b3-chip b3-chip--middle${canSort ? " fn__grab" : " b3-chip--pointer"}" data-content="${escapeAttr(item.content)}" data-name="${escapeAttr(item.content)}" data-desc="${escapeAttr(option?.desc || "")}" data-color="${escapeAttr(option?.color || item.color)}" data-value-color="${escapeAttr(item.color)}" style="white-space: nowrap;max-width:100%;background-color:var(--b3-font-background${item.color});color:var(--b3-font-color${item.color})"><span class="fn__ellipsis">${escapeHtml(item.content)}</span><svg class="b3-chip__close" data-type="removeCellOption"><use xlink:href="#iconClose"></use></svg></div>`;
diff --git a/app/src/protyle/render/av/view.ts b/app/src/protyle/render/av/view.ts
index 9b0bab0872..ac211d402a 100644
--- a/app/src/protyle/render/av/view.ts
+++ b/app/src/protyle/render/av/view.ts
@@ -7,6 +7,7 @@ import {upDownHint} from "../../../util/upDownHint";
import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
import {hasClosestByClassName} from "../../util/hasClosest";
import {Constants} from "../../../constants";
+import {clearSelect} from "../../util/clear";
// countFilterLeaves 递归统计过滤节点树中的叶子数量(分组不计入)。
const countFilterLeaves = (filters: IAVFilter[]): number => {
@@ -262,6 +263,11 @@ export const bindSwitcherEvent = (options: { protyle: IProtyle, menuElement: Ele
if (event.key === "Enter") {
const currentElement = options.menuElement.querySelector(".b3-menu__item--current") as HTMLElement;
if (currentElement) {
+ const currentViewID = options.blockElement.querySelector(".av__views .item--focus")?.
+ getAttribute("data-id");
+ if (currentElement.dataset.id !== currentViewID) {
+ clearSelect(["row", "galleryItem"], options.blockElement);
+ }
transaction(options.protyle, [{
action: "setAttrViewBlockView",
blockID: options.blockElement.getAttribute("data-node-id"),
@@ -270,7 +276,7 @@ export const bindSwitcherEvent = (options: { protyle: IProtyle, menuElement: Ele
}], [{
action: "setAttrViewBlockView",
blockID: options.blockElement.getAttribute("data-node-id"),
- id: options.blockElement.querySelector(".av__views .item--focus").getAttribute("data-id"),
+ id: currentViewID,
avID: options.blockElement.getAttribute("data-av-id"),
}]);
options.menuElement.remove();
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index cf360c3382..85c775a5ea 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -2916,6 +2916,7 @@ export class WYSIWYG {
if (avTabHeaderElement.classList.contains("item--focus")) {
openViewMenu({protyle, blockElement: nodeElement, element: avTabHeaderElement});
} else {
+ clearSelect(["row", "galleryItem"], nodeElement);
transaction(protyle, [{
action: "setAttrViewBlockView",
blockID: nodeElement.getAttribute("data-node-id"),
diff --git a/app/tests/batchValue.test.ts b/app/tests/batchValue.test.ts
new file mode 100644
index 0000000000..98db8b800e
--- /dev/null
+++ b/app/tests/batchValue.test.ts
@@ -0,0 +1,38 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {mergeAVBatchRelationValue} from "../src/protyle/render/av/batchValue";
+
+const relationValue = (blockIDs: string[]): IAVCellRelationValue => ({
+ blockIDs,
+ contents: blockIDs.map(itemID => ({
+ type: "block",
+ block: {
+ id: itemID,
+ content: itemID,
+ }
+ }))
+});
+
+test("adds only the relation introduced by the current batch edit", () => {
+ const result = mergeAVBatchRelationValue(
+ relationValue(["original", "previous"]),
+ relationValue(["previous"]),
+ relationValue(["previous", "added"]),
+ "add"
+ );
+
+ assert.deepEqual(result.blockIDs, ["original", "previous", "added"]);
+ assert.deepEqual(result.contents?.map(item => item.block.id), ["original", "previous", "added"]);
+});
+
+test("removes only the relation cleared by the current batch edit", () => {
+ const result = mergeAVBatchRelationValue(
+ relationValue(["kept-by-row", "removed"]),
+ relationValue(["kept-by-display", "removed"]),
+ relationValue(["kept-by-display"]),
+ "remove"
+ );
+
+ assert.deepEqual(result.blockIDs, ["kept-by-row"]);
+ assert.deepEqual(result.contents?.map(item => item.block.id), ["kept-by-row"]);
+});