An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Share database card layout rendering and state https://github.com/siyuan-note/siyuan/issues/20293
Daniel5f1a79428d48
diff --git a/app/src/protyle/render/av/cardLayout.test.ts b/app/src/protyle/render/av/cardLayout.test.tsnew file mode 100644index 0000000000..00a20919de--- /dev/null+++ b/app/src/protyle/render/av/cardLayout.test.ts@@ -0,0 +1,144 @@+import * as assert from "node:assert/strict";+import {createHash} from "node:crypto";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const fixture = () => {+ const calls: Array<{rowIndex: number, type: string}> = [];+ const saved: Record<string, unknown[]> = {};+ const record = (name: string) => (...args: unknown[]) => { (saved[name] ||= []).push(args); };+ const document = {activeElement: undefined as unknown};+ const jobs: Array<() => void> = [];+ const dependencies = {+ "../../../constants": {Constants: {ATTRIBUTE_V_SCROLL: "vscroll", TIMEOUT_LOAD: 1}},+ "../../util/hasClosest": {hasClosestByClassName: (item: {body: unknown}) => item.body},+ "../../util/selection": {focusBlock: record("focus")},+ "../../util/focusRestore": {getPendingBlockFocusMode: (): undefined => undefined},+ "./row": {+ getRowHTML: ({row, rowIndex, type}: {row: {id: string}, rowIndex: number, type: string}) => {+ calls.push({rowIndex, type});+ return `<article data-id="${row.id}" data-index="${rowIndex}" data-layout="${type}"></article>`;+ },+ stickyRow: record("sticky"), updateAVSelectionStatus: record("selection"), updateHeader: record("header"),+ },+ "./gallery/style": {getCardStyle: () => "card-style"},+ "./virtualScroll": {+ getAVSelectedItemPoints: () => [{groupID: "group", itemID: "selected"}],+ getBodyVirtualData: (_body: unknown, selector: string, index: number) => {+ assert.equal(selector, ".av__gallery-add");+ return {renderedStart: index, renderedEnd: index + 1};+ },+ initVirtualScroll: record("virtual"), setAVData: record("data"),+ },+ "../../util/processCode": {processRender: record("code")},+ "./richText": {renderAVRichTextElements: record("rich")},+ "./search": {bindAvSearch: record("search")},+ "./render": {updateSearch: record("updateSearch")},+ "./locate": {finishAVLocate: record("locate")},+ };+ const compiled = transpileModule(readFileSync("src/protyle/render/av/cardLayout.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const exports: Record<string, (...args: unknown[]) => any> = {};+ new Function("require", "exports", "window", "document", "getSelection", "setTimeout", compiled)(+ (name: keyof typeof dependencies) => {+ assert.ok(dependencies[name], "unexpected module: " + name);+ return dependencies[name];+ }, exports, {siyuan: {languages: {newRow: "new", loadMore: "more"}}}, document,+ () => ({rangeCount: 0}), (job: () => void) => { jobs.push(job); });+ return {api: exports, calls, saved, document, jobs};+};++test("card HTML preserves both layout baselines and virtual windows", () => {+ // 摘要取自重构前两份生成器,冻结大小、分页与虚拟窗口的完整 HTML。+ const hashes = {+ gallery: ["8b33413d1f62e7d4d750e83d1b9ff8641c916e283cf85760dbd59494885e9429",+ "74c516f745b1cf092151dad546d2fc4e45b6acb920ba643bf85628316529a1cd",+ "3a54cbfbfba4272be706ff7ac05bc9c8cc4c62f29d2b2de077c40250e922312d",+ "c634a59b9d368c6e09ddd2f8b8ba5b642c7b1514edfb2d5cb828a3761ffa757d",+ "f398bf302576f165a8a645b4506199e9e69d63e14bb4bb453950ea11ea2cf2d2"],+ kanban: ["7f0f04ddbe90be7b686f5eb2f6cdb8d07ba16107364df7b4bb69e92eb30d9aeb",+ "7f0f04ddbe90be7b686f5eb2f6cdb8d07ba16107364df7b4bb69e92eb30d9aeb",+ "7f0f04ddbe90be7b686f5eb2f6cdb8d07ba16107364df7b4bb69e92eb30d9aeb",+ "60059084cd0e141245b322e3e67f99b144c8c9deeba23353f5dd11d725ec558a",+ "d66910165ba9d54ac2761161a2cd72ef65c934787e50176e640f2a604cc0b988"],+ };+ for (const type of ["gallery", "kanban"] as const) {+ for (let index = 0; index < 5; index++) {+ const f = fixture();+ const count = index < 3 ? 3 : 105;+ const attributes: Record<string, string> = {};+ const virtual = index === 4 ? {renderedStart: 10, renderedEnd: 12, rowOffset: 20, topSpacerHeight: 100} : undefined;+ const html = f.api.getAVCardHTML(type, {cards: Array.from({length: count}, (_, i) => ({id: `row${i}`})),+ cardCount: count + 5, pageSize: index < 3 ? 10 : 200, cardSize: index < 3 ? index : 1},+ {setAttribute: (key: string, value: string) => { attributes[key] = value; }}, virtual);+ assert.equal(createHash("sha256").update(html).digest("hex"), hashes[type][index], `${type}: ${index}`);+ assert.deepEqual(f.calls.map(item => item.rowIndex), index === 4 ? [30, 31, 32] :+ Array.from({length: index < 3 ? 3 : 100}, (_, i) => i));+ assert.ok(f.calls.every(item => item.type === type));+ assert.deepEqual(attributes, index < 3 ? {} : {vscroll: "true"});+ }+ }+});++test("card state preserves group paging and ignores ghost or locate-only windows", () => {+ for (const type of ["gallery", "kanban"]) {+ const f = fixture();+ const search = {textContent: " query "};+ f.document.activeElement = search;+ const body = (id: string, ghost = false, locate = false) => ({+ dataset: {groupId: id, pageSize: "200", avLocateWindow: locate ? "true" : ""},+ getAttribute: () => id,+ querySelector: (selector: string) => selector.includes(":not") && ghost ? null :+ {getAttribute: () => "12"},+ });+ const blockElement = {+ style: {alignSelf: "start"}, getAttribute: () => "true",+ querySelector: (selector: string) => selector.includes("av-search") ? search : {scrollLeft: 17},+ querySelectorAll: (selector: string) => selector.includes("fields--edit") ?+ [{body: {dataset: {groupId: "group"}}, parentElement: {getAttribute: () => "edited"}}] :+ [body(""), body("ghost", true), body("locate", false, true)],+ };+ const state = f.api.captureAVCardRenderState({blockElement, protyle: {contentElement: {scrollTop: 42}}}, type);+ assert.deepEqual(state.editIds, [{groupId: "group", fieldId: "edited"}]);+ assert.deepEqual(state.selectItemIds, [{groupId: "group", fieldId: "selected"}]);+ assert.deepEqual(state.pageSizes, {unGroup: "200", ghost: "200", locate: "200"});+ assert.deepEqual(state.virtualData, {[type === "gallery" ? "all" : ""]: {renderedStart: 12, renderedEnd: 13}});+ assert.equal(state.query, " query ");+ assert.equal(state.isSearching, true);+ assert.equal(state.oldOffset, 42);+ assert.equal(state.alignSelf, "start");+ assert.equal(state.left, type === "kanban" ? 17 : undefined);+ }+});++test("card restoration retains viewport, callback and virtual selection before locate completion", () => {+ const f = fixture();+ const sizes: Record<string, string> = {};+ const scroller = {scrollLeft: 0};+ const blockElement = {+ style: {alignSelf: ""}, classList: {toggle: () => {}}, getAttribute: () => "",+ setAttribute: (name: string, value: string) => { sizes[name] = value; },+ querySelector: (selector: string) => selector === ".av__kanban" ? scroller :+ selector.includes(".av__body") ? {dataset: sizes} : null,+ };+ const protyle = {contentElement: {scrollTop: 0}};+ const data = {view: {displayEmptyFields: true, coverFrom: 0}};+ let callback = 0;+ f.api.afterRenderCards({blockElement, protyle, data, renderAll: false,+ cb: (received: unknown) => { assert.equal(received, data); callback++; },+ resetData: {oldOffset: 42, alignSelf: "start", left: 17, selectItemIds: [], editIds: [],+ pageSizes: {unGroup: "200"}, query: "query", isSearching: true, virtualData: {}},+ });+ assert.equal(protyle.contentElement.scrollTop, 42);+ assert.equal(blockElement.style.alignSelf, "start");+ assert.equal(scroller.scrollLeft, 17);+ assert.equal(sizes.pageSize, "200");+ assert.equal(sizes["data-render"], "true");+ assert.equal(callback, 1);+ assert.equal(f.saved.virtual.length, 1);+ assert.equal(f.saved.locate.length, 1);+ assert.equal(f.jobs.length, 0);+ assert.equal(f.saved.search, undefined);+});diff --git a/app/src/protyle/render/av/cardLayout.ts b/app/src/protyle/render/av/cardLayout.tsnew file mode 100644index 0000000000..c3f94d4ccd--- /dev/null+++ b/app/src/protyle/render/av/cardLayout.ts@@ -0,0 +1,187 @@+import type {IAVCardRenderOptions, IAVCardRenderState, IAVRenderItemID} from "./renderState";+import {Constants} from "../../../constants";+import {hasClosestBlock, hasClosestByClassName} from "../../util/hasClosest";+import {focusBlock} from "../../util/selection";+import {getPendingBlockFocusMode} from "../../util/focusRestore";+import {getRowHTML, stickyRow, updateAVSelectionStatus, updateHeader} from "./row";+import {getCardStyle} from "./gallery/style";+import {getAVSelectedItemPoints, getBodyVirtualData, initVirtualScroll, setAVData} from "./virtualScroll";+import {processRender} from "../../util/processCode";+import {renderAVRichTextElements} from "./richText";+import {bindAvSearch} from "./search";+import {updateSearch} from "./render";+import {finishAVLocate} from "./locate";++export const getAVCardHTML = (type: "gallery" | "kanban", data: IAVGallery | IAVKanban, e: HTMLElement, virtualData: IAVVirtualData) => {+ let galleryHTML = "";+ // 两种卡片布局共用行生成、虚拟窗口和加载更多控件。+ data.cards.find((item: IAVGalleryItem, rowIndex: number) => {+ if (virtualData && typeof virtualData.renderedEnd === "number") {+ if (rowIndex === 0) {+ e.setAttribute(Constants.ATTRIBUTE_V_SCROLL, "true");+ }+ if (rowIndex > virtualData.renderedEnd) {+ return true;+ }+ if (rowIndex < virtualData.renderedStart) {+ return;+ }+ } else if (data.pageSize > 100 && rowIndex > 99) {+ e.setAttribute(Constants.ATTRIBUTE_V_SCROLL, "true");+ return true;+ }+ galleryHTML += getRowHTML({data, row: item, rowIndex: rowIndex + (virtualData?.rowOffset || 0), type});+ return false;+ });+ galleryHTML += `<div class="av__gallery-add" data-type="av-add-bottom"><svg class="svg"><use xlink:href="#iconAdd"></use></svg><span class="fn__space"></span>${window.siyuan.languages.newRow}</div>`;+ return `<div class="av__gallery${type === "kanban" || data.cardSize === 0 ? " av__gallery--small" : (data.cardSize === 2 ? " av__gallery--big" : "")}"${type === "gallery" ? ` style="${getCardStyle(data)}"` : ""}>+ ${virtualData?.topSpacerHeight ? `<div class="av__spacer" style="height: ${virtualData.topSpacerHeight}px;"></div>` : ""}${galleryHTML}+</div>+<div class="av__gallery-load${data.cardCount > data.cards.length ? "" : " fn__none"}">+ <button class="b3-button av__button" data-type="av-load-more">+ <svg><use xlink:href="#iconArrowDown"></use></svg>+ <span>${window.siyuan.languages.loadMore}</span>+ <svg data-type="set-page-size" data-size="${data.pageSize}"><use xlink:href="#iconMore"></use></svg>+ </button>+</div>`;+};++export const captureAVCardRenderState = (options: {blockElement: HTMLElement, protyle: IProtyle},+ type: "gallery" | "kanban"): IAVCardRenderState => {+ const searchInputElement = options.blockElement.querySelector('[data-type="av-search"]');+ const editIds: IAVRenderItemID[] = [];+ options.blockElement.querySelectorAll(".av__gallery-fields--edit").forEach(item => {+ editIds.push({+ groupId: (hasClosestByClassName(item, "av__body") as HTMLElement).dataset.groupId || "",+ fieldId: item.parentElement.getAttribute("data-id"),+ });+ });+ const selectItemIds: IAVRenderItemID[] = getAVSelectedItemPoints(options.blockElement).map(item => ({+ groupId: item.groupID,+ fieldId: item.itemID,+ }));+ const pageSizes: { [key: string]: string } = {};+ const virtualData: { [key: string]: IAVVirtualData } = {};+ options.blockElement.querySelectorAll(".av__body").forEach((item: HTMLElement) => {+ pageSizes[item.dataset.groupId || "unGroup"] = item.dataset.pageSize;+ if (item.dataset.avLocateWindow === "true") {+ return;+ }+ if (!item.querySelector(".av__gallery-item") || options.blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) !== "true") {+ return;+ }+ // 守卫只保证至少 1 个 .av__gallery-item,但首行索引用 :not([data-type=ghost]) 过滤。+ // body 内全是 ghost 占位行(插入动画进行中)时查询返回 null,需跳过避免解引用 null.getAttribute+ const firstItem = item.querySelector(".av__gallery-item:not([data-type=ghost])") as HTMLElement;+ if (!firstItem) {+ return;+ }+ const firstItemIndex = parseInt(firstItem.getAttribute("data-index"));+ const groupID = item.getAttribute("data-group-id");+ virtualData[type === "gallery" ? (groupID || "all") : groupID] =+ getBodyVirtualData(item, ".av__gallery-add", firstItemIndex);+ });+ return {+ isSearching: searchInputElement && document.activeElement === searchInputElement,+ query: searchInputElement?.textContent || "",+ alignSelf: options.blockElement.style.alignSelf,+ oldOffset: options.protyle.contentElement.scrollTop,+ editIds,+ selectItemIds,+ pageSizes,+ ...(type === "kanban" ? {left: options.blockElement.querySelector(".av__kanban")?.scrollLeft} : {}),+ virtualData+ };+};++export const afterRenderCards = (options: IAVCardRenderOptions) => {+ 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) {+ processRender(options.blockElement);+ }+ renderAVRichTextElements(options.blockElement);+ if (typeof options.resetData.oldOffset === "number") {+ options.protyle.contentElement.scrollTop = options.resetData.oldOffset;+ }+ const pendingFocusMode = getPendingBlockFocusMode(options.blockElement.getAttribute("data-need-focus"));+ if (pendingFocusMode) {+ focusBlock(options.blockElement, undefined, true, pendingFocusMode === "zoom");+ options.blockElement.removeAttribute("data-need-focus");+ }+ options.blockElement.setAttribute("data-render", "true");+ if (options.resetData.alignSelf) {+ options.blockElement.style.alignSelf = options.resetData.alignSelf;+ }+ if (options.resetData.left) {+ options.blockElement.querySelector(".av__kanban").scrollLeft = options.resetData.left;+ }+ options.resetData.selectItemIds.find(selectId => {+ let itemElement = options.blockElement.querySelector(`.av__body[data-group-id="${selectId.groupId}"] .av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;+ if (!itemElement) {+ itemElement = options.blockElement.querySelector(`.av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;+ }+ if (itemElement) {+ itemElement.classList.add("av__gallery-item--select");+ }+ });+ // 重渲后恢复的选中态需刷新计数器显示+ const restoredItem = options.blockElement.querySelector(".av__gallery-item--select") as HTMLElement;+ if (restoredItem) {+ updateHeader(restoredItem);+ }+ if (!view.displayEmptyFields) {+ options.resetData.editIds.find(selectId => {+ let itemElement = options.blockElement.querySelector(`.av__body[data-group-id="${selectId.groupId}"] .av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;+ if (!itemElement) {+ itemElement = options.blockElement.querySelector(`.av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;+ }+ if (itemElement) {+ itemElement.querySelector(".av__gallery-fields").classList.add("av__gallery-fields--edit");+ itemElement.querySelector('.protyle-icon[data-type="av-gallery-edit"]')?.setAttribute("aria-label", window.siyuan.languages.hideEmptyFields);+ }+ });+ }+ Object.keys(options.resetData.pageSizes).forEach((groupId) => {+ const bodyElement = options.blockElement.querySelector(`.av__body[data-group-id="${groupId === "unGroup" ? "" : groupId}"]`) as HTMLElement;+ if (bodyElement) {+ bodyElement.dataset.pageSize = options.resetData.pageSizes[groupId];+ }+ });+ if (getSelection().rangeCount > 0) {+ // 修改表头后光标重新定位+ const range = getSelection().getRangeAt(0);+ if (!hasClosestByClassName(range.startContainer, "av__title")) {+ const blockElement = hasClosestBlock(range.startContainer);+ if (blockElement && options.blockElement === blockElement && !options.resetData.isSearching) {+ focusBlock(options.blockElement);+ }+ }+ }+ if (options.cb) {+ options.cb(options.data);+ }+ initVirtualScroll({+ ...options,+ selectedItemPoints: options.resetData.selectItemIds.map(item => ({+ groupID: item.groupId,+ itemID: item.fieldId,+ })),+ });+ updateAVSelectionStatus(options.blockElement);+ if (!options.renderAll) {+ finishAVLocate(options.blockElement, options.protyle, options.data);+ return;+ }+ setTimeout(() => {+ stickyRow(options.blockElement, options.protyle.contentElement, "top");+ }, Constants.TIMEOUT_LOAD);+ bindAvSearch({+ blockElement: options.blockElement,+ query: options.resetData.query,+ isSearching: options.resetData.isSearching,+ onChange: () => updateSearch(options.blockElement, options.protyle),+ });+ finishAVLocate(options.blockElement, options.protyle, options.data);+};diff --git a/app/src/protyle/render/av/gallery/render.ts b/app/src/protyle/render/av/gallery/render.tsindex 2507fb6381..1e26f56f3a 100644--- a/app/src/protyle/render/av/gallery/render.ts+++ b/app/src/protyle/render/av/gallery/render.ts@@ -1,94 +1,26 @@+import {afterRenderCards, captureAVCardRenderState, getAVCardHTML} from "../cardLayout";+import type {IAVCardRenderOptions} from "../renderState";import {escapeHtmlTextAndAttr} from "../../../../util/escape";import {isTableLikeView} from "../viewType";import {isAVRenderData} from "../renderData";-import {hasClosestBlock, hasClosestByClassName} from "../../../util/hasClosest";+import {Constants} from "../../../../constants";import {fetchSyncPost} from "../../../../util/fetch";-import {focusBlock} from "../../../util/selection";-import {getPendingBlockFocusMode} from "../../../util/focusRestore";-import {avRender, genTabHeaderHTML, getGroupTitleHTML, updateSearch} from "../render";-import {bindAvSearch} from "../search";-import {processRender} from "../../../util/processCode";++import {avRender, genTabHeaderHTML, getGroupTitleHTML} from "../render";+import {getPageSize} from "../groups";import {renderKanban} from "../kanban/render";-import {getAVSelectedItemPoints, getBodyVirtualData, initVirtualScroll, setAVData} from "../virtualScroll";-import {getRowHTML, stickyRow, updateAVSelectionStatus, updateHeader} from "../row";-import {- applyAVRenderContext,- beginAVRender,- failAVRender,- finishAVLocate,- getAVLocateParams,- isCurrentAVRender,- persistAVLocateView,- prepareAVLocate-} from "../locate";-import {getCardStyle} from "./style";++import {applyAVRenderContext, beginAVRender, failAVRender, getAVLocateParams, isCurrentAVRender, persistAVLocateView, prepareAVLocate} from "../locate";+import {setGroupFoldedStates} from "../groupFold";import {getPublishAVView} from "../publishState";import {getReadonlyAVView} from "../readonlyState";-import {renderAVRichTextElements} from "../richText";-import {replaceAVContainer} from "../container";--interface IIds {- groupId: string,- fieldId: string,-}-interface ITableOptions {- protyle: IProtyle,- blockElement: HTMLElement,- cb: (data: IAV) => void,- data: IAV,- renderAll: boolean,- resetData: {- alignSelf: string,- selectItemIds: IIds[],- editIds: IIds[],- isSearching: boolean,- pageSizes: { [key: string]: string },- query: string,- oldOffset: number,- left?: number,- virtualData: { [key: string]: IAVVirtualData },- }-}--const getGalleryHTML = (data: IAVGallery, e: HTMLElement, virtualData: IAVVirtualData) => {- let galleryHTML = "";- // body- data.cards.find((item: IAVGalleryItem, rowIndex: number) => {- if (virtualData && typeof virtualData.renderedEnd === "number") {- if (rowIndex === 0) {- e.setAttribute(Constants.ATTRIBUTE_V_SCROLL, "true");- }- if (rowIndex > virtualData.renderedEnd) {- return true;- }- if (rowIndex < virtualData.renderedStart) {- return;- }- } else if (data.pageSize > 100 && rowIndex > 99) {- e.setAttribute(Constants.ATTRIBUTE_V_SCROLL, "true");- return true;- }- galleryHTML += getRowHTML({data, row: item, rowIndex: rowIndex + (virtualData?.rowOffset || 0), type: "gallery"});- return false;- });- galleryHTML += `<div class="av__gallery-add" data-type="av-add-bottom"><svg class="svg"><use xlink:href="#iconAdd"></use></svg><span class="fn__space"></span>${window.siyuan.languages.newRow}</div>`;- return `<div class="av__gallery${data.cardSize === 0 ? " av__gallery--small" : (data.cardSize === 2 ? " av__gallery--big" : "")}" style="${getCardStyle(data)}">- ${virtualData?.topSpacerHeight ? `<div class="av__spacer" style="height: ${virtualData.topSpacerHeight}px;"></div>` : ""}${galleryHTML}-</div>-<div class="av__gallery-load${data.cardCount > data.cards.length ? "" : " fn__none"}">- <button class="b3-button av__button" data-type="av-load-more">- <svg><use xlink:href="#iconArrowDown"></use></svg>- <span>${window.siyuan.languages.loadMore}</span>- <svg data-type="set-page-size" data-size="${data.pageSize}"><use xlink:href="#iconMore"></use></svg>- </button>-</div>`;-};+import {replaceAVContainer} from "../container";-const renderGroupGallery = (options: ITableOptions) => {+const renderGroupGallery = (options: IAVCardRenderOptions) => {setGroupFoldedStates(options.blockElement, options.data.view.groups);const searchInputElement = options.blockElement.querySelector('[data-type="av-search"]');const isSearching = searchInputElement && document.activeElement === searchInputElement;@@ -98,7 +30,7 @@ const renderGroupGallery = (options: ITableOptions) => {options.data.view.groups.forEach((group: IAVGallery) => {if (group.groupHidden === 0) {avBodyHTML += `${getGroupTitleHTML(group, group.cardCount)}-<div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${options.resetData.virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body${group.groupFolded ? " fn__none" : ""}">${getGalleryHTML(group, options.blockElement, options.resetData.virtualData[group.id])}</div>`;+<div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${options.resetData.virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body${group.groupFolded ? " fn__none" : ""}">${getAVCardHTML("gallery", group, options.blockElement, options.resetData.virtualData[group.id])}</div>`;}});if (options.renderAll) {@@ -112,99 +44,7 @@ const renderGroupGallery = (options: ITableOptions) => {} else {options.blockElement.querySelector(".av__header").nextElementSibling.innerHTML = avBodyHTML;}- afterRenderGallery(options);-};--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) {- processRender(options.blockElement);- }- renderAVRichTextElements(options.blockElement);- if (typeof options.resetData.oldOffset === "number") {- options.protyle.contentElement.scrollTop = options.resetData.oldOffset;- }- const pendingFocusMode = getPendingBlockFocusMode(options.blockElement.getAttribute("data-need-focus"));- if (pendingFocusMode) {- focusBlock(options.blockElement, undefined, true, pendingFocusMode === "zoom");- options.blockElement.removeAttribute("data-need-focus");- }- options.blockElement.setAttribute("data-render", "true");- if (options.resetData.alignSelf) {- options.blockElement.style.alignSelf = options.resetData.alignSelf;- }- if (options.resetData.left) {- options.blockElement.querySelector(".av__kanban").scrollLeft = options.resetData.left;- }- options.resetData.selectItemIds.find(selectId => {- let itemElement = options.blockElement.querySelector(`.av__body[data-group-id="${selectId.groupId}"] .av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;- if (!itemElement) {- itemElement = options.blockElement.querySelector(`.av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;- }- if (itemElement) {- itemElement.classList.add("av__gallery-item--select");- }- });- // 重渲后恢复的选中态需刷新计数器显示- const restoredItem = options.blockElement.querySelector(".av__gallery-item--select") as HTMLElement;- if (restoredItem) {- updateHeader(restoredItem);- }- if (!view.displayEmptyFields) {- options.resetData.editIds.find(selectId => {- let itemElement = options.blockElement.querySelector(`.av__body[data-group-id="${selectId.groupId}"] .av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;- if (!itemElement) {- itemElement = options.blockElement.querySelector(`.av__gallery-item[data-id="${selectId.fieldId}"]`) as HTMLElement;- }- if (itemElement) {- itemElement.querySelector(".av__gallery-fields").classList.add("av__gallery-fields--edit");- itemElement.querySelector('.protyle-icon[data-type="av-gallery-edit"]')?.setAttribute("aria-label", window.siyuan.languages.hideEmptyFields);- }- });- }- Object.keys(options.resetData.pageSizes).forEach((groupId) => {- const bodyElement = options.blockElement.querySelector(`.av__body[data-group-id="${groupId === "unGroup" ? "" : groupId}"]`) as HTMLElement;- if (bodyElement) {- bodyElement.dataset.pageSize = options.resetData.pageSizes[groupId];- }- });- if (getSelection().rangeCount > 0) {- // 修改表头后光标重新定位- const range = getSelection().getRangeAt(0);- if (!hasClosestByClassName(range.startContainer, "av__title")) {- const blockElement = hasClosestBlock(range.startContainer);- if (blockElement && options.blockElement === blockElement && !options.resetData.isSearching) {- focusBlock(options.blockElement);- }- }- }- if (options.cb) {- options.cb(options.data);- }- initVirtualScroll({- ...options,- selectedItemPoints: options.resetData.selectItemIds.map(item => ({- groupID: item.groupId,- itemID: item.fieldId,- })),- });- updateAVSelectionStatus(options.blockElement);- if (!options.renderAll) {- finishAVLocate(options.blockElement, options.protyle, options.data);- return;- }- setTimeout(() => {- stickyRow(options.blockElement, options.protyle.contentElement, "top");- }, Constants.TIMEOUT_LOAD);- bindAvSearch({- blockElement: options.blockElement,- query: options.resetData.query,- isSearching: options.resetData.isSearching,- onChange: () => updateSearch(options.blockElement, options.protyle),- });- finishAVLocate(options.blockElement, options.protyle, options.data);+ afterRenderCards(options);};export const renderGallery = async (options: {@@ -215,47 +55,8 @@ export const renderGallery = async (options: {data?: IAV,}) => {const renderToken = beginAVRender(options.blockElement);- const searchInputElement = options.blockElement.querySelector('[data-type="av-search"]');- const editIds: IIds[] = [];- options.blockElement.querySelectorAll(".av__gallery-fields--edit").forEach(item => {- editIds.push({- groupId: (hasClosestByClassName(item, "av__body") as HTMLElement).dataset.groupId || "",- fieldId: item.parentElement.getAttribute("data-id"),- });- });- const selectItemIds: IIds[] = getAVSelectedItemPoints(options.blockElement).map(item => ({- groupId: item.groupID,- fieldId: item.itemID,- }));- const pageSizes: { [key: string]: string } = {};- const virtualData: { [key: string]: IAVVirtualData } = {};- options.blockElement.querySelectorAll(".av__body").forEach((item: HTMLElement) => {- pageSizes[item.dataset.groupId || "unGroup"] = item.dataset.pageSize;- if (item.dataset.avLocateWindow === "true") {- return;- }- if (!item.querySelector(".av__gallery-item") || options.blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) !== "true") {- return;- }- // 守卫只保证至少 1 个 .av__gallery-item,但首行索引用 :not([data-type=ghost]) 过滤。- // body 内全是 ghost 占位行(插入动画进行中)时查询返回 null,需跳过避免解引用 null.getAttribute- const firstItem = item.querySelector(".av__gallery-item:not([data-type=ghost])") as HTMLElement;- if (!firstItem) {- return;- }- const firstItemIndex = parseInt(firstItem.getAttribute("data-index"));- virtualData[item.getAttribute("data-group-id") || "all"] = getBodyVirtualData(item, ".av__gallery-add", firstItemIndex);- });- const resetData = {- isSearching: searchInputElement && document.activeElement === searchInputElement,- query: searchInputElement?.textContent || "",- alignSelf: options.blockElement.style.alignSelf,- oldOffset: options.protyle.contentElement.scrollTop,- editIds,- selectItemIds,- pageSizes,- virtualData- };+ const resetData = captureAVCardRenderState(options, "gallery");+ const virtualData = resetData.virtualData;if (options.blockElement.firstElementChild.innerHTML === "") {options.blockElement.style.alignSelf = "";options.blockElement.firstElementChild.outerHTML = `<div class="av__gallery">@@ -340,7 +141,7 @@ export const renderGallery = async (options: {});return;}- const bodyHTML = getGalleryHTML(view, options.blockElement, virtualData.all);+ const bodyHTML = getAVCardHTML("gallery", view, options.blockElement, virtualData.all);if (options.renderAll) {replaceAVContainer(options.blockElement, `<div class="av__container fn__block">${genTabHeaderHTML(data, resetData.isSearching || !!resetData.query, !options.protyle.disabled, options.blockElement)}@@ -361,7 +162,7 @@ export const renderGallery = async (options: {bodyElement.removeAttribute("data-av-locate-window");}}- afterRenderGallery({+ afterRenderCards({resetData,renderAll: options.renderAll,data,diff --git a/app/src/protyle/render/av/kanban/render.ts b/app/src/protyle/render/av/kanban/render.tsindex cf04d17a63..63066c8c06 100644--- a/app/src/protyle/render/av/kanban/render.ts+++ b/app/src/protyle/render/av/kanban/render.ts@@ -1,18 +1,18 @@+import {afterRenderCards, captureAVCardRenderState, getAVCardHTML} from "../cardLayout";import {isAVDateType, isAVSelectType} from "../capabilities";import {isTableLikeView} from "../viewType";import {isAVRenderData} from "../renderData";import {getPublishAVView} from "../publishState";import {getReadonlyAVView} from "../readonlyState";-import {hasClosestByAttribute, hasClosestByClassName} from "../../../util/hasClosest";+import {hasClosestByAttribute} from "../../../util/hasClosest";import {getPageSize} from "../groups";import {fetchSyncPost} from "../../../../util/fetch";import {Constants} from "../../../../constants";import {avRender, genTabHeaderHTML} from "../render";import {replaceAVContainer} from "../container";-import {afterRenderGallery, renderGallery} from "../gallery/render";+import {renderGallery} from "../gallery/render";import {escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../../../../util/escape";-import {getRowHTML} from "../row";-import {getAVSelectedItemPoints, getBodyVirtualData} from "../virtualScroll";+import {applyAVRenderContext,beginAVRender,@@ -25,11 +25,6 @@ import {import {getCardStyle} from "../gallery/style";import {getAVBackgroundColor, getAVColorStyle} from "../color";-interface IIds {- groupId: string,- fieldId: string,-}-const getKanbanTitleHTML = (group: IAVView, counter: number, draggable: boolean) => {let nameHTML = "";let optionMenuHTML = "";@@ -56,40 +51,6 @@ const getKanbanTitleHTML = (group: IAVView, counter: number, draggable: boolean)</div>`;};-const getKanbanHTML = (data: IAVKanban, e: HTMLElement, virtualData: IAVVirtualData) => {- let galleryHTML = "";- // body- data.cards.find((item: IAVGalleryItem, rowIndex: number) => {- if (virtualData && typeof virtualData.renderedEnd === "number") {- if (rowIndex === 0) {- e.setAttribute(Constants.ATTRIBUTE_V_SCROLL, "true");- }- if (rowIndex > virtualData.renderedEnd) {- return true;- }- if (rowIndex < virtualData.renderedStart) {- return;- }- } else if (data.pageSize > 100 && rowIndex > 99) {- e.setAttribute(Constants.ATTRIBUTE_V_SCROLL, "true");- return true;- }- galleryHTML += getRowHTML({data, row: item, rowIndex: rowIndex + (virtualData?.rowOffset || 0), type: "kanban"});- return false;- });- galleryHTML += `<div class="av__gallery-add" data-type="av-add-bottom"><svg class="svg"><use xlink:href="#iconAdd"></use></svg><span class="fn__space"></span>${window.siyuan.languages.newRow}</div>`;- return `<div class="av__gallery av__gallery--small">- ${virtualData?.topSpacerHeight ? `<div class="av__spacer" style="height: ${virtualData.topSpacerHeight}px;"></div>` : ""}${galleryHTML}-</div>-<div class="av__gallery-load${data.cardCount > data.cards.length ? "" : " fn__none"}">- <button class="b3-button av__button" data-type="av-load-more">- <svg><use xlink:href="#iconArrowDown"></use></svg>- <span>${window.siyuan.languages.loadMore}</span>- <svg data-type="set-page-size" data-size="${data.pageSize}"><use xlink:href="#iconMore"></use></svg>- </button>-</div>`;-};-export const renderKanban = async (options: {blockElement: HTMLElement,protyle: IProtyle,@@ -98,48 +59,8 @@ export const renderKanban = async (options: {data?: IAV,}) => {const renderToken = beginAVRender(options.blockElement);- const searchInputElement = options.blockElement.querySelector('[data-type="av-search"]');- const editIds: IIds[] = [];- options.blockElement.querySelectorAll(".av__gallery-fields--edit").forEach(item => {- editIds.push({- groupId: (hasClosestByClassName(item, "av__body") as HTMLElement).dataset.groupId || "",- fieldId: item.parentElement.getAttribute("data-id"),- });- });- const selectItemIds: IIds[] = getAVSelectedItemPoints(options.blockElement).map(item => ({- groupId: item.groupID,- fieldId: item.itemID,- }));- const pageSizes: { [key: string]: string } = {};- const virtualData: { [key: string]: IAVVirtualData } = {};- options.blockElement.querySelectorAll(".av__body").forEach((item: HTMLElement) => {- pageSizes[item.dataset.groupId || "unGroup"] = item.dataset.pageSize;- if (item.dataset.avLocateWindow === "true") {- return;- }- if (!item.querySelector(".av__gallery-item") || options.blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) !== "true") {- return;- }- // 守卫只保证至少 1 个 .av__gallery-item,但首行索引用 :not([data-type=ghost]) 过滤。- // body 内全是 ghost 占位行(插入动画进行中)时查询返回 null,需跳过避免解引用 null.getAttribute- const firstItem = item.querySelector(".av__gallery-item:not([data-type=ghost])") as HTMLElement;- if (!firstItem) {- return;- }- const firstItemIndex = parseInt(firstItem.getAttribute("data-index"));- virtualData[item.getAttribute("data-group-id")] = getBodyVirtualData(item, ".av__gallery-add", firstItemIndex);- });- const resetData = {- isSearching: searchInputElement && document.activeElement === searchInputElement,- query: searchInputElement?.textContent || "",- alignSelf: options.blockElement.style.alignSelf,- oldOffset: options.protyle.contentElement.scrollTop,- editIds,- selectItemIds,- pageSizes,- left: options.blockElement.querySelector(".av__kanban")?.scrollLeft,- virtualData- };+ const resetData = captureAVCardRenderState(options, "kanban");+ const virtualData = resetData.virtualData;if (options.blockElement.firstElementChild.innerHTML === "") {options.blockElement.style.alignSelf = "";options.blockElement.firstElementChild.outerHTML = `<div class="av__kanban fn__flex">@@ -238,7 +159,7 @@ export const renderKanban = async (options: {}bodyHTML += `<div class="av__kanban-group${group.cardSize === 0 ? " av__kanban-group--small" : (group.cardSize === 2 ? " av__kanban-group--big" : "")}" data-group-id="${group.id}" data-previous-group-id="${view.groups[groupIndex - 1]?.id || ""}" data-group-config="${groupConfig}"${selectBg}>${getKanbanTitleHTML(group, group.cardCount, groupDraggable)}- <div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body">${getKanbanHTML(group, options.blockElement, virtualData[group.id])}</div>+ <div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body">${getAVCardHTML("kanban", group, options.blockElement, virtualData[group.id])}</div></div>`;}});@@ -261,7 +182,7 @@ export const renderKanban = async (options: {kanbanElement.classList.remove("av__kanban--bg");}}- afterRenderGallery({+ afterRenderCards({resetData,renderAll: options.renderAll,data,diff --git a/app/src/protyle/render/av/renderState.ts b/app/src/protyle/render/av/renderState.tsnew file mode 100644index 0000000000..93d1bb610c--- /dev/null+++ b/app/src/protyle/render/av/renderState.ts@@ -0,0 +1,25 @@+export interface IAVRenderItemID {+ groupId: string;+ fieldId: string;+}++export interface IAVCardRenderState {+ alignSelf: string;+ selectItemIds: IAVRenderItemID[];+ editIds: IAVRenderItemID[];+ isSearching: boolean;+ pageSizes: {[key: string]: string};+ query: string;+ oldOffset: number;+ left?: number;+ virtualData: {[key: string]: IAVVirtualData};+}++export interface IAVCardRenderOptions {+ protyle: IProtyle;+ blockElement: HTMLElement;+ cb?: (data: IAV) => void;+ data: IAV;+ renderAll: boolean;+ resetData: IAVCardRenderState;+}diff --git a/app/src/protyle/render/av/standalonePreview.test.ts b/app/src/protyle/render/av/standalonePreview.test.tsindex 002889bda1..4d899fe3cb 100644--- a/app/src/protyle/render/av/standalonePreview.test.ts+++ b/app/src/protyle/render/av/standalonePreview.test.ts@@ -19,13 +19,19 @@ for (const layout of ["table", "gallery", "kanban"]) {return {code: 0};},};+ const cards: Record<string, unknown> = {};+ const dependencies = () => new Proxy(imports, {get: (target, key: string) =>+ target[key] || ((): undefined => undefined)});+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/cardLayout.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+ }).outputText, {exports: cards, require: dependencies, document: {activeElement: null}});runInNewContext(transpileModule(readFileSync(`src/protyle/render/av/${layout === "table" ? "" : layout + "/"}render.ts`, "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},}).outputText, {exports: methods,window: {siyuan: {}},- require: () => new Proxy(imports, {get: (target, key: string) => target[key] || ((): undefined => undefined)}),+ require: (name: string) => name === "../cardLayout" ? cards : dependencies(),});const block = {style: {}, firstElementChild: {innerHTML: "loading"},