Skip to content

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

:sparkles: Improve database relation selection with multi-field table display https://github.com/siyuan-note/siyuan/issues/13645

Daniel799fc3895baf
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index bc9ac9b569..8760d172d5 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -1841,3 +1841,149 @@ img.av__cellassetimg {
bottom: -2px;
}
}
+
+.av__relation-panel {
+ .av__relation {
+ min-width: 0;
+ }
+
+ .av__relation-table {
+ overflow: auto;
+ overscroll-behavior: contain;
+ }
+
+ .av__relation-table-header,
+ .av__relation-table-row {
+ display: grid;
+ min-width: 100%;
+ width: max-content;
+ }
+
+ .av__relation-table-header {
+ background-color: var(--b3-menu-background);
+ border-bottom: 1px solid var(--b3-border-color);
+ color: var(--b3-theme-on-surface);
+ font-size: 12px;
+ position: sticky;
+ top: 0;
+ z-index: 4;
+
+ .av__relation-table-cell {
+ font-weight: 600;
+
+ > svg {
+ height: 14px;
+ margin-right: 6px;
+ width: 14px;
+ }
+ }
+ }
+
+ .av__relation-table-row {
+ border-bottom: 1px solid var(--b3-border-color);
+ border-radius: 0;
+ height: auto;
+ margin: 0;
+ padding: 0;
+ position: relative;
+ text-align: left;
+
+ &:hover,
+ &.b3-menu__item--current {
+ background-color: var(--b3-list-hover);
+ }
+
+ &[data-relation-type="selected"] {
+ background-color: var(--b3-theme-primary-lightest);
+ }
+
+ .av__relation-table-cell > :not(.fn__grab),
+ .av__relation-table-check > * {
+ pointer-events: none;
+ }
+ }
+
+ .av__relation-table-check,
+ .av__relation-table-cell {
+ align-items: center;
+ box-sizing: border-box;
+ display: flex;
+ min-height: 34px;
+ min-width: 0;
+ overflow: hidden;
+ padding: 4px 8px;
+ }
+
+ .av__relation-table-check {
+ background-color: inherit;
+ left: 0;
+ padding: 8px;
+ position: sticky;
+ z-index: 2;
+
+ svg {
+ height: 16px;
+ width: 16px;
+ }
+ }
+
+ .av__relation-table-primary {
+ background-color: inherit;
+ border-right: 1px solid var(--b3-border-color);
+ left: 32px;
+ position: sticky;
+ z-index: 2;
+
+ .fn__grab {
+ cursor: grab;
+ flex: 0 0 auto;
+ height: 14px;
+ margin: 0 6px 0 0;
+ width: 14px;
+ }
+ }
+
+ .av__relation-table-cell {
+ .av__celltext,
+ .b3-menu__label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .av__row-actions,
+ .block__icon {
+ display: none;
+ }
+ }
+
+ .av__relation-table-selected,
+ .av__relation-table-candidates {
+ display: contents;
+ }
+
+ .av__relation-table-footer {
+ border-radius: 0;
+ margin: 0;
+ }
+
+ .av__relation-table-row.dragover__top::after,
+ .av__relation-table-row.dragover__bottom::after {
+ background-color: var(--b3-theme-primary-lighter);
+ content: '';
+ height: 4px;
+ left: 0;
+ pointer-events: none;
+ position: absolute;
+ right: 0;
+ z-index: 5;
+ }
+
+ .av__relation-table-row.dragover__top::after {
+ top: -2px;
+ }
+
+ .av__relation-table-row.dragover__bottom::after {
+ bottom: -2px;
+ }
+}
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index 1c69266601..602e325dd3 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -180,7 +180,7 @@ export const openMenuPanel = (options: {
document.body.insertAdjacentHTML("beforeend", `<div class="av__panel" style="z-index: ${++window.siyuan.zIndex};">
<div class="b3-dialog__scrim" data-type="close"></div>
- <div class="b3-menu${options.type === "filters" ? " av__filter-panel" : ""}" ${["select", "date", "asset", "relation", "rollup"].includes(options.type) ? `style="${["select", "asset", "relation"].includes(options.type) ? "max-height: calc(100vh - 32px);display: flex;flex-direction: column;" : ""}min-width: 200px;${isMobile() ? "max-width: 90vw;" : "max-width: 50vw;"}"` : ""}>${html}</div>
+ <div class="b3-menu${options.type === "filters" ? " av__filter-panel" : ""}${options.type === "relation" ? " av__relation-panel" : ""}" ${["select", "date", "asset", "relation", "rollup"].includes(options.type) ? `style="${["select", "asset", "relation"].includes(options.type) ? "max-height: calc(100vh - 32px);display: flex;flex-direction: column;" : ""}min-width: 200px;${options.type === "relation" ? `width: 760px;max-width: ${isMobile() ? "90vw" : "calc(100vw - 32px)"};` : isMobile() ? "max-width: 90vw;" : "max-width: 50vw;"}"` : ""}>${html}</div>
</div>`);
avPanelElement = document.querySelector(".av__panel");
let closeCB: () => void;
diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.ts
index a6899ea441..e9b116fbd7 100644
--- a/app/src/protyle/render/av/relation.ts
+++ b/app/src/protyle/render/av/relation.ts
@@ -2,15 +2,15 @@ import {Menu} from "../../../plugin/Menu";
import {hasClosestByClassName, hasTopClosestByClassName} from "../../util/hasClosest";
import {UDLRHint, upDownHint} from "../../../util/upDownHint";
import {fetchPost} from "../../../util/fetch";
-import {escapeHtml, escapeLessThans} from "../../../util/escape";
+import {escapeAttr, escapeHtml, escapeLessThans} from "../../../util/escape";
import {transaction} from "../../wysiwyg/transaction";
-import {updateCellsValue} from "./cell";
+import {renderCell, updateCellsValue} from "./cell";
import {updateAttrViewCellAnimation} from "./action";
import {focusBlock} from "../../util/selection";
import {setPosition} from "../../../util/setPosition";
import * as dayjs from "dayjs";
import {getFieldsByData, getViewName} from "./view";
-import {getColId} from "./col";
+import {getColIconByType, getColId} from "./col";
import {getFieldIdByCellElement} from "./row";
import {isMobile} from "../../../util/functions";
import {showMessage} from "../../../dialog/message";
@@ -258,7 +258,7 @@ export const toggleUpdateRelationBtn = (menuItemsElement: HTMLElement, avId: str
const updateCopyRelatedItems = (menuElement: Element) => {
const inputElement = menuElement.querySelector(".b3-form__icona .b3-text-field") as HTMLInputElement;
- if (menuElement.querySelector(".b3-menu__icon.fn__grab")) {
+ if (menuElement.querySelector('[data-relation-type="selected"]')) {
inputElement.nextElementSibling.classList.remove("fn__none");
inputElement.style.paddingRight = "26px";
} else {
@@ -267,68 +267,69 @@ const updateCopyRelatedItems = (menuElement: Element) => {
}
};
-const genSelectItemHTML = (options: {
- type: "selected" | "empty" | "unselect",
- id?: string,
- isDetached?: boolean,
- text?: string,
- className?: string,
- rowId?: string,
- newName?: string
-}) => {
- if (options.type === "selected") {
- return `<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
-<span class="b3-menu__label fn__ellipsis ${options.isDetached ? "" : " popover__block"}" ${options.isDetached ? "" : 'style="color:var(--b3-protyle-inline-blockref-color)"'} data-id="${options.id}">${options.text}</span>
-<svg class="b3-menu__action"><use xlink:href="#iconMin"></use></svg>`;
- }
- if (options.type === "empty") {
- if (options.newName) {
- return `<button class="b3-menu__item" data-type="setRelationCell" data-relation-type="create">
- <span class="b3-menu__label fn__ellipsis">${window.siyuan.languages.newRowInRelation.replace("${x}", options.text).replace("${y}", options.newName)}</span>
-</button>`;
+const getRelationGridTemplate = (columns: IAVColumn[]) => {
+ return `32px ${columns.map((column, index) => {
+ if (index === 0) {
+ return "240px";
}
- return `<button class="b3-menu__item" data-relation-type="empty">
- <span class="b3-menu__label">${window.siyuan.languages.emptyContent}</span>
-</button>`;
- }
- if (options.type == "unselect") {
- return `<button data-row-id="${options.rowId}" class="${options.className || "b3-menu__item ariaLabel"}" data-position="west" data-type="setRelationCell" data-relation-type="candidate">
- <span class="b3-menu__label fn__ellipsis${options.isDetached ? "" : " popover__block"}" ${options.isDetached ? "" : 'style="color:var(--b3-protyle-inline-blockref-color)"'} data-id="${options.id}">${options.text}</span>
- <svg class="b3-menu__action"><use xlink:href="#iconAdd"></use></svg>
-</button>`;
- }
+ return ["relation", "rollup", "mAsset"].includes(column.type) ? "200px" : "160px";
+ }).join(" ")}`;
};
-const genSelectedItemsHTML = (cellElement: HTMLElement, keyword: string) => {
- let html = "";
- const selectedIDs = new Set<string>();
- const lowerKeyword = keyword.toLowerCase();
- cellElement.querySelectorAll(".av__cell--relation").forEach((relationItem: HTMLElement) => {
- const item = relationItem.querySelector(".av__celltext") as HTMLElement;
- selectedIDs.add(relationItem.dataset.rowId);
- html += `<button data-row-id="${relationItem.dataset.rowId}" data-position="west" data-type="setRelationCell" data-relation-type="selected"
-class="b3-menu__item ariaLabel${item.textContent.toLowerCase().includes(lowerKeyword) ? "" : " fn__none"}"
-draggable="true">${genSelectItemHTML({
- type: "selected",
- id: item.dataset.id,
- isDetached: !item.classList.contains("av__celltext--ref"),
- text: Lute.EscapeHTMLStr(item.textContent || window.siyuan.languages.untitled)
- })}</button>`;
+const getRelationPrimaryCell = (row: IAVRow) => {
+ return row.cells.find((cell) => cell.value?.type === "block");
+};
+
+const genRelationHeaderHTML = (columns: IAVColumn[], gridTemplate: string) => {
+ let html = `<div class="av__relation-table-header" data-relation-type="header" style="grid-template-columns:${gridTemplate}">
+<span class="av__relation-table-check"></span>`;
+ columns.forEach((column, index) => {
+ html += `<span class="av__relation-table-cell${index === 0 ? " av__relation-table-primary" : ""}">
+ <svg><use xlink:href="#${getColIconByType(column.type)}"></use></svg>
+ <span class="fn__ellipsis">${escapeHtml(column.name)}</span>
+</span>`;
});
- return {html, selectedIDs};
+ return html + "</div>";
};
-const genCandidateItemsHTML = (cells: IAVCellValue[], excludedIDs: Set<string>) => {
+const genRelationRowHTML = (row: IAVRow, columns: IAVColumn[], type: "selected" | "candidate", gridTemplate: string) => {
+ const primaryCell = getRelationPrimaryCell(row);
+ if (!primaryCell?.value) {
+ return "";
+ }
+ const primaryValue = primaryCell.value;
+ const selected = type === "selected";
+ let html = `<div data-row-id="${escapeAttr(row.id)}" data-position="west" data-type="setRelationCell"
+data-relation-type="${type}" class="b3-menu__item av__relation-table-row" ${selected ? 'draggable="true"' : ""}
+style="grid-template-columns:${gridTemplate}">
+<span class="av__relation-table-check"><svg><use xlink:href="#icon${selected ? "Check" : "Uncheck"}"></use></svg></span>`;
+ columns.forEach((column, index) => {
+ const cell = row.cells.find((item) => item.value?.keyID === column.id) || row.cells[index];
+ if (index === 0) {
+ const isDetached = primaryValue.isDetached;
+ html += `<span class="av__relation-table-cell av__relation-table-primary" data-row-id="${escapeAttr(row.id)}"
+style="${primaryCell.bgColor ? `background-color:${primaryCell.bgColor};` : ""}${primaryCell.color ? `color:${primaryCell.color};` : ""}">
+ ${selected ? '<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>' : ""}
+ <span class="b3-menu__label fn__ellipsis${isDetached ? "" : " popover__block"}"
+ ${isDetached ? "" : 'style="color:var(--b3-protyle-inline-blockref-color)"'}
+ data-id="${escapeAttr(primaryValue.block?.id || "")}">${Lute.EscapeHTMLStr(primaryValue.block?.content || window.siyuan.languages.untitled)}</span>
+</span>`;
+ } else {
+ html += `<span class="av__relation-table-cell"
+style="${cell?.bgColor ? `background-color:${cell.bgColor};` : ""}${cell?.color ? `color:${cell.color};` : ""}">${cell?.value ?
+ renderCell(cell.value, 0, false, "table", column.options) : ""}</span>`;
+ }
+ });
+ return html + "</div>";
+};
+
+const genRelationRowsHTML = (rows: IAVRow[], columns: IAVColumn[], type: "selected" | "candidate",
+ gridTemplate: string, excludedIDs = new Set<string>()) => {
let html = "";
- cells.forEach((item) => {
- if (!excludedIDs.has(item.blockID)) {
- html += genSelectItemHTML({
- type: "unselect",
- rowId: item.blockID,
- id: item.block.id,
- isDetached: item.isDetached,
- text: Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled)
- });
+ rows.forEach((row) => {
+ if (!excludedIDs.has(row.id)) {
+ html += genRelationRowHTML(row, columns, type, gridTemplate);
+ excludedIDs.add(row.id);
}
});
return html;
@@ -337,14 +338,17 @@ const genCandidateItemsHTML = (cells: IAVCellValue[], excludedIDs: Set<string>)
const genRelationFooterHTML = (menuElement: HTMLElement, keyword: string, hasCandidates: boolean, hasMore: boolean) => {
if (keyword) {
const refElement = menuElement.querySelector(".popover__block");
- return genSelectItemHTML({
- type: "empty",
- newName: Lute.EscapeHTMLStr(keyword),
- text: `<span style="color: var(--b3-protyle-inline-blockref-color);" class="popover__block" data-id="${refElement.getAttribute("data-id")}">${refElement.textContent}</span>`,
- });
+ const databaseName = `<span style="color: var(--b3-protyle-inline-blockref-color);" class="popover__block"
+data-id="${escapeAttr(refElement?.getAttribute("data-id") || "")}">${escapeHtml(refElement?.textContent || "")}</span>`;
+ return `<button class="b3-menu__item av__relation-table-footer" data-type="setRelationCell" data-relation-type="create">
+ <span class="b3-menu__label fn__ellipsis">${window.siyuan.languages.newRowInRelation.replace("${x}", databaseName).
+ replace("${y}", Lute.EscapeHTMLStr(keyword))}</span>
+</button>`;
}
if (!hasCandidates && !hasMore) {
- return genSelectItemHTML({type: "empty"});
+ return `<button class="b3-menu__item av__relation-table-footer" data-relation-type="empty">
+ <span class="b3-menu__label">${window.siyuan.languages.emptyContent}</span>
+</button>`;
}
return "";
};
@@ -366,6 +370,7 @@ export const bindRelationEvent = (options: {
total: 0,
keyword: "",
loading: false,
+ columns: [] as IAVColumn[],
controller: undefined as AbortController | undefined,
};
let searchTimer: number;
@@ -421,38 +426,69 @@ export const bindRelationEvent = (options: {
}
});
};
- const renderPage = (cells: IAVCellValue[], reset: boolean) => {
- let excludedIDs: Set<string>;
- let selectedHTML = "";
- if (reset) {
- const selected = genSelectedItemsHTML(options.cellElements[0], state.keyword);
- excludedIDs = selected.selectedIDs;
- selectedHTML = selected.html;
- } else {
- excludedIDs = new Set(Array.from(listElement.querySelectorAll(
- '[data-relation-type="selected"], [data-relation-type="candidate"]'
- )).map((item: HTMLElement) => item.dataset.rowId));
+ const getSelectedItems = () => {
+ const selectedRows = listElement.querySelectorAll('[data-relation-type="selected"]');
+ if (selectedRows.length > 0 || listElement.querySelector('[data-relation-type="header"]')) {
+ return Array.from(selectedRows).map((item: HTMLElement) => {
+ const blockElement = item.querySelector(".b3-menu__label") as HTMLElement;
+ return {
+ id: item.dataset.rowId,
+ blockID: blockElement.dataset.id,
+ content: blockElement.textContent,
+ isDetached: !blockElement.classList.contains("popover__block"),
+ };
+ });
}
- const candidateHTML = genCandidateItemsHTML(cells, excludedIDs);
+ return Array.from(options.cellElements[0].querySelectorAll(".av__cell--relation")).
+ map((item: HTMLElement) => {
+ const blockElement = item.querySelector(".av__celltext") as HTMLElement;
+ return {
+ id: item.dataset.rowId,
+ blockID: blockElement.dataset.id,
+ content: blockElement.textContent,
+ isDetached: !blockElement.classList.contains("av__celltext--ref"),
+ };
+ });
+ };
+ const renderFooter = (hasCandidates: boolean) => {
+ listElement.querySelector('[data-relation-type="create"], [data-relation-type="empty"]')?.remove();
const more = hasMore();
listElement.dataset.hasMore = more.toString();
+ const footerHTML = genRelationFooterHTML(options.menuElement, state.keyword, hasCandidates, more);
+ if (footerHTML) {
+ listElement.querySelector('[data-relation-type="loader"]').insertAdjacentHTML("beforebegin", footerHTML);
+ }
+ };
+ const renderPage = (data: {
+ columns: IAVColumn[],
+ selectedRows: IAVRow[],
+ rows: IAVRow[]
+ }, reset: boolean) => {
+ state.columns = data.columns || state.columns;
+ const gridTemplate = getRelationGridTemplate(state.columns);
+ const excludedIDs = new Set(Array.from(listElement.querySelectorAll(
+ '[data-relation-type="selected"], [data-relation-type="candidate"]'
+ )).map((item: HTMLElement) => item.dataset.rowId));
+ let candidateHTML = "";
if (reset) {
- listElement.innerHTML = `${selectedHTML}
-<button class="b3-menu__separator" data-relation-type="separator"></button>
-${candidateHTML}
-${genRelationFooterHTML(options.menuElement, state.keyword, !!candidateHTML, more)}
+ excludedIDs.clear();
+ const selectedHTML = genRelationRowsHTML(data.selectedRows || [], state.columns, "selected",
+ gridTemplate, excludedIDs);
+ candidateHTML = genRelationRowsHTML(data.rows || [], state.columns, "candidate", gridTemplate, excludedIDs);
+ listElement.innerHTML = `${genRelationHeaderHTML(state.columns, gridTemplate)}
+<div class="av__relation-table-selected" data-relation-type="selectedRows">${selectedHTML}</div>
+<div class="b3-menu__separator" data-relation-type="separator"></div>
+<div class="av__relation-table-candidates" data-relation-type="candidateRows">${candidateHTML}</div>
${genRelationLoaderHTML(state.loading)}`;
} else {
+ candidateHTML = genRelationRowsHTML(data.rows || [], state.columns, "candidate", gridTemplate, excludedIDs);
if (candidateHTML) {
- listElement.querySelector('[data-relation-type="empty"]')?.remove();
- const anchorElement = listElement.querySelector('[data-relation-type="create"], [data-relation-type="loader"]');
- anchorElement.insertAdjacentHTML("beforebegin", candidateHTML);
- } else if (!state.keyword && !more && !listElement.querySelector('[data-relation-type="candidate"], [data-relation-type="empty"]')) {
- listElement.querySelector('[data-relation-type="loader"]').insertAdjacentHTML("beforebegin", genSelectItemHTML({type: "empty"}));
+ listElement.querySelector('[data-relation-type="candidateRows"]').insertAdjacentHTML("beforeend", candidateHTML);
}
}
+ renderFooter(!!listElement.querySelector('[data-relation-type="candidate"]'));
if (!listElement.querySelector(".b3-menu__item--current")) {
- listElement.querySelector(".b3-menu__item:not(.fn__none)")?.classList.add("b3-menu__item--current");
+ listElement.querySelector('[data-type="setRelationCell"]')?.classList.add("b3-menu__item--current");
}
updateCopyRelatedItems(options.menuElement);
};
@@ -470,30 +506,60 @@ ${genRelationLoaderHTML(state.loading)}`;
const page = reset ? 1 : state.page + 1;
const keyword = state.keyword;
const controller = new AbortController();
+ const selectedItems = getSelectedItems();
state.controller = controller;
state.loading = true;
setLoading(true);
let succeeded = false;
- fetchPost("/api/av/getAttributeViewPrimaryKeyValues", {
+ fetchPost("/api/av/getAttributeViewRelationCandidates", {
id: options.menuElement.firstElementChild.getAttribute("data-av-id"),
keyword,
page,
pageSize: RELATION_PAGE_SIZE,
+ selectedBlockIDs: selectedItems.map((item) => item.id),
}, response => {
if (controller.signal.aborted || keyword !== state.keyword) {
return;
}
- const cells = response.data.rows?.values as IAVCellValue[] || [];
+ const rows = response.data.rows as IAVRow[] || [];
state.page = page;
state.total = typeof response.data.total === "number" ? response.data.total :
- (page - 1) * RELATION_PAGE_SIZE + cells.length + (cells.length === RELATION_PAGE_SIZE ? 1 : 0);
+ (page - 1) * RELATION_PAGE_SIZE + rows.length + (rows.length === RELATION_PAGE_SIZE ? 1 : 0);
const databaseName = inputElement.parentElement.parentElement.querySelector(".popover__block");
databaseName.textContent = response.data.name;
databaseName.setAttribute("data-id", response.data.blockIDs?.[0] || "");
- renderPage(cells, reset);
+ const columns = response.data.columns as IAVColumn[] || [];
+ const selectedRowsByID = new Map<string, IAVRow>((response.data.selectedRows as IAVRow[] || []).
+ map((row) => [row.id, row]));
+ const selectedRows: IAVRow[] = selectedItems.map((item) => {
+ return selectedRowsByID.get(item.id) || {
+ id: item.id,
+ cells: [{
+ id: "",
+ color: "",
+ bgColor: "",
+ valueType: "block",
+ value: {
+ keyID: columns[0]?.id,
+ blockID: item.id,
+ type: "block",
+ isDetached: item.isDetached,
+ block: {
+ id: item.blockID,
+ content: item.content,
+ }
+ }
+ }]
+ } as IAVRow;
+ });
+ renderPage({
+ columns,
+ selectedRows,
+ rows,
+ }, reset);
setLoading(false);
let listHeightChanged = false;
- if (listNaturalMaxHeight < 1 && (keyword === "" || cells.length === RELATION_PAGE_SIZE)) {
+ if (listNaturalMaxHeight < 1 && (keyword === "" || rows.length === RELATION_PAGE_SIZE)) {
listNaturalMaxHeight = listElement.scrollHeight;
if (listNaturalMaxHeight > 0) {
listHeightChanged = updateListMaxHeight();
@@ -557,6 +623,10 @@ ${genRelationLoaderHTML(state.loading)}`;
loadPage(false);
}
});
+ const refresh = () => {
+ loadPage(true);
+ };
+ options.menuElement.addEventListener("relationrefresh", refresh);
options.menuElement.querySelector('[data-type="copyRelatedItems"]').addEventListener("click", () => {
let copyText = "";
const selectedElements = options.menuElement.querySelectorAll('.b3-menu__item[draggable="true"]');
@@ -581,6 +651,7 @@ ${genRelationLoaderHTML(state.loading)}`;
return () => {
state.controller?.abort();
window.removeEventListener("resize", resize);
+ options.menuElement.removeEventListener("relationrefresh", refresh);
if (searchTimer) {
clearTimeout(searchTimer);
}
@@ -596,7 +667,7 @@ export const getRelationHTML = (data: IAV, cellElements?: HTMLElement[]) => {
}
});
if (colRelationData && colRelationData.avID) {
- return `<div data-av-id="${colRelationData.avID}" class="fn__flex-column">
+ return `<div data-av-id="${colRelationData.avID}" class="fn__flex-column av__relation">
<div class="b3-menu__item" data-type="nobg">
<div class="b3-form__icona fn__flex-1" style="overflow: visible">
<input class="b3-text-field fn__block" style="min-width: 190px"/>
@@ -605,7 +676,7 @@ export const getRelationHTML = (data: IAV, cellElements?: HTMLElement[]) => {
<span class="fn__space"></span>
<span style="color: var(--b3-protyle-inline-blockref-color);max-width: 200px" data-id="" class="popover__block fn__pointer fn__ellipsis"></span>
</div>
-<div class="b3-menu__items">
+<div class="b3-menu__items av__relation-table">
${genRelationLoaderHTML(true)}
</div>`;
} else {
@@ -613,6 +684,39 @@ export const getRelationHTML = (data: IAV, cellElements?: HTMLElement[]) => {
}
};
+const getRelationValue = (menuElement: HTMLElement) => {
+ const value: IAVCellRelationValue = {blockIDs: [], contents: []};
+ menuElement.querySelectorAll('[data-relation-type="selected"]').forEach((item: HTMLElement) => {
+ const blockElement = item.querySelector(".b3-menu__label") as HTMLElement;
+ value.blockIDs.push(item.dataset.rowId);
+ value.contents.push({
+ type: "block",
+ block: {
+ id: blockElement.dataset.id,
+ content: blockElement.textContent
+ },
+ isDetached: !blockElement.classList.contains("popover__block")
+ });
+ });
+ return value;
+};
+
+const genCreatedRelationRowHTML = (menuElement: HTMLElement, rowID: string, content: string) => {
+ const headerElement = menuElement.querySelector('[data-relation-type="header"]') as HTMLElement;
+ const columnCount = headerElement?.querySelectorAll(".av__relation-table-cell").length || 1;
+ let cellsHTML = `<span class="av__relation-table-cell av__relation-table-primary" data-row-id="${rowID}">
+ <svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
+ <span class="b3-menu__label fn__ellipsis" data-id="">${Lute.EscapeHTMLStr(content)}</span>
+</span>`;
+ for (let i = 1; i < columnCount; i++) {
+ cellsHTML += '<span class="av__relation-table-cell"></span>';
+ }
+ return `<div data-row-id="${rowID}" data-position="west" data-type="setRelationCell"
+data-relation-type="selected" class="b3-menu__item av__relation-table-row" draggable="true"
+style="grid-template-columns:${headerElement?.style.gridTemplateColumns || "32px 240px"}">
+<span class="av__relation-table-check"><svg><use xlink:href="#iconCheck"></use></svg></span>${cellsHTML}</div>`;
+};
+
export const setRelationCell = async (protyle: IProtyle, nodeElement: HTMLElement, target: HTMLElement, cellElements: HTMLElement[]) => {
const menuElement = hasClosestByClassName(target, "b3-menu");
if (!menuElement) {
@@ -633,78 +737,30 @@ export const setRelationCell = async (protyle: IProtyle, nodeElement: HTMLElemen
}
}
- const newValue: IAVCellRelationValue = {blockIDs: [], contents: []};
- menuElement.querySelectorAll('[draggable="true"]').forEach(item => {
- const rowId = item.getAttribute("data-row-id");
- const blockPopElement = item.querySelector(".b3-menu__label");
- newValue.blockIDs.push(rowId);
- newValue.contents.push({
- type: "block",
- block: {
- id: blockPopElement.getAttribute("data-id"),
- content: blockPopElement.textContent
- },
- isDetached: !blockPopElement.classList.contains("popover__block")
- });
- });
if (target.classList.contains("b3-menu__item")) {
const rowId = target.getAttribute("data-row-id");
- const id = target.querySelector(".b3-menu__label").getAttribute("data-id");
- const separatorElement = menuElement.querySelector(".b3-menu__separator");
- const listElement = separatorElement.parentElement;
- const searchValue = menuElement.querySelector("input").value;
- if (target.getAttribute("draggable")) {
- listElement.querySelector('[data-relation-type="empty"]')?.remove();
- const removeIndex = newValue.blockIDs.indexOf(rowId);
- newValue.blockIDs.splice(removeIndex, 1);
- newValue.contents.splice(removeIndex, 1);
- separatorElement.after(target);
- target.outerHTML = genSelectItemHTML({
- type: "unselect",
- rowId,
- id,
- isDetached: !target.querySelector(".popover__block"),
- text: Lute.EscapeHTMLStr(target.querySelector(".b3-menu__label").textContent),
- className: target.className
- });
- updateCellsValue(protyle, nodeElement, newValue, cellElements);
+ if (target.dataset.relationType === "selected") {
+ target.remove();
+ updateCellsValue(protyle, nodeElement, getRelationValue(menuElement), cellElements);
+ menuElement.dispatchEvent(new CustomEvent("relationrefresh"));
} else if (rowId) {
- newValue.blockIDs.push(rowId);
- newValue.contents.push({
- type: "block",
- block: {
- id,
- content: target.firstElementChild.textContent
- },
- isDetached: !target.firstElementChild.getAttribute("style")
- });
- separatorElement.before(target);
- target.outerHTML = `<button data-row-id="${rowId}" data-position="west" data-type="setRelationCell" data-relation-type="selected" class="${target.className}"
-draggable="true">${genSelectItemHTML({
- type: "selected",
- rowId,
- id,
- isDetached: !target.querySelector(".popover__block"),
- text: Lute.EscapeHTMLStr(target.querySelector(".b3-menu__label").textContent)
- })}</button>`;
- if (!searchValue && listElement.dataset.hasMore !== "true" &&
- !listElement.querySelector('[data-relation-type="candidate"], [data-relation-type="empty"]')) {
- listElement.querySelector('[data-relation-type="loader"]').insertAdjacentHTML("beforebegin", genSelectItemHTML({type: "empty"}));
- }
- updateCellsValue(protyle, nodeElement, newValue, cellElements);
+ target.dataset.relationType = "selected";
+ target.setAttribute("draggable", "true");
+ target.querySelector(".av__relation-table-check use").setAttribute("xlink:href", "#iconCheck");
+ const primaryElement = target.querySelector(".av__relation-table-primary");
+ primaryElement.insertAdjacentHTML("afterbegin",
+ '<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>');
+ menuElement.querySelector('[data-relation-type="selectedRows"]').append(target);
+ updateCellsValue(protyle, nodeElement, getRelationValue(menuElement), cellElements);
+ menuElement.dispatchEvent(new CustomEvent("relationrefresh"));
} else {
const blockID = target.querySelector(".popover__block").getAttribute("data-id");
const content = target.querySelector("b").textContent;
const rowId = Lute.NewNodeID();
const bodyElement = hasClosestByClassName(cellElements[0], "av__body");
- newValue.blockIDs.push(rowId);
- newValue.contents.push({
- type: "block",
- block: {
- content
- },
- isDetached: true
- });
+ menuElement.querySelector('[data-relation-type="selectedRows"]').insertAdjacentHTML(
+ "beforeend", genCreatedRelationRowHTML(menuElement, rowId, content));
+ const newValue = getRelationValue(menuElement);
const updateOptions = await updateCellsValue(protyle, nodeElement, newValue, cellElements, null, null, true);
const doOperations: IOperation[] = [{
action: "insertAttrViewBlock",
@@ -723,13 +779,6 @@ draggable="true">${genSelectItemHTML({
id: blockID,
data: dayjs().format("YYYYMMDDHHmmss"),
}];
- separatorElement.insertAdjacentHTML("beforebegin", `<button data-row-id="${rowId}" data-position="west" data-type="setRelationCell"
-data-relation-type="selected" class="${target.className} ariaLabel" draggable="true">${genSelectItemHTML({
- type: "selected",
- rowId,
- isDetached: true,
- text: Lute.EscapeHTMLStr(content)
- })}</button>`);
transaction(protyle, doOperations.concat(updateOptions.doOperations));
}
}
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 04113c19fc..aaf5094a92 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -1932,6 +1932,48 @@
* `data.blockIDs`: このデータベースを参照する全データベースブロック(ミラー)の ID
* `data.total`: フィルタリング後、ページング前の主キー値の数
+### リレーション候補アイテムを取得
+
+* `/api/av/getAttributeViewRelationCandidates`
+* パラメータ
+
+ ```json
+ {
+ "id": "20240118120204-kwyzf77",
+ "keyword": "",
+ "page": 1,
+ "pageSize": 16,
+ "selectedBlockIDs": ["20240118203831-fkfvvtx"]
+ }
+ ```
+
+ * `id`:データベース ID
+ * `keyword`:任意の検索テキスト。空白で区切られたキーワードは同じフィールド内にすべて含まれる必要があり、すべてのフィールドが検索対象になります
+ * `page`:候補アイテムのページ番号。`1` から始まり、既定値は `1` です
+ * `pageSize`:1 ページあたりの候補アイテム数。`-1` または省略時は `16` です
+ * `selectedBlockIDs`:任意の選択済みアイテムの行 ID。`selectedRows` では指定した順序が維持されます
+* 戻り値
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "name": "データベース",
+ "blockIDs": ["20240118120201-kldj15t"],
+ "columns": [],
+ "selectedRows": [],
+ "rows": [],
+ "total": 0
+ }
+ }
+ ```
+
+ * `columns`:行番号を除くデータベースの全フィールド。主キーが先頭です
+ * `selectedRows`:`selectedBlockIDs` に対応する完全なレンダリング済み行。`keyword` とページングの影響を受けません
+ * `rows`:`keyword` に一致する候補行。作成日時の降順で並びます
+ * `total`:ページング前に `keyword` と一致した候補行の総数
+
### 検索
* `/api/av/searchAttributeView`
diff --git a/docs/API.md b/docs/API.md
index 561d7d6c5c..5d660f9e92 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1943,6 +1943,48 @@ The field types (`keyType`) are:
* `data.blockIDs`: IDs of all database blocks (mirrors) that reference this database
* `data.total`: Number of primary-key values after filtering and before pagination
+### Get relation candidates
+
+* `/api/av/getAttributeViewRelationCandidates`
+* Parameters
+
+ ```json
+ {
+ "id": "20240118120204-kwyzf77",
+ "keyword": "",
+ "page": 1,
+ "pageSize": 16,
+ "selectedBlockIDs": ["20240118203831-fkfvvtx"]
+ }
+ ```
+
+ * `id`: Database ID
+ * `keyword`: Optional search text. Space-separated terms must all occur in the same field; all fields are searched
+ * `page`: Candidate page number, 1-based. Defaults to `1`
+ * `pageSize`: Candidates per page. `-1` or omitted means `16`
+ * `selectedBlockIDs`: Optional row IDs of selected items. Their order is preserved in `selectedRows`
+* Return value
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "name": "Database",
+ "blockIDs": ["20240118120201-kldj15t"],
+ "columns": [],
+ "selectedRows": [],
+ "rows": [],
+ "total": 0
+ }
+ }
+ ```
+
+ * `columns`: All database fields except line numbers, with the primary key first
+ * `selectedRows`: Complete rendered rows matching `selectedBlockIDs`; not affected by `keyword` or pagination
+ * `rows`: Candidate rows matching `keyword`, sorted by creation time descending
+ * `total`: Total number of candidate rows matching `keyword` before pagination
+
### Search
* `/api/av/searchAttributeView`
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 8c15e4cf7c..5ce6f832a0 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -1932,6 +1932,48 @@
* `data.blockIDs`: 引用该数据库的所有数据库块(镜像)ID
* `data.total`: 过滤后、分页前的主键值数量
+### 获取关系候选条目
+
+* `/api/av/getAttributeViewRelationCandidates`
+* 参数
+
+ ```json
+ {
+ "id": "20240118120204-kwyzf77",
+ "keyword": "",
+ "page": 1,
+ "pageSize": 16,
+ "selectedBlockIDs": ["20240118203831-fkfvvtx"]
+ }
+ ```
+
+ * `id`:数据库 ID
+ * `keyword`:可选搜索文本。以空格分隔的关键词必须同时出现在同一个字段中,搜索范围为全部字段
+ * `page`:候选条目页码,从 `1` 开始,默认为 `1`
+ * `pageSize`:每页候选条目数,传入 `-1` 或省略时默认为 `16`
+ * `selectedBlockIDs`:可选的已选条目行 ID,`selectedRows` 会保留其顺序
+* 返回值
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "name": "数据库",
+ "blockIDs": ["20240118120201-kldj15t"],
+ "columns": [],
+ "selectedRows": [],
+ "rows": [],
+ "total": 0
+ }
+ }
+ ```
+
+ * `columns`:数据库的全部字段,不包含行号,主键位于第一列
+ * `selectedRows`:与 `selectedBlockIDs` 对应的完整渲染行,不受 `keyword` 和分页影响
+ * `rows`:与 `keyword` 匹配的候选行,按创建时间降序排列
+ * `total`:分页前与 `keyword` 匹配的候选行总数
+
### 搜索
* `/api/av/searchAttributeView`
diff --git a/kernel/api/av.go b/kernel/api/av.go
index ca7a4f8fe0..83ddd96e7d 100644
--- a/kernel/api/av.go
+++ b/kernel/api/av.go
@@ -453,6 +453,54 @@ func getAttributeViewPrimaryKeyValues(c *gin.Context) {
}
}
+func getAttributeViewRelationCandidates(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ id := arg["id"].(string)
+ keyword := ""
+ if keywordArg := arg["keyword"]; nil != keywordArg {
+ keyword = keywordArg.(string)
+ }
+ page := 1
+ if pageArg := arg["page"]; nil != pageArg {
+ page = int(pageArg.(float64))
+ }
+ pageSize := -1
+ if pageSizeArg := arg["pageSize"]; nil != pageSizeArg {
+ pageSize = int(pageSizeArg.(float64))
+ }
+ var selectedBlockIDs []string
+ if selectedBlockIDsArg, ok := arg["selectedBlockIDs"].([]any); ok {
+ for _, selectedBlockIDArg := range selectedBlockIDsArg {
+ if selectedBlockID, ok := selectedBlockIDArg.(string); ok && "" != selectedBlockID {
+ selectedBlockIDs = append(selectedBlockIDs, selectedBlockID)
+ }
+ }
+ }
+
+ name, blockIDs, columns, selectedRows, rows, total, err := model.GetAttributeViewRelationCandidates(
+ id, keyword, selectedBlockIDs, page, pageSize)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = map[string]any{
+ "name": name,
+ "blockIDs": blockIDs,
+ "columns": columns,
+ "selectedRows": selectedRows,
+ "rows": rows,
+ "total": total,
+ }
+}
+
func appendAttributeViewDetachedBlocksWithValues(c *gin.Context) {
// Add an internal kernel API `/api/av/appendAttributeViewDetachedBlocksWithValues` https://github.com/siyuan-note/siyuan/issues/11608
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 1d85494f1f..e75cdb3961 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -549,6 +549,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/av/addAttributeViewBlocks", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, addAttributeViewBlocks)
ginServer.Handle("POST", "/api/av/removeAttributeViewBlocks", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeAttributeViewBlocks)
ginServer.Handle("POST", "/api/av/getAttributeViewPrimaryKeyValues", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getAttributeViewPrimaryKeyValues)
+ ginServer.Handle("POST", "/api/av/getAttributeViewRelationCandidates", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getAttributeViewRelationCandidates)
ginServer.Handle("POST", "/api/av/setDatabaseBlockView", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setDatabaseBlockView)
ginServer.Handle("POST", "/api/av/getMirrorDatabaseBlocks", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getMirrorDatabaseBlocks)
ginServer.Handle("POST", "/api/av/getAttributeViewKeysByAvID", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getAttributeViewKeysByAvID)
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 486af811ed..84a0ba5b6f 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -2056,6 +2056,176 @@ func GetAttributeViewPrimaryKeyValues(avID, keyword string, blockIDs []string, p
return
}
+func GetAttributeViewRelationCandidates(avID, keyword string, selectedBlockIDs []string, page, pageSize int) (
+ attributeViewName string, databaseBlockIDs []string, columns []*av.TableColumn, selectedRows, rows []*av.TableRow,
+ total int, err error,
+) {
+ waitForSyncingStorages()
+
+ attrView, err := av.ParseAttributeView(avID)
+ if err != nil {
+ logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
+ return
+ }
+ attributeViewName = getAttrViewName(attrView)
+ databaseBlockIDs = treenode.GetMirrorAttrViewBlockIDs(avID)
+
+ table := renderAttributeViewRelationCandidates(attrView)
+ if nil == table {
+ err = av.ErrViewNotFound
+ return
+ }
+ columns = table.Columns
+
+ rowsByID := map[string]*av.TableRow{}
+ for _, row := range table.Rows {
+ rowsByID[row.ID] = row
+ }
+ for _, blockID := range selectedBlockIDs {
+ if row := rowsByID[blockID]; nil != row {
+ selectedRows = append(selectedRows, row)
+ }
+ }
+ if nil == selectedRows {
+ selectedRows = []*av.TableRow{}
+ }
+
+ rows, total = filterSortPageRelationCandidates(table.Rows, keyword, page, pageSize)
+ return
+}
+
+func filterSortPageRelationCandidates(tableRows []*av.TableRow, keyword string, page, pageSize int) (
+ rows []*av.TableRow, total int,
+) {
+ for _, row := range tableRows {
+ if relationCandidateMatches(row, keyword) {
+ rows = append(rows, row)
+ }
+ }
+ sort.Slice(rows, func(i, j int) bool {
+ iCreated := relationCandidateCreatedAt(rows[i])
+ jCreated := relationCandidateCreatedAt(rows[j])
+ if iCreated == jCreated {
+ return rows[i].ID > rows[j].ID
+ }
+ return iCreated > jCreated
+ })
+
+ total = len(rows)
+ if 1 > page {
+ page = 1
+ }
+ if 1 > pageSize {
+ pageSize = 16
+ }
+ start := min(len(rows), (page-1)*pageSize)
+ end := min(len(rows), start+pageSize)
+ rows = rows[start:end]
+ if nil == rows {
+ rows = []*av.TableRow{}
+ }
+ return
+}
+
+func renderAttributeViewRelationCandidates(attrView *av.AttributeView) (ret *av.Table) {
+ if nil == attrView {
+ return
+ }
+
+ keysByID := map[string]*av.Key{}
+ for _, keyValues := range attrView.KeyValues {
+ if nil != keyValues && nil != keyValues.Key {
+ keysByID[keyValues.Key.ID] = keyValues.Key
+ }
+ }
+
+ var keys []*av.Key
+ added := map[string]bool{}
+ if blockKey := attrView.GetBlockKey(); nil != blockKey {
+ keys = append(keys, blockKey)
+ added[blockKey.ID] = true
+ }
+ appendKey := func(key *av.Key) {
+ if nil == key || added[key.ID] || av.KeyTypeLineNumber == key.Type {
+ return
+ }
+ keys = append(keys, key)
+ added[key.ID] = true
+ }
+ for _, keyID := range attrView.KeyIDs {
+ appendKey(keysByID[keyID])
+ }
+ for _, keyValues := range attrView.KeyValues {
+ if nil != keyValues {
+ appendKey(keyValues.Key)
+ }
+ }
+
+ view := &av.View{
+ ID: ast.NewNodeID(),
+ Filters: []*av.ViewFilter{},
+ Sorts: []*av.ViewSort{},
+ PageSize: av.ViewDefaultPageSize,
+ LayoutType: av.LayoutTypeTable,
+ Table: av.NewLayoutTable(),
+ }
+ for _, key := range keys {
+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{
+ BaseField: &av.BaseField{ID: key.ID},
+ })
+ }
+
+ viewable := sql.RenderView(attrView, view, "", false)
+ ret, _ = viewable.(*av.Table)
+ return
+}
+
+func relationCandidateMatches(row *av.TableRow, keyword string) bool {
+ keywords := strings.Fields(strings.TrimSpace(keyword))
+ if 1 > len(keywords) {
+ return true
+ }
+ for _, cell := range row.Cells {
+ if nil == cell || nil == cell.Value {
+ continue
+ }
+ content := cell.Value.String(true)
+ allKeywordsHit := true
+ for _, currentKeyword := range keywords {
+ if util.SearchCaseSensitive {
+ if !strings.Contains(content, currentKeyword) {
+ allKeywordsHit = false
+ break
+ }
+ } else if !strings.Contains(strings.ToLower(content), strings.ToLower(currentKeyword)) {
+ allKeywordsHit = false
+ break
+ }
+ }
+ if allKeywordsHit {
+ return true
+ }
+ }
+ return false
+}
+
+func relationCandidateCreatedAt(row *av.TableRow) int64 {
+ if nil == row {
+ return 0
+ }
+ blockValue := row.GetBlockValue()
+ if nil == blockValue {
+ return 0
+ }
+ if 0 < blockValue.CreatedAt {
+ return blockValue.CreatedAt
+ }
+ if nil != blockValue.Block {
+ return blockValue.Block.Created
+ }
+ return 0
+}
+
func GetAttributeViewFilterSort(avID, blockID string) (filters []*av.ViewFilter, sorts []*av.ViewSort) {
waitForSyncingStorages()
diff --git a/kernel/model/attribute_view_relation_test.go b/kernel/model/attribute_view_relation_test.go
new file mode 100644
index 0000000000..9c12cb5366
--- /dev/null
+++ b/kernel/model/attribute_view_relation_test.go
@@ -0,0 +1,97 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+func TestRenderAttributeViewRelationCandidates(t *testing.T) {
+ attrView, alphaID, betaID := newRelationCandidateTestAttributeView()
+
+ table := renderAttributeViewRelationCandidates(attrView)
+ if 3 != len(table.Columns) {
+ t.Fatalf("line number columns should be excluded, got %d columns", len(table.Columns))
+ }
+ if av.KeyTypeBlock != table.Columns[0].Type || "Text" != table.Columns[1].Name || "Number" != table.Columns[2].Name {
+ t.Fatalf("unexpected relation candidate columns: %+v", table.Columns)
+ }
+ if 2 != len(table.Rows) {
+ t.Fatalf("expected two candidate rows, got %d", len(table.Rows))
+ }
+
+ var selectedRows, rows []*av.TableRow
+ for _, row := range table.Rows {
+ if row.ID == betaID {
+ selectedRows = append(selectedRows, row)
+ }
+ if relationCandidateMatches(row, "alpha red") {
+ rows = append(rows, row)
+ }
+ }
+ if 1 != len(selectedRows) || betaID != selectedRows[0].ID {
+ t.Fatalf("unexpected selected rows: %+v", selectedRows)
+ }
+ if 1 != len(rows) || alphaID != rows[0].ID {
+ t.Fatalf("search should match multiple keywords in one field: %+v", rows)
+ }
+}
+
+func TestRelationCandidateOrderingAndPaging(t *testing.T) {
+ attrView, alphaID, betaID := newRelationCandidateTestAttributeView()
+ table := renderAttributeViewRelationCandidates(attrView)
+ rows, total := filterSortPageRelationCandidates(table.Rows, "", 1, 1)
+ if 2 != total || 1 != len(rows) || betaID != rows[0].ID {
+ t.Fatalf("the first page should contain the newest candidate: total=%d rows=%+v", total, rows)
+ }
+
+ rows, total = filterSortPageRelationCandidates(table.Rows, "", 2, 1)
+ if 2 != total || 1 != len(rows) || alphaID != rows[0].ID {
+ t.Fatalf("the second page should contain the older candidate: total=%d rows=%+v", total, rows)
+ }
+
+ rows, total = filterSortPageRelationCandidates(table.Rows, "blue", 1, 16)
+ if 1 != total || 1 != len(rows) || betaID != rows[0].ID {
+ t.Fatalf("search should inspect all fields: total=%d rows=%+v", total, rows)
+ }
+}
+
+func newRelationCandidateTestAttributeView() (attrView *av.AttributeView, alphaID, betaID string) {
+ blockKey := av.NewKey(ast.NewNodeID(), "Primary", "", av.KeyTypeBlock)
+ textKey := av.NewKey(ast.NewNodeID(), "Text", "", av.KeyTypeText)
+ numberKey := av.NewKey(ast.NewNodeID(), "Number", "", av.KeyTypeNumber)
+ lineNumberKey := av.NewKey(ast.NewNodeID(), "Line number", "", av.KeyTypeLineNumber)
+ alphaID, betaID = ast.NewNodeID(), ast.NewNodeID()
+
+ attrView = &av.AttributeView{
+ ID: ast.NewNodeID(),
+ KeyValues: []*av.KeyValues{
+ {Key: blockKey, Values: []*av.Value{
+ {ID: ast.NewNodeID(), KeyID: blockKey.ID, BlockID: alphaID, Type: av.KeyTypeBlock, IsDetached: true,
+ CreatedAt: 100, Block: &av.ValueBlock{Content: "Alpha"}},
+ {ID: ast.NewNodeID(), KeyID: blockKey.ID, BlockID: betaID, Type: av.KeyTypeBlock, IsDetached: true,
+ CreatedAt: 200, Block: &av.ValueBlock{Content: "Beta"}},
+ }},
+ {Key: textKey, Values: []*av.Value{
+ {ID: ast.NewNodeID(), KeyID: textKey.ID, BlockID: alphaID, Type: av.KeyTypeText,
+ Text: &av.ValueText{Content: "Alpha red"}},
+ {ID: ast.NewNodeID(), KeyID: textKey.ID, BlockID: betaID, Type: av.KeyTypeText,
+ Text: &av.ValueText{Content: "Beta blue"}},
+ }},
+ {Key: numberKey},
+ {Key: lineNumberKey},
+ },
+ KeyIDs: []string{textKey.ID, lineNumberKey.ID, blockKey.ID, numberKey.ID},
+ RenderedViewables: map[string]av.Viewable{},
+ }
+ return
+}