An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
import {isTableLikeView} from "./viewType";
import {Menu} from "../../../plugin/Menu";
import {transaction} from "../../wysiwyg/transaction";
import {hasClosestBlock, hasClosestByClassName} from "../../util/hasClosest";
import {confirmDialog} from "../../../dialog/confirmDialog";
import {upDownHint} from "../../../util/upDownHint";
import {bindEditEvent, getColId, getEditHTML} from "./col";
import {updateAttrViewCellAnimation} from "./action";
import {isCustomAttr} from "./blockAttr";
import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
import {genCellValueByElement, getTypeByCellElement, updateAttrViewCellInOtherElements} from "./cell";
import dayjs from "dayjs";
import {getFieldsByData} from "./view";
import {getFieldIdByCellElement} from "./row";
import {Constants} from "../../../constants";
import {setSelectMenuPosition} from "./selectPosition";
import {getAVBatchEditMode, getAVBatchSourceValue} from "./batchValue";
import {
AV_MANAGE_CUSTOM_COLORS_TYPE,
applyAVColorPalette,
getAVColorGridHTML,
getAVColorOrder,
getAVColorStyle,
getAVCustomColors,
getAVResolvedColor,
getNextAVOptionColor,
} from "./color";
import {openAVCustomColorDialog} from "./colorDialog";
import {isMobile} from "../../../util/functions";
let cellValues: IAVCellValue[];
const filterSelectHTML = (key: string, options: {
name: string,
color: string,
resolvedColor?: IAVColor,
desc?: string
}[], selected: string[] = []) => {
let html = "";
let hasMatch = false;
if (selected.length === 0) {
document.querySelectorAll(".av__panel .b3-chips .b3-chip").forEach((item: HTMLElement) => {
selected.push(item.dataset.content);
});
}
if (options) {
const currentName = document.querySelector(".av__panel .b3-menu__item--current")?.getAttribute("data-name") || "";
options.forEach(item => {
if (!key ||
(key.toLowerCase().indexOf(item.name.toLowerCase()) > -1 ||
item.name.toLowerCase().indexOf(key.toLowerCase()) > -1)) {
const airaLabel = item.desc ? `${escapeAriaLabel(item.name)}<div class='ft__on-surface'>${escapeAriaLabel(item.desc || "")}</div>` : "";
html += `<button data-type="addColOptionOrCell" class="b3-menu__item${currentName === item.name ? " b3-menu__item--current" : ""}" data-name="${escapeAttr(item.name)}" data-desc="${escapeAttr(item.desc || "")}" data-option-row="true" data-color="${escapeAttr(item.color)}">
<span draggable="true" class="b3-menu__icon b3-menu__icon--custom fn__grab"><svg><use xlink:href="#iconDrag"></use></svg></span>
<div class="fn__flex-1 ariaLabel" data-position="parentW" aria-label="${airaLabel}">
<span class="b3-chip" style="${getAVColorStyle(item)}">
<span class="fn__ellipsis">${escapeHtml(item.name)}</span>
</span>
</div>
<svg class="b3-menu__action" data-type="setColOption"><use xlink:href="#iconEdit"></use></svg>
${selected.includes(item.name) ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg></span>' : ""}
</button>`;
}
if (key === item.name) {
hasMatch = true;
}
});
}
if (!hasMatch && key) {
html = html.replace('class="b3-menu__item b3-menu__item--current"', 'class="b3-menu__item"');
const colorIndex = getNextAVOptionColor(options?.length || 0);
html = `<button data-type="addColOptionOrCell" class="b3-menu__item b3-menu__item--current" data-name="${key}" data-color="${colorIndex}">
<svg class="b3-menu__icon"><use xlink:href="#iconAdd"></use></svg>
<div class="fn__flex-1">
<span class="b3-chip" style="${getAVColorStyle(colorIndex)}">
<span class="fn__ellipsis">${escapeHtml(key)}</span>
</span>
</div>
<span class="b3-menu__accelerator b3-menu__accelerator--hotkey">${window.siyuan.languages.enterKey}</span>
</button>${html}`;
} else if (html.indexOf("b3-menu__item--current") === -1) {
html = html.replace('class="b3-menu__item"', 'class="b3-menu__item b3-menu__item--current"');
}
return html;
};
export const removeCellOption = (protyle: IProtyle, cellElements: HTMLElement[], target: HTMLElement, blockElement: Element) => {
if (!target) {
return;
}
const viewType = blockElement.getAttribute("data-av-type") as TAVView;
const colId = getColId(cellElements[0], viewType);
const doOperations: IOperation[] = [];
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) {
return;
}
if (!blockElement.contains(item)) {
if (isTableLikeView(viewType)) {
item = cellElements[elementIndex] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${item.dataset.colId}"]`) ||
blockElement.querySelector(`.fn__flex-1[data-col-id="${item.dataset.colId}"]`)) as HTMLElement;
} else {
item = cellElements[elementIndex] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`)) as HTMLElement;
}
}
const cellValue: IAVCellValue = batchMode === "replace" ?
cellValues[elementIndex] :
getAVBatchSourceValue(item, cellValues[elementIndex]);
const oldValue = JSON.parse(JSON.stringify(cellValue));
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);
return true;
}
});
mSelectValue = cellValue.mSelect;
} else {
cellValue.mSelect = mSelectValue;
}
cellValues[elementIndex] = cellValue;
doOperations.push({
action: "updateAttrViewCell",
id: cellValue.id,
keyID: colId,
rowID,
avID,
data: cellValue
});
undoOperations.push({
action: "updateAttrViewCell",
id: cellValue.id,
keyID: colId,
rowID,
avID,
data: oldValue
});
if (!item.classList.contains("custom-attr__avvalue")) {
updateAttrViewCellAnimation(item, cellValue);
}
updateAttrViewCellInOtherElements(protyle, avID, rowID, colId, cellValue, item);
});
doOperations.push({
action: "doUpdateUpdated",
id: blockElement.getAttribute("data-node-id"),
data: dayjs().format("YYYYMMDDHHmmss"),
});
transaction(protyle, doOperations, undoOperations);
Array.from(document.querySelectorAll(".av__panel .b3-menu__item")).find((item: HTMLElement) => {
if (item.dataset.name === target.dataset.content) {
item.querySelector(".b3-menu__checked")?.remove();
return true;
}
});
// chips 减少导致菜单高度变化后重新定位(锁底部,顶部自适应),需在移除 target 前获取 menuElement
const menuElement = hasClosestByClassName(target, "b3-menu");
target.remove();
if (menuElement) {
setSelectMenuPosition(menuElement, cellElements[cellElements.length - 1]);
}
};
export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement, blockElement: Element, isCustomAttr: boolean,
cellElements?: HTMLElement[], keepMenuOpen = false) => {
const menuElement = hasClosestByClassName(target, "b3-menu");
const optionElement = target.closest("[data-name]") as HTMLElement;
if (!menuElement || !optionElement) {
return;
}
const blockID = blockElement.getAttribute("data-node-id");
const viewType = blockElement.getAttribute("data-av-type") as TAVView;
const colId = (cellElements && cellElements[0]) ? getColId(cellElements[0], viewType) : menuElement.querySelector(".b3-menu__item").getAttribute("data-col-id");
let name = optionElement.dataset.name;
let desc = optionElement.dataset.desc;
let color = optionElement.dataset.color;
const fields = getFieldsByData(data);
const menu = new Menu(Constants.MENU_AV_COL_OPTION, () => {
if ((name === inputElement.value && desc === descElement.value) || !inputElement.value) {
return;
}
// cell 不判断重名 https://github.com/siyuan-note/siyuan/issues/11484
transaction(protyle, [{
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
blockID,
data: {
newColor: color,
oldName: name,
newName: inputElement.value,
newDesc: descElement.value
},
}, {
action: "doUpdateUpdated",
id: blockID,
data: dayjs().format("YYYYMMDDHHmmss"),
}], [{
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
blockID,
data: {
newColor: color,
oldName: inputElement.value,
newName: name,
newDesc: desc
},
}]);
fields.find(column => {
if (column.id === colId) {
// 重名不进行更新 https://github.com/siyuan-note/siyuan/issues/13554
const sameItem = column.options.find((item) => {
if (item.name === inputElement.value && item.desc === descElement.value) {
return true;
}
});
if (!sameItem) {
column.options.find((item) => {
if (item.name === name) {
item.name = inputElement.value;
item.desc = descElement.value;
return true;
}
});
}
return true;
}
});
const oldScroll = menuElement.querySelector(".b3-menu__items").scrollTop;
const selectedElement = menuElement.querySelector(".b3-chips");
const oldChipsHeight = selectedElement ? selectedElement.clientHeight : 0;
if (!cellElements) {
menuElement.innerHTML = getEditHTML({protyle, data, colId, isCustomAttr});
bindEditEvent({protyle, data, menuElement, isCustomAttr, blockID});
} else {
cellElements.forEach((cellElement: HTMLElement, index) => {
const rowID = getFieldIdByCellElement(cellElement, viewType);
if (!blockElement.contains(cellElement)) {
if (isTableLikeView(viewType) || 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) => {
if (item.content === name) {
item.content = inputElement.value;
return true;
}
});
if (!cellElement.classList.contains("custom-attr__avvalue")) {
updateAttrViewCellAnimation(cellElement, cellValues[index]);
}
updateAttrViewCellInOtherElements(protyle, data.id, rowID, colId, cellValues[index], cellElement);
});
menuElement.innerHTML = getSelectHTML(fields, cellElements, false, blockElement);
bindSelectEvent(protyle, data, menuElement, cellElements, blockElement);
}
if (selectedElement) {
menuElement.querySelector(".b3-menu__items").scrollTop = oldScroll + (menuElement.querySelector(".b3-chips").clientHeight - oldChipsHeight);
// chips 增减导致菜单高度变化后重新定位(锁底部,顶部自适应,避免底部溢出视口)
setSelectMenuPosition(menuElement, cellElements[cellElements.length - 1]);
}
}, keepMenuOpen);
if (menu.isOpen) {
return;
}
applyAVColorPalette(menu.element, getAVCustomColors());
menu.addItem({
iconHTML: "",
type: "empty",
label: `<div class="fn__hr"></div>
<div class="b3-form__icona fn__block">
<input class="b3-text-field b3-form__icona-input" type="text" size="16">
<svg data-position="north" class="b3-form__icona-icon ariaLabel" aria-label="${desc ? escapeAriaLabel(desc) : window.siyuan.languages.addDesc}"><use xlink:href="#iconInfo"></use></svg>
</div>
<div class="fn__none">
<div class="fn__hr"></div>
<textarea rows="1" placeholder="${window.siyuan.languages.addDesc}" class="b3-text-field fn__block" type="text" data-value="${escapeAttr(desc)}">${escapeHtml(desc)}</textarea>
</div>
${isMobile() ? "" : '<div class="fn__hr--small"></div>'}`,
bind(element) {
const inputElement = element.querySelector("input");
element.classList.add("b3-menu__custom", "av__option-custom");
inputElement.addEventListener("keydown", (event: KeyboardEvent) => {
if (event.isComposing) {
return;
}
if (event.key === "Enter") {
menu.close();
}
});
inputElement.value = name;
const descElement = element.querySelector("textarea");
inputElement.nextElementSibling.addEventListener("click", () => {
const descPanelElement = descElement.parentElement;
descPanelElement.classList.toggle("fn__none");
if (!descPanelElement.classList.contains("fn__none")) {
descElement.focus();
}
});
descElement.addEventListener("keydown", (event: KeyboardEvent) => {
if (event.isComposing) {
return;
}
if (event.key === "Enter") {
menu.close();
}
});
descElement.addEventListener("input", () => {
inputElement.nextElementSibling.setAttribute("aria-label", descElement.value ? escapeHtml(descElement.value) : window.siyuan.languages.addDesc);
});
}
});
if (isMobile()) {
menu.addSeparator();
}
menu.addItem({
id: "delete",
label: window.siyuan.languages.delete,
icon: "iconTrashcan",
click() {
confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.confirmDelete, () => {
let colOptions: { name: string, color: string }[] = [];
fields.find(column => {
if (column.id === colId) {
colOptions = column.options;
return true;
}
});
const newName = target.parentElement.dataset.name;
transaction(protyle, [{
action: "removeAttrViewColOption",
id: colId,
avID: data.id,
blockID,
data: newName,
}, {
action: "doUpdateUpdated",
id: blockID,
data: dayjs().format("YYYYMMDDHHmmss"),
}], [{
action: "updateAttrViewColOptions",
id: colId,
avID: data.id,
blockID,
data: colOptions.map(option => ({...option}))
}]);
colOptions.find((item, index) => {
if (item.name === newName) {
colOptions.splice(index, 1);
return true;
}
});
const oldScroll = menuElement.querySelector(".b3-menu__items").scrollTop;
const selectedElement = menuElement.querySelector(".b3-chips");
const oldChipsHeight = selectedElement ? selectedElement.clientHeight : 0;
if (!cellElements) {
menuElement.innerHTML = getEditHTML({protyle, data, colId, isCustomAttr});
bindEditEvent({protyle, data, menuElement, isCustomAttr, blockID});
} else {
cellElements.forEach((cellElement: HTMLElement, index) => {
const rowID = getFieldIdByCellElement(cellElement, viewType);
if (!blockElement.contains(cellElement)) {
if (isTableLikeView(viewType) || 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) {
cellValues[index].mSelect.splice(selectIndex, 1);
return true;
}
});
if (!cellElement.classList.contains("custom-attr__avvalue")) {
updateAttrViewCellAnimation(cellElement, cellValues[index]);
}
updateAttrViewCellInOtherElements(protyle, data.id, rowID, colId,
cellValues[index], cellElement);
});
menuElement.innerHTML = getSelectHTML(fields, cellElements, false, blockElement);
bindSelectEvent(protyle, data, menuElement, cellElements, blockElement);
}
if (selectedElement) {
menuElement.querySelector(".b3-menu__items").scrollTop = oldScroll + (menuElement.querySelector(".b3-chips").clientHeight - oldChipsHeight);
// chips 增减导致菜单高度变化后重新定位(锁底部,顶部自适应,避免底部溢出视口)
setSelectMenuPosition(menuElement, cellElements[cellElements.length - 1]);
}
}, undefined, true);
}
});
menu.addSeparator();
const html = `<div class="fn__flex fn__flex-wrap av__option-colors">${getAVColorGridHTML(
getAVCustomColors(), color, window.siyuan.languages.manageColors, getAVColorOrder())}</div>`;
menu.addItem({
type: "empty",
iconHTML: "",
label: html,
bind(element) {
element.classList.add("b3-menu__custom", "av__option-custom");
element.addEventListener("click", (event) => {
const colorTarget = (event.target as HTMLElement).closest<HTMLElement>("button");
if (colorTarget?.dataset.type === AV_MANAGE_CUSTOM_COLORS_TYPE) {
menu.close();
document.querySelector(".av__panel")?.remove();
openAVCustomColorDialog({
protyle,
data,
blockElement: blockElement as HTMLElement,
});
return;
}
if (colorTarget?.classList.contains("color__square") && !colorTarget.classList.contains("color__square--current")) {
element.querySelector(".color__square--current")?.classList.remove("color__square--current");
colorTarget.classList.add("color__square--current");
const newColor = colorTarget.getAttribute("data-color");
transaction(protyle, [{
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
blockID,
data: {
oldName: name,
newName: inputElement.value,
oldColor: color,
newColor,
newDesc: descElement.value
},
}, {
action: "doUpdateUpdated",
id: blockID,
data: dayjs().format("YYYYMMDDHHmmss"),
}], [{
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
blockID,
data: {
oldName: inputElement.value,
newName: name,
oldColor: newColor,
newColor: color,
newDesc: descElement.value
},
}]);
fields.find(column => {
if (column.id === colId) {
column.options.find((item) => {
if (item.name === name) {
item.name = inputElement.value;
item.color = newColor;
item.resolvedColor = getAVResolvedColor(newColor);
return true;
}
});
return true;
}
});
const oldScroll = menuElement.querySelector(".b3-menu__items").scrollTop;
if (!cellElements) {
menuElement.innerHTML = getEditHTML({protyle, data, colId, isCustomAttr});
bindEditEvent({protyle, data, menuElement, isCustomAttr, blockID});
} else {
cellElements.forEach((cellElement: HTMLElement, cellIndex) => {
const rowID = getFieldIdByCellElement(cellElement, viewType);
if (!blockElement.contains(cellElement)) {
if (isTableLikeView(viewType) || 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) {
item.content = inputElement.value;
item.color = newColor;
item.resolvedColor = getAVResolvedColor(newColor);
return true;
}
});
if (!cellElement.classList.contains("custom-attr__avvalue")) {
updateAttrViewCellAnimation(cellElement, cellValues[cellIndex]);
}
updateAttrViewCellInOtherElements(protyle, data.id, rowID, colId,
cellValues[cellIndex], cellElement);
});
menuElement.innerHTML = getSelectHTML(fields, cellElements, false, blockElement);
bindSelectEvent(protyle, data, menuElement, cellElements, blockElement);
}
menuElement.querySelector(".b3-menu__items").scrollTop = oldScroll;
// chips 增减导致菜单高度变化后重新定位(锁底部,顶部自适应,避免底部溢出视口)
setSelectMenuPosition(menuElement, cellElements[cellElements.length - 1]);
name = inputElement.value;
desc = descElement.value;
color = newColor;
}
});
}
});
const rect = target.getBoundingClientRect();
menu.open({
x: rect.right,
y: rect.bottom,
w: rect.width,
h: rect.height,
});
const inputElement = menu.element.querySelector("input");
// 移动端由用户点击输入框进入编辑,避免与菜单打开时的键盘收起流程冲突。
if (!isMobile()) {
inputElement.select();
}
const descElement = menu.element.querySelector("textarea");
};
export const bindSelectEvent = (protyle: IProtyle, data: IAV, menuElement: HTMLElement, cellElements: HTMLElement[], blockElement: Element) => {
const inputElement = menuElement.querySelector("input");
// 在选项按钮获得焦点前记录搜索状态,重建多选面板时仅恢复用户主动进入的输入。
menuElement.onpointerdown = () => {
menuElement.dataset.restoreSearchFocus = String(document.activeElement === inputElement);
};
const colId = getColId(cellElements[0], blockElement.getAttribute("data-av-type") as TAVView);
let colData: IAVColumn;
getFieldsByData(data).find((item: IAVColumn) => {
if (item.id === colId) {
colData = item;
return;
}
});
if (!colData.options) {
colData.options = [];
}
const listElement = menuElement.lastElementChild.lastElementChild as HTMLElement;
inputElement.addEventListener("input", (event: InputEvent) => {
if (event.isComposing) {
return;
}
listElement.innerHTML = filterSelectHTML(inputElement.value, colData.options);
});
inputElement.addEventListener("compositionend", () => {
listElement.innerHTML = filterSelectHTML(inputElement.value, colData.options);
});
inputElement.addEventListener("keydown", (event: KeyboardEvent) => {
if (event.isComposing) {
return;
}
let currentElement = upDownHint(listElement, event, "b3-menu__item--current", listElement.firstElementChild);
if (event.key === "Enter") {
if (!currentElement) {
currentElement = menuElement.querySelector(".b3-menu__item--current");
}
if (currentElement.querySelector(".b3-menu__checked")) {
removeCellOption(protyle, cellElements, menuElement.querySelector(`.b3-chips .b3-chip[data-content="${escapeAttr(currentElement.dataset.name)}"]`), blockElement);
} else {
addColOptionOrCell(protyle, data, cellElements, currentElement, menuElement, blockElement);
}
} else if (event.key === "Backspace" && inputElement.value === "") {
removeCellOption(protyle, cellElements, inputElement.previousElementSibling as HTMLElement, blockElement);
}
});
};
export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: HTMLElement[], currentElement: HTMLElement, menuElement: HTMLElement, blockElement: Element) => {
const inputElement = menuElement.querySelector("input");
const restoreSearchFocus = !isMobile() || document.activeElement === inputElement ||
menuElement.dataset.restoreSearchFocus === "true";
let hasSelected = false;
Array.from(menuElement.querySelectorAll(".b3-chips .b3-chip")).find((item: HTMLElement) => {
if (item.dataset.content === currentElement.dataset.name) {
hasSelected = true;
return true;
}
});
if (hasSelected) {
if (restoreSearchFocus) {
inputElement.focus();
}
return;
}
const nodeElement = hasClosestBlock(cellElements[0]);
if (!nodeElement) {
cellElements.forEach((item, index) => {
const rowID = getFieldIdByCellElement(item, data.viewType);
if (isTableLikeView(data.viewType) || isCustomAttr(item)) {
cellElements[index] = (blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${item.dataset.colId}"]`) ||
blockElement.querySelector(`.fn__flex-1[data-col-id="${item.dataset.colId}"]`)) as HTMLElement;
} else {
cellElements[index] = (blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`)) as HTMLElement;
}
});
}
const colId = getColId(cellElements[0], blockElement.getAttribute("data-av-type") as TAVView);
let colData: IAVColumn;
const fields = getFieldsByData(data);
fields.find((item: IAVColumn) => {
if (item.id === colId) {
colData = item;
if (!colData.options) {
colData.options = [];
}
return;
}
});
const cellDoOperations: IOperation[] = [];
const cellUndoOperations: IOperation[] = [];
const resolvedColor = colData.options.find(option => option.name === currentElement.dataset.name)?.resolvedColor ||
getAVResolvedColor(currentElement.dataset.color);
let mSelectValue: IAVCellSelectValue[];
const batchMode = getAVBatchEditMode(cellElements[0]);
cellElements.forEach((item, index) => {
const rowID = getFieldIdByCellElement(item, data.viewType);
if (!rowID) {
return;
}
const cellValue: IAVCellValue = batchMode === "replace" ?
cellValues[index] :
getAVBatchSourceValue(item, cellValues[index]);
const oldValue = JSON.parse(JSON.stringify(cellValue));
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,
resolvedColor,
});
}
} else if (index === 0) {
if (colData.type === "mSelect") {
let hasOption = false;
cellValue.mSelect.find((item) => {
if (item.content === currentElement.dataset.name) {
hasOption = true;
return true;
}
});
if (!hasOption) {
cellValue.mSelect.push({
color: currentElement.dataset.color,
content: currentElement.dataset.name,
resolvedColor,
});
}
} else {
cellValue.mSelect = [{
color: currentElement.dataset.color,
content: currentElement.dataset.name,
resolvedColor,
}];
}
mSelectValue = cellValue.mSelect;
} else {
cellValue.mSelect = mSelectValue;
}
cellValues[index] = cellValue;
cellDoOperations.push({
action: "updateAttrViewCell",
id: cellValue.id,
keyID: colId,
rowID,
avID: data.id,
data: cellValue
});
cellUndoOperations.push({
action: "updateAttrViewCell",
id: cellValue.id,
keyID: colId,
rowID,
avID: data.id,
data: oldValue
});
if (!item.classList.contains("custom-attr__avvalue")) {
updateAttrViewCellAnimation(item, cellValue);
}
updateAttrViewCellInOtherElements(protyle, data.id, rowID, colId, cellValue, item);
});
if (currentElement.querySelector(".b3-menu__accelerator")) {
colData.options.push({
color: currentElement.dataset.color,
name: currentElement.dataset.name
});
cellDoOperations.splice(0, 0, {
action: "updateAttrViewColOptions",
id: colId,
avID: data.id,
data: colData.options
});
cellDoOperations.push({
action: "doUpdateUpdated",
id: blockElement.getAttribute("data-node-id"),
data: dayjs().format("YYYYMMDDHHmmss"),
});
transaction(protyle, cellDoOperations, [{
action: "removeAttrViewColOption",
id: colId,
avID: data.id,
data: currentElement.dataset.name,
}]);
} else {
cellDoOperations.push({
action: "doUpdateUpdated",
id: blockElement.getAttribute("data-node-id"),
data: dayjs().format("YYYYMMDDHHmmss"),
});
transaction(protyle, cellDoOperations, cellUndoOperations);
}
if (colData.type === "select") {
if (blockElement.classList.contains("av")) {
blockElement.setAttribute("data-rendering", "true");
}
menuElement.parentElement.dispatchEvent(new CustomEvent("click", {detail: "close"}));
} else {
const oldScroll = menuElement.querySelector(".b3-menu__items").scrollTop;
const oldChipsHeight = menuElement.querySelector(".b3-chips").clientHeight;
menuElement.innerHTML = getSelectHTML(fields, cellElements, false, blockElement);
bindSelectEvent(protyle, data, menuElement, cellElements, blockElement);
if (restoreSearchFocus) {
menuElement.querySelector("input").focus();
}
menuElement.querySelector(".b3-menu__items").scrollTop = oldScroll + (menuElement.querySelector(".b3-chips").clientHeight - oldChipsHeight);
// chips 增减导致菜单高度变化后重新定位(锁底部,顶部自适应,避免底部溢出视口)
setSelectMenuPosition(menuElement, cellElements[cellElements.length - 1]);
}
};
export const getSelectHTML = (fields: IAVColumn[], cellElements: HTMLElement[], init = false, blockElement: Element) => {
if (init) {
// 快速选中后如果 render 了再使用 genCellValueByElement 获取的元素和当前选中的不一致, https://github.com/siyuan-note/siyuan/issues/11268
cellValues = [];
const isCustomAttr = cellElements[0].classList.contains("custom-attr__avvalue");
cellElements.forEach(item => {
cellValues.push(genCellValueByElement(isCustomAttr ? item.dataset.type as TAVCol : getTypeByCellElement(item), item));
});
}
const colId = getColId(cellElements[0], blockElement.getAttribute("data-av-type") as TAVView);
const colData = fields.find(item => {
if (item.id === colId) {
return item;
}
});
cellValues.forEach(value => {
value.mSelect?.forEach(item => {
item.resolvedColor = colData.options?.find(option => option.name === item.content)?.resolvedColor;
});
});
let selectedHTML = "";
const selected: string[] = [];
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 ? option.color : item.color)}" data-value-color="${escapeAttr(item.color)}" style="white-space: nowrap;max-width:100%;${getAVColorStyle({
color: option ? option.color : item.color,
resolvedColor: option ? option.resolvedColor : item.resolvedColor,
})}"><span class="fn__ellipsis">${escapeHtml(item.content)}</span><svg class="b3-chip__close" data-type="removeCellOption"><use xlink:href="#iconClose"></use></svg></div>`;
});
return `<div class="b3-menu__items" style="display: flex;flex-direction: column;flex: 1;">
<div class="b3-chips" style="max-width: 50vw">
${selectedHTML}
<input spellcheck="false" placeholder="${escapeAttr(window.siyuan.languages.search)} / ${escapeAttr(window.siyuan.languages.addAttr)}" aria-label="${escapeAttr(window.siyuan.languages.search)} / ${escapeAttr(window.siyuan.languages.addAttr)}">
</div>
<div class="av__select-list" style="flex: 1;overflow: auto;">${filterSelectHTML("", colData.options, selected)}</div>
</div>`;
};
export const mergeAddOption = (column: IAVColumn, cellValue: IAVCellValue, avID: string) => {
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
cellValue.mSelect.forEach((item: IAVCellSelectValue) => {
if (!column.options) {
column.options = [];
}
const needAdd = column.options.find((option) => {
if (option.name === item.content) {
item.color = option.color;
item.resolvedColor = option.resolvedColor;
return true;
}
});
if (!needAdd) {
const newColor = getNextAVOptionColor(column.options?.length || 0);
column.options.push({
name: item.content,
color: newColor
});
item.color = newColor;
doOperations.push({
action: "updateAttrViewColOptions",
id: column.id,
avID,
data: column.options
});
undoOperations.push({
action: "removeAttrViewColOption",
id: column.id,
avID,
data: item.content,
});
}
});
return {
doOperations,
undoOperations
};
};