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 {isAVTimestampType} from "./capabilities";
import {getConditionalItemStyle, getConditionalCellStyle} from "./conditionalColor";
import {isTableLikeView} from "./viewType";
import {updateFrozenColumns} from "./frozenColumns";
import {hasClosestBlock, hasClosestByClassName, hasTopClosestByAttribute} from "../../util/hasClosest";
import {focusBlock} from "../../util/selection";
import {Menu} from "../../../plugin/Menu";
import {openViewSettingMenu} from "./viewSettingMenu";
import {transaction} from "../../wysiwyg/transaction";
import {
cellValueIsEmpty,
genCellValue,
getTypeByCellElement,
renderCell,
renderCellAttr
} from "./cell";
import {fetchPost} from "../../../util/fetch";
import dayjs from "dayjs";
import {Constants} from "../../../constants";
import {insertGalleryItemAnimation} from "./gallery/item";
import {clearSelect} from "../../util/clear";
import {isCustomAttr} from "./blockAttr";
import {getColIconByType, getColNameByType} from "./col";
import {unicode2Emoji} from "../../../emoji";
import {escapeAriaLabel, escapeAttr, escapeHtmlTextAndAttr} from "../../../util/escape";
import {getCompressURL} from "../../../util/image";
import {
getAVSelectStat,
getAVSelectedItemInfos,
getAvBodyData,
IAVItemInfo,
resetAVRowSelect,
updateAVRowSelect
} from "./virtualScroll";
import {getCardCoverHTML, getCardCoverSource} from "./cover";
import {getCardFieldsClass} from "./gallery/cardLayout";
import {getAVFilteredTipContext} from "./filteredTip";
import {clearAVItemSelectionState} from "./selectionState";
import {renderAVRichTextElements} from "./richText";
const getGalleryActionsHTML = (data: IAVGallery | IAVKanban, row: IAVGalleryItem, primaryHidden = false) => {
const canPosition = Boolean(row.coverURL && !row.coverURL.startsWith("background") && getCardCoverSource(data));
const positionHTML = canPosition ? `<span class="protyle-icon protyle-icon--first ariaLabel${data.fitImage ? " fn__none" : ""}" data-position="4north" aria-label="${window.siyuan.languages.dragPosition}" data-type="av-cover-position"><svg><use xlink:href="#iconMove"></use></svg></span>` : "";
const editFirst = !canPosition || data.fitImage;
const openFirst = editFirst && data.displayEmptyFields;
const openHTML = primaryHidden ? `<span class="protyle-icon${openFirst ? " protyle-icon--first" : ""} ariaLabel" data-position="4north" aria-label="${window.siyuan.languages.openBy}" data-type="av-gallery-open"><svg><use xlink:href="#iconOpen"></use></svg></span>` : "";
const moreFirst = editFirst && data.displayEmptyFields && !primaryHidden;
return `<div class="av__gallery-actions">
${positionHTML}
<span class="protyle-icon${editFirst ? " protyle-icon--first" : ""} ariaLabel${data.displayEmptyFields ? " fn__none" : ""}" data-position="4north" aria-label="${window.siyuan.languages.displayEmptyFields}" data-type="av-gallery-edit"><svg><use xlink:href="#iconEdit"></use></svg></span>
${openHTML}
<span class="protyle-icon${moreFirst ? " protyle-icon--first" : ""} protyle-icon--last ariaLabel" data-position="4north" aria-label="${window.siyuan.languages.more}" data-type="av-gallery-more"><svg><use xlink:href="#iconMore"></use></svg></span>
</div>`;
};
export const getRowHTML = (options: {
data: IAVView
row: IAVRow | IAVGalleryItem
rowIndex: number
type: TAVView
pinIndex?: number
}) => {
let html = "";
if (options.type === "gallery") {
const galleryRow = options.row as IAVGalleryItem;
const galleryData = options.data as IAVGallery;
const primaryHidden = galleryData.fields.find(field => field.type === "block")?.hidden === true;
const hasVisibleFields = galleryData.fields.some(field => !field.hidden);
const emptyClass = !hasVisibleFields && galleryData.coverFrom === 0 ? " av__gallery-item--empty" : "";
html += `<div data-id="${galleryRow.id}" data-index="${options.rowIndex}" draggable="true" class="av__gallery-item${emptyClass}" style="${getConditionalItemStyle(galleryRow)}">`;
if (galleryData.coverFrom !== 0) {
const coverClass = "av__gallery-cover av__gallery-cover--" + galleryData.cardAspectRatio;
if (galleryRow.coverURL) {
html += getCardCoverHTML(coverClass, galleryRow.coverURL, getCompressURL(galleryRow.coverURL),
galleryData.fitImage, getCardCoverSource(galleryData), galleryRow.coverPosition);
} else if (galleryRow.coverContent) {
html += `<div class="${coverClass}"><div class="av__gallery-content" inert>${galleryRow.coverContent}</div><div></div></div>`;
} else {
html += `<div class="${coverClass}"></div>`;
}
}
html += `<div class="${getCardFieldsClass(galleryData.cardLayout, hasVisibleFields)}">`;
galleryRow.values.forEach((cell, fieldsIndex) => {
if (galleryData.fields[fieldsIndex].hidden) {
return;
}
let checkClass = "";
if (cell.valueType === "checkbox") {
checkClass = cell.value?.checkbox?.checked ? " av__cell-check" : " av__cell-uncheck";
}
const isEmpty = cellValueIsEmpty(cell.value, true, galleryData.fields[fieldsIndex].renderTemplate);
// NOTE: innerHTML 中不能换行否则 https://github.com/siyuan-note/siyuan/issues/15132
let ariaLabel = escapeAttr(galleryData.fields[fieldsIndex].name) || getColNameByType(galleryData.fields[fieldsIndex].type);
if (galleryData.fields[fieldsIndex].desc) {
ariaLabel += escapeAttr(`<div class="ft__on-surface">${galleryData.fields[fieldsIndex].desc}</div>`);
}
if (cell.valueType === "checkbox" && !galleryData.displayFieldName) {
cell.value.checkbox.content = galleryData.fields[fieldsIndex].name || getColNameByType(galleryData.fields[fieldsIndex].type);
}
const fullRowClass = galleryData.fields[fieldsIndex].type === "block" ||
galleryData.fields[fieldsIndex].fullRow || galleryData.displayFieldName ?
" av__gallery-field--full-row" : "";
const cellHTML = `<div class="av__cell${checkClass}${galleryData.displayFieldName ? "" : " ariaLabel"}"
data-wrap="${galleryData.fields[fieldsIndex].wrap}"
aria-label="${ariaLabel}"
data-position="5west"
data-id="${cell.id}"
data-field-id="${galleryData.fields[fieldsIndex].id}"
data-dtype="${cell.valueType}"
data-date-format="${galleryData.fields[fieldsIndex].dateFormat || ""}"
${galleryData.fields[fieldsIndex].renderTemplate?.trim() ? 'data-render-template="true"' : ""}
${cell.value?.isDetached ? ' data-detached="true"' : ""}
style="${cell.bgColor ? `background-color:${cell.bgColor};` : ""}
${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, galleryData.showIcon, "gallery", galleryData.fields[fieldsIndex].options, galleryData.fields[fieldsIndex].dateFormat, galleryData.fields[fieldsIndex].renderTemplate)}</div>`;
if (galleryData.displayFieldName) {
html += `<div class="av__gallery-field av__gallery-field--name${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-name">
${galleryData.fields[fieldsIndex].icon ? unicode2Emoji(galleryData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(galleryData.fields[fieldsIndex].type)}"></use></svg>`}${escapeHtmlTextAndAttr(galleryData.fields[fieldsIndex].name)}
${galleryData.fields[fieldsIndex].desc ? `<svg aria-label="${escapeAriaLabel(galleryData.fields[fieldsIndex].desc)}" data-position="north" class="ariaLabel"><use xlink:href="#iconInfo"></use></svg>` : ""}
</div>
${cellHTML}
</div>`;
} else {
html += `<div class="av__gallery-field${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-tip">
${galleryData.fields[fieldsIndex].icon ? unicode2Emoji(galleryData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(galleryData.fields[fieldsIndex].type)}"></use></svg>`}${window.siyuan.languages.edit} ${escapeHtmlTextAndAttr(galleryData.fields[fieldsIndex].name)}
</div>
${cellHTML}
</div>`;
}
});
html += `</div>
${getGalleryActionsHTML(galleryData, galleryRow, primaryHidden)}
</div>`;
return html;
}
if (options.type === "kanban") {
const kanbanRow = options.row as IAVGalleryItem;
const kanbanData = options.data as IAVKanban;
html += `<div data-id="${kanbanRow.id}" data-index="${options.rowIndex}" draggable="true" class="av__gallery-item" style="${getConditionalItemStyle(kanbanRow)}">`;
if (kanbanData.coverFrom !== 0) {
const coverClass = "av__gallery-cover av__gallery-cover--" + kanbanData.cardAspectRatio;
if (kanbanRow.coverURL) {
html += getCardCoverHTML(coverClass, kanbanRow.coverURL, getCompressURL(kanbanRow.coverURL),
kanbanData.fitImage, getCardCoverSource(kanbanData), kanbanRow.coverPosition);
} else if (kanbanRow.coverContent.trim()) {
html += `<div class="${coverClass}"><div class="av__gallery-content" inert>${kanbanRow.coverContent}</div><div></div></div>`;
}
}
html += `<div class="${getCardFieldsClass(kanbanData.cardLayout)}">`;
kanbanRow.values.forEach((cell, fieldsIndex) => {
if (kanbanData.fields[fieldsIndex].hidden) {
return;
}
let checkClass = "";
if (cell.valueType === "checkbox") {
checkClass = cell.value?.checkbox?.checked ? " av__cell-check" : " av__cell-uncheck";
}
const isEmpty = cellValueIsEmpty(cell.value, true, kanbanData.fields[fieldsIndex].renderTemplate);
// NOTE: innerHTML 中不能换行否则 https://github.com/siyuan-note/siyuan/issues/15132
let ariaLabel = escapeAttr(kanbanData.fields[fieldsIndex].name) || getColNameByType(kanbanData.fields[fieldsIndex].type);
if (kanbanData.fields[fieldsIndex].desc) {
ariaLabel += escapeAttr(`<div class="ft__on-surface">${kanbanData.fields[fieldsIndex].desc}</div>`);
}
if (cell.valueType === "checkbox" && !kanbanData.displayFieldName) {
cell.value.checkbox.content = kanbanData.fields[fieldsIndex].name || getColNameByType(kanbanData.fields[fieldsIndex].type);
}
const fullRowClass = kanbanData.fields[fieldsIndex].type === "block" ||
kanbanData.fields[fieldsIndex].fullRow || kanbanData.displayFieldName ?
" av__gallery-field--full-row" : "";
const cellHTML = `<div class="av__cell${checkClass}${kanbanData.displayFieldName ? "" : " ariaLabel"}"
data-wrap="${kanbanData.fields[fieldsIndex].wrap}"
aria-label="${ariaLabel}"
data-position="5west"
data-id="${cell.id}"
data-field-id="${kanbanData.fields[fieldsIndex].id}"
data-dtype="${cell.valueType}"
data-date-format="${kanbanData.fields[fieldsIndex].dateFormat || ""}"
${kanbanData.fields[fieldsIndex].renderTemplate?.trim() ? 'data-render-template="true"' : ""}
${cell.value?.isDetached ? ' data-detached="true"' : ""}
style="${cell.bgColor ? `background-color:${cell.bgColor};` : ""}
${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, kanbanData.showIcon, "kanban", kanbanData.fields[fieldsIndex].options, kanbanData.fields[fieldsIndex].dateFormat, kanbanData.fields[fieldsIndex].renderTemplate)}</div>`;
if (kanbanData.displayFieldName) {
html += `<div class="av__gallery-field av__gallery-field--name${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-name">
${kanbanData.fields[fieldsIndex].icon ? unicode2Emoji(kanbanData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(kanbanData.fields[fieldsIndex].type)}"></use></svg>`}${escapeHtmlTextAndAttr(kanbanData.fields[fieldsIndex].name)}
${kanbanData.fields[fieldsIndex].desc ? `<svg aria-label="${escapeAriaLabel(kanbanData.fields[fieldsIndex].desc)}" data-position="north" class="ariaLabel"><use xlink:href="#iconInfo"></use></svg>` : ""}
</div>
${cellHTML}
</div>`;
} else {
html += `<div class="av__gallery-field${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-tip">
${kanbanData.fields[fieldsIndex].icon ? unicode2Emoji(kanbanData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(kanbanData.fields[fieldsIndex].type)}"></use></svg>`}${window.siyuan.languages.edit} ${escapeHtmlTextAndAttr(kanbanData.fields[fieldsIndex].name)}
</div>
${cellHTML}
</div>`;
}
});
html += `</div>
${getGalleryActionsHTML(kanbanData, kanbanRow)}
</div>`;
return html;
}
const tableRow = options.row as IAVRow;
const tableData = options.data as IAVTable;
const isList = options.type === "list";
const pinIndex = isList ? -1 : options.pinIndex;
html = `<div class="av__row${tableRow.conditionalColors ? " av__row--conditional" : ""}" data-index="${options.rowIndex}" data-id="${tableRow.id}" style="${getConditionalItemStyle(tableRow)}">`;
if (pinIndex > -1) {
html += `<div class="av__colsticky av__colsticky--freeze"><div class="av__firstcol"><svg><use xlink:href="#iconUncheck"></use></svg>${getFreezeDragHTML()}</div>`;
} else {
html += `<div class="av__colsticky"><div class="av__firstcol"><svg><use xlink:href="#iconUncheck"></use></svg>${isList ? "" : getFreezeDragHTML()}</div></div>`;
}
tableRow.cells.forEach((cell, index) => {
const column = tableData.columns[index];
if (column.hidden) {
return;
}
// https://github.com/siyuan-note/siyuan/issues/10262
let checkClass = "";
if (cell.valueType === "checkbox") {
checkClass = cell.value?.checkbox?.checked ? " av__cell-check" : " av__cell-uncheck";
}
html += `<div class="av__cell${checkClass}${isList ? " ariaLabel" : ""}" data-id="${cell.id}" data-col-id="${column.id}" ${isList ? `aria-label="${escapeAriaLabel(column.name)}" data-position="north"` : ""}
data-wrap="${column.wrap}"
data-dtype="${column.type}"
data-date-format="${column.dateFormat || ""}"
${column.renderTemplate?.trim() ? 'data-render-template="true"' : ""}
data-align="${column.align || ""}"
${cell.value?.isDetached ? ' data-detached="true"' : ""}
style="${getConditionalCellStyle(tableRow, column.id)}${isList ? "" : `width: ${escapeAttr(column.width) || "200px"};`}
${cell.bgColor && !tableRow.conditionalColors?.background && !tableRow.conditionalColors?.properties?.[column.id] ? `background-color:${cell.bgColor};` : ""}
${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, tableData.showIcon, "table", column.options, column.dateFormat, column.renderTemplate)}</div>`;
if (pinIndex === index) {
html += "</div>";
}
});
return html + "<div></div></div>";
};
const getFreezeDragHTML = () => `<div class="av__freeze-drag ariaLabel" data-position="east" aria-label="${escapeAttr(window.siyuan.languages.freezeDrag)}"></div>`;
export const getFieldIdByCellElement = (cellElement: Element, viewType: TAVView): string => {
if (isCustomAttr(cellElement)) {
return cellElement.getAttribute("data-row-id");
}
return (hasClosestByClassName(cellElement, isTableLikeView(viewType) ? "av__row" : "av__gallery-item") as HTMLElement).dataset.id;
};
export const selectRow = (checkElement: Element, type: "toggle" | "select" | "unselect" | "unselectAll") => {
const rowElement = hasClosestByClassName(checkElement, "av__row");
if (!rowElement) {
return;
}
const useElement = checkElement.querySelector("use");
const bodyElement = hasClosestByClassName(rowElement, "av__body") as HTMLElement;
const blockElement = hasClosestByClassName(rowElement, "av") as HTMLElement;
if (blockElement && (type === "select" ||
(type === "toggle" && useElement.getAttribute("xlink:href") !== "#iconCheck"))) {
clearSelect(["cell"], blockElement);
}
if (rowElement.classList.contains("av__row--header") || type === "unselectAll") {
if (blockElement) {
clearAVItemSelectionState(blockElement);
}
if ("#iconCheck" === useElement.getAttribute("xlink:href") || type === "unselectAll") {
rowElement.parentElement.querySelectorAll(".av__firstcol").forEach(item => {
item.querySelector("use").setAttribute("xlink:href", "#iconUncheck");
const rowItemElement = hasClosestByClassName(item, "av__row");
if (rowItemElement) {
rowItemElement.classList.remove("av__row--select");
}
});
// 全不选:清空选中快照,避免被 trim 掉的行回填后仍带选中态
if (bodyElement) {
resetAVRowSelect(bodyElement, []);
}
} else {
// 全选:范围以当前已加载的分页行(dataStore 的 view.rows)为准,而非仅 DOM 内已渲染的行。
// 虚拟滚动下被 trim 掉的行 ID 一并存入快照,回填时由 restoreSelect 恢复高亮。
rowElement.parentElement.querySelectorAll(".av__firstcol").forEach(item => {
item.querySelector("use").setAttribute("xlink:href", "#iconCheck");
const rowItemElement = hasClosestByClassName(item, "av__row");
if (rowItemElement) {
rowItemElement.classList.add("av__row--select");
}
});
const allRowIds: string[] = [];
if (bodyElement) {
const view = getAvBodyData(bodyElement) as IAVTable;
if (view?.rows) {
view.rows.forEach((row: IAVRow) => {
if (row.id) {
allRowIds.push(row.id);
}
});
}
resetAVRowSelect(bodyElement, allRowIds);
}
}
} else {
const rowId = rowElement.getAttribute("data-id");
if (type === "select" || (useElement.getAttribute("xlink:href") === "#iconUncheck" && type === "toggle")) {
rowElement.classList.add("av__row--select");
useElement.setAttribute("xlink:href", "#iconCheck");
if (bodyElement && rowId) {
updateAVRowSelect(bodyElement, rowId, true);
}
} else if (type === "unselect" || (useElement.getAttribute("xlink:href") === "#iconCheck" && type === "toggle")) {
rowElement.classList.remove("av__row--select");
useElement.setAttribute("xlink:href", "#iconUncheck");
if (bodyElement && rowId) {
updateAVRowSelect(bodyElement, rowId, false);
}
}
}
focusBlock(hasClosestBlock(rowElement) as HTMLElement);
updateHeader(rowElement);
};
export const updateHeader = (rowElement: HTMLElement) => {
const blockElement = hasClosestBlock(rowElement);
if (!blockElement) {
return;
}
updateAVSelectionStatus(blockElement as HTMLElement);
};
export const updateAVSelectionStatus = (blockElement: HTMLElement) => {
const avType = blockElement.getAttribute("data-av-type") as TAVView;
let selectCount = 0;
if (isTableLikeView(avType)) {
blockElement.querySelectorAll(".av__body").forEach((bodyElement: HTMLElement) => {
if (hasClosestByClassName(bodyElement, "av") !== blockElement) {
return;
}
// 虚拟滚动下 DOM 内只有渲染窗口的行,直接计数会低估;优先用选中快照与已加载行总数。
const stat = getAVSelectStat(bodyElement);
const bodySelectCount = stat ? stat.selectCount :
bodyElement.querySelectorAll(".av__row--select[data-id]").length;
const count = stat ? stat.loadedCount : bodyElement.querySelectorAll(".av__row[data-id]").length;
selectCount += bodySelectCount;
const headElement = bodyElement.firstElementChild as HTMLElement;
const headUseElement = headElement?.querySelector("use");
if (!headElement || !headUseElement) {
return;
}
if (count === bodySelectCount && count !== 0) {
headElement.classList.add("av__row--select");
headUseElement.setAttribute("xlink:href", "#iconCheck");
} else if (bodySelectCount === 0) {
headElement.classList.remove("av__row--select");
headUseElement.setAttribute("xlink:href", "#iconUncheck");
} else {
headElement.classList.add("av__row--select");
headUseElement.setAttribute("xlink:href", "#iconIndeterminateCheck");
}
});
} else {
// 卡片/看板视图按分组(.av__body)聚合选中数,看板与分组卡片视图存在多个 body。
blockElement.querySelectorAll(".av__body").forEach((bodyItem: HTMLElement) => {
if (hasClosestByClassName(bodyItem, "av") !== blockElement) {
return;
}
const stat = getAVSelectStat(bodyItem);
selectCount += stat ? stat.selectCount : bodyItem.querySelectorAll(".av__gallery-item--select").length;
});
}
const viewsElement = Array.from(blockElement.querySelectorAll<HTMLElement>(".av__views")).find(
item => hasClosestByClassName(item, "av") === blockElement
);
const countElement = viewsElement?.querySelector<HTMLElement>(".av__selection-count");
if (!viewsElement || !countElement) {
return;
}
if (selectCount === 0) {
viewsElement.classList.remove("av__views--selection");
countElement.textContent = "";
return;
}
viewsElement.classList.add("av__views--selection");
countElement.textContent = `${selectCount} ${window.siyuan.languages.selected}`;
};
export const setPage = (blockElement: Element) => {
const avType = blockElement.getAttribute("data-av-type") as TAVView;
blockElement.querySelectorAll(".av__body").forEach((item: HTMLElement) => {
const pageSize = item.dataset.pageSize;
if (pageSize) {
const currentCount = item.querySelectorAll(isTableLikeView(avType) ? ".av__row:not(.av__row--header)" : ".av__gallery-item").length;
if (parseInt(pageSize) < currentCount) {
item.dataset.pageSize = currentCount.toString();
}
}
});
};
/**
* 前端插入一假行
* @param options.protyle
* @param options.blockElement
* @param options.srcIDs
* @param options.previousId
* @param options.avId 存在为新增否则为拖拽插入
*/
export const insertAttrViewBlockAnimation = (options: {
protyle: IProtyle,
blockElement: Element,
srcIDs: string[], // node id
previousId: string,
groupID?: string
}) => {
const getPreviousTableRow = (element: Element) => {
let previousElement = element?.previousElementSibling as HTMLElement;
while (previousElement && !previousElement.matches(".av__row[data-id], .av__row--header")) {
previousElement = previousElement.previousElementSibling as HTMLElement;
}
return previousElement;
};
options.blockElement.querySelector('[data-type="av-search"]').textContent = "";
const isList = options.blockElement.getAttribute("data-av-type") === "list";
const groupQuery = options.groupID ? `.av__body[data-group-id="${options.groupID}"] ` : "";
let previousElement = options.blockElement.querySelector(groupQuery + `.av__row[data-id="${options.previousId}"]`) || options.blockElement.querySelector(groupQuery + ".av__row--header");
// 有排序需要加入最后一行
const hasSort = options.blockElement.querySelector('.av__views [data-type="av-sort"]').classList.contains("block__icon--active");
if (hasSort) {
previousElement = getPreviousTableRow(options.blockElement.querySelector(groupQuery + ".av__row--util"));
}
const bodyElement = options.blockElement.querySelector(`.av__body[data-group-id="${options.groupID}"] `);
if (bodyElement && isAVTimestampType(bodyElement.getAttribute("data-dtype")) &&
bodyElement.getAttribute("data-content") !== "_@today@_") {
previousElement = getPreviousTableRow(
options.blockElement.querySelector('.av__body[data-content="_@today@_"] .av__row--util'));
}
if (!previousElement) {
return;
}
let cellsHTML = `<div class="av__colsticky"><div class="av__firstcol"><svg><use xlink:href="#iconUncheck"></use></svg>${getFreezeDragHTML()}</div></div>`;
const pinIndex = previousElement.querySelectorAll(".av__colsticky .av__cell").length - 1;
if (pinIndex > -1) {
cellsHTML = `<div class="av__colsticky av__colsticky--freeze"><div class="av__firstcol"><svg><use xlink:href="#iconUncheck"></use></svg>${getFreezeDragHTML()}</div>`;
}
previousElement.querySelectorAll(".av__cell").forEach((item: HTMLElement, index) => {
let lineNumber = 1;
const colType = getTypeByCellElement(item);
if (colType === "lineNumber") {
const lineNumberValue = item.querySelector(".av__celltext")?.getAttribute("data-value");
if (lineNumberValue) {
lineNumber = parseInt(lineNumberValue);
}
}
cellsHTML += `<div class="av__cell${colType === "checkbox" ? " av__cell-uncheck" : ""}" data-col-id="${item.dataset.colId}"
data-wrap="${item.dataset.wrap}"
data-dtype="${item.dataset.dtype}"
data-date-format="${item.dataset.dateFormat || ""}"
data-align="${item.dataset.align || ""}"
style="${isList ? "" : `width: ${item.style.width};`}"${colType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(colType, null), lineNumber,
true, "table", undefined, item.dataset.dateFormat as TAVDateFormat)}</div>`;
if (pinIndex === index) {
cellsHTML += "</div>";
}
});
let html = "";
clearSelect(["cell", "row"], options.blockElement);
options.srcIDs.forEach(() => {
html += `<div class="av__row" data-type="ghost">
${cellsHTML}
</div>`;
});
previousElement.insertAdjacentHTML("afterend", html);
fetchPost("/api/av/getAttributeViewAddingBlockDefaultValues", {
avID: options.blockElement.getAttribute("data-av-id"),
blockID: options.blockElement.getAttribute("data-node-id"),
groupID: options.groupID,
previousID: options.previousId,
}, (response) => {
if (response.data.values) {
let popCellElement: HTMLElement;
const updateIds = Object.keys(response.data.values);
options.blockElement.querySelectorAll('[data-type="ghost"]').forEach(rowItem => {
rowItem.querySelectorAll(".av__cell").forEach((cellItem: HTMLElement) => {
if (!popCellElement && cellItem.getAttribute("data-detached") === "true") {
popCellElement = cellItem;
}
if (updateIds.includes(cellItem.dataset.colId)) {
const cellValue = response.data.values[cellItem.dataset.colId];
cellItem.innerHTML = renderCell(cellValue, 0, true, "table", undefined,
cellItem.dataset.dateFormat as TAVDateFormat);
renderCellAttr(cellItem, cellValue);
renderAVRichTextElements(cellItem);
}
});
});
}
setPage(options.blockElement);
});
};
const applyFixedClip = (el: HTMLElement, scrollEl: HTMLElement) => {
const scrollLeft = scrollEl.scrollLeft;
const clientWidth = scrollEl.clientWidth;
const scrollWidth = scrollEl.scrollWidth;
const right = Math.max(0, scrollWidth - scrollLeft - clientWidth);
applyFixedViewportClip(el, scrollWidth > clientWidth ? scrollLeft : 0, right);
};
const applyFixedViewportClip = (el: HTMLElement, left = 0, right = 0) => {
// 固定栏按编辑器与分屏的交集裁剪,避免分屏缩小时覆盖相邻文档。
const viewport = el.closest(".protyle-content");
const pane = el.closest(".layout-tab-container");
const rect = el.getBoundingClientRect();
let top = 0;
let bottom = 0;
[viewport, pane].forEach(element => {
if (!element) {
return;
}
const bounds = element.getBoundingClientRect();
top = Math.max(top, bounds.top - rect.top);
bottom = Math.max(bottom, rect.bottom - bounds.bottom);
left = Math.max(left, bounds.left - rect.left);
right = Math.max(right, rect.right - bounds.right);
});
el.style.clipPath = `inset(${top}px ${right}px ${bottom}px ${left}px)`;
};
const stickyScrollElMap = new WeakMap<HTMLElement, HTMLElement>();
const bindHeaderScrollSync = (blockElement: HTMLElement, scrollEl: HTMLElement) => {
if (stickyScrollElMap.get(blockElement) === scrollEl) {
return;
}
stickyScrollElMap.set(blockElement, scrollEl);
const syncHeaders = () => {
const x = -scrollEl.scrollLeft;
blockElement.querySelectorAll(".av__row--header--fixed, .av__row--footer--fixed").forEach((el: HTMLElement) => {
el.style.transform = `translateX(${x}px)`;
applyFixedClip(el, scrollEl);
});
};
scrollEl.addEventListener("scroll", syncHeaders, {passive: true});
if (scrollEl.scrollLeft > 0) {
syncHeaders();
}
};
const addFixedRow = (item: HTMLElement, fixedClass: string, placeholderClass: string, height: number, width: number) => {
item.classList.add(fixedClass);
const placeholder = document.createElement("div");
placeholder.className = placeholderClass;
placeholder.style.height = height + "px";
placeholder.style.width = width + "px";
item.insertAdjacentElement("afterend", placeholder);
};
const addFixedViews = (item: HTMLElement, height: number, width: number) => {
item.classList.add("av__views--fixed");
const placeholder = document.createElement("div");
placeholder.className = "av__views-placeholder";
placeholder.style.height = height + "px";
// 保留工具栏对容器宽度的支撑,并允许占位随可用空间收缩。
placeholder.style.width = width + "px";
placeholder.style.maxWidth = "100%";
item.insertAdjacentElement("afterend", placeholder);
};
const removeFixedRow = (item: HTMLElement, fixedClass: string, placeholderClass: string) => {
if (!item.classList.contains(fixedClass)) {
return;
}
item.classList.remove(fixedClass);
item.style.top = "";
item.style.bottom = "";
item.style.left = "";
item.style.width = "";
item.style.transform = "";
item.style.clipPath = "";
const next = item.nextElementSibling as HTMLElement;
if (next?.classList.contains(placeholderClass)) {
next.remove();
}
};
const syncFixedRowPos = (item: HTMLElement, bodyRect: DOMRect, scrollLeft: number, scrollEl: HTMLElement) => {
item.style.left = Math.round(bodyRect.left + scrollLeft) + "px";
item.style.width = Math.round(bodyRect.width) + "px";
item.style.transform = `translateX(${-scrollLeft}px)`;
if (scrollEl) {
applyFixedClip(item, scrollEl);
}
};
export const stickyRow = (blockElement: HTMLElement, scrollElement: HTMLElement, status: "top" | "bottom" | "all") => {
updateFrozenColumns(blockElement);
// 内部滚动的反链数据库不使用相对窗口固定的表头,避免占位和固定坐标干扰内部布局。
const skipFixed = blockElement.classList.contains("av--backlink") || hasTopClosestByAttribute(blockElement, "fold", "1");
if (skipFixed) {
const viewsElement = blockElement.querySelector(".av__views") as HTMLElement;
if (viewsElement) {
removeFixedRow(viewsElement, "av__views--fixed", "av__views-placeholder");
}
blockElement.querySelectorAll(".av__row--header--fixed").forEach((item: HTMLElement) => {
removeFixedRow(item, "av__row--header--fixed", "av__row--header-placeholder");
});
blockElement.querySelectorAll(".av__row--footer--fixed").forEach((item: HTMLElement) => {
removeFixedRow(item, "av__row--footer--fixed", "av__row--footer--placeholder");
});
return;
}
const isTable = blockElement.dataset.avType === "table";
const scrollEl = blockElement.querySelector(".av__scroll") as HTMLElement;
if (isTable && scrollEl) {
bindHeaderScrollSync(blockElement, scrollEl);
}
// 先批量读取吸顶判定所需的几何信息,再更新固定栏位置及裁剪范围。
const elementRect = scrollElement.getBoundingClientRect();
const breadcrumbElement = scrollElement.previousElementSibling as HTMLElement;
// 移动端面包屑隐藏后仍保留布局尺寸,吸顶位置需回到滚动视口顶部。
const breadcrumbBottom = breadcrumbElement?.classList.contains("protyle-breadcrumb") &&
breadcrumbElement.getAttribute("aria-hidden") !== "true" ?
breadcrumbElement.getBoundingClientRect().bottom : elementRect.top;
const scrollTop = scrollElement.scrollTop;
const scrollLeft = scrollEl ? scrollEl.scrollLeft : 0;
const doTop = status === "top" || status === "all";
const doBottom = status === "bottom" || status === "all";
const stickyTop = Math.round(Math.max(elementRect.top, breadcrumbBottom));
const viewsElement = blockElement.querySelector(".av__views") as HTMLElement;
let viewsTask: {
element: HTMLElement;
height: number;
left: number;
top: number;
width: number;
shouldFix: boolean;
} | undefined;
let headerStickyTop = stickyTop;
if (doTop && viewsElement) {
const placeholderElement = viewsElement.classList.contains("av__views--fixed") &&
viewsElement.nextElementSibling?.classList.contains("av__views-placeholder")
? viewsElement.nextElementSibling as HTMLElement
: viewsElement;
const viewsRect = placeholderElement.getBoundingClientRect();
// 吸顶栏保留可用宽度的小数精度,并同步换行后的占位高度,保持表头位置与文档布局一致。
if (placeholderElement !== viewsElement) {
const width = viewsRect.width + "px";
if (viewsElement.style.width !== width) {
viewsElement.style.width = width;
}
}
const height = viewsElement.offsetHeight;
if (placeholderElement !== viewsElement && placeholderElement.style.height !== height + "px") {
placeholderElement.style.height = height + "px";
}
const blockRect = blockElement.getBoundingClientRect();
const shouldFix = height > 0 && viewsRect.top < stickyTop && blockRect.bottom > stickyTop;
const top = blockRect.bottom < stickyTop + height ? Math.round(blockRect.bottom - height) : stickyTop;
viewsTask = {
element: viewsElement,
height,
left: Math.round(viewsRect.left),
top,
width: viewsRect.width,
shouldFix,
};
if (shouldFix) {
headerStickyTop = top + height;
}
}
// 第一遍:纯读取,收集每个 header/footer 的几何与判定结果
const headerTasks: Array<{
item: HTMLElement;
bodyRect: DOMRect;
headerH: number;
shouldFix: boolean;
scrollLeft: number;
scrollEl: HTMLElement;
}> = [];
const footerTasks: Array<{
item: HTMLElement;
bodyRect: DOMRect;
footerH: number;
shouldFix: boolean;
scrollLeft: number;
scrollEl: HTMLElement;
}> = [];
if (doTop && isTable) {
blockElement.querySelectorAll(".av__row--header").forEach((item: HTMLElement) => {
const body = item.parentElement as HTMLElement;
const bodyRect = body.getBoundingClientRect();
const headerH = item.offsetHeight;
headerTasks.push({
item,
bodyRect,
headerH,
shouldFix: bodyRect.top < headerStickyTop && bodyRect.bottom > headerStickyTop,
scrollLeft,
scrollEl,
});
});
}
if (doBottom && isTable) {
blockElement.querySelectorAll(".av__row--footer").forEach((item: HTMLElement) => {
if (!item.querySelector(".av__calc--ashow")) {
return;
}
const body = item.parentElement as HTMLElement;
const bodyRect = body.getBoundingClientRect();
const bottomInit = Math.round(bodyRect.bottom + scrollTop);
const footerH = item.offsetHeight;
const bodyH = body.offsetHeight;
const bottomOffset = bottomInit - Math.round(elementRect.bottom);
const footerDist = bottomInit - scrollTop - Math.round(elementRect.bottom);
footerTasks.push({
item,
bodyRect,
footerH,
shouldFix: scrollTop < bottomOffset && footerDist < bodyH - footerH,
scrollLeft,
scrollEl,
});
});
}
// 第二遍:应用固定栏位置,并按定位后的实际边界裁剪。
const stickyBottom = Math.round(window.innerHeight - elementRect.bottom);
if (viewsTask) {
if (viewsTask.shouldFix) {
if (!viewsTask.element.classList.contains("av__views--fixed")) {
addFixedViews(viewsTask.element, viewsTask.height, viewsTask.width);
}
viewsTask.element.style.left = viewsTask.left + "px";
viewsTask.element.style.top = viewsTask.top + "px";
viewsTask.element.style.width = viewsTask.width + "px";
applyFixedViewportClip(viewsTask.element);
} else {
removeFixedRow(viewsTask.element, "av__views--fixed", "av__views-placeholder");
}
}
headerTasks.forEach((task) => {
const {item, bodyRect, headerH, shouldFix} = task;
if (shouldFix) {
if (!item.classList.contains("av__row--header--fixed")) {
addFixedRow(item, "av__row--header--fixed", "av__row--header-placeholder", headerH, Math.round(bodyRect.width));
}
item.style.top = bodyRect.bottom < headerStickyTop + headerH
? Math.round(bodyRect.bottom - headerH) + "px"
: headerStickyTop + "px";
syncFixedRowPos(item, bodyRect, task.scrollLeft, task.scrollEl);
} else {
removeFixedRow(item, "av__row--header--fixed", "av__row--header-placeholder");
}
});
footerTasks.forEach((task) => {
const {item, bodyRect, footerH, shouldFix} = task;
if (shouldFix) {
if (!item.classList.contains("av__row--footer--fixed")) {
addFixedRow(item, "av__row--footer--fixed", "av__row--footer--placeholder", footerH, Math.round(bodyRect.width));
}
item.style.bottom = stickyBottom + "px";
syncFixedRowPos(item, bodyRect, task.scrollLeft, task.scrollEl);
} else {
removeFixedRow(item, "av__row--footer--fixed", "av__row--footer--placeholder");
}
});
};
const updatePageSize = (options: {
currentPageSize: string,
newPageSize: string,
protyle: IProtyle,
avID: string,
nodeElement: Element
}) => {
if (options.currentPageSize === options.newPageSize) {
return;
}
options.nodeElement.querySelectorAll(".av__body").forEach((item: HTMLElement) => {
item.dataset.pageSize = options.newPageSize;
});
const blockID = options.nodeElement.getAttribute("data-node-id");
transaction(options.protyle, [{
action: "setAttrViewPageSize",
avID: options.avID,
data: parseInt(options.newPageSize),
blockID
}], [{
action: "setAttrViewPageSize",
data: parseInt(options.currentPageSize),
avID: options.avID,
blockID
}]);
document.querySelector(".av__panel")?.remove();
};
export const setPageSize = (options: {
target: HTMLElement,
protyle: IProtyle,
avID: string,
nodeElement: Element
}) => {
const menu = new Menu(Constants.MENU_AV_PAGE_SIZE);
if (menu.isOpen) {
return;
}
const currentPageSize = options.target.dataset.size;
menu.addItem({
iconHTML: "",
label: "5",
checked: currentPageSize === "5",
click() {
updatePageSize({
currentPageSize,
newPageSize: "5",
protyle: options.protyle,
avID: options.avID,
nodeElement: options.nodeElement
});
}
});
menu.addItem({
iconHTML: "",
label: "10",
checked: currentPageSize === "10",
click() {
updatePageSize({
currentPageSize,
newPageSize: "10",
protyle: options.protyle,
avID: options.avID,
nodeElement: options.nodeElement
});
}
});
menu.addItem({
iconHTML: "",
checked: currentPageSize === "25",
label: "25",
click() {
updatePageSize({
currentPageSize,
newPageSize: "25",
protyle: options.protyle,
avID: options.avID,
nodeElement: options.nodeElement
});
}
});
menu.addItem({
iconHTML: "",
checked: currentPageSize === "50",
label: "50",
click() {
updatePageSize({
currentPageSize,
newPageSize: "50",
protyle: options.protyle,
avID: options.avID,
nodeElement: options.nodeElement
});
}
});
menu.addItem({
iconHTML: "",
checked: currentPageSize === "100",
label: "100",
click() {
updatePageSize({
currentPageSize,
newPageSize: "100",
protyle: options.protyle,
avID: options.avID,
nodeElement: options.nodeElement
});
}
});
menu.addItem({
iconHTML: "",
checked: currentPageSize === Constants.SIZE_DATABASE_MAZ_SIZE.toString(),
label: window.siyuan.languages.all,
click() {
updatePageSize({
currentPageSize,
newPageSize: Constants.SIZE_DATABASE_MAZ_SIZE.toString(),
protyle: options.protyle,
avID: options.avID,
nodeElement: options.nodeElement
});
}
});
openViewSettingMenu(menu, options.target);
};
export const deleteRow = (blockElement: HTMLElement, protyle: IProtyle,
selectedItems: IAVItemInfo[] = getAVSelectedItemInfos(blockElement)) => {
if (selectedItems.length === 0) {
return;
}
const primaryValues = selectedItems.map(item => item.primaryCell?.value);
if (primaryValues.some(value => !value)) {
return;
}
const avID = blockElement.getAttribute("data-av-id");
const undoOperations: IOperation[] = [];
const blockIds: string[] = [];
selectedItems.forEach(item => blockIds.push(item.itemID));
selectedItems.forEach((item, index) => {
const blockValue = primaryValues[index];
undoOperations.push({
action: "insertAttrViewBlock",
avID,
previousID: item.previousID,
srcs: [{
itemID: item.itemID,
id: blockValue.isDetached ? item.itemID : blockValue.block.id,
isDetached: blockValue.isDetached === true,
content: blockValue.block.content
}],
blockID: blockElement.dataset.nodeId,
groupID: item.groupID
});
});
const newUpdated = dayjs().format("YYYYMMDDHHmmss");
undoOperations.push({
action: "doUpdateUpdated",
id: blockElement.dataset.nodeId,
data: blockElement.getAttribute("updated")
});
transaction(protyle, [{
action: "removeAttrViewBlock",
srcIDs: blockIds,
avID,
blockID: blockElement.dataset.nodeId,
}, {
action: "doUpdateUpdated",
id: blockElement.dataset.nodeId,
data: newUpdated,
}], undoOperations);
const selectedIDs = new Set(selectedItems.map(item => item.itemID));
blockElement.querySelectorAll<HTMLElement>(".av__row[data-id], .av__gallery-item[data-id], .av__calendar-item[data-id]").forEach(item => {
if (selectedIDs.has(item.dataset.id)) {
item.remove();
}
});
clearSelect(["row", "galleryItem"], blockElement);
if (blockElement.dataset.avType !== "calendar") {
stickyRow(blockElement, protyle.contentElement, "all");
updateHeader(blockElement.querySelector(".av__row"));
}
blockElement.setAttribute("updated", newUpdated);
};
export const insertRows = (options: {
blockElement: HTMLElement,
protyle: IProtyle,
count: number,
previousID: string,
groupID?: string
}) => {
const avID = options.blockElement.getAttribute("data-av-id");
const srcIDs: string[] = [];
const srcs: IOperationSrcs[] = [];
new Array(options.count).fill(0).forEach(() => {
const newNodeID = Lute.NewNodeID();
const itemID = Lute.NewNodeID();
srcIDs.push(itemID);
srcs.push({
itemID,
id: newNodeID,
isDetached: true,
content: "",
});
});
const newUpdated = dayjs().format("YYYYMMDDHHmmss");
transaction(options.protyle, [{
action: "insertAttrViewBlock",
avID,
previousID: options.previousID,
srcs,
blockID: options.blockElement.dataset.nodeId,
groupID: options.groupID,
viewID: options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW) ||
options.blockElement.querySelector(".layout-tab-bar .item--focus")?.getAttribute("data-id") || "",
context: getAVFilteredTipContext("target", options.protyle, true),
}, {
action: "doUpdateUpdated",
id: options.blockElement.dataset.nodeId,
data: newUpdated,
}], [{
action: "removeAttrViewBlock",
srcIDs,
avID,
}, {
action: "doUpdateUpdated",
id: options.blockElement.dataset.nodeId,
data: options.blockElement.getAttribute("updated")
}]);
if (["gallery", "kanban"].includes(options.blockElement.getAttribute("data-av-type"))) {
insertGalleryItemAnimation({
blockElement: options.blockElement,
protyle: options.protyle,
srcIDs,
previousId: options.previousID,
groupID: options.groupID
});
} else {
insertAttrViewBlockAnimation({
protyle: options.protyle,
blockElement: options.blockElement,
srcIDs,
previousId: options.previousID,
groupID: options.groupID
});
}
options.blockElement.setAttribute("updated", newUpdated);
};
export const duplicateRows = (blockElement: HTMLElement, protyle: IProtyle, rowIDs: string[]) => {
if (rowIDs.length === 0) {
return;
}
const avID = blockElement.getAttribute("data-av-id");
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
const newRowIDs: string[] = [];
// 副本统一插入到最后选中的条目之后,按源序排列
const anchorID = rowIDs[rowIDs.length - 1];
let previousID = anchorID;
rowIDs.forEach(srcRowID => {
const newRowID = Lute.NewNodeID();
newRowIDs.push(newRowID);
doOperations.push({
action: "duplicateAttrViewRow",
avID,
id: newRowID,
srcIDs: [srcRowID],
previousID,
});
// 后续副本接在前一个副本之后,保证源序
previousID = newRowID;
});
const newUpdated = dayjs().format("YYYYMMDDHHmmss");
doOperations.push({
action: "doUpdateUpdated",
id: blockElement.dataset.nodeId,
data: newUpdated,
});
undoOperations.push({
action: "removeAttrViewBlock",
srcIDs: newRowIDs,
avID,
});
undoOperations.push({
action: "doUpdateUpdated",
id: blockElement.dataset.nodeId,
data: blockElement.getAttribute("updated")
});
transaction(protyle, doOperations, undoOperations);
blockElement.setAttribute("updated", newUpdated);
};