Skip to content

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

:sparkles: Support editing fields for selected database items https://github.com/siyuan-note/siyuan/issues/14975

Daniel49af8803cb84
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 018ea74354..a991c04606 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "editFields": "تحرير الحقول",
"startDate": "تاريخ البدء",
"addToDictionary": "إضافة إلى القاموس",
"addToDictionaryFailed": "تعذرت إضافة الكلمة إلى القاموس",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 94f3f8bb13..85d772c6da 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Felder bearbeiten",
"startDate": "Startdatum",
"addToDictionary": "Zum Wörterbuch hinzufügen",
"addToDictionaryFailed": "Das Wort konnte nicht zum Wörterbuch hinzugefügt werden",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index f6aa92bdfa..3f04cfc8d3 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Edit fields",
"startDate": "Start date",
"addToDictionary": "Add to dictionary",
"addToDictionaryFailed": "Failed to add the word to the dictionary",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 137b1c893e..86f21fa0d1 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Editar campos",
"startDate": "Fecha de inicio",
"addToDictionary": "Añadir al diccionario",
"addToDictionaryFailed": "No se pudo añadir la palabra al diccionario",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 91c77db618..09f6fc092c 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Modifier les champs",
"startDate": "Date de début",
"addToDictionary": "Ajouter au dictionnaire",
"addToDictionaryFailed": "Impossible d'ajouter le mot au dictionnaire",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 07c4995cb3..266f09e3e9 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "editFields": "עריכת שדות",
"startDate": "תאריך התחלה",
"addToDictionary": "הוספה למילון",
"addToDictionaryFailed": "לא ניתן להוסיף את המילה למילון",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 9381536ad5..f7385650ee 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "editFields": "फ़ील्ड संपादित करें",
"startDate": "प्रारंभ तिथि",
"addToDictionary": "शब्दकोश में जोड़ें",
"addToDictionaryFailed": "शब्द को शब्दकोश में नहीं जोड़ा जा सका",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index feea2d62d4..23a3e455c8 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Edit bidang",
"startDate": "Tanggal mulai",
"addToDictionary": "Tambahkan ke kamus",
"addToDictionaryFailed": "Kata gagal ditambahkan ke kamus",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index cf53692e5d..157749d230 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Modifica campi",
"startDate": "Data di inizio",
"addToDictionary": "Aggiungi al dizionario",
"addToDictionaryFailed": "Impossibile aggiungere la parola al dizionario",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 036968da4c..f733b0b4dc 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "editFields": "フィールドを編集",
"startDate": "開始日",
"addToDictionary": "辞書に追加",
"addToDictionaryFailed": "単語を辞書に追加できませんでした",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index a5a859e5df..a8d4d42e65 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "editFields": "필드 편집",
"startDate": "시작일",
"addToDictionary": "사전에 추가",
"addToDictionaryFailed": "단어를 사전에 추가하지 못했습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index dd07a22e92..92bd849419 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Velden bewerken",
"startDate": "Begindatum",
"addToDictionary": "Toevoegen aan woordenboek",
"addToDictionaryFailed": "Het woord kon niet aan het woordenboek worden toegevoegd",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 5f45e4c51e..246472d219 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Edytuj pola",
"startDate": "Data rozpoczęcia",
"addToDictionary": "Dodaj do słownika",
"addToDictionaryFailed": "Nie udało się dodać słowa do słownika",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index d42621d563..9245615a81 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Editar campos",
"startDate": "Data inicial",
"addToDictionary": "Adicionar ao dicionário",
"addToDictionaryFailed": "Não foi possível adicionar a palavra ao dicionário",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 2944e183ad..6426771425 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Редактировать поля",
"startDate": "Дата начала",
"addToDictionary": "Добавить в словарь",
"addToDictionaryFailed": "Не удалось добавить слово в словарь",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 34aca36a73..1f6031be21 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Upraviť polia",
"startDate": "Dátum začiatku",
"addToDictionary": "Pridať do slovníka",
"addToDictionaryFailed": "Slovo sa nepodarilo pridať do slovníka",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 55ad1cdbff..ccdbc8941b 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "editFields": "แก้ไขฟิลด์",
"startDate": "วันที่เริ่มต้น",
"addToDictionary": "เพิ่มลงในพจนานุกรม",
"addToDictionaryFailed": "ไม่สามารถเพิ่มคำลงในพจนานุกรมได้",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 222d62ada4..a98029f128 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Alanları düzenle",
"startDate": "Başlangıç tarihi",
"addToDictionary": "Sözlüğe ekle",
"addToDictionaryFailed": "Sözcük sözlüğe eklenemedi",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 6b9f07aa46..7f89f54209 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "editFields": "Редагувати поля",
"startDate": "Дата початку",
"addToDictionary": "Додати до словника",
"addToDictionaryFailed": "Не вдалося додати слово до словника",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index c148e2eba2..db4b28a7bb 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "editFields": "编辑字段",
"startDate": "开始时间",
"addToDictionary": "添加到词典",
"addToDictionaryFailed": "无法将单词添加到词典",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 13d4856da1..0218808c8b 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "editFields": "編輯欄位",
"startDate": "開始日期",
"addToDictionary": "加入字典",
"addToDictionaryFailed": "無法將單字加入字典",
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index e55d0ea2ce..98ddcaa3c5 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -15,7 +15,7 @@ import {
updateCellsValue,
updateHeaderCell
} from "./cell";
-import {addCol, getColIconByType, showColMenu} from "./col";
+import {addCol, getColIconByType, getColNameByType, showColMenu} from "./col";
import {deleteRow, duplicateRows, insertRows, selectRow, setPageSize, updateHeader} from "./row";
import {getAVSelectedItems, resetAVRowSelect, updateAVRowSelect} from "./virtualScroll";
import {emitOpenMenu} from "../../../plugin/EventBus";
@@ -50,6 +50,7 @@ import {
resetCardCoverPosition,
startCardCoverPosition
} from "./coverPosition";
+import {getEditableAVFields, openAVFieldEditor} from "./batchEdit";
import {getAVTemplateInteractiveElement, isAVTemplateLink} from "./attributeValue";
const isDetachedDatabaseCell = (cellElement: HTMLElement) => {
@@ -933,44 +934,25 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
}
});
const editAttrSubmenu: IMenu[] = [];
- if (avType === "table") {
- rowElement.parentElement.querySelectorAll(".av__row--header .av__cell").forEach((cellElement: HTMLElement) => {
- const selectElements: HTMLElement[] = Array.from(blockElement.querySelectorAll(`.av__row--select:not(.av__row--header) .av__cell[data-col-id="${cellElement.dataset.colId}"]`));
- const type = cellElement.getAttribute("data-dtype") as TAVCol;
- if (!["updated", "created"].includes(type)) {
- const icon = cellElement.dataset.icon;
- editAttrSubmenu.push({
- iconHTML: icon ? unicode2Emoji(icon, "b3-menu__icon", true) : `<svg class="b3-menu__icon"><use xlink:href="#${getColIconByType(type)}"></use></svg>`,
- label: escapeHtml(cellElement.querySelector(".av__celltext").textContent.trim()),
- click() {
- popTextCell(protyle, selectElements);
- }
- });
- }
- });
- } else {
- rowElement.querySelectorAll(".av__cell").forEach((cellElement: HTMLElement) => {
- const selectElements: HTMLElement[] = Array.from(blockElement.querySelectorAll(`.av__gallery-item--select .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`));
- const type = cellElement.getAttribute("data-dtype") as TAVCol;
- if (!["updated", "created"].includes(type)) {
- const iconElement = cellElement.parentElement.querySelector(".av__gallery-tip, .av__gallery-name").firstElementChild.cloneNode(true) as HTMLElement;
- iconElement.classList.add("b3-menu__icon");
- editAttrSubmenu.push({
- iconHTML: iconElement.outerHTML,
- label: escapeHtml(cellElement.getAttribute("aria-label").split('<div class="ft__on-surface">')[0]),
- click() {
- rowElement.querySelector(".av__gallery-fields").classList.add("av__gallery-fields--edit");
- rowElement.querySelector('[data-type="av-gallery-edit"]').setAttribute("aria-label", window.siyuan.languages.hideEmptyFields);
- popTextCell(protyle, selectElements);
- }
+ 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,
});
}
});
- }
+ });
menu.addItem({
id: "fields",
icon: "iconAttr",
- label: window.siyuan.languages.fields,
+ label: window.siyuan.languages.editFields,
type: "submenu",
submenu: editAttrSubmenu
});
diff --git a/app/src/protyle/render/av/batchEdit.ts b/app/src/protyle/render/av/batchEdit.ts
new file mode 100644
index 0000000000..53ab66d08e
--- /dev/null
+++ b/app/src/protyle/render/av/batchEdit.ts
@@ -0,0 +1,135 @@
+import {createEmptyAVValue} from "./attributeValue";
+import {popTextCell, renderCell} from "./cell";
+import {getAVData, getAVSelectedItemIDs} from "./virtualScroll";
+import {getFieldsByData} from "./view";
+
+const EDITABLE_FIELD_TYPES: TAVCol[] = [
+ "block",
+ "text",
+ "number",
+ "select",
+ "mSelect",
+ "date",
+ "checkbox",
+ "url",
+ "email",
+ "phone",
+ "mAsset",
+ "relation",
+];
+
+export const getEditableAVFields = (blockElement: HTMLElement) => {
+ const data = getAVData(blockElement);
+ if (!data) {
+ return [];
+ }
+ return getFieldsByData(data).filter((field) => EDITABLE_FIELD_TYPES.includes(field.type));
+};
+
+const getItemCell = (view: IAVView, itemID: string, fieldID: string): IAVCell | undefined => {
+ if (view.groups?.length > 0) {
+ for (const group of view.groups) {
+ const cell = getItemCell(group, itemID, fieldID);
+ if (cell) {
+ return cell;
+ }
+ }
+ return;
+ }
+ const isTable = view.type === "table";
+ const fields = isTable ? (view as IAVTable).columns : (view as IAVGallery).fields;
+ const fieldIndex = fields.findIndex((field) => field.id === fieldID);
+ if (fieldIndex < 0) {
+ return;
+ }
+ if (isTable) {
+ const item = (view as IAVTable).rows.find((currentItem) => currentItem.id === itemID);
+ return item?.cells[fieldIndex];
+ }
+ const item = (view as IAVGallery).cards.find((currentItem) => currentItem.id === itemID);
+ return item?.values[fieldIndex];
+};
+
+const createEditProxy = (options: {
+ data: IAV;
+ field: IAVColumn;
+ itemID: string;
+}) => {
+ const cell = getItemCell(options.data.view, 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);
+ value.id = value.id || cell?.id;
+ value.keyID = options.field.id;
+ value.blockID = options.itemID;
+
+ const cellElement = document.createElement("div");
+ cellElement.className = "custom-attr__avvalue";
+ cellElement.dataset.avId = options.data.id;
+ cellElement.dataset.colId = options.field.id;
+ 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.options = JSON.stringify(options.field.options || []);
+ if (value.id) {
+ cellElement.dataset.id = value.id;
+ }
+ if (value.isDetached) {
+ cellElement.dataset.detached = "true";
+ }
+ cellElement.style.cssText = "position:absolute;inset:0;";
+ cellElement.innerHTML = renderCell(value, 0, options.data.view.showIcon, "table", options.field.options);
+ return cellElement;
+};
+
+export const openAVFieldEditor = (options: {
+ protyle: IProtyle;
+ blockElement: HTMLElement;
+ field: IAVColumn;
+ anchorElement: HTMLElement;
+}) => {
+ const data = getAVData(options.blockElement);
+ const itemIDs = getAVSelectedItemIDs(options.blockElement);
+ if (!data || itemIDs.length === 0) {
+ return;
+ }
+
+ const anchorRect = options.anchorElement.getBoundingClientRect();
+ const proxyElement = document.createElement("div");
+ proxyElement.className = "custom-attr av__batch-edit-proxy";
+ 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({
+ data,
+ field: options.field,
+ itemID,
+ }));
+ cellElements.forEach((cellElement) => proxyElement.append(cellElement));
+ options.blockElement.append(proxyElement);
+
+ let destroyed = false;
+ const destroy = () => {
+ if (destroyed) {
+ return;
+ }
+ destroyed = true;
+ cellElements.forEach((cellElement, index) => {
+ const cell = getItemCell(data.view, itemIDs[index], options.field.id);
+ if (!cell || !cellElement.dataset.cellValue) {
+ return;
+ }
+ const value = JSON.parse(decodeURIComponent(cellElement.dataset.cellValue)) as IAVCellValue;
+ cell.id = value.id || "";
+ cell.value = value;
+ cell.valueType = value.type;
+ });
+ proxyElement.remove();
+ };
+ popTextCell(options.protyle, cellElements, options.field.type, {
+ scrollIntoView: false,
+ data,
+ destroyCallback: destroy,
+ });
+};
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index bf48f41df5..31ecb268a0 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -497,18 +497,23 @@ export const getTypeByCellElement = (cellElement: Element) => {
export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type?: TAVCol, options?: {
scrollIntoView?: boolean;
+ data?: IAV;
+ destroyCallback?: () => void;
}) => {
if (cellElements.length === 0 || (cellElements.length === 1 && !cellElements[0])) {
+ options?.destroyCallback?.();
return;
}
if (!type) {
type = getTypeByCellElement(cellElements[0]);
}
if (type === "updated" || type === "created" || document.querySelector(".av__mask")) {
+ options?.destroyCallback?.();
return;
}
const blockElement = hasClosestBlock(cellElements[0]);
if (!blockElement) {
+ options?.destroyCallback?.();
return;
}
const viewType = blockElement.getAttribute("data-av-type") as TAVView;
@@ -542,28 +547,62 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type
} else {
if (["select", "mSelect"].includes(type)) {
if (blockElement.getAttribute("data-rendering") === "true") {
+ options?.destroyCallback?.();
return;
}
- openMenuPanel({protyle, blockElement, type: "select", cellElements});
+ openMenuPanel({
+ protyle,
+ blockElement,
+ type: "select",
+ cellElements,
+ data: options?.data,
+ destroyCallback: options?.destroyCallback,
+ });
} else if (type === "mAsset") {
- openMenuPanel({protyle, blockElement, type: "asset", cellElements});
+ openMenuPanel({
+ protyle,
+ blockElement,
+ type: "asset",
+ cellElements,
+ data: options?.data,
+ destroyCallback: options?.destroyCallback,
+ });
if (!hasClosestByClassName(cellElements[0], "custom-attr")) {
focusBlock(blockElement);
}
} else if (type === "date") {
- openMenuPanel({protyle, blockElement, type: "date", cellElements});
+ openMenuPanel({
+ protyle,
+ blockElement,
+ type: "date",
+ cellElements,
+ data: options?.data,
+ destroyCallback: options?.destroyCallback,
+ });
} else if (type === "checkbox") {
updateCellValueByInput(protyle, type, blockElement, cellElements);
+ options?.destroyCallback?.();
} else if (type === "relation") {
- openMenuPanel({protyle, blockElement, type: "relation", cellElements});
+ openMenuPanel({
+ protyle,
+ blockElement,
+ type: "relation",
+ cellElements,
+ data: options?.data,
+ destroyCallback: options?.destroyCallback,
+ });
} else if (type === "rollup") {
openMenuPanel({
protyle,
blockElement,
type: "rollup",
cellElements,
- colId: getColId(cellElements[0], viewType)
+ colId: getColId(cellElements[0], viewType),
+ data: options?.data,
+ destroyCallback: options?.destroyCallback,
});
+ } else {
+ options?.destroyCallback?.();
}
if (viewType === "table" && !hasClosestByClassName(cellElements[0], "custom-attr")) {
cellElements[0].classList.add("av__cell--select");
@@ -574,13 +613,28 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type
window.siyuan.menus.menu.remove();
document.body.insertAdjacentHTML("beforeend", `<div class="av__mask" style="z-index: ${++window.siyuan.zIndex}">
${html}
-</div>`);
+ </div>`);
const avMaskElement = document.querySelector(".av__mask");
+ if (options?.destroyCallback) {
+ const parentElement = avMaskElement.parentElement;
+ const observer = new MutationObserver(() => {
+ if (!avMaskElement.isConnected) {
+ observer.disconnect();
+ options.destroyCallback();
+ }
+ });
+ observer.observe(parentElement, {childList: true});
+ }
const inputElement = avMaskElement.querySelector(".b3-text-field") as HTMLInputElement;
if (inputElement) {
if (["text", "email", "phone", "block", "template"].includes(type)) {
inputElement.value = cellElements[0].querySelector(".av__celltext")?.textContent || "";
}
+ if (type !== "template") {
+ inputElement.addEventListener("input", () => {
+ inputElement.dataset.changed = "true";
+ });
+ }
inputElement.select();
inputElement.focus();
callMobileAppShowKeyboard();
@@ -598,7 +652,7 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type
});
});
}
- if (type === "block") {
+ if (type === "block" && !cellElements[0].dataset.avId) {
inputElement.addEventListener("input", (event: InputEvent) => {
if (Constants.BLOCK_HINT_KEYS.includes(inputElement.value.substring(0, 2))) {
protyle.toolbar.range = document.createRange();
@@ -680,7 +734,7 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type
const updateCellValueByInput = (protyle: IProtyle, type: TAVCol, blockElement: HTMLElement, cellElements: HTMLElement[]) => {
const viewType = blockElement.getAttribute("data-av-type") as TAVView;
- if (viewType === "table") {
+ if (viewType === "table" && !cellElements[0].dataset.avId) {
const rowElement = hasClosestByClassName(cellElements[0], "av__row");
if (!rowElement) {
return;
@@ -711,9 +765,18 @@ const updateCellValueByInput = (protyle: IProtyle, type: TAVCol, blockElement: H
blockElement.setAttribute("data-loading", "true");
}
} else {
+ const inputElement = avMaskElement?.querySelector(".b3-text-field") as HTMLInputElement;
+ const unchanged = type !== "checkbox" && inputElement?.dataset.changed !== "true";
+ if (unchanged) {
+ document.querySelectorAll(".av__mask").forEach((item) => {
+ item.remove();
+ });
+ focusBlock(blockElement);
+ return;
+ }
updateCellsValue(protyle, blockElement, type === "checkbox" ? {
checked: cellElements[0].querySelector("use").getAttribute("xlink:href") === "#iconUncheck"
- } : (avMaskElement.querySelector(".b3-text-field") as HTMLInputElement).value, cellElements);
+ } : inputElement.value, cellElements);
}
if (viewType === "table" &&
// 兼容新增行后台隐藏
diff --git a/app/src/protyle/render/av/date.ts b/app/src/protyle/render/av/date.ts
index 48e1dd9f41..fb960285cd 100644
--- a/app/src/protyle/render/av/date.ts
+++ b/app/src/protyle/render/av/date.ts
@@ -1,5 +1,6 @@
import * as dayjs from "dayjs";
import {genCellValueByElement, updateCellsValue} from "./cell";
+import {getFieldsByData} from "./view";
export const getDateHTML = (cellElements: HTMLElement[]) => {
const cellValue = genCellValueByElement("date", cellElements[0]).date;
@@ -57,6 +58,7 @@ export const bindDateEvent = (options: {
cellElements: HTMLElement[]
}) => {
const inputElements: NodeListOf<HTMLInputElement> = options.menuElement.querySelectorAll("input");
+ let dirty = false;
// <input type="date"> 对非法日期会清空 input.value。原生 date input 不触发 beforeinput,用 keydown 区分删空与非法日输入。
const lastNonEmptyValue: string[] = [inputElements[0].value, inputElements[1].value];
@@ -85,6 +87,7 @@ export const bindDateEvent = (options: {
});
});
input.addEventListener("input", () => {
+ dirty = true;
if (input.value) {
invalidEmpty[index] = false;
// 仅当 input.value 是合法完整日期时才更新
@@ -125,6 +128,9 @@ export const bindDateEvent = (options: {
};
const submit = () => {
+ if (!dirty) {
+ return;
+ }
const dateStr1 = buildDateStr(0);
const dateStr2 = buildDateStr(1);
const content1 = getFullYearTime(dateStr1) || 0;
@@ -136,7 +142,7 @@ export const bindDateEvent = (options: {
isNotEmpty2: content2 !== 0,
hasEndDate: inputElements[2].checked,
isNotTime: !inputElements[3].checked,
- }, options.cellElements);
+ }, options.cellElements, getFieldsByData(options.data));
};
inputElements.forEach(item => {
@@ -151,12 +157,15 @@ export const bindDateEvent = (options: {
});
});
inputElements[0].addEventListener("change", () => {
+ dirty = true;
inputElements[0].dataset.value = inputElements[0].value.length > 10 ? inputElements[0].value : inputElements[0].value + " 00:00";
});
inputElements[1].addEventListener("change", () => {
+ dirty = true;
inputElements[1].dataset.value = inputElements[1].value.length > 10 ? inputElements[1].value : inputElements[1].value + " 00:00";
});
inputElements[2].addEventListener("change", () => {
+ dirty = true;
if (inputElements[2].checked) {
if (!inputElements[1].dataset.value) {
const currentDate = Date.now();
@@ -169,6 +178,7 @@ export const bindDateEvent = (options: {
}
});
inputElements[3].addEventListener("change", () => {
+ dirty = true;
inputElements[0].value = "";
inputElements[1].value = "";
if (inputElements[3].checked) {
diff --git a/app/src/protyle/render/av/gallery/render.ts b/app/src/protyle/render/av/gallery/render.ts
index 2a9e981975..f61e48c25f 100644
--- a/app/src/protyle/render/av/gallery/render.ts
+++ b/app/src/protyle/render/av/gallery/render.ts
@@ -7,7 +7,7 @@ import {bindAvSearch} from "../search";
import {processRender} from "../../../util/processCode";
import {getPageSize} from "../groups";
import {renderKanban} from "../kanban/render";
-import {getBodyVirtualData, initVirtualScroll} from "../virtualScroll";
+import {getBodyVirtualData, initVirtualScroll, setAVData} from "../virtualScroll";
import {getRowHTML, stickyRow, updateHeader} from "../row";
import {beginAVRender, finishAVLocate, getAVLocateParams, isCurrentAVRender, prepareAVLocate} from "../locate";
import {getCardStyle} from "./style";
@@ -99,6 +99,7 @@ const renderGroupGallery = (options: ITableOptions) => {
};
export const afterRenderGallery = (options: ITableOptions) => {
+ setAVData(options.blockElement, options.data);
const view = options.data.view as IAVGallery;
options.blockElement.classList.toggle("av--display-empty-fields", view.displayEmptyFields);
if (view.coverFrom === 1 || view.coverFrom === 3) {
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index 985d088f17..c9600427df 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -89,11 +89,13 @@ export const openMenuPanel = (options: {
cellElements?: HTMLElement[], // for select & date & relation & asset
// 复用调用方已构造好的视图数据,跳过内部 fetch,避免与刚提交的事务产生读写时序竞争
data?: IAV,
- cb?: (avPanelElement: Element) => void
+ cb?: (avPanelElement: Element) => void,
+ destroyCallback?: () => void,
}) => {
let avPanelElement = document.querySelector(".av__panel");
if (avPanelElement) {
avPanelElement.remove();
+ options.destroyCallback?.();
return;
}
const avID = options.blockElement.getAttribute("data-av-id");
@@ -183,6 +185,17 @@ export const openMenuPanel = (options: {
<div class="b3-menu${options.type === "filters" ? " av__filter-panel" : ""}${options.type === "relation" ? " av__relation-panel" : ""}" ${["select", "date", "asset", "relation", "rollup"].includes(options.type) ? `style="${["select", "asset", "relation"].includes(options.type) ? "max-height: calc(100vh - 32px);display: flex;flex-direction: column;" : ""}min-width: 200px;${options.type === "relation" ? `width: 760px;max-width: ${isMobile() ? "90vw" : "calc(100vw - 32px)"};` : isMobile() ? "max-width: 90vw;" : "max-width: 50vw;"}"` : ""}>${html}</div>
</div>`);
avPanelElement = document.querySelector(".av__panel");
+ if (options.destroyCallback) {
+ const renderedPanelElement = avPanelElement;
+ const parentElement = renderedPanelElement.parentElement;
+ const observer = new MutationObserver(() => {
+ if (!renderedPanelElement.isConnected) {
+ observer.disconnect();
+ options.destroyCallback();
+ }
+ });
+ observer.observe(parentElement, {childList: true});
+ }
let closeCB: () => void;
const menuElement = avPanelElement.lastElementChild as HTMLElement;
let tabRect = options.blockElement.querySelector(`.av__views, .av__row[data-col-id="${options.colId}"] > .block__logo`)?.getBoundingClientRect();
@@ -1709,7 +1722,7 @@ export const openMenuPanel = (options: {
content2: null,
hasEndDate: false,
isNotTime: colData.date ? !colData.date.fillSpecificTime : true,
- }, options.cellElements);
+ }, options.cellElements, fields);
avPanelElement.remove();
event.preventDefault();
event.stopPropagation();
diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.ts
index dc9864432f..8cc17d9d61 100644
--- a/app/src/protyle/render/av/render.ts
+++ b/app/src/protyle/render/av/render.ts
@@ -19,7 +19,7 @@ import {clearSelect} from "../../util/clear";
import {showMessage} from "../../../dialog/message";
import {renderKanban} from "./kanban/render";
import {bindAvSearch} from "./search";
-import {getBodyVirtualData, initVirtualScroll} from "./virtualScroll";
+import {getBodyVirtualData, initVirtualScroll, setAVData} from "./virtualScroll";
import {beginAVRender, finishAVLocate, getAVLocateParams, isCurrentAVRender, prepareAVLocate, setAVLocateRequest} from "./locate";
import {setGroupFoldedStates, updateGroupFoldedStates} from "./groupFold";
import {updateHotkeyTip} from "../../util/compatibility";
@@ -296,6 +296,7 @@ const renderGroupTable = (options: ITableOptions) => {
};
const afterRenderTable = (options: ITableOptions) => {
+ setAVData(options.blockElement, options.data);
if (options.blockElement.getAttribute("data-need-focus") === "true") {
focusBlock(options.blockElement);
options.blockElement.removeAttribute("data-need-focus");
diff --git a/app/src/protyle/render/av/select.ts b/app/src/protyle/render/av/select.ts
index 5bb0b83159..b1813cf5a0 100644
--- a/app/src/protyle/render/av/select.ts
+++ b/app/src/protyle/render/av/select.ts
@@ -222,11 +222,13 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
} else {
cellElements.forEach((cellElement: HTMLElement, index) => {
const rowID = getFieldIdByCellElement(cellElement, viewType);
- if (viewType === "table" || isCustomAttr) {
- cellElement = cellElements[index] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||
- blockElement.querySelector(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`)) as HTMLElement;
- } else {
- cellElement = cellElements[index] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`)) as HTMLElement;
+ if (!blockElement.contains(cellElement)) {
+ if (viewType === "table" || isCustomAttr) {
+ cellElement = cellElements[index] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||
+ blockElement.querySelector(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`)) as HTMLElement;
+ } else {
+ cellElement = cellElements[index] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`)) as HTMLElement;
+ }
}
cellValues[index].mSelect.find((item) => {
@@ -344,11 +346,13 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
} else {
cellElements.forEach((cellElement: HTMLElement, index) => {
const rowID = getFieldIdByCellElement(cellElement, viewType);
- if (viewType === "table" || isCustomAttr) {
- cellElement = cellElements[index] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||
- blockElement.querySelector(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`)) as HTMLElement;
- } else {
- cellElement = cellElements[index] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`)) as HTMLElement;
+ if (!blockElement.contains(cellElement)) {
+ if (viewType === "table" || isCustomAttr) {
+ cellElement = cellElements[index] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||
+ blockElement.querySelector(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`)) as HTMLElement;
+ } else {
+ cellElement = cellElements[index] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`)) as HTMLElement;
+ }
}
cellValues[index].mSelect.find((item, selectIndex) => {
if (item.content === newName) {
@@ -439,11 +443,13 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
} else {
cellElements.forEach((cellElement: HTMLElement, cellIndex) => {
const rowID = getFieldIdByCellElement(cellElement, viewType);
- if (viewType === "table" || isCustomAttr) {
- cellElement = cellElements[cellIndex] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||
- blockElement.querySelector(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`)) as HTMLElement;
- } else {
- cellElement = cellElements[cellIndex] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`)) as HTMLElement;
+ if (!blockElement.contains(cellElement)) {
+ if (viewType === "table" || isCustomAttr) {
+ cellElement = cellElements[cellIndex] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||
+ blockElement.querySelector(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`)) as HTMLElement;
+ } else {
+ cellElement = cellElements[cellIndex] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`)) as HTMLElement;
+ }
}
cellValues[cellIndex].mSelect.find((item) => {
if (item.content === name) {
diff --git a/app/src/protyle/render/av/virtualScroll.ts b/app/src/protyle/render/av/virtualScroll.ts
index 9e86a2a54b..7c959fcbf4 100644
--- a/app/src/protyle/render/av/virtualScroll.ts
+++ b/app/src/protyle/render/av/virtualScroll.ts
@@ -22,6 +22,7 @@ const dataStore = new Map<string, {
protyle: IProtyle;
data: IAV;
}>();
+const blockDataStore = new WeakMap<HTMLElement, IAV>();
const bodyStates = new WeakMap<HTMLElement, IBodyState>();
const trimPending = new WeakSet<HTMLElement>();
let lastScrollTop: number;
@@ -491,6 +492,50 @@ export const getAVSelectedItems = (blockElement: HTMLElement): { itemID: string,
return Array.from(selectedItems, ([itemID, isDetached]) => ({itemID, isDetached}));
};
+export const getAVData = (blockElement: HTMLElement) => {
+ return blockDataStore.get(blockElement);
+};
+
+export const setAVData = (blockElement: HTMLElement, data: IAV) => {
+ blockDataStore.set(blockElement, data);
+};
+
+export const getAVSelectedItemIDs = (blockElement: HTMLElement) => {
+ const selectedIDs = new Set<string>();
+ blockElement.querySelectorAll(".av__body").forEach((bodyElement: HTMLElement) => {
+ const state = bodyStates.get(bodyElement);
+ if (state?.selectedRowIds) {
+ state.selectedRowIds.forEach((itemID) => selectedIDs.add(itemID));
+ } else {
+ bodyElement.querySelectorAll(".av__row--select:not(.av__row--header), .av__gallery-item--select").forEach((item: HTMLElement) => {
+ if (item.dataset.id) {
+ selectedIDs.add(item.dataset.id);
+ }
+ });
+ }
+ });
+ const data = blockDataStore.get(blockElement);
+ if (!data) {
+ return Array.from(selectedIDs);
+ }
+
+ const orderedIDs: string[] = [];
+ const collectIDs = (view: IAVView) => {
+ if (view.groups?.length > 0) {
+ view.groups.forEach(collectIDs);
+ return;
+ }
+ const items = (view as IAVTable).rows || (view as IAVGallery).cards || [];
+ items.forEach((item: IAVRow | IAVGalleryItem) => {
+ if (selectedIDs.delete(item.id)) {
+ orderedIDs.push(item.id);
+ }
+ });
+ };
+ collectIDs(data.view);
+ return orderedIDs;
+};
+
export const trimAVRows = (blockElement: HTMLElement, elementRect: DOMRect): void => {
if (blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) !== "true" || trimPending.has(blockElement)) {
return;
@@ -516,6 +561,7 @@ export const initVirtualScroll = (options: {
blockElement: HTMLElement,
data: IAV,
}): void => {
+ setAVData(options.blockElement, options.data);
if (options.blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) !== "true") {
return;
}