An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support custom colors for database select and multi-select options https://github.com/siyuan-note/siyuan/issues/18931
Daniela3fb894871a7
diff --git a/app/src/dialog/themeColorEditor.ts b/app/src/dialog/themeColorEditor.tsnew file mode 100644index 0000000000..2831e0a9f9--- /dev/null+++ b/app/src/dialog/themeColorEditor.ts@@ -0,0 +1,95 @@+export type TThemeColorEditorType = "color" | "backgroundColor" | "style1";++export interface IThemeColorValue {+ light: {+ color?: string,+ backgroundColor?: string,+ },+ dark: {+ color?: string,+ backgroundColor?: string,+ },+}++const DEFAULT_THEME_COLOR_VALUE: IThemeColorValue = {+ light: {+ color: "#000000",+ backgroundColor: "#fff3cd",+ },+ dark: {+ color: "#ffffff",+ backgroundColor: "#554b00",+ },+};++export const getThemeColorEditorHTML = () => `<div data-type="themeColorEditor" class="b3-label b3-label--inner fn__flex" style="align-items:flex-start;gap:24px;flex-wrap:wrap">+ <div class="fn__flex-1" style="min-width:200px">+ <div>${window.siyuan.languages.themeLight}</div>+ <label class="fn__flex" data-property="color" style="align-items:center;margin-top:8px">+ <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>+ <input class="b3-text-field" data-field="lightColor" type="color">+ </label>+ <label class="fn__flex" data-property="backgroundColor" style="align-items:center;margin-top:8px">+ <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>+ <input class="b3-text-field" data-field="lightBackgroundColor" type="color">+ </label>+ </div>+ <div class="fn__flex-1" style="min-width:200px">+ <div>${window.siyuan.languages.themeDark}</div>+ <label class="fn__flex" data-property="color" style="align-items:center;margin-top:8px">+ <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>+ <input class="b3-text-field" data-field="darkColor" type="color">+ </label>+ <label class="fn__flex" data-property="backgroundColor" style="align-items:center;margin-top:8px">+ <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>+ <input class="b3-text-field" data-field="darkBackgroundColor" type="color">+ </label>+ </div>+</div>`;++export const bindThemeColorEditor = (element: Element) => {+ const editorElement = element.matches('[data-type="themeColorEditor"]') ? element :+ element.querySelector('[data-type="themeColorEditor"]');+ const lightColorElement = editorElement.querySelector('[data-field="lightColor"]') as HTMLInputElement;+ const darkColorElement = editorElement.querySelector('[data-field="darkColor"]') as HTMLInputElement;+ const lightBackgroundElement = editorElement.querySelector('[data-field="lightBackgroundColor"]') as HTMLInputElement;+ const darkBackgroundElement = editorElement.querySelector('[data-field="darkBackgroundColor"]') as HTMLInputElement;++ const setType = (type: TThemeColorEditorType) => {+ editorElement.querySelectorAll<HTMLElement>('[data-property="color"]').forEach(item => {+ item.classList.toggle("fn__none", type === "backgroundColor");+ });+ editorElement.querySelectorAll<HTMLElement>('[data-property="backgroundColor"]').forEach(item => {+ item.classList.toggle("fn__none", type === "color");+ });+ };+ const setValue = (value: IThemeColorValue = DEFAULT_THEME_COLOR_VALUE, type: TThemeColorEditorType = "style1") => {+ lightColorElement.value = value.light.color || DEFAULT_THEME_COLOR_VALUE.light.color;+ darkColorElement.value = value.dark.color || DEFAULT_THEME_COLOR_VALUE.dark.color;+ lightBackgroundElement.value = value.light.backgroundColor || DEFAULT_THEME_COLOR_VALUE.light.backgroundColor;+ darkBackgroundElement.value = value.dark.backgroundColor || DEFAULT_THEME_COLOR_VALUE.dark.backgroundColor;+ setType(type);+ };+ const getValue = (type: TThemeColorEditorType = "style1"): IThemeColorValue => {+ const value: IThemeColorValue = {+ light: {},+ dark: {},+ };+ if (type !== "backgroundColor") {+ value.light.color = lightColorElement.value;+ value.dark.color = darkColorElement.value;+ }+ if (type !== "color") {+ value.light.backgroundColor = lightBackgroundElement.value;+ value.dark.backgroundColor = darkBackgroundElement.value;+ }+ return value;+ };++ setValue();+ return {+ getValue,+ setType,+ setValue,+ };+};diff --git a/app/src/protyle/render/av/attributePanel.ts b/app/src/protyle/render/av/attributePanel.tsindex 4acf2e969f..eaa256a496 100644--- a/app/src/protyle/render/av/attributePanel.ts+++ b/app/src/protyle/render/av/attributePanel.ts@@ -20,6 +20,7 @@ const refreshActions = new Set<TOperation>(["setAttrViewColIcon","setAttrViewColDesc","setAttrViewName",+ "setAttrViewCustomColors","updateAttrViewColNumberFormat","setAttrViewColDateFormat",]);diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.tsindex 150d34615e..56ae7a0753 100644--- a/app/src/protyle/render/av/attributeValue.ts+++ b/app/src/protyle/render/av/attributeValue.ts@@ -5,6 +5,7 @@ import {getCompressURL} from "../../../util/image";import {isBrowserRenderableImagePath} from "../../../util/imageURL";import {formatDateDisplay, formatDateValue} from "./dateFormat";import {getAVBlockRefSubtype} from "./cellValue";+import {getAVColorStyle} from "./color";export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: string) => ({type,@@ -138,7 +139,7 @@ export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat =if (value.type === "select" && index > 0) {return;}- html += `<span class="b3-chip b3-chip--middle" style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">${escapeHtml(item.content)}</span>`;+ html += `<span class="b3-chip b3-chip--middle" data-color="${escapeAttr(item.color)}" style="${getAVColorStyle(item)}">${escapeHtml(item.content)}</span>`;});break;case "mAsset":diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex 949ef59da0..7be7e8fd96 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -32,6 +32,7 @@ import {} from "./cellValue";import {setPosition} from "../../../util/setPosition";import {getAVSelectedCells, IAVSelectedCell, updateAVSelectedCellValue} from "./selectionState";+import {getAVColorStyle} from "./color";import {getAVBatchDisplayValue,getAVBatchEditMode,@@ -113,7 +114,7 @@ export const genCellValueByElement = (colType: TAVCol, cellElement: HTMLElement)cellElement.querySelectorAll(".b3-chip").forEach((item: HTMLElement) => {mSelect.push({content: item.textContent.trim(),- color: item.style.color.replace("var(--b3-font-color", "").replace(")", "")+ color: item.dataset.color || item.style.color.replace("var(--b3-font-color", "").replace(")", "")});});cellValue.mSelect = mSelect;@@ -1122,11 +1123,15 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = truif (cellValue.type === "select" && index > 0) {return;}- const desc = selectOptions?.find(option => option.name === item.content)?.desc;+ const option = selectOptions?.find(selectOption => selectOption.name === item.content);+ const desc = option?.desc;const tooltip = desc ?` data-position="north" aria-label="${escapeAriaLabel(item.content)}<div class='ft__on-surface'>${escapeAriaLabel(desc)}</div>"` :"";- text += `<span class="b3-chip${desc ? " ariaLabel" : ""}"${tooltip} style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">${escapeHtml(item.content)}</span>`;+ text += `<span class="b3-chip${desc ? " ariaLabel" : ""}"${tooltip} data-color="${escapeAttr(option ? option.color : item.color)}" style="${getAVColorStyle({+ color: option ? option.color : item.color,+ resolvedColor: option ? option.resolvedColor : item.resolvedColor,+ })}">${escapeHtml(item.content)}</span>`;});} else if (cellValue.type === "date") {const dataValue = cellValue ? cellValue.date : null;diff --git a/app/src/protyle/render/av/col.ts b/app/src/protyle/render/av/col.tsindex 13dcb12e04..3d1949d778 100644--- a/app/src/protyle/render/av/col.ts+++ b/app/src/protyle/render/av/col.ts@@ -23,6 +23,7 @@ import {openFieldVisibility} from "./fieldVisibility";import {createEmptyAVValue, genAVAttributeRowHTML} from "./attributeValue";import {getAVColumnTextMeasurer, getAVDistributedColumnWidth, getAVTableFitWidths} from "./columnWidth";import {getAVData} from "./virtualScroll";+import {getAVColorStyle, getNextAVOptionColor} from "./color";export const getColId = (element: Element, viewType: TAVView) => {if (viewType === "table" || hasClosestByClassName(element, "custom-attr")) {@@ -140,7 +141,7 @@ export const getEditHTML = (options: {html += `<button class="b3-menu__item${html ? "" : " b3-menu__item--current"}" draggable="true" data-name="${escapeAttr(item.name)}" data-desc="${escapeAttr(item.desc || "")}" data-color="${escapeAttr(item.color)}"><svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg><div class="fn__flex-1 ariaLabel" data-position="parentW" aria-label="${airaLabel}">- <span class="b3-chip" style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">+ <span class="b3-chip" style="${getAVColorStyle(item)}"><span class="fn__ellipsis">${escapeHtml(item.name)}</span></span></div>@@ -466,7 +467,7 @@ export const bindEditEvent = (options: {return;}colData.options.push({- color: ((colData.options.length || 0) % 14 + 1).toString(),+ color: getNextAVOptionColor(colData.options.length || 0),name: addOptionElement.value});transaction(options.protyle, [{diff --git a/app/src/protyle/render/av/color.test.ts b/app/src/protyle/render/av/color.test.tsnew file mode 100644index 0000000000..207c99b926--- /dev/null+++ b/app/src/protyle/render/av/color.test.ts@@ -0,0 +1,70 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ getAvailableAVCustomColorIndex,+ getAVBackgroundColor,+ getAVColorGridHTML,+ getAVColorStyle,+ getNextAVOptionColor,+ normalizeAVColorIndex,+} from "./color";++const customColor: IAVCustomColor = {+ index: 15,+ light: {+ color: "#112233",+ backgroundColor: "#ddeeff",+ },+ dark: {+ color: "#fefefe",+ backgroundColor: "#223344",+ },+};++describe("AV color indexes", () => {+ it("accepts only bounded decimal indexes", () => {+ assert.equal(normalizeAVColorIndex("15"), 15);+ assert.equal(normalizeAVColorIndex("15suffix"), 14);+ assert.equal(normalizeAVColorIndex(79), 14);+ });++ it("cycles new options through built-in colors", () => {+ assert.equal(getNextAVOptionColor(0), "1");+ assert.equal(getNextAVOptionColor(14), "1");+ });++ it("finds the first available custom index", () => {+ assert.equal(getAvailableAVCustomColorIndex([{index: 15}, {index: 17}]), 16);+ });+});++describe("AV resolved colors", () => {+ it("renders local light and dark chip colors", () => {+ assert.equal(getAVColorStyle({color: "15", resolvedColor: customColor}),+ "background-color:light-dark(#ddeeff, #223344);color:light-dark(#112233, #fefefe)");+ assert.equal(getAVBackgroundColor({color: "15", resolvedColor: customColor}),+ "light-dark(#ddeeff, #223344)");+ });++ it("uses numbered variables for built-ins and a neutral fallback for unresolved custom colors", () => {+ assert.equal(getAVColorStyle("13"),+ "background-color:var(--b3-font-background13);color:var(--b3-font-color13)");+ assert.equal(getAVColorStyle("42"),+ "background-color:var(--b3-font-background14);color:var(--b3-font-color14)");+ assert.equal(getAVBackgroundColor("42"), "var(--b3-font-background14)");+ assert.equal(getAVColorStyle({+ color: "15",+ resolvedColor: {+ ...customColor,+ light: {...customColor.light, backgroundColor: "red);background-image:url(javascript:alert(1))"},+ },+ }), "background-color:var(--b3-font-background14);color:var(--b3-font-color14)");+ });++ it("renders multi-digit custom swatches and the management entry", () => {+ const html = getAVColorGridHTML([customColor], "15", "Manage");+ assert.match(html, /data-color="15" class="color__square color__square--current"/);+ assert.match(html, /data-type="manageAVCustomColors"/);+ assert.match(html, /light-dark\(#ddeeff, #223344\)/);+ });+});diff --git a/app/src/protyle/render/av/color.ts b/app/src/protyle/render/av/color.tsnew file mode 100644index 0000000000..40220169af--- /dev/null+++ b/app/src/protyle/render/av/color.ts@@ -0,0 +1,124 @@+import {escapeAttr} from "../../../util/escape";++export const AV_BUILTIN_COLOR_COUNT = 14;+export const AV_CUSTOM_COLOR_MIN = 15;+export const AV_CUSTOM_COLOR_MAX = 78;+export const AV_CUSTOM_COLOR_LIMIT = 64;+export const AV_MANAGE_CUSTOM_COLORS_TYPE = "manageAVCustomColors";++type TAVColorReference = string | {+ color?: string,+ resolvedColor?: IAVColor,+};++const COLOR_PATTERN = /^#[0-9a-f]{6}$/i;++export const normalizeAVColorIndex = (color: string | number) => {+ const value = typeof color === "number" ? color.toString() : color;+ if (!/^\d+$/.test(value)) {+ return AV_BUILTIN_COLOR_COUNT;+ }+ const index = Number(value);+ return Number.isInteger(index) && index >= 1 && index <= AV_CUSTOM_COLOR_MAX ?+ index : AV_BUILTIN_COLOR_COUNT;+};++const getColorReference = (value: TAVColorReference) => typeof value === "string" ? {+ color: value,+ resolvedColor: undefined as IAVColor | undefined,+} : value;++const isResolvedColor = (color: IAVColor | undefined): color is IAVColor => !!color &&+ COLOR_PATTERN.test(color.light?.color) && COLOR_PATTERN.test(color.light?.backgroundColor) &&+ COLOR_PATTERN.test(color.dark?.color) && COLOR_PATTERN.test(color.dark?.backgroundColor);++const getModeColor = (light: string, dark: string) => `light-dark(${light}, ${dark})`;++export const getAVColorStyle = (value: TAVColorReference) => {+ const reference = getColorReference(value);+ if (isResolvedColor(reference.resolvedColor)) {+ return `background-color:${getModeColor(reference.resolvedColor.light.backgroundColor,+ reference.resolvedColor.dark.backgroundColor)};color:${getModeColor(reference.resolvedColor.light.color,+ reference.resolvedColor.dark.color)}`;+ }+ const normalizedIndex = normalizeAVColorIndex(reference.color || AV_BUILTIN_COLOR_COUNT);+ const index = normalizedIndex > AV_BUILTIN_COLOR_COUNT ? AV_BUILTIN_COLOR_COUNT : normalizedIndex;+ return `background-color:var(--b3-font-background${index});color:var(--b3-font-color${index})`;+};++export const getAVBackgroundColor = (value: TAVColorReference) => {+ const reference = getColorReference(value);+ if (isResolvedColor(reference.resolvedColor)) {+ return getModeColor(reference.resolvedColor.light.backgroundColor,+ reference.resolvedColor.dark.backgroundColor);+ }+ const index = normalizeAVColorIndex(reference.color || AV_BUILTIN_COLOR_COUNT);+ return `var(--b3-font-background${index > AV_BUILTIN_COLOR_COUNT ? AV_BUILTIN_COLOR_COUNT : index})`;+};++export const getNextAVOptionColor = (optionCount: number) =>+ (Math.max(0, optionCount) % AV_BUILTIN_COLOR_COUNT + 1).toString();++export const getAvailableAVCustomColorIndex = (colors: Pick<IAVCustomColor, "index">[]) => {+ const usedIndexes = new Set(colors.map(item => item.index));+ for (let index = AV_CUSTOM_COLOR_MIN; index <= AV_CUSTOM_COLOR_MAX; index++) {+ if (!usedIndexes.has(index)) {+ return index;+ }+ }+};++const normalizeAVCustomColors = (colors: IAVCustomColor[]) => colors+ .filter(item => item.index >= AV_CUSTOM_COLOR_MIN && item.index <= AV_CUSTOM_COLOR_MAX)+ .sort((a, b) => a.index - b.index)+ .slice(0, AV_CUSTOM_COLOR_LIMIT);++export const getAVCustomColors = (data: IAV | undefined) => normalizeAVCustomColors(data?.customColors || []);++export const getAVResolvedColor = (data: IAV | undefined, color: string) => {+ const index = normalizeAVColorIndex(color);+ return getAVCustomColors(data).find(item => item.index === index);+};++export const getAVColorGridHTML = (customColors: IAVCustomColor[], currentColor: string,+ manageLabel: string) => {+ const currentIndex = normalizeAVColorIndex(currentColor);+ const colors: TAVColorReference[] = Array.from({length: AV_BUILTIN_COLOR_COUNT}, (_, index) => ({+ color: (index + 1).toString(),+ }));+ normalizeAVCustomColors(customColors).forEach(item => {+ colors.push({+ color: item.index.toString(),+ resolvedColor: item,+ });+ });+ const colorHTML = colors.map(item => {+ const reference = getColorReference(item);+ const index = normalizeAVColorIndex(reference.color);+ return `<button data-color="${index}" class="color__square${currentIndex === index ?+ " color__square--current" : ""}" style="${getAVColorStyle(item)}">A</button>`;+ }).join("");+ return colorHTML + `<button data-type="${AV_MANAGE_CUSTOM_COLORS_TYPE}" class="color__square ariaLabel" ` ++ `aria-label="${escapeAttr(manageLabel)}"><svg><use xlink:href="#iconAdd"></use></svg></button>`;+};++const mountedPaletteIndexes = new WeakMap<HTMLElement, number[]>();++export const applyAVColorPalette = (element: HTMLElement, customColors: IAVCustomColor[] = []) => {+ mountedPaletteIndexes.get(element)?.forEach(index => {+ element.style.removeProperty(`--b3-font-color${index}`);+ element.style.removeProperty(`--b3-font-background${index}`);+ });+ const indexes: number[] = [];+ normalizeAVCustomColors(customColors).forEach(item => {+ if (!isResolvedColor(item)) {+ return;+ }+ indexes.push(item.index);+ element.style.setProperty(`--b3-font-color${item.index}`,+ getModeColor(item.light.color, item.dark.color));+ element.style.setProperty(`--b3-font-background${item.index}`,+ getModeColor(item.light.backgroundColor, item.dark.backgroundColor));+ });+ mountedPaletteIndexes.set(element, indexes);+};diff --git a/app/src/protyle/render/av/colorDialog.ts b/app/src/protyle/render/av/colorDialog.tsnew file mode 100644index 0000000000..a02170f6e1--- /dev/null+++ b/app/src/protyle/render/av/colorDialog.ts@@ -0,0 +1,203 @@+import {Dialog} from "../../../dialog";+import {confirmDialog} from "../../../dialog/confirmDialog";+import {showMessage} from "../../../dialog/message";+import {bindThemeColorEditor, getThemeColorEditorHTML} from "../../../dialog/themeColorEditor";+import {escapeAttr, escapeHtml} from "../../../util/escape";+import {isMobile} from "../../../util/functions";+import {transaction} from "../../wysiwyg/transaction";+import {+ AV_CUSTOM_COLOR_LIMIT,+ getAvailableAVCustomColorIndex,+ getAVColorStyle,+ getAVCustomColors,+} from "./color";+import {getInlineStyleType, getInlineStylesCache} from "../../toolbar/inlineStyle";+import * as dayjs from "dayjs";++const cloneCustomColors = (colors: IAVCustomColor[]) => JSON.parse(JSON.stringify(colors)) as IAVCustomColor[];++export const openAVCustomColorDialog = (options: {+ protyle: IProtyle,+ data: IAV,+ blockElement: HTMLElement,+}) => {+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {+ return;+ }+ const originalColors = cloneCustomColors(getAVCustomColors(options.data));+ const draft = cloneCustomColors(originalColors);+ const usedIndexes = new Set(options.data.usedCustomColorIndexes || []);+ const appearanceStyles = getInlineStylesCache().styles.filter(style => getInlineStyleType(style) === "style1");+ let editingIndex: number | undefined;+ let editingColorIndex: number | undefined;+ const dialog = new Dialog({+ title: window.siyuan.languages.manageCustomColors,+ width: isMobile() ? "92vw" : "600px",+ content: `<div class="b3-dialog__content" style="max-height:70vh;overflow:auto">+ <div data-panel="list">+ <div data-type="avCustomColorList" class="b3-list b3-list--background fn__selectnone" style="--file-toggle-width:0px"></div>+ <button class="b3-button b3-button--outline" data-action="new" type="button">+ <svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.new}+ </button>+ </div>+ <div data-panel="editor" class="fn__none">+ <div class="b3-label b3-label--inner" data-field="colorIndex"></div>+ ${appearanceStyles.length > 0 ? `<label class="b3-label b3-label--inner fn__flex" style="align-items:center">+ <span style="min-width:96px">${window.siyuan.languages.appearance}</span>+ <select class="b3-select fn__flex-1" data-field="appearance" style="margin-top:0">+ <option value="">${window.siyuan.languages.select}</option>+ ${appearanceStyles.map((style, index) => `<option value="${index}">${escapeHtml(style.name)}</option>`).join("")}+ </select>+ </label>` : ""}+ ${getThemeColorEditorHTML()}+ </div>+</div>+<div class="b3-dialog__action">+ <button class="b3-button b3-button--cancel" data-action="cancel" type="button">${window.siyuan.languages.cancel}</button>+ <div class="fn__space"></div>+ <button class="b3-button b3-button--text" data-action="save" type="button">${window.siyuan.languages.save}</button>+</div>`,+ });+ const listPanel = dialog.element.querySelector('[data-panel="list"]') as HTMLElement;+ const editorPanel = dialog.element.querySelector('[data-panel="editor"]') as HTMLElement;+ const listElement = dialog.element.querySelector('[data-type="avCustomColorList"]') as HTMLElement;+ const newElement = dialog.element.querySelector('[data-action="new"]') as HTMLButtonElement;+ const cancelElement = dialog.element.querySelector('[data-action="cancel"]') as HTMLButtonElement;+ const saveElement = dialog.element.querySelector('[data-action="save"]') as HTMLButtonElement;+ const colorIndexElement = dialog.element.querySelector('[data-field="colorIndex"]') as HTMLElement;+ const themeColorEditor = bindThemeColorEditor(editorPanel);+ const appearanceElement = dialog.element.querySelector('[data-field="appearance"]') as HTMLSelectElement;++ const renderList = () => {+ listElement.innerHTML = draft.map((color, index) => {+ const used = usedIndexes.has(color.index);+ return `<div class="b3-list-item b3-list-item--narrow" data-index="${index}">+ <span class="color__square color__square--list" style="${getAVColorStyle({+ color: color.index.toString(),+ resolvedColor: color,+ })}">A</span>+ <span class="b3-list-item__text">${window.siyuan.languages.color} ${color.index}</span>+ <span class="b3-list-item__action ariaLabel" data-action="edit" data-index="${index}" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.edit)}"><svg><use xlink:href="#iconEdit"></use></svg></span>+ <span class="b3-list-item__action b3-list-item__action--warning ariaLabel" data-action="delete" data-index="${index}" data-position="north" aria-disabled="${used}"${used ? ' style="cursor:not-allowed;opacity:.38"' : ""} aria-label="${escapeAttr(window.siyuan.languages.delete)}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>+</div>`;+ }).join("");+ newElement.disabled = draft.length >= AV_CUSTOM_COLOR_LIMIT;+ newElement.style.marginTop = draft.length === 0 ? "0" : "8px";+ };++ const setEditorActionMode = (editing: boolean) => {+ cancelElement.dataset.action = editing ? "cancelEdit" : "cancel";+ saveElement.dataset.action = editing ? "confirmEdit" : "save";+ saveElement.textContent = editing ? window.siyuan.languages.confirm : window.siyuan.languages.save;+ };+ const showList = () => {+ editingIndex = undefined;+ editingColorIndex = undefined;+ editorPanel.classList.add("fn__none");+ listPanel.classList.remove("fn__none");+ setEditorActionMode(false);+ renderList();+ };+ const showEditor = (index?: number) => {+ const color = typeof index === "number" ? draft[index] : undefined;+ const colorIndex = color?.index || getAvailableAVCustomColorIndex(draft);+ if (!colorIndex) {+ showMessage(window.siyuan.languages.invalid, 6000, "error");+ return;+ }+ editingIndex = index ?? -1;+ editingColorIndex = colorIndex;+ colorIndexElement.textContent = `${window.siyuan.languages.color} ${colorIndex}`;+ if (appearanceElement) {+ appearanceElement.value = "";+ }+ themeColorEditor.setValue(color, "style1");+ listPanel.classList.add("fn__none");+ editorPanel.classList.remove("fn__none");+ setEditorActionMode(true);+ };+ const confirmEditor = () => {+ const value = themeColorEditor.getValue("style1");+ const color: IAVCustomColor = {+ index: editingColorIndex,+ light: {+ color: value.light.color,+ backgroundColor: value.light.backgroundColor,+ },+ dark: {+ color: value.dark.color,+ backgroundColor: value.dark.backgroundColor,+ },+ };+ if (editingIndex >= 0) {+ draft[editingIndex] = color;+ } else {+ draft.push(color);+ draft.sort((a, b) => a.index - b.index);+ }+ showList();+ };++ appearanceElement?.addEventListener("change", () => {+ const style = appearanceStyles[parseInt(appearanceElement.value)];+ if (style) {+ themeColorEditor.setValue(style, "style1");+ }+ });++ dialog.element.addEventListener("click", event => {+ const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");+ if (!actionElement || actionElement.hasAttribute("disabled")) {+ return;+ }+ const action = actionElement.dataset.action;+ const index = parseInt(actionElement.dataset.index);+ if (action === "new") {+ showEditor();+ } else if (action === "edit") {+ showEditor(index);+ } else if (action === "delete") {+ const color = draft[index];+ if (!color) {+ return;+ }+ if (usedIndexes.has(color.index)) {+ showMessage(window.siyuan.languages.invalid, 6000, "error");+ return;+ }+ confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.confirmDelete, () => {+ draft.splice(index, 1);+ renderList();+ }, undefined, true);+ } else if (action === "cancelEdit") {+ showList();+ } else if (action === "confirmEdit") {+ confirmEditor();+ } else if (action === "cancel") {+ dialog.destroy();+ } else if (action === "save") {+ transaction(options.protyle, [{+ action: "setAttrViewCustomColors",+ avID: options.data.id,+ blockID: options.blockElement.dataset.nodeId,+ data: draft,+ }, {+ action: "doUpdateUpdated",+ id: options.blockElement.dataset.nodeId,+ data: dayjs().format("YYYYMMDDHHmmss"),+ }], [{+ action: "setAttrViewCustomColors",+ avID: options.data.id,+ blockID: options.blockElement.dataset.nodeId,+ data: originalColors,+ }], {+ callback: () => {+ dialog.destroy();+ },+ });+ }+ event.preventDefault();+ event.stopPropagation();+ });+ renderList();+};diff --git a/app/src/protyle/render/av/filter.ts b/app/src/protyle/render/av/filter.tsindex 354af69f57..c56066af19 100644--- a/app/src/protyle/render/av/filter.ts+++ b/app/src/protyle/render/av/filter.ts@@ -10,6 +10,7 @@ import {fetchPost, fetchSyncPost} from "../../../util/fetch";import {getFieldsByData} from "./view";import {Constants} from "../../../constants";import {countFilterLeaves} from "./filterTree";+import {getAVColorStyle} from "./color";const isExactRelationOperator = (operator: string) =>operator === "Contains any item" || operator === "Does not contain any item";@@ -693,7 +694,11 @@ const genInlineSelectHTML = (filter: IAVFilter, colData: IAVColumn, path: string// 触发器:显示已选值的 chip(与表格单元格样式一致),无选中时显示 placeholder + 下拉箭头const selectedChips = selectedValues.map((item: IAVCellSelectValue) => {- return `<span class="b3-chip b3-chip--middle av__select-chip" style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">${escapeHtml(item.content)}</span>`;+ const option = options.find(colOption => colOption.name === item.content);+ return `<span class="b3-chip b3-chip--middle av__select-chip" style="${getAVColorStyle({+ color: option ? option.color : item.color,+ resolvedColor: option ? option.resolvedColor : item.resolvedColor,+ })}">${escapeHtml(item.content)}</span>`;}).join("");const triggerContent = selectedChips || `<span class="ft__on-surface fn__ellipsis">${placeholder}</span>`;const trigger = `<span class="av__select-trigger" data-type="selectTrigger" data-path="${path}">${triggerContent}<svg class="av__select-trigger-arrow"><use xlink:href="#iconDown"></use></svg></span>`;@@ -702,11 +707,11 @@ const genInlineSelectHTML = (filter: IAVFilter, colData: IAVColumn, path: stringconst searchInput = options.length > 5? `<input class="b3-text-field" placeholder="${window.siyuan.languages.searchPlaceholder}" data-type="filterSearch" data-path="${path}">`: "";- const chips = options.map((option: { name: string; color: string; desc?: string }) => {+ const chips = options.map(option => {const selected = selectedValues.some((s: IAVCellSelectValue) => s.content === option.name);return `<button type="button" class="av__select-option" data-name="${escapeAttr(option.name)}" data-color="${escapeAttr(option.color)}" data-type="selectOption" data-path="${path}"><svg class="av__select-option-check"><use xlink:href="#${selected ? "iconCheck" : "iconUncheck"}"></use></svg>-<span class="b3-chip b3-chip--middle" style="background-color:var(--b3-font-background${escapeAttr(option.color)});color:var(--b3-font-color${escapeAttr(option.color)})"><span class="fn__ellipsis">${escapeHtml(option.name)}</span></span>+<span class="b3-chip b3-chip--middle" style="${getAVColorStyle(option)}"><span class="fn__ellipsis">${escapeHtml(option.name)}</span></span></button>`;}).join("");const dropdown = `<div class="av__select-dropdown" data-type="selectDropdown" data-path="${path}" data-single="${allowMultiple ? "false" : "true"}" data-value-type="${valueType}" style="display:none;">@@ -1199,8 +1204,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, proconst itemUseElement = item.querySelector(".av__select-option-check use");if (itemUseElement && itemUseElement.getAttribute("xlink:href") === "#iconCheck") {const name = item.dataset.name;- const color = item.dataset.color;- selectedChips.push(`<span class="b3-chip b3-chip--middle av__select-chip" style="background-color:var(--b3-font-background${escapeAttr(color)});color:var(--b3-font-color${escapeAttr(color)})">${escapeHtml(name)}</span>`);+ const chipStyle = item.querySelector(".b3-chip")?.getAttribute("style") ||+ getAVColorStyle(item.dataset.color);+ selectedChips.push(`<span class="b3-chip b3-chip--middle av__select-chip" style="${escapeAttr(chipStyle)}">${escapeHtml(name)}</span>`);}});const contentHTML = selectedChips.join("") || `<span class="ft__on-surface fn__ellipsis">${placeholderStr}</span>`;diff --git a/app/src/protyle/render/av/groups.ts b/app/src/protyle/render/av/groups.tsindex a33bda56f7..0e5419edab 100644--- a/app/src/protyle/render/av/groups.ts+++ b/app/src/protyle/render/av/groups.ts@@ -1,6 +1,6 @@import {unicode2Emoji} from "../../../emoji";import {getColIconByType} from "./col";-import {escapeAttr, escapeHtml} from "../../../util/escape";+import {escapeHtml} from "../../../util/escape";import {setPosition} from "../../../util/setPosition";import {getFieldsByData} from "./view";import {fetchSyncPost} from "../../../util/fetch";@@ -8,6 +8,7 @@ import {Menu} from "../../../plugin/Menu";import {objEquals} from "../../../util/functions";import {Constants} from "../../../constants";import {mergeGroupResponseView} from "./groupResponse";+import {getAVColorStyle} from "./color";export const getPageSize = (blockElement: Element) => {const groupPageSize: {@@ -201,7 +202,7 @@ export const getGroupsHTML = (columns: IAVColumn[], view: IAVView) => {let titleHTML = `<div class="b3-menu__label fn__flex-1 fn__ellipsis">${escapeHtml(item.name || "")}</div>`;if (item.groupValue?.mSelect?.length > 0) {titleHTML = `<div class="fn__flex-1">- <span class="b3-chip" style="background-color:var(--b3-font-background${escapeAttr(item.groupValue.mSelect[0].color)});color:var(--b3-font-color${escapeAttr(item.groupValue.mSelect[0].color)})">+ <span class="b3-chip" style="${getAVColorStyle(item.groupValue.mSelect[0])}"><span class="fn__ellipsis">${escapeHtml(item.groupValue.mSelect[0].content)}</span></span></div>`;diff --git a/app/src/protyle/render/av/kanban/groupMenu.ts b/app/src/protyle/render/av/kanban/groupMenu.tsindex abaf63b163..46f78f4792 100644--- a/app/src/protyle/render/av/kanban/groupMenu.ts+++ b/app/src/protyle/render/av/kanban/groupMenu.ts@@ -3,6 +3,14 @@ import {Constants} from "../../../../constants";import {transaction} from "../../../wysiwyg/transaction";import {confirmDialog} from "../../../../dialog/confirmDialog";import * as dayjs from "dayjs";+import {getAVData} from "../virtualScroll";+import {+ AV_MANAGE_CUSTOM_COLORS_TYPE,+ applyAVColorPalette,+ getAVColorGridHTML,+ getAVCustomColors,+} from "../color";+import {openAVCustomColorDialog} from "../colorDialog";export const openKanbanGroupMenu = (options: {protyle: IProtyle,@@ -25,9 +33,11 @@ export const openKanbanGroupMenu = (options: {desc?: string,}[];const option = colOptions.find(item => item.name === name);+ const data = getAVData(options.blockElement as HTMLElement);if (!option) {return;}+ applyAVColorPalette(menu.element, getAVCustomColors(data));menu.addItem({icon: "iconTrashcan",@@ -79,19 +89,28 @@ export const openKanbanGroupMenu = (options: {}});menu.addSeparator();- let colorHTML = `<div class="b3-menu__labels">${window.siyuan.languages.color}</div>-<div class="fn__flex fn__flex-wrap" style="width: 238px">`;- Array.from(Array(14).keys()).forEach(index => {- colorHTML += `<button data-color="${index + 1}" class="color__square${parseInt(option.color) === index + 1 ? " color__square--current" : ""}" style="color: var(--b3-font-color${index + 1});background-color: var(--b3-font-background${index + 1});">A</button>`;- });+ const colorHTML = `<div class="b3-menu__labels">${window.siyuan.languages.color}</div>+<div class="fn__flex fn__flex-wrap" style="width:238px;max-height:238px;overflow:auto">${getAVColorGridHTML(+ getAVCustomColors(data), option.color, window.siyuan.languages.manageCustomColors)}</div>`;menu.addItem({type: "empty",iconHTML: "",- label: colorHTML + "</div>",+ label: colorHTML,bind(element) {element.addEventListener("click", (event) => {- const colorTarget = event.target as HTMLElement;- if (!colorTarget.classList.contains("color__square") ||+ const colorTarget = (event.target as HTMLElement).closest<HTMLElement>("button");+ if (colorTarget?.dataset.type === AV_MANAGE_CUSTOM_COLORS_TYPE) {+ menu.close();+ if (data) {+ openAVCustomColorDialog({+ protyle: options.protyle,+ data,+ blockElement: options.blockElement as HTMLElement,+ });+ }+ return;+ }+ if (!colorTarget || !colorTarget.classList.contains("color__square") ||colorTarget.classList.contains("color__square--current")) {return;}diff --git a/app/src/protyle/render/av/kanban/render.ts b/app/src/protyle/render/av/kanban/render.tsindex 21371da4cd..441943a1cf 100644--- a/app/src/protyle/render/av/kanban/render.ts+++ b/app/src/protyle/render/av/kanban/render.ts@@ -17,6 +17,7 @@ import {prepareAVLocate} from "../locate";import {getCardStyle} from "../gallery/style";+import {getAVBackgroundColor, getAVColorStyle} from "../color";interface IIds {groupId: string,@@ -28,7 +29,7 @@ const getKanbanTitleHTML = (group: IAVView, counter: number, draggable: boolean)let optionMenuHTML = "";if (["mSelect", "select"].includes(group.groupValue.type)) {group.groupValue.mSelect.forEach((item) => {- nameHTML += `<span class="b3-chip" style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">${escapeHtml(item.content)}</span>`;+ nameHTML += `<span class="b3-chip" style="${getAVColorStyle(item)}">${escapeHtml(item.content)}</span>`;});if (draggable && group.groupValue.mSelect.length === 1) {const value = group.groupValue.mSelect[0];@@ -212,7 +213,7 @@ export const renderKanban = async (options: {}if (isSelectGroup) {if (group.groupValue.mSelect && group.groupValue.mSelect.length > 0) {- selectBg = `style="--b3-av-kanban-background: var(--b3-font-background${escapeAttr(group.groupValue.mSelect[0].color)});"`;+ selectBg = `style="--b3-av-kanban-background: ${getAVBackgroundColor(group.groupValue.mSelect[0])};"`;} else {selectBg = 'style="--b3-av-kanban-background: var(--b3-border-color);"';}diff --git a/app/src/protyle/render/av/locate.ts b/app/src/protyle/render/av/locate.tsindex 3b27489ca3..3d58b733b8 100644--- a/app/src/protyle/render/av/locate.ts+++ b/app/src/protyle/render/av/locate.ts@@ -7,6 +7,7 @@ import {scrollCenter} from "../../../util/highlightById";import {setAVCellAnchor, setAVItemAnchor} from "./rangeSelect";import {updateAVRowSelect} from "./virtualScroll";import {getAVLocateViewChange} from "./locateView";+import {applyAVColorPalette, getAVCustomColors} from "./color";export interface IAVLocateRequest {itemID: string;@@ -245,6 +246,7 @@ export const getAVLocateParams = (blockElement: HTMLElement, enabled = true) =>export const applyAVRenderContext = (blockElement: HTMLElement, data: IAV) => {blockElement.setAttribute(Constants.CUSTOM_SY_AV_VIEW, data.viewID);blockElement.setAttribute("data-av-type", data.viewType);+ applyAVColorPalette(blockElement, getAVCustomColors(data));};export const persistAVLocateView = (blockElement: HTMLElement, protyle: IProtyle, data: IAV) => {diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.tsindex 099150fb70..4de1e30b49 100644--- a/app/src/protyle/render/av/newItemTemplate.ts+++ b/app/src/protyle/render/av/newItemTemplate.ts@@ -14,6 +14,7 @@ import {upDownHint} from "../../../util/upDownHint";import {hasClosestByClassName} from "../../util/hasClosest";import * as dayjs from "dayjs";import {getAVBlockRefSubtype} from "./cellValue";+import {getAVColorStyle} from "./color";interface ICreatePosition {previousID?: string;@@ -42,17 +43,17 @@ const getSelectedOptionNames = (element: HTMLElement) => {};const getSelectedOptionsHTML = (column: IAVColumn, selected: string[]) => {- return selected.map(name => (column.options || []).find(item => item.name === name)).filter(item => item).map(item => `<span class="b3-chip b3-chip--middle" style="max-width:100%;background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})"><span class="fn__ellipsis">${escapeHtml(item.name)}</span></span>`).join("");+ return selected.map(name => (column.options || []).find(item => item.name === name)).filter(item => item).map(item => `<span class="b3-chip b3-chip--middle" style="max-width:100%;${getAVColorStyle(item)}"><span class="fn__ellipsis">${escapeHtml(item.name)}</span></span>`).join("");};const getFieldSelectMenuHTML = (column: IAVColumn, selected: string[], keyword = "") => {- const selectedHTML = selected.map(name => (column.options || []).find(item => item.name === name)).filter(item => item).map(item => `<div class="b3-chip b3-chip--middle" data-name="${escapeAttr(item.name)}" style="white-space:nowrap;max-width:100%;background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})"><span class="fn__ellipsis">${escapeHtml(item.name)}</span><svg class="b3-chip__close" data-role="remove-field-option"><use xlink:href="#iconClose"></use></svg></div>`).join("");+ const selectedHTML = selected.map(name => (column.options || []).find(item => item.name === name)).filter(item => item).map(item => `<div class="b3-chip b3-chip--middle" data-name="${escapeAttr(item.name)}" style="white-space:nowrap;max-width:100%;${getAVColorStyle(item)}"><span class="fn__ellipsis">${escapeHtml(item.name)}</span><svg class="b3-chip__close" data-role="remove-field-option"><use xlink:href="#iconClose"></use></svg></div>`).join("");const normalizedKeyword = keyword.toLowerCase();const options = (column.options || []).filter(item => !normalizedKeyword ||item.name.toLowerCase().includes(normalizedKeyword) || normalizedKeyword.includes(item.name.toLowerCase()));const optionsHTML = options.map((option, index) => `<button class="b3-menu__item${index === 0 ? " b3-menu__item--current" : ""}" data-role="field-option" data-name="${escapeAttr(option.name)}"><div class="fn__flex-1">- <span class="b3-chip" style="background-color:var(--b3-font-background${escapeAttr(option.color)});color:var(--b3-font-color${escapeAttr(option.color)})"><span class="fn__ellipsis">${escapeHtml(option.name)}</span></span>+ <span class="b3-chip" style="${getAVColorStyle(option)}"><span class="fn__ellipsis">${escapeHtml(option.name)}</span></span></div>${selected.includes(option.name) ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}</button>`).join("");diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex fd5fc25c0b..55b927880b 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -80,6 +80,7 @@ import {} from "./groups";import {openFieldVisibilityPanel} from "./fieldVisibility";import {clearSelect} from "../../util/clear";+import {applyAVColorPalette, getAVCustomColors} from "./color";export const openMenuPanel = (options: {protyle: IProtyle,@@ -205,6 +206,7 @@ export const openMenuPanel = (options: {<div class="b3-menu${options.type === "filters" ? " av__filter-panel" : ""}${options.type === "relation" ? " av__relation-panel" : ""}" ${options.keepMenuOpen ? "data-menu=\"true\"" : ""} ${["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");+ applyAVColorPalette(avPanelElement as HTMLElement, getAVCustomColors(data));if (options.destroyCallback) {const renderedPanelElement = avPanelElement;const parentElement = renderedPanelElement.parentElement;diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.tsindex 339be5271a..645322e782 100644--- a/app/src/protyle/render/av/render.ts+++ b/app/src/protyle/render/av/render.ts@@ -54,6 +54,7 @@ import {GROUP_TABLE_INITIAL_ROW_BUDGET,} from "./groupTableVirtual";import {getAVHeaderEditingState} from "./headerEditing";+import {getAVColorStyle} from "./color";interface IIds {groupId: string,@@ -279,7 +280,7 @@ export const getGroupTitleHTML = (group: IAVView, counter: number) => {let nameHTML = "";if (["mSelect", "select"].includes(group.groupValue.type)) {group.groupValue.mSelect.forEach((item) => {- nameHTML += `<span class="b3-chip" style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">${escapeHtml(item.content)}</span>`;+ nameHTML += `<span class="b3-chip" style="${getAVColorStyle(item)}">${escapeHtml(item.content)}</span>`;});} else if (group.groupValue.type === "checkbox") {nameHTML = `<svg style="width:calc(1.625em - 12px);height:calc(1.625em - 12px)"><use xlink:href="#icon${group.groupValue.checkbox.checked ? "Check" : "Uncheck"}"></use></svg>`;@@ -955,7 +956,7 @@ export const refreshAV = (protyle: IProtyle, operation: IOperation) => {if (operation.data && hasSelect) {const nameElement = item.querySelector(".av__group-title .b3-chip") as HTMLElement;if (nameElement) {- item.setAttribute("style", `--b3-av-kanban-background:var(--b3-font-background${nameElement.style.backgroundColor.slice(-2, -1)})`);+ item.setAttribute("style", `--b3-av-kanban-background:${nameElement.style.backgroundColor}`);} else {item.setAttribute("style", "--b3-av-kanban-background: var(--b3-border-color)");}diff --git a/app/src/protyle/render/av/select.ts b/app/src/protyle/render/av/select.tsindex 6bf6139c98..6dc81c8737 100644--- a/app/src/protyle/render/av/select.ts+++ b/app/src/protyle/render/av/select.ts@@ -15,12 +15,23 @@ import {getFieldIdByCellElement} from "./row";import {Constants} from "../../../constants";import {setPosition} from "../../../util/setPosition";import {getAVBatchEditMode, getAVBatchSourceValue} from "./batchValue";+import {+ AV_MANAGE_CUSTOM_COLORS_TYPE,+ applyAVColorPalette,+ getAVColorGridHTML,+ getAVColorStyle,+ getAVCustomColors,+ getAVResolvedColor,+ getNextAVOptionColor,+} from "./color";+import {openAVCustomColorDialog} from "./colorDialog";let cellValues: IAVCellValue[];const filterSelectHTML = (key: string, options: {name: string,color: string,+ resolvedColor?: IAVColor,desc?: string}[], selected: string[] = []) => {let html = "";@@ -40,7 +51,7 @@ const filterSelectHTML = (key: string, options: {html += `<button data-type="addColOptionOrCell" class="b3-menu__item${currentName === item.name ? " b3-menu__item--current" : ""}" data-name="${escapeAttr(item.name)}" data-desc="${escapeAttr(item.desc || "")}" draggable="true" data-color="${escapeAttr(item.color)}"><svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg><div class="fn__flex-1 ariaLabel" data-position="parentW" aria-label="${airaLabel}">- <span class="b3-chip" style="background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})">+ <span class="b3-chip" style="${getAVColorStyle(item)}"><span class="fn__ellipsis">${escapeHtml(item.name)}</span></span></div>@@ -55,11 +66,11 @@ const filterSelectHTML = (key: string, options: {}if (!hasMatch && key) {html = html.replace('class="b3-menu__item b3-menu__item--current"', 'class="b3-menu__item"');- const colorIndex = (options?.length || 0) % 14 + 1;+ const colorIndex = getNextAVOptionColor(options?.length || 0);html = `<button data-type="addColOptionOrCell" class="b3-menu__item b3-menu__item--current" data-name="${key}" data-color="${colorIndex}"><svg class="b3-menu__icon"><use xlink:href="#iconAdd"></use></svg><div class="fn__flex-1">- <span class="b3-chip" style="background-color:var(--b3-font-background${colorIndex});color:var(--b3-font-color${colorIndex})">+ <span class="b3-chip" style="${getAVColorStyle(colorIndex)}"><span class="fn__ellipsis">${escapeHtml(key)}</span></span></div>@@ -265,6 +276,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,if (menu.isOpen) {return;}+ applyAVColorPalette(menu.element, getAVCustomColors(data));menu.addItem({iconHTML: "",type: "empty",@@ -389,18 +401,26 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,}});menu.addSeparator();- let html = "<div class=\"fn__flex fn__flex-wrap\" style=\"width: 238px\">";- Array.from(Array(14).keys()).forEach(index => {- html += `<button data-color="${index + 1}" class="color__square${parseInt(color) === index + 1 ? " color__square--current" : ""}" style="color: var(--b3-font-color${index + 1});background-color: var(--b3-font-background${index + 1});">A</button>`;- });+ const html = `<div class="fn__flex fn__flex-wrap" style="width:238px;max-height:238px;overflow:auto">${getAVColorGridHTML(+ getAVCustomColors(data), color, window.siyuan.languages.manageCustomColors)}</div>`;menu.addItem({type: "empty",iconHTML: "",- label: html + "</div>",+ label: html,bind(element) {element.addEventListener("click", (event) => {- const colorTarget = event.target as HTMLElement;- if (colorTarget.classList.contains("color__square") && !colorTarget.classList.contains("color__square--current")) {+ const colorTarget = (event.target as HTMLElement).closest<HTMLElement>("button");+ if (colorTarget?.dataset.type === AV_MANAGE_CUSTOM_COLORS_TYPE) {+ menu.close();+ document.querySelector(".av__panel")?.remove();+ openAVCustomColorDialog({+ protyle,+ data,+ blockElement: blockElement as HTMLElement,+ });+ return;+ }+ if (colorTarget?.classList.contains("color__square") && !colorTarget.classList.contains("color__square--current")) {element.querySelector(".color__square--current")?.classList.remove("color__square--current");colorTarget.classList.add("color__square--current");const newColor = colorTarget.getAttribute("data-color");@@ -438,6 +458,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,if (item.name === name) {item.name = inputElement.value;item.color = newColor;+ item.resolvedColor = getAVResolvedColor(data, newColor);return true;}});@@ -463,6 +484,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,if (item.content === name) {item.content = inputElement.value;item.color = newColor;+ item.resolvedColor = getAVResolvedColor(data, newColor);return true;}});@@ -583,6 +605,8 @@ export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: Hconst cellDoOperations: IOperation[] = [];const cellUndoOperations: IOperation[] = [];+ const resolvedColor = colData.options.find(option => option.name === currentElement.dataset.name)?.resolvedColor ||+ getAVResolvedColor(data, currentElement.dataset.color);let mSelectValue: IAVCellSelectValue[];const batchMode = getAVBatchEditMode(cellElements[0]);cellElements.forEach((item, index) => {@@ -604,7 +628,8 @@ export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: H}cellValue.mSelect.push({color: currentElement.dataset.color,- content: currentElement.dataset.name+ content: currentElement.dataset.name,+ resolvedColor,});}} else if (index === 0) {@@ -619,13 +644,15 @@ export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: Hif (!hasOption) {cellValue.mSelect.push({color: currentElement.dataset.color,- content: currentElement.dataset.name+ content: currentElement.dataset.name,+ resolvedColor,});}} else {cellValue.mSelect = [{color: currentElement.dataset.color,- content: currentElement.dataset.name+ content: currentElement.dataset.name,+ resolvedColor,}];}mSelectValue = cellValue.mSelect;@@ -720,6 +747,11 @@ export const getSelectHTML = (fields: IAVColumn[], cellElements: HTMLElement[],return item;}});+ cellValues.forEach(value => {+ value.mSelect?.forEach(item => {+ item.resolvedColor = colData.options?.find(option => option.name === item.content)?.resolvedColor;+ });+ });let selectedHTML = "";const selected: string[] = [];const batchMode = getAVBatchEditMode(cellElements[0]);@@ -728,7 +760,10 @@ export const getSelectHTML = (fields: IAVColumn[], cellElements: HTMLElement[],visibleValues?.forEach((item) => {const option = colData.options?.find((colOption) => colOption.name === item.content);selected.push(item.content);- selectedHTML += `<div class="b3-chip b3-chip--middle${canSort ? " fn__grab" : " b3-chip--pointer"}" data-content="${escapeAttr(item.content)}" data-name="${escapeAttr(item.content)}" data-desc="${escapeAttr(option?.desc || "")}" data-color="${escapeAttr(option?.color || item.color)}" data-value-color="${escapeAttr(item.color)}" style="white-space: nowrap;max-width:100%;background-color:var(--b3-font-background${escapeAttr(item.color)});color:var(--b3-font-color${escapeAttr(item.color)})"><span class="fn__ellipsis">${escapeHtml(item.content)}</span><svg class="b3-chip__close" data-type="removeCellOption"><use xlink:href="#iconClose"></use></svg></div>`;+ selectedHTML += `<div class="b3-chip b3-chip--middle${canSort ? " fn__grab" : " b3-chip--pointer"}" data-content="${escapeAttr(item.content)}" data-name="${escapeAttr(item.content)}" data-desc="${escapeAttr(option?.desc || "")}" data-color="${escapeAttr(option ? option.color : item.color)}" data-value-color="${escapeAttr(item.color)}" style="white-space: nowrap;max-width:100%;${getAVColorStyle({+ color: option ? option.color : item.color,+ resolvedColor: option ? option.resolvedColor : item.resolvedColor,+ })}"><span class="fn__ellipsis">${escapeHtml(item.content)}</span><svg class="b3-chip__close" data-type="removeCellOption"><use xlink:href="#iconClose"></use></svg></div>`;});return `<div class="b3-menu__items" style="display: flex;flex-direction: column;flex: 1;">@@ -747,17 +782,15 @@ export const mergeAddOption = (column: IAVColumn, cellValue: IAVCellValue, avID:if (!column.options) {column.options = [];}- const needAdd = column.options.find((option: {- name: string,- color: string,- }) => {+ const needAdd = column.options.find((option) => {if (option.name === item.content) {item.color = option.color;+ item.resolvedColor = option.resolvedColor;return true;}});if (!needAdd) {- const newColor = ((column.options?.length || 0) % 14 + 1).toString();+ const newColor = getNextAVOptionColor(column.options?.length || 0);column.options.push({name: item.content,color: newColordiff --git a/app/src/protyle/toolbar/inlineStyleDialog.ts b/app/src/protyle/toolbar/inlineStyleDialog.tsindex f60d73a885..aa5f036f05 100644--- a/app/src/protyle/toolbar/inlineStyleDialog.ts+++ b/app/src/protyle/toolbar/inlineStyleDialog.ts@@ -3,6 +3,7 @@ import {confirmDialog} from "../../dialog/confirmDialog";import {showMessage} from "../../dialog/message";import {escapeAttr, escapeHtml} from "../../util/escape";import {isMobile} from "../../util/functions";+import {bindThemeColorEditor, getThemeColorEditorHTML} from "../../dialog/themeColorEditor";import {getCurrentInlineStyleMode,getInlineStylePreview,@@ -69,30 +70,7 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun</select><span class="fn__flex-1 fn__none" data-field="typeLabel"></span></label>- <div class="b3-label b3-label--inner fn__flex" style="align-items:flex-start;gap:24px;flex-wrap:wrap">- <div class="fn__flex-1" style="min-width:200px">- <div>${window.siyuan.languages.themeLight}</div>- <label class="fn__flex" data-property="color" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>- <input class="b3-text-field" data-field="lightColor" type="color">- </label>- <label class="fn__flex" data-property="backgroundColor" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>- <input class="b3-text-field" data-field="lightBackgroundColor" type="color">- </label>- </div>- <div class="fn__flex-1" style="min-width:200px">- <div>${window.siyuan.languages.themeDark}</div>- <label class="fn__flex" data-property="color" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>- <input class="b3-text-field" data-field="darkColor" type="color">- </label>- <label class="fn__flex" data-property="backgroundColor" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>- <input class="b3-text-field" data-field="darkBackgroundColor" type="color">- </label>- </div>- </div>+ ${getThemeColorEditorHTML()}</div></div><div class="b3-dialog__action" data-panel="actions">@@ -110,10 +88,7 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrounconst nameElement = dialog.element.querySelector('[data-field="name"]') as HTMLInputElement;const typeElement = dialog.element.querySelector('[data-field="type"]') as HTMLSelectElement;const typeLabelElement = dialog.element.querySelector('[data-field="typeLabel"]') as HTMLElement;- const lightColorElement = dialog.element.querySelector('[data-field="lightColor"]') as HTMLInputElement;- const darkColorElement = dialog.element.querySelector('[data-field="darkColor"]') as HTMLInputElement;- const lightBackgroundElement = dialog.element.querySelector('[data-field="lightBackgroundColor"]') as HTMLInputElement;- const darkBackgroundElement = dialog.element.querySelector('[data-field="darkBackgroundColor"]') as HTMLInputElement;+ const themeColorEditor = bindThemeColorEditor(editorPanel);const renderList = () => {listElement.innerHTML = draft.styles.length === 0 ?@@ -130,16 +105,6 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrounnewElement.style.marginTop = draft.styles.length === 0 ? "0" : "8px";};- const updateColorVisibility = () => {- const type = typeElement.value as TInlineStyleType;- dialog.element.querySelectorAll<HTMLElement>('[data-property="color"]').forEach(item => {- item.classList.toggle("fn__none", type === "backgroundColor");- });- dialog.element.querySelectorAll<HTMLElement>('[data-property="backgroundColor"]').forEach(item => {- item.classList.toggle("fn__none", type === "color");- });- };-const setEditorActionMode = (editing: boolean) => {cancelElement.dataset.action = editing ? "cancelEdit" : "cancel";saveElement.dataset.action = editing ? "confirmEdit" : "save";@@ -162,11 +127,7 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrountypeElement.classList.toggle("fn__none", !!style);typeLabelElement.classList.toggle("fn__none", !style);typeLabelElement.textContent = getTypeLabel(typeElement.value as TInlineStyleType);- lightColorElement.value = style?.light.color || "#000000";- darkColorElement.value = style?.dark.color || "#ffffff";- lightBackgroundElement.value = style?.light.backgroundColor || "#fff3cd";- darkBackgroundElement.value = style?.dark.backgroundColor || "#554b00";- updateColorVisibility();+ themeColorEditor.setValue(style, typeElement.value as TInlineStyleType);listPanel.classList.add("fn__none");editorPanel.classList.remove("fn__none");setEditorActionMode(true);@@ -187,20 +148,13 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun}const type = typeElement.value as TInlineStyleType;const previous = editingIndex >= 0 ? draft.styles[editingIndex] : undefined;+ const value = themeColorEditor.getValue(type);const style: IInlineStyle = {id: previous?.id || Lute.NewNodeID(),name,- light: {},- dark: {},+ light: value.light,+ dark: value.dark,};- if (type !== "backgroundColor") {- style.light.color = lightColorElement.value;- style.dark.color = darkColorElement.value;- }- if (type !== "color") {- style.light.backgroundColor = lightBackgroundElement.value;- style.dark.backgroundColor = darkBackgroundElement.value;- }if (previous) {draft.styles[editingIndex] = style;} else {@@ -270,7 +224,9 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrounclearDragStyles();});- typeElement.addEventListener("change", updateColorVisibility);+ typeElement.addEventListener("change", () => {+ themeColorEditor.setType(typeElement.value as TInlineStyleType);+ });dialog.element.addEventListener("click", async event => {const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");if (!actionElement || actionElement.hasAttribute("disabled")) {diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex e6c0efb508..ea4e0654cf 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -1269,7 +1269,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndif (["addAttrViewCol", "updateAttrViewCol", "updateAttrViewColOptions","updateAttrViewColOption", "updateAttrViewCell", "updateAttrViewCells", "sortAttrViewRow", "sortAttrViewCol", "setAttrViewColHidden","setAttrViewColWrap", "setAttrViewColWidth", "setAttrViewColsWidth", "setAttrViewColAlign", "removeAttrViewColOption", "setAttrViewName", "setAttrViewFilters",- "setAttrViewSorts", "setAttrViewNewItemTemplates", "setAttrViewColCalc", "removeAttrViewCol", "updateAttrViewColNumberFormat", "setAttrViewColDateFormat", "removeAttrViewBlock",+ "setAttrViewSorts", "setAttrViewNewItemTemplates", "setAttrViewCustomColors", "setAttrViewColCalc", "removeAttrViewCol", "updateAttrViewColNumberFormat", "setAttrViewColDateFormat", "removeAttrViewBlock","replaceAttrViewBlock", "updateAttrViewColTemplate", "setAttrViewColPin", "addAttrViewView", "setAttrViewColIcon","removeAttrViewView", "setAttrViewViewName", "setAttrViewViewIcon", "duplicateAttrViewView", "duplicateAttrViewRow", "sortAttrViewView","updateAttrViewColRelation", "setAttrViewColRelationFilters", "setAttrViewPageSize", "updateAttrViewColRollup",diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex c96720e73d..dca3d0048e 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -38,6 +38,7 @@ type TOperation =| "updateAttrViewColOptions"| "removeAttrViewColOption"| "updateAttrViewColOption"+ | "setAttrViewCustomColors"| "setAttrViewName"| "setAttrViewNewItemTemplates"| "doUpdateUpdated"@@ -1204,6 +1205,20 @@ interface IBazaarPackageDetail {available?: IBazaarItem;}+interface IAVColorTheme {+ color: string;+ backgroundColor: string;+}++interface IAVColor {+ light: IAVColorTheme;+ dark: IAVColorTheme;+}++interface IAVCustomColor extends IAVColor {+ index: number;+}+interface IAV {id: string;name: string;@@ -1214,6 +1229,8 @@ interface IAV {isMirror?: boolean;newItemTemplates?: IAVNewItemTemplate[];defaultTemplateID?: string;+ customColors?: IAVCustomColor[];+ usedCustomColorIndexes?: number[];target?: IAVRenderTarget;}@@ -1394,6 +1411,7 @@ interface IAVColumn {options?: {name: string,color: string,+ resolvedColor?: IAVColor,desc?: string,}[],relation?: IAVColumnRelation,@@ -1492,7 +1510,8 @@ interface IAVCellDateValue {interface IAVCellSelectValue {content: string,- color: string+ color: string,+ resolvedColor?: IAVColor}interface IAVCellAssetValue {diff --git a/kernel/api/av.go b/kernel/api/av.goindex 12ea54d47d..297b1c7733 100644--- a/kernel/api/av.go+++ b/kernel/api/av.go@@ -533,7 +533,7 @@ func getAttributeViewRelationCandidates(c *gin.Context) {}}- name, blockIDs, columns, selectedRows, rows, total, err := model.GetAttributeViewRelationCandidates(+ name, blockIDs, customColors, columns, selectedRows, rows, total, err := model.GetAttributeViewRelationCandidates(avID, keyID, keyword, selectedBlockIDs, page, pageSize)if err != nil {ret.Code = -1@@ -549,6 +549,7 @@ func getAttributeViewRelationCandidates(c *gin.Context) {ret.Data = map[string]any{"name": name,"blockIDs": blockIDs,+ "customColors": customColors,"notebookID": notebookID,"columns": columns,"selectedRows": selectedRows,@@ -1142,15 +1143,17 @@ func renderSnapshotAttributeView(c *gin.Context) {}ret.Data = map[string]any{- "name": attrView.Name,- "id": attrView.ID,- "viewType": view.GetType(),- "viewID": view.GetID(),- "views": views,- "view": view,- "isMirror": av.IsMirror(attrView.ID),- "newItemTemplates": attrView.NewItemTemplates,- "defaultTemplateID": attrView.DefaultTemplateID,+ "name": attrView.Name,+ "id": attrView.ID,+ "customColors": attrView.CustomColors,+ "usedCustomColorIndexes": attrView.UsedCustomColorIndexes(),+ "viewType": view.GetType(),+ "viewID": view.GetID(),+ "views": views,+ "view": view,+ "isMirror": av.IsMirror(attrView.ID),+ "newItemTemplates": attrView.NewItemTemplates,+ "defaultTemplateID": attrView.DefaultTemplateID,}}@@ -1237,15 +1240,17 @@ func renderHistoryAttributeView(c *gin.Context) {}ret.Data = map[string]any{- "name": attrView.Name,- "id": attrView.ID,- "viewType": view.GetType(),- "viewID": view.GetID(),- "views": views,- "view": view,- "isMirror": av.IsMirror(attrView.ID),- "newItemTemplates": attrView.NewItemTemplates,- "defaultTemplateID": attrView.DefaultTemplateID,+ "name": attrView.Name,+ "id": attrView.ID,+ "customColors": attrView.CustomColors,+ "usedCustomColorIndexes": attrView.UsedCustomColorIndexes(),+ "viewType": view.GetType(),+ "viewID": view.GetID(),+ "views": views,+ "view": view,+ "isMirror": av.IsMirror(attrView.ID),+ "newItemTemplates": attrView.NewItemTemplates,+ "defaultTemplateID": attrView.DefaultTemplateID,}}@@ -1392,15 +1397,17 @@ func renderAttrView(blockID, avID, viewID, query string, page, pageSize int, gro}retData := map[string]any{- "name": attrView.Name,- "id": attrView.ID,- "viewType": view.GetType(),- "viewID": view.GetID(),- "views": views,- "view": view,- "isMirror": av.IsMirror(attrView.ID),- "newItemTemplates": attrView.NewItemTemplates,- "defaultTemplateID": attrView.DefaultTemplateID,+ "name": attrView.Name,+ "id": attrView.ID,+ "customColors": attrView.CustomColors,+ "usedCustomColorIndexes": attrView.UsedCustomColorIndexes(),+ "viewType": view.GetType(),+ "viewID": view.GetID(),+ "views": views,+ "view": view,+ "isMirror": av.IsMirror(attrView.ID),+ "newItemTemplates": attrView.NewItemTemplates,+ "defaultTemplateID": attrView.DefaultTemplateID,}if nil != target {retData["target"] = targetdiff --git a/kernel/av/av.go b/kernel/av/av.goindex 59ecd005a5..e0d3d85473 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -41,14 +41,17 @@ import (// AttributeView 描述了属性视图的结构。type AttributeView struct {- Spec int `json:"spec"` // 格式版本- ID string `json:"id"` // 属性视图 ID- Name string `json:"name"` // 属性视图名称- KeyValues []*KeyValues `json:"keyValues"` // 属性视图属性键值- KeyIDs []string `json:"keyIDs"` // 属性视图属性键 ID,用于排序- Views []*View `json:"views"` // 视图- NewItemTemplates []*NewItemTemplate `json:"newItemTemplates,omitempty"` // 新增条目模板- DefaultTemplateID string `json:"defaultTemplateID,omitempty"` // 默认新增条目模板 ID+ Spec int `json:"spec"` // 格式版本+ ID string `json:"id"` // 属性视图 ID+ Name string `json:"name"` // 属性视图名称+ KeyValues []*KeyValues `json:"keyValues"` // 属性视图属性键值+ KeyIDs []string `json:"keyIDs"` // 属性视图属性键 ID,用于排序+ Views []*View `json:"views"` // 视图+ NewItemTemplates []*NewItemTemplate `json:"newItemTemplates,omitempty"` // 新增条目模板+ DefaultTemplateID string `json:"defaultTemplateID,omitempty"` // 默认新增条目模板 ID+ CustomColors []*AttributeViewCustomColor `json:"customColors,omitempty"` // 数据库级自定义选项颜色+ // CustomColorRenderContext 保存只读渲染期间的关联数据库调色板上下文。+ CustomColorRenderContext *CustomColorRenderContext `json:"-"`// 卡片封面位置,条目 ID -> 封面来源 -> 位置CardCoverPositions map[string]map[string]*CardCoverPosition `json:"cardCoverPositions,omitempty"`@@ -57,6 +60,11 @@ type AttributeView struct {cardCoverPositionsChanged bool}+// CustomColorRenderContext 为历史和仓库快照渲染解析关联数据库当时的调色板。+type CustomColorRenderContext struct {+ ResolveRelatedCustomColors func(avID string) (colors []*AttributeViewCustomColor, found bool)+}+// NewItemTargetType 描述新增条目模板创建的目标类型。type NewItemTargetType string@@ -258,12 +266,13 @@ type Relation struct {}type SelectOption struct {- Name string `json:"name"` // 选项名称- Color string `json:"color"` // 选项颜色- Desc string `json:"desc"` // 选项描述+ Name string `json:"name"` // 选项名称+ Color string `json:"color"` // 选项颜色+ Desc string `json:"desc"` // 选项描述+ ResolvedColor *AttributeViewColor `json:"resolvedColor,omitempty"` // 渲染阶段解析后的自定义颜色}-// FilterColorValue 校验选项颜色值,仅允许空字符串或 1-14 的调色板索引,非法值返回空字符串+// FilterColorValue 校验内置选项颜色值,仅允许空字符串或 1-14 的调色板索引,非法值返回空字符串。func FilterColorValue(color string) string {color = strings.TrimSpace(color)if "" == color {@@ -506,6 +515,7 @@ func NewAttributeView(id string) (ret *AttributeView) {ID: id,KeyValues: []*KeyValues{{Key: blockKey}, {Key: selectKey}},Views: []*View{view},+ CustomColors: []*AttributeViewCustomColor{},RenderedViewables: map[string]Viewable{},}return@@ -882,6 +892,8 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeViewerr = CheckSpec(ret)}if nil == err {+ _ = ret.NormalizeCustomColors(false)+ ret.ResolveDirectColors()cache.SetAVSearchDataInBox(avID, boxID, dataVersion, newAttributeViewSearchInfo(ret))}return@@ -901,6 +913,9 @@ func SaveAttributeView(av *AttributeView) (err error) {// 做一些数据兼容和订正处理UpgradeSpec(av)+ if err = av.NormalizeCustomColors(true); nil != err {+ return+ }// 值去重blockValues := av.GetBlockKeyValues()@@ -944,11 +959,13 @@ func SaveAttributeView(av *AttributeView) (err error) {}var data []byte+ restoreResolvedColors := av.suspendResolvedColors()if util.UseSingleLineSave {data, err = gulu.JSON.MarshalJSON(av)} else {data, err = gulu.JSON.MarshalIndentJSON(av, "", "\t")}+ restoreResolvedColors()if err != nil {logging.LogErrorf("marshal attribute view [%s] failed: %s", av.ID, err)returndiff --git a/kernel/av/av_fix.go b/kernel/av/av_fix.goindex a32059b47a..0912f865a8 100644--- a/kernel/av/av_fix.go+++ b/kernel/av/av_fix.go@@ -24,7 +24,7 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-const CurrentSpec = 7+const CurrentSpec = 8const MaxFilterNestingDepth = 3@@ -40,6 +40,7 @@ func UpgradeSpec(av *AttributeView) {upgradeSpec5(av)upgradeSpec6(av)upgradeSpec7(av)+ upgradeSpec8(av)}func CheckSpec(av *AttributeView) (err error) {@@ -61,6 +62,18 @@ func upgradeSpec7(av *AttributeView) {av.Spec = 7}+// upgradeSpec8 初始化数据库级自定义选项颜色。+func upgradeSpec8(av *AttributeView) {+ if 8 <= av.Spec {+ return+ }++ if nil == av.CustomColors {+ av.CustomColors = []*AttributeViewCustomColor{}+ }+ av.Spec = 8+}+// upgradeSpec6 将卡片和看板的预设尺寸转换为可连续调节的实际宽度和宽高比。func upgradeSpec6(av *AttributeView) {if 6 <= av.Spec {diff --git a/kernel/av/av_fix_test.go b/kernel/av/av_fix_test.goindex 023a8d9682..6aada8ed8f 100644--- a/kernel/av/av_fix_test.go+++ b/kernel/av/av_fix_test.go@@ -62,8 +62,8 @@ func TestUpgradeSpec7RemovesPersistedCurrentView(t *testing.T) {t.Fatal(err)}UpgradeSpec(attrView)- if 7 != attrView.Spec {- t.Fatalf("expected spec 7, got %d", attrView.Spec)+ if CurrentSpec != attrView.Spec {+ t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)}data, err := json.Marshal(attrView)if nil != err {@@ -77,3 +77,25 @@ func TestUpgradeSpec7RemovesPersistedCurrentView(t *testing.T) {t.Fatalf("legacy viewID was persisted: %s", data)}}++func TestUpgradeSpec8InitializesCustomColors(t *testing.T) {+ attrView := &AttributeView{Spec: 7}+ UpgradeSpec(attrView)+ if CurrentSpec != attrView.Spec {+ t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)+ }+ if nil == attrView.CustomColors || 0 != len(attrView.CustomColors) {+ t.Fatalf("spec 8 upgrade should initialize an empty custom palette: %+v", attrView.CustomColors)+ }++ attrView = &AttributeView{Spec: 7, CustomColors: []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#000000", "#ffffff", "#ffffff", "#000000"),+ }}+ UpgradeSpec(attrView)+ if CurrentSpec != attrView.Spec {+ t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)+ }+ if 1 != len(attrView.CustomColors) || 15 != attrView.CustomColors[0].Index {+ t.Fatalf("spec 8 upgrade discarded an assigned custom palette: %+v", attrView.CustomColors)+ }+}diff --git a/kernel/av/av_search_test.go b/kernel/av/av_search_test.goindex 8778b36d75..77eb994834 100644--- a/kernel/av/av_search_test.go+++ b/kernel/av/av_search_test.go@@ -48,7 +48,7 @@ func TestParseAttributeViewSearchInfo(t *testing.T) {t.Fatalf("unexpected second view: %+v", info.Views[1])}- if _, err = parseAttributeViewSearchInfo([]byte(`{"spec": 8}`)); err != ErrSpecTooNew {+ if _, err = parseAttributeViewSearchInfo([]byte(`{"spec": 9}`)); err != ErrSpecTooNew {t.Fatalf("expected newer spec error, got %v", err)}}diff --git a/kernel/av/color.go b/kernel/av/color.gonew file mode 100644index 0000000000..5849b769d2--- /dev/null+++ b/kernel/av/color.go@@ -0,0 +1,613 @@+// SiYuan - From thought to insight, with agents+// 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.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package av++import (+ "errors"+ "fmt"+ "regexp"+ "sort"+ "strconv"+ "strings"++ "github.com/goccy/go-json"+)++const (+ CustomColorMinIndex = 15+ CustomColorMaxIndex = 78+ MaxCustomColors = CustomColorMaxIndex - CustomColorMinIndex + 1+)++var attributeViewColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)++// AttributeViewColorTheme 描述一种主题模式下的数据库选项颜色。+type AttributeViewColorTheme struct {+ Color string `json:"color"`+ BackgroundColor string `json:"backgroundColor"`+}++// AttributeViewColor 描述数据库选项在明暗主题下的颜色。+type AttributeViewColor struct {+ Light AttributeViewColorTheme `json:"light"`+ Dark AttributeViewColorTheme `json:"dark"`+}++// AttributeViewCustomColor 描述数据库级自定义选项颜色及其稳定编号。+type AttributeViewCustomColor struct {+ Index int `json:"index"`+ AttributeViewColor+}++// UnmarshalJSON 忽略外部输入中的派生颜色,派生颜色只能由内核根据数据库调色板生成。+func (option *SelectOption) UnmarshalJSON(data []byte) error {+ decoded := struct {+ Name string `json:"name"`+ Color string `json:"color"`+ Desc string `json:"desc"`+ }{}+ if err := json.Unmarshal(data, &decoded); nil != err {+ return err+ }+ option.Name = decoded.Name+ option.Color = decoded.Color+ option.Desc = decoded.Desc+ option.ResolvedColor = nil+ return nil+}++// UnmarshalJSON 忽略外部输入中的派生颜色,派生颜色只能由内核根据数据库调色板生成。+func (value *ValueSelect) UnmarshalJSON(data []byte) error {+ decoded := struct {+ Content string `json:"content"`+ Color string `json:"color"`+ }{}+ if err := json.Unmarshal(data, &decoded); nil != err {+ return err+ }+ value.Content = decoded.Content+ value.Color = decoded.Color+ value.ResolvedColor = nil+ return nil+}++// NormalizeAttributeViewCustomColors 校验并规范化数据库自定义颜色。+func NormalizeAttributeViewCustomColors(colors []*AttributeViewCustomColor, strict bool) (ret []*AttributeViewCustomColor, err error) {+ if strict && MaxCustomColors < len(colors) {+ return nil, fmt.Errorf("attribute view custom colors count exceeds the %d item limit", MaxCustomColors)+ }++ indexes := map[int]struct{}{}+ for _, color := range colors {+ normalized, normalizeErr := normalizeAttributeViewCustomColor(color)+ if nil != normalizeErr {+ if strict {+ return nil, normalizeErr+ }+ continue+ }+ if _, ok := indexes[normalized.Index]; ok {+ if strict {+ return nil, fmt.Errorf("duplicated attribute view custom color index [%d]", normalized.Index)+ }+ continue+ }+ indexes[normalized.Index] = struct{}{}+ ret = append(ret, normalized)+ }++ sort.Slice(ret, func(i, j int) bool {+ return ret[i].Index < ret[j].Index+ })+ if nil == ret {+ ret = []*AttributeViewCustomColor{}+ }+ return+}++func normalizeAttributeViewCustomColor(color *AttributeViewCustomColor) (ret *AttributeViewCustomColor, err error) {+ if nil == color {+ return nil, errors.New("attribute view custom color must not be null")+ }+ if color.Index < CustomColorMinIndex || CustomColorMaxIndex < color.Index {+ return nil, fmt.Errorf("attribute view custom color index [%d] is out of range [%d, %d]",+ color.Index, CustomColorMinIndex, CustomColorMaxIndex)+ }++ ret = &AttributeViewCustomColor{Index: color.Index}+ ret.Light, err = normalizeAttributeViewColorTheme(color.Light)+ if nil != err {+ return nil, fmt.Errorf("invalid light theme of attribute view custom color [%d]: %w", color.Index, err)+ }+ ret.Dark, err = normalizeAttributeViewColorTheme(color.Dark)+ if nil != err {+ return nil, fmt.Errorf("invalid dark theme of attribute view custom color [%d]: %w", color.Index, err)+ }+ return+}++func normalizeAttributeViewColorTheme(theme AttributeViewColorTheme) (ret AttributeViewColorTheme, err error) {+ ret.Color = strings.ToLower(strings.TrimSpace(theme.Color))+ ret.BackgroundColor = strings.ToLower(strings.TrimSpace(theme.BackgroundColor))+ if !attributeViewColorPattern.MatchString(ret.Color) {+ return AttributeViewColorTheme{}, fmt.Errorf("invalid foreground color [%s]", theme.Color)+ }+ if !attributeViewColorPattern.MatchString(ret.BackgroundColor) {+ return AttributeViewColorTheme{}, fmt.Errorf("invalid background color [%s]", theme.BackgroundColor)+ }+ return+}++// NormalizeCustomColors 校验并替换数据库自定义颜色。+func (av *AttributeView) NormalizeCustomColors(strict bool) error {+ if nil == av {+ return errors.New("attribute view must not be nil")+ }+ colors, err := NormalizeAttributeViewCustomColors(av.CustomColors, strict)+ if nil != err {+ return err+ }+ av.CustomColors = colors+ return nil+}++// NextCustomColorIndex 返回最小的可用自定义颜色编号,没有可用编号时返回 0。+func (av *AttributeView) NextCustomColorIndex() int {+ used := map[int]struct{}{}+ if nil != av {+ for _, color := range av.CustomColors {+ if nil != color {+ used[color.Index] = struct{}{}+ }+ }+ }+ for index := CustomColorMinIndex; index <= CustomColorMaxIndex; index++ {+ if _, ok := used[index]; !ok {+ return index+ }+ }+ return 0+}++// ResolveColor 根据自定义颜色编号返回经过校验的明暗主题颜色。+func (av *AttributeView) ResolveColor(color string) *AttributeViewColor {+ index, err := strconv.Atoi(strings.TrimSpace(color))+ if nil != err || index < CustomColorMinIndex || CustomColorMaxIndex < index || nil == av {+ return nil+ }+ for _, customColor := range av.CustomColors {+ if nil == customColor || customColor.Index != index {+ continue+ }+ normalized, normalizeErr := normalizeAttributeViewCustomColor(customColor)+ if nil != normalizeErr {+ return nil+ }+ return &AttributeViewColor{Light: normalized.Light, Dark: normalized.Dark}+ }+ return nil+}++// FilterColorValue 校验数据库上下文中的选项颜色编号。+func (av *AttributeView) FilterColorValue(color string) string {+ if filtered := FilterColorValue(color); "" != filtered {+ return filtered+ }+ color = strings.TrimSpace(color)+ index, err := strconv.Atoi(color)+ if nil != err || nil == av.ResolveColor(color) {+ return ""+ }+ return strconv.Itoa(index)+}++// ResolveDirectColors 为本数据库直接持有的选项和值填充派生颜色。+func (av *AttributeView) ResolveDirectColors() {+ if nil == av {+ return+ }+ for _, keyValues := range av.KeyValues {+ if nil == keyValues {+ continue+ }+ if nil != keyValues.Key {+ for _, option := range keyValues.Key.Options {+ if nil != option {+ option.ResolvedColor = av.ResolveColor(option.Color)+ }+ }+ }+ for _, value := range keyValues.Values {+ resolveValueSelectColors(value, av)+ }+ }+ for _, view := range av.Views {+ av.resolveDirectViewGroupColors(view)+ }+}++// ApplyRelatedCustomColorRenderContext 为关联数据库应用当前只读渲染请求中的历史调色板。+func (av *AttributeView) ApplyRelatedCustomColorRenderContext(target *AttributeView) {+ if nil == av || nil == target || nil == av.CustomColorRenderContext ||+ nil == av.CustomColorRenderContext.ResolveRelatedCustomColors {+ return+ }++ context := av.CustomColorRenderContext+ if target.CustomColorRenderContext == context {+ return+ }+ target.CustomColorRenderContext = context+ colors, found := context.ResolveRelatedCustomColors(target.ID)+ if !found {+ colors = []*AttributeViewCustomColor{}+ }+ target.CustomColors, _ = NormalizeAttributeViewCustomColors(colors, false)+ target.ResolveDirectColors()+}++func (av *AttributeView) resolveDirectViewGroupColors(view *View) {+ if nil == view {+ return+ }+ if nil != view.GroupKey {+ if key, err := av.GetKey(view.GroupKey.ID); nil == err &&+ (KeyTypeSelect == key.Type || KeyTypeMSelect == key.Type) {+ for _, option := range view.GroupKey.Options {+ if nil != option {+ option.ResolvedColor = av.ResolveColor(option.Color)+ }+ }+ resolveValueSelectColors(view.GroupVal, av)+ }+ }+ for _, group := range view.Groups {+ av.resolveDirectViewGroupColors(group)+ }+}++// ResolveValueSelectColors 为数据库上下文中的直接选择值填充派生颜色。+func (av *AttributeView) ResolveValueSelectColors(value *Value) {+ resolveValueSelectColors(value, av)+}++func resolveValueSelectColors(value *Value, av *AttributeView) {+ if nil == value {+ return+ }+ for _, selection := range value.MSelect {+ if nil != selection {+ selection.ResolvedColor = av.ResolveColor(selection.Color)+ }+ }+}++type resolvedColorBinding struct {+ option *SelectOption+ selection *ValueSelect+ color *AttributeViewColor+}++// suspendResolvedColors 在序列化持久化数据期间临时清除所有派生颜色。+func (av *AttributeView) suspendResolvedColors() (restore func()) {+ var bindings []resolvedColorBinding+ if nil != av {+ av.visitPersistedColorHolders(func(option *SelectOption) {+ if nil != option.ResolvedColor {+ bindings = append(bindings, resolvedColorBinding{option: option, color: option.ResolvedColor})+ option.ResolvedColor = nil+ }+ }, func(selection *ValueSelect) {+ if nil != selection.ResolvedColor {+ bindings = append(bindings, resolvedColorBinding{selection: selection, color: selection.ResolvedColor})+ selection.ResolvedColor = nil+ }+ })+ }+ return func() {+ for _, binding := range bindings {+ if nil != binding.option {+ binding.option.ResolvedColor = binding.color+ } else if nil != binding.selection {+ binding.selection.ResolvedColor = binding.color+ }+ }+ av.ResolveDirectColors()+ }+}++func (av *AttributeView) visitPersistedColorHolders(visitOption func(*SelectOption), visitSelection func(*ValueSelect)) {+ for _, keyValues := range av.KeyValues {+ if nil == keyValues {+ continue+ }+ visitKeyColorHolders(keyValues.Key, visitOption, visitSelection)+ for _, value := range keyValues.Values {+ walkValueSelects(value, visitSelection)+ }+ }+ for _, view := range av.Views {+ visitViewColorHolders(view, visitOption, visitSelection)+ }+ for _, itemTemplate := range av.NewItemTemplates {+ if nil == itemTemplate {+ continue+ }+ for _, fieldValue := range itemTemplate.FieldValues {+ if nil != fieldValue {+ walkValueSelects(fieldValue.Value, visitSelection)+ }+ }+ }+}++func visitKeyColorHolders(key *Key, visitOption func(*SelectOption), visitSelection func(*ValueSelect)) {+ if nil == key {+ return+ }+ for _, option := range key.Options {+ if nil != option {+ visitOption(option)+ }+ }+ if nil != key.Relation {+ visitFilterColorHolders(key.Relation.CandidateFilters, visitSelection)+ }+ if nil != key.Rollup {+ visitFilterColorHolders(key.Rollup.Filters, visitSelection)+ if nil != key.Rollup.Calc {+ walkValueSelects(key.Rollup.Calc.Result, visitSelection)+ }+ }+}++func visitFilterColorHolders(filters []*ViewFilter, visitSelection func(*ValueSelect)) {+ for _, filter := range filters {+ if nil == filter {+ continue+ }+ walkValueSelects(filter.Value, visitSelection)+ visitFilterColorHolders(filter.Filters, visitSelection)+ }+}++func visitViewColorHolders(view *View, visitOption func(*SelectOption), visitSelection func(*ValueSelect)) {+ if nil == view {+ return+ }+ visitKeyColorHolders(view.GroupKey, visitOption, visitSelection)+ walkValueSelects(view.GroupVal, visitSelection)+ visitFilterColorHolders(view.Filters, visitSelection)+ if nil != view.GroupCalc && nil != view.GroupCalc.FieldCalc {+ walkValueSelects(view.GroupCalc.FieldCalc.Result, visitSelection)+ }+ if nil != view.Table {+ if nil != view.Table.BaseLayout {+ visitFilterColorHolders(view.Table.Filters, visitSelection)+ }+ for _, column := range view.Table.Columns {+ if nil == column {+ continue+ }+ visitBaseFieldColorHolders(column.BaseField, visitSelection)+ if nil != column.Calc {+ walkValueSelects(column.Calc.Result, visitSelection)+ }+ }+ }+ if nil != view.Gallery {+ if nil != view.Gallery.BaseLayout {+ visitFilterColorHolders(view.Gallery.Filters, visitSelection)+ }+ for _, field := range view.Gallery.CardFields {+ if nil != field {+ visitBaseFieldColorHolders(field.BaseField, visitSelection)+ }+ }+ }+ if nil != view.Kanban {+ if nil != view.Kanban.BaseLayout {+ visitFilterColorHolders(view.Kanban.Filters, visitSelection)+ }+ for _, field := range view.Kanban.Fields {+ if nil != field {+ visitBaseFieldColorHolders(field.BaseField, visitSelection)+ }+ }+ }+ for _, group := range view.Groups {+ visitViewColorHolders(group, visitOption, visitSelection)+ }+}++func visitBaseFieldColorHolders(field *BaseField, visitSelection func(*ValueSelect)) {+ if nil != field && nil != field.Calc {+ walkValueSelects(field.Calc.Result, visitSelection)+ }+}++func walkValueSelects(value *Value, fn func(*ValueSelect)) {+ if nil == value {+ return+ }+ for _, selection := range value.MSelect {+ if nil != selection {+ fn(selection)+ }+ }+ if nil != value.Relation {+ for _, content := range value.Relation.Contents {+ walkValueSelects(content, fn)+ }+ }+ if nil != value.Rollup {+ for _, content := range value.Rollup.Contents {+ walkValueSelects(content, fn)+ }+ }+}++// copyValueResolvedColors 让内核内部值克隆保留已经可信解析的派生颜色。+func copyValueResolvedColors(cloned, original *Value) {+ if nil == cloned || nil == original {+ return+ }+ for i, selection := range original.MSelect {+ if len(cloned.MSelect) <= i || nil == cloned.MSelect[i] || nil == selection || nil == selection.ResolvedColor {+ continue+ }+ resolved := *selection.ResolvedColor+ cloned.MSelect[i].ResolvedColor = &resolved+ }+ if nil != cloned.Relation && nil != original.Relation {+ for i, content := range original.Relation.Contents {+ if len(cloned.Relation.Contents) <= i {+ break+ }+ copyValueResolvedColors(cloned.Relation.Contents[i], content)+ }+ }+ if nil != cloned.Rollup && nil != original.Rollup {+ for i, content := range original.Rollup.Contents {+ if len(cloned.Rollup.Contents) <= i {+ break+ }+ copyValueResolvedColors(cloned.Rollup.Contents[i], content)+ }+ }+}++// UsesCustomColor 判断数据库持久化数据是否仍引用指定的自定义颜色编号。+func (av *AttributeView) UsesCustomColor(index int) bool {+ if nil == av || index < CustomColorMinIndex || CustomColorMaxIndex < index {+ return false+ }+ _, ret := av.usedCustomColorIndexSet()[index]+ return ret+}++func (av *AttributeView) usedCustomColorIndexSet() map[int]struct{} {+ ret := map[int]struct{}{}+ if nil == av {+ return ret+ }+ addColor := func(color string) {+ index, err := strconv.Atoi(strings.TrimSpace(color))+ if nil == err && CustomColorMinIndex <= index && index <= CustomColorMaxIndex {+ ret[index] = struct{}{}+ }+ }+ for _, keyValues := range av.KeyValues {+ if nil == keyValues {+ continue+ }+ collectKeyCustomColorIndexes(keyValues.Key, addColor)+ for _, value := range keyValues.Values {+ collectValueCustomColorIndexes(value, addColor)+ }+ }+ for _, view := range av.Views {+ collectViewCustomColorIndexes(view, av, addColor)+ }+ for _, itemTemplate := range av.NewItemTemplates {+ if nil == itemTemplate {+ continue+ }+ for _, fieldValue := range itemTemplate.FieldValues {+ if nil != fieldValue {+ collectValueCustomColorIndexes(fieldValue.Value, addColor)+ }+ }+ }+ return ret+}++// UsedCustomColorIndexes 返回数据库中仍被引用的自定义颜色编号。+func (av *AttributeView) UsedCustomColorIndexes() (ret []int) {+ used := av.usedCustomColorIndexSet()+ for index := CustomColorMinIndex; index <= CustomColorMaxIndex; index++ {+ if _, ok := used[index]; ok {+ ret = append(ret, index)+ }+ }+ if nil == ret {+ ret = []int{}+ }+ return+}++func collectKeyCustomColorIndexes(key *Key, addColor func(string)) {+ if nil == key {+ return+ }+ for _, option := range key.Options {+ if nil != option {+ addColor(option.Color)+ }+ }+}++func collectFilterCustomColorIndexes(filters []*ViewFilter, attrView *AttributeView, addColor func(string)) {+ for _, filter := range filters {+ if nil == filter {+ continue+ }+ if key, err := attrView.GetKey(filter.Column); nil == err &&+ (KeyTypeSelect == key.Type || KeyTypeMSelect == key.Type) {+ collectValueCustomColorIndexes(filter.Value, addColor)+ }+ collectFilterCustomColorIndexes(filter.Filters, attrView, addColor)+ }+}++func collectValueCustomColorIndexes(value *Value, addColor func(string)) {+ if nil == value {+ return+ }+ for _, selection := range value.MSelect {+ if nil != selection {+ addColor(selection.Color)+ }+ }+}++func collectViewCustomColorIndexes(view *View, attrView *AttributeView, addColor func(string)) {+ if nil == view {+ return+ }+ collectKeyCustomColorIndexes(view.GroupKey, addColor)+ collectFilterCustomColorIndexes(view.Filters, attrView, addColor)+ collectValueCustomColorIndexes(view.GroupVal, addColor)+ if nil != view.Table {+ if nil != view.Table.BaseLayout {+ collectFilterCustomColorIndexes(view.Table.Filters, attrView, addColor)+ }+ }+ if nil != view.Gallery {+ if nil != view.Gallery.BaseLayout {+ collectFilterCustomColorIndexes(view.Gallery.Filters, attrView, addColor)+ }+ }+ if nil != view.Kanban {+ if nil != view.Kanban.BaseLayout {+ collectFilterCustomColorIndexes(view.Kanban.Filters, attrView, addColor)+ }+ }+ for _, group := range view.Groups {+ collectViewCustomColorIndexes(group, attrView, addColor)+ }+}diff --git a/kernel/av/color_render_context_test.go b/kernel/av/color_render_context_test.gonew file mode 100644index 0000000000..f002fec632--- /dev/null+++ b/kernel/av/color_render_context_test.go@@ -0,0 +1,85 @@+// SiYuan - From thought to insight, with agents+// 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.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package av++import "testing"++func TestRollupFilterUsesHistoricalTargetCustomColorContext(t *testing.T) {+ relationKey := &Key{ID: "relation", Type: KeyTypeRelation, Relation: &Relation{AvID: "target"}}+ rollupKey := &Key{+ ID: "rollup", Type: KeyTypeRollup,+ Rollup: &Rollup{RelationKeyID: relationKey.ID, KeyID: "select"},+ }+ source := &AttributeView{+ CustomColorRenderContext: &CustomColorRenderContext{+ ResolveRelatedCustomColors: func(string) ([]*AttributeViewCustomColor, bool) {+ return []*AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: AttributeViewColor{+ Light: AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}, true+ },+ },+ KeyValues: []*KeyValues{+ {Key: relationKey, Values: []*Value{{+ KeyID: relationKey.ID, BlockID: "source-item", Type: KeyTypeRelation,+ Relation: &ValueRelation{BlockIDs: []string{"target-item"}},+ }}},+ {Key: rollupKey},+ },+ }+ targetValue := &Value{+ KeyID: "select", BlockID: "target-item", Type: KeyTypeSelect,+ MSelect: []*ValueSelect{{Content: "Current target value", Color: "15"}},+ }+ target := &AttributeView{+ ID: "target",+ CustomColors: []*AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: AttributeViewColor{+ Light: AttributeViewColorTheme{Color: "#111213", BackgroundColor: "#141516"},+ Dark: AttributeViewColorTheme{Color: "#171819", BackgroundColor: "#1a1b1c"},+ },+ }},+ KeyValues: []*KeyValues{{+ Key: &Key{ID: "select", Type: KeyTypeSelect}, Values: []*Value{targetValue},+ }},+ }+ target.ResolveDirectColors()+ rollupValue := &Value{KeyID: rollupKey.ID, BlockID: "source-item", Type: KeyTypeRollup, Rollup: &ValueRollup{}}+ filter := &ViewFilter{+ Qualifier: FilterQuantifierAny,+ Operator: FilterOperatorIsEqual,+ Value: &Value{Type: KeyTypeRollup, Rollup: &ValueRollup{Contents: []*Value{{+ Type: KeyTypeSelect, MSelect: []*ValueSelect{{Content: "Current target value", Color: "15"}},+ }}}},+ }++ if !rollupValue.Filter(filter, source, "source-item", map[string]*RollupRenderContext{},+ map[string]*AttributeView{"target": target}) {+ t.Fatal("matching current target value did not pass the rollup filter")+ }+ if "Current target value" != targetValue.MSelect[0].Content {+ t.Fatal("historical palette context changed the current target value")+ }+ if 1 != len(rollupValue.Rollup.Contents) || nil == rollupValue.Rollup.Contents[0].MSelect[0].ResolvedColor ||+ "#010203" != rollupValue.Rollup.Contents[0].MSelect[0].ResolvedColor.Light.Color {+ t.Fatalf("filter rollup did not use the historical target palette: %+v", rollupValue.Rollup.Contents)+ }+}diff --git a/kernel/av/color_test.go b/kernel/av/color_test.goindex 60460168e8..1ef86abad8 100644--- a/kernel/av/color_test.go+++ b/kernel/av/color_test.go@@ -16,7 +16,24 @@package av-import "testing"+import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/goccy/go-json"+)++func testAttributeViewCustomColor(index int, lightColor, lightBackground, darkColor, darkBackground string) *AttributeViewCustomColor {+ return &AttributeViewCustomColor{+ Index: index,+ AttributeViewColor: AttributeViewColor{+ Light: AttributeViewColorTheme{Color: lightColor, BackgroundColor: lightBackground},+ Dark: AttributeViewColorTheme{Color: darkColor, BackgroundColor: darkBackground},+ },+ }+}func TestFilterColorValuePreservesPaletteIndex(t *testing.T) {for _, color := range []string{"", "1", "14"} {@@ -44,3 +61,252 @@ func TestFilterColorValueRejectsUnsafeValues(t *testing.T) {}}}++func TestNormalizeAttributeViewCustomColors(t *testing.T) {+ colors, err := NormalizeAttributeViewCustomColors([]*AttributeViewCustomColor{+ testAttributeViewCustomColor(16, " #AABBCC ", "#DDEEFF", "#112233", "#445566"),+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0A0B0C"),+ }, true)+ if nil != err {+ t.Fatalf("normalize attribute view custom colors failed: %s", err)+ }+ if 2 != len(colors) || 15 != colors[0].Index || 16 != colors[1].Index {+ t.Fatalf("custom colors were not sorted by index: %+v", colors)+ }+ if "#aabbcc" != colors[1].Light.Color || "#0a0b0c" != colors[0].Dark.BackgroundColor {+ t.Fatalf("custom colors were not normalized: %+v", colors)+ }++ invalid := [][]*AttributeViewCustomColor{+ {testAttributeViewCustomColor(14, "#000000", "#ffffff", "#000000", "#ffffff")},+ {testAttributeViewCustomColor(79, "#000000", "#ffffff", "#000000", "#ffffff")},+ {testAttributeViewCustomColor(15, "red", "#ffffff", "#000000", "#ffffff")},+ {testAttributeViewCustomColor(15, "#000000", `url("javascript:alert(1)")`, "#000000", "#ffffff")},+ {+ testAttributeViewCustomColor(15, "#000000", "#ffffff", "#000000", "#ffffff"),+ testAttributeViewCustomColor(15, "#111111", "#eeeeee", "#111111", "#eeeeee"),+ },+ }+ for _, input := range invalid {+ if _, err = NormalizeAttributeViewCustomColors(input, true); nil == err {+ t.Fatalf("expected invalid custom colors to fail: %+v", input)+ }+ }++ tooMany := make([]*AttributeViewCustomColor, MaxCustomColors+1)+ if _, err = NormalizeAttributeViewCustomColors(tooMany, true); nil == err {+ t.Fatal("expected an oversized custom palette to fail")+ }++ data, err := json.Marshal(colors[0])+ if nil != err {+ t.Fatalf("marshal custom color failed: %s", err)+ }+ fields := map[string]json.RawMessage{}+ if err = json.Unmarshal(data, &fields); nil != err {+ t.Fatalf("unmarshal custom color fields failed: %s", err)+ }+ if 3 != len(fields) || nil == fields["index"] || nil == fields["light"] || nil == fields["dark"] {+ t.Fatalf("custom color JSON must contain only index/light/dark: %s", data)+ }++ invalidView := &AttributeView{ID: "20260824120000-colors1", Spec: CurrentSpec}+ invalidView.CustomColors = []*AttributeViewCustomColor{+ testAttributeViewCustomColor(14, "#000000", "#ffffff", "#000000", "#ffffff"),+ }+ if err = SaveAttributeView(invalidView); nil == err {+ t.Fatal("save attribute view accepted an invalid custom palette")+ }+}++func TestAttributeViewCustomColorIndexes(t *testing.T) {+ attrView := &AttributeView{CustomColors: []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),+ testAttributeViewCustomColor(17, "#111213", "#141516", "#171819", "#1a1b1c"),+ }}+ if 16 != attrView.NextCustomColorIndex() {+ t.Fatalf("expected the smallest free custom color index, got %d", attrView.NextCustomColorIndex())+ }+ if "15" != attrView.FilterColorValue(" 15 ") {+ t.Fatal("defined custom color index was rejected")+ }+ if "" != attrView.FilterColorValue("16") || "" != attrView.FilterColorValue(`15);color:red`) {+ t.Fatal("undefined or unsafe custom color index was accepted")+ }+ resolved := attrView.ResolveColor("15")+ if nil == resolved || "#010203" != resolved.Light.Color || "#0a0b0c" != resolved.Dark.BackgroundColor {+ t.Fatalf("unexpected resolved custom color: %+v", resolved)+ }++ key := NewKey("key", "Select", "", KeyTypeSelect)+ key.Options = []*SelectOption{{Name: "Used", Color: " 015 "}}+ attrView.KeyValues = []*KeyValues{{Key: key}}+ if !attrView.UsesCustomColor(15) {+ t.Fatal("custom color reference with a non-canonical index was not detected")+ }+ used := attrView.UsedCustomColorIndexes()+ if 1 != len(used) || 15 != used[0] {+ t.Fatalf("unexpected used custom color indexes: %+v", used)+ }++ attrView.KeyValues = []*KeyValues{{Values: []*Value{+ {Rollup: &ValueRollup{Contents: []*Value{{MSelect: []*ValueSelect{{Content: "Target", Color: "15"}}}}}},+ {Relation: &ValueRelation{Contents: []*Value{{MSelect: []*ValueSelect{{Content: "Target", Color: "15"}}}}}},+ }}}+ if attrView.UsesCustomColor(15) || 0 != len(attrView.UsedCustomColorIndexes()) {+ t.Fatal("target database colors in rollup/relation contents were counted as current database references")+ }+ if 16 != attrView.NextCustomColorIndex() {+ t.Fatalf("existing gaps were unexpectedly reordered, got next index %d", attrView.NextCustomColorIndex())+ }+ attrView.CustomColors = attrView.CustomColors[1:]+ if 15 != attrView.NextCustomColorIndex() || 17 != attrView.CustomColors[0].Index {+ t.Fatalf("deleting a color reordered stable indexes: %+v", attrView.CustomColors)+ }+}++func TestUsedCustomColorIndexesScansPersistedReferences(t *testing.T) {+ selectValue := func(index string) *Value {+ return &Value{MSelect: []*ValueSelect{{Content: "Value", Color: index}}}+ }+ filter := func(column, index string) *ViewFilter {+ return &ViewFilter{Column: column, Value: selectValue(index)}+ }+ selectKey := &Key{ID: "select", Type: KeyTypeSelect, Options: []*SelectOption{{Color: "20"}}}+ attrView := &AttributeView{+ KeyValues: []*KeyValues{+ {Key: &Key{ID: "relation", Type: KeyTypeRelation, Relation: &Relation{+ CandidateFilters: []*ViewFilter{{Filters: []*ViewFilter{filter("target-select", "15")}}},+ }}},+ {Key: &Key{ID: "rollup", Type: KeyTypeRollup, Rollup: &Rollup{+ Filters: []*ViewFilter{filter("target-select", "16")}, Calc: &RollupCalc{Result: selectValue("17")},+ }}},+ {Key: selectKey, Values: []*Value{selectValue("18")}},+ },+ Views: []*View{{+ Filters: []*ViewFilter{filter(selectKey.ID, "19")},+ GroupKey: selectKey,+ GroupVal: selectValue("21"),+ GroupCalc: &GroupCalc{FieldCalc: &FieldCalc{Result: selectValue("22")}},+ Table: &LayoutTable{+ BaseLayout: &BaseLayout{Filters: []*ViewFilter{filter(selectKey.ID, "23")}},+ Columns: []*ViewTableColumn{{+ BaseField: &BaseField{Calc: &FieldCalc{Result: selectValue("24")}},+ Calc: &FieldCalc{Result: selectValue("25")},+ }},+ },+ Groups: []*View{{GroupVal: selectValue("26")}},+ }},+ NewItemTemplates: []*NewItemTemplate{{FieldValues: map[string]*NewItemFieldValue{+ "field": {Value: selectValue("27")},+ }}},+ }+ want := []int{18, 19, 20, 21, 23, 26, 27}+ got := attrView.UsedCustomColorIndexes()+ if len(want) != len(got) {+ t.Fatalf("unexpected used custom color indexes: %+v", got)+ }+ for i := range want {+ if want[i] != got[i] {+ t.Fatalf("unexpected used custom color indexes: %+v", got)+ }+ }+}++func TestResolvedColorCannotBeLoadedFromJSON(t *testing.T) {+ payload := `{"name":"Option","content":"Value","color":"15","resolvedColor":{"light":{"color":"#000000","backgroundColor":"#ffffff"},"dark":{"color":"#ffffff","backgroundColor":"#000000"}}}`+ option := &SelectOption{}+ if err := json.Unmarshal([]byte(payload), option); nil != err {+ t.Fatalf("unmarshal select option failed: %s", err)+ }+ if nil != option.ResolvedColor {+ t.Fatal("select option accepted an externally supplied resolved color")+ }+ selection := &ValueSelect{}+ if err := json.Unmarshal([]byte(payload), selection); nil != err {+ t.Fatalf("unmarshal select value failed: %s", err)+ }+ if nil != selection.ResolvedColor {+ t.Fatal("select value accepted an externally supplied resolved color")+ }++ attrView := &AttributeView{+ CustomColors: []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),+ },+ KeyValues: []*KeyValues{{+ Key: &Key{Options: []*SelectOption{option}},+ Values: []*Value{{Type: KeyTypeSelect, MSelect: []*ValueSelect{selection}}},+ }},+ }+ attrView.ResolveDirectColors()+ if nil == option.ResolvedColor || nil == selection.ResolvedColor {+ t.Fatal("direct option and value colors were not resolved from the validated palette")+ }+ restore := attrView.suspendResolvedColors()+ data, err := json.Marshal(attrView)+ if nil != err {+ t.Fatalf("marshal attribute view failed: %s", err)+ }+ if strings.Contains(string(data), "resolvedColor") {+ t.Fatalf("derived colors leaked into persisted JSON: %s", data)+ }+ restore()+ if nil == option.ResolvedColor || nil == selection.ResolvedColor {+ t.Fatal("derived colors were not restored after persistence serialization")+ }++ nested := &Value{Rollup: &ValueRollup{Contents: []*Value{{MSelect: []*ValueSelect{selection}}}}}+ cloned := nested.Clone()+ if nil == cloned || nil == cloned.Rollup || 1 != len(cloned.Rollup.Contents) ||+ nil == cloned.Rollup.Contents[0].MSelect[0].ResolvedColor {+ t.Fatalf("internal value clone discarded a trusted resolved color: %+v", cloned)+ }+ if cloned.Rollup.Contents[0].MSelect[0].ResolvedColor == selection.ResolvedColor {+ t.Fatal("internal value clone reused a mutable resolved color pointer")+ }+}++func TestGroupResolvedColorSurvivesPersistenceRoundTrip(t *testing.T) {+ selectKey := &Key{ID: "select", Type: KeyTypeSelect}+ selectKey.Options = []*SelectOption{{Name: "Group", Color: "15"}}+ attrView := &AttributeView{+ Spec: CurrentSpec,+ ID: "20260824120000-colors2",+ CustomColors: []*AttributeViewCustomColor{testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c")},+ KeyValues: []*KeyValues{{Key: selectKey}},+ Views: []*View{{+ ID: "view",+ LayoutType: LayoutTypeTable,+ Group: &ViewGroup{Field: selectKey.ID},+ Groups: []*View{{+ GroupKey: selectKey,+ GroupVal: &Value{Type: KeyTypeSelect, MSelect: []*ValueSelect{{Content: "Group", Color: "15"}}},+ }},+ }},+ }+ attrView.ResolveDirectColors()+ if nil == attrView.Views[0].Groups[0].GroupVal.MSelect[0].ResolvedColor {+ t.Fatal("group value color was not initially resolved")+ }++ restore := attrView.suspendResolvedColors()+ data, err := json.Marshal(attrView)+ restore()+ if nil != err {+ t.Fatalf("marshal attribute view failed: %s", err)+ }+ path := filepath.Join(t.TempDir(), attrView.ID+".json")+ if err = os.WriteFile(path, data, 0o600); nil != err {+ t.Fatalf("write attribute view failed: %s", err)+ }++ parsed, err := ParseAttributeViewByPath(path)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ groupValue := parsed.Views[0].Groups[0].GroupVal.MSelect[0]+ if nil == groupValue.ResolvedColor || "#010203" != groupValue.ResolvedColor.Light.Color {+ t.Fatalf("group value color was not resolved after persistence round trip: %+v", groupValue)+ }+}diff --git a/kernel/av/filter.go b/kernel/av/filter.goindex 0587470980..09b833e3a7 100644--- a/kernel/av/filter.go+++ b/kernel/av/filter.go@@ -609,6 +609,7 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID sif nil == destAv {return false}+ attrView.ApplyRelatedCustomColorRenderContext(destAv)destKey, _ := destAv.GetKey(key.Rollup.KeyID)if nil == destKey {@@ -616,7 +617,7 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID s}rollupContext := rollupFurtherCollections[key.ID]- value.Rollup.BuildContents(destAv.KeyValues, destKey, relVal, key.Rollup.Calc, rollupContext)+ value.Rollup.BuildContents(destAv, destKey, relVal, key.Rollup.Calc, rollupContext)relationContentCount := len(relVal.Relation.Contents)if nil != rollupContext && nil != rollupContext.EligibleItemIDs {relationContentCount = 0diff --git a/kernel/av/value.go b/kernel/av/value.goindex d0b6ffad3b..41ec6db19e 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -204,6 +204,7 @@ func (value *Value) Clone() (ret *Value) {if err != nil {return}+ copyValueResolvedColors(ret, value)return}@@ -820,8 +821,9 @@ func Round(val float64, precision int) float64 {}type ValueSelect struct {- Content string `json:"content"`- Color string `json:"color"` // 1-14+ Content string `json:"content"`+ Color string `json:"color"` // 1-78+ ResolvedColor *AttributeViewColor `json:"resolvedColor,omitempty"` // 渲染阶段解析后的自定义颜色}func MSelectRemoveOption(mSelect []*ValueSelect, opt string) (ret []*ValueSelect) {@@ -1001,15 +1003,18 @@ type RollupRenderContext struct {EligibleItemIDs map[string]bool}-func (r *ValueRollup) BuildContents(keyValues []*KeyValues, destKey *Key, relationVal *Value, calc *RollupCalc,+func (r *ValueRollup) BuildContents(attrView *AttributeView, destKey *Key, relationVal *Value, calc *RollupCalc,context *RollupRenderContext) {r.Contents = nil+ if nil == attrView {+ return+ }for _, blockID := range relationVal.Relation.BlockIDs {if nil != context && nil != context.EligibleItemIDs && !context.EligibleItemIDs[blockID] {continue}- destVal := GetValue(keyValues, destKey.ID, blockID)+ destVal := GetValue(attrView.KeyValues, destKey.ID, blockID)if nil != context && nil != context.FurtherCollection &&(KeyTypeTemplate == destKey.Type || KeyTypeUpdated == destKey.Type || KeyTypeCreated == destKey.Type) {destVal = context.FurtherCollection.GetValue(blockID, destKey.ID)@@ -1042,7 +1047,11 @@ func (r *ValueRollup) BuildContents(keyValues []*KeyValues, destKey *Key, relatidestVal.Updated.FormatDate(destKey.DateFormat, isNotTime)}- r.Contents = append(r.Contents, destVal.Clone())+ cloned := destVal.Clone()+ if KeyTypeSelect == destKey.Type || KeyTypeMSelect == destKey.Type {+ resolveValueSelectColors(cloned, attrView)+ }+ r.Contents = append(r.Contents, cloned)}r.calcContents(calc, destKey)diff --git a/kernel/av/value_test.go b/kernel/av/value_test.goindex 4f6b8fb4fc..08fc85fa19 100644--- a/kernel/av/value_test.go+++ b/kernel/av/value_test.go@@ -178,7 +178,7 @@ func TestValueRollupBuildContentsFiltersEligibleItems(t *testing.T) {}rollup := &ValueRollup{}- rollup.BuildContents(keyValues, destKey, relationValue, &RollupCalc{Operator: CalcOperatorCountAll},+ rollup.BuildContents(&AttributeView{KeyValues: keyValues}, destKey, relationValue, &RollupCalc{Operator: CalcOperatorCountAll},&RollupRenderContext{EligibleItemIDs: map[string]bool{"item-b": true, "item-c": true}})if 1 != len(rollup.Contents) || nil == rollup.Contents[0].Number {@@ -202,10 +202,42 @@ func TestValueRollupBuildContentsPreservesBlockRefSubtype(t *testing.T) {relationValue := &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"item-a"}}}rollup := &ValueRollup{}- rollup.BuildContents(keyValues, destKey, relationValue, nil, nil)+ rollup.BuildContents(&AttributeView{KeyValues: keyValues}, destKey, relationValue, nil, nil)if 1 != len(rollup.Contents) || nil == rollup.Contents[0].Block ||BlockRefSubtypeDynamic != rollup.Contents[0].Block.RefSubtype {t.Fatalf("rollup did not preserve the block reference subtype: %+v", rollup.Contents)}}++func TestValueRollupBuildContentsResolvesTargetCustomColor(t *testing.T) {+ destKey := &Key{ID: "select", Type: KeyTypeSelect}+ destView := &AttributeView{+ CustomColors: []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),+ },+ KeyValues: []*KeyValues{{+ Key: destKey,+ Values: []*Value{{+ BlockID: "item-a",+ Type: KeyTypeSelect,+ MSelect: []*ValueSelect{{Content: "Target", Color: "15"}},+ }},+ }},+ }+ relationValue := &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"item-a"}}}+ rollup := &ValueRollup{}++ rollup.BuildContents(destView, destKey, relationValue, nil, nil)+ if 1 != len(rollup.Contents) || 1 != len(rollup.Contents[0].MSelect) {+ t.Fatalf("unexpected rollup contents: %+v", rollup.Contents)+ }+ selection := rollup.Contents[0].MSelect[0]+ if nil == selection.ResolvedColor || "#010203" != selection.ResolvedColor.Light.Color ||+ "#0a0b0c" != selection.ResolvedColor.Dark.BackgroundColor {+ t.Fatalf("rollup did not resolve the target database color: %+v", selection)+ }+ if nil != destView.KeyValues[0].Values[0].MSelect[0].ResolvedColor {+ t.Fatal("rollup resolution mutated the persisted target value")+ }+}diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex f1efe3013e..e26a3eda6e 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -371,12 +371,22 @@ func GetAttrViewAddingBlockDefaultValues(avID, blockID, viewID, groupID, previoureturn}+func newAttrViewValueSelect(option *av.SelectOption) *av.ValueSelect {+ ret := &av.ValueSelect{Content: option.Name, Color: option.Color}+ if nil != option.ResolvedColor {+ resolved := *option.ResolvedColor+ ret.ResolvedColor = &resolved+ }+ return ret+}+func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, groupView *av.View, previousItemID, addingItemID string, isCreate, useGroupDefault bool) (ret map[string]*av.Value) {ret = map[string]*av.Value{}defer func() {for keyID, value := range ret {key, _ := attrView.GetKey(keyID)normalizeAttrViewAddingDefaultValue(key, value)+ attrView.ResolveValueSelectColors(value)}}()@@ -444,23 +454,23 @@ func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, groupif nil != newValue {if !av.MSelectExistOption(newValue.MSelect, groupView.GetGroupValue()) {if 1 > len(newValue.MSelect) || av.KeyTypeMSelect == groupKey.Type {- newValue.MSelect = append(newValue.MSelect, &av.ValueSelect{Content: opt.Name, Color: opt.Color})+ newValue.MSelect = append(newValue.MSelect, newAttrViewValueSelect(opt))} else {- newValue.MSelect = []*av.ValueSelect{{Content: opt.Name, Color: opt.Color}}+ newValue.MSelect = []*av.ValueSelect{newAttrViewValueSelect(opt)}}} else {var vals []*av.ValueSelectif isCreate {- vals = append(vals, &av.ValueSelect{Content: opt.Name, Color: opt.Color})+ vals = append(vals, newAttrViewValueSelect(opt))} else {existingVal := keyValues.GetValue(addingItemID)if nil != existingVal {if !av.MSelectExistOption(existingVal.MSelect, opt.Name) {- existingVal.MSelect = append(existingVal.MSelect, &av.ValueSelect{Content: opt.Name, Color: opt.Color})+ existingVal.MSelect = append(existingVal.MSelect, newAttrViewValueSelect(opt))}vals = existingVal.MSelect} else {- vals = append(vals, &av.ValueSelect{Content: opt.Name, Color: opt.Color})+ vals = append(vals, newAttrViewValueSelect(opt))}}@@ -476,7 +486,7 @@ func getAttrViewAddingBlockDefaultValues(attrView *av.AttributeView, view, group}} else {newValue = av.GetAttributeViewDefaultValue(ast.NewNodeID(), groupKey.ID, addingItemID, groupKey.Type, false)- newValue.MSelect = append(newValue.MSelect, &av.ValueSelect{Content: opt.Name, Color: opt.Color})+ newValue.MSelect = append(newValue.MSelect, newAttrViewValueSelect(opt))}}@@ -2041,7 +2051,7 @@ func AppendAttributeViewDetachedBlocksWithValues(avID string, blocksValues [][]*for _, valOpt := range v.MSelect {if opt := key.GetOption(valOpt.Content); nil == opt {// 不存在的选项新建保存- opt = &av.SelectOption{Name: valOpt.Content, Color: av.FilterColorValue(valOpt.Color)}+ opt = &av.SelectOption{Name: valOpt.Content, Color: attrView.FilterColorValue(valOpt.Color)}key.Options = append(key.Options, opt)} else {// 已经存在的选项颜色需要保持不变@@ -2153,7 +2163,7 @@ func DuplicateAttributeViewRow(tx *Transaction, avID, previousItemID, srcRowID,if 0 < len(newVal.MSelect) {for _, valOpt := range newVal.MSelect {if opt := keyValues.Key.GetOption(valOpt.Content); nil == opt {- opt = &av.SelectOption{Name: valOpt.Content, Color: av.FilterColorValue(valOpt.Color)}+ opt = &av.SelectOption{Name: valOpt.Content, Color: attrView.FilterColorValue(valOpt.Color)}keyValues.Key.Options = append(keyValues.Key.Options, opt)} else {valOpt.Color = opt.Color@@ -2512,7 +2522,8 @@ func GetAttributeViewPrimaryKeyValues(avID, keyword string, blockIDs []string, p}func GetAttributeViewRelationCandidates(srcAvID, relationKeyID, keyword string, selectedBlockIDs []string, page, pageSize int) (- attributeViewName string, databaseBlockIDs []string, columns []*av.TableColumn, selectedRows, rows []*av.TableRow,+ attributeViewName string, databaseBlockIDs []string, customColors []*av.AttributeViewCustomColor,+ columns []*av.TableColumn, selectedRows, rows []*av.TableRow,total int, err error,) {waitForSyncingStorages()@@ -2540,6 +2551,7 @@ func GetAttributeViewRelationCandidates(srcAvID, relationKeyID, keyword string,}attributeViewName = getAttrViewName(attrView)databaseBlockIDs = treenode.GetMirrorAttrViewBlockIDs(attrView.ID)+ customColors = attrView.CustomColorstable := renderAttributeViewRelationCandidates(attrView)if nil == table {@@ -2788,6 +2800,7 @@ type AttributeViewData struct {Spec int `json:"spec"`ID string `json:"id"`Name string `json:"name"`+ CustomColors []*av.AttributeViewCustomColor `json:"customColors"`KeyValues []*av.KeyValues `json:"keyValues"`KeyIDs []string `json:"keyIDs"`ViewID string `json:"viewID"`@@ -2804,7 +2817,7 @@ func NewAttributeViewData(attrView *av.AttributeView) (ret *AttributeViewData) {ret = &AttributeViewData{Spec: attrView.Spec, ID: attrView.ID, Name: attrView.Name, KeyValues: attrView.KeyValues, KeyIDs: attrView.KeyIDs,Views: attrView.Views, NewItemTemplates: attrView.NewItemTemplates, DefaultTemplateID: attrView.DefaultTemplateID,- CardCoverPositions: attrView.CardCoverPositions,+ CardCoverPositions: attrView.CardCoverPositions, CustomColors: attrView.CustomColors,}if view, _ := attrView.GetFirstView(); nil != view {ret.ViewID = view.ID@@ -3256,11 +3269,12 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*}type BlockAttributeViewKeys struct {- AvID string `json:"avID"`- AvName string `json:"avName"`- BlockIDs []string `json:"blockIDs"`- KeyValues []*av.KeyValues `json:"keyValues"`- ItemPositions []*AttributeViewItemPosition `json:"itemPositions"`+ AvID string `json:"avID"`+ AvName string `json:"avName"`+ CustomColors []*av.AttributeViewCustomColor `json:"customColors"`+ BlockIDs []string `json:"blockIDs"`+ KeyValues []*av.KeyValues `json:"keyValues"`+ ItemPositions []*AttributeViewItemPosition `json:"itemPositions"`}type AttributeViewItemPosition struct {@@ -3614,6 +3628,7 @@ func GetAttributeViewItemKeys(avID, itemID, valueID string) (ret []*BlockAttriburet = append(ret, &BlockAttributeViewKeys{AvID: avID,AvName: getAttrViewName(attrView),+ CustomColors: attrView.CustomColors,BlockIDs: treenode.GetMirrorAttrViewBlockIDs(avID),KeyValues: keyValues,ItemPositions: getAttributeViewItemPositions(attrView, itemID),@@ -3739,6 +3754,7 @@ func GetBlockAttributeViewKeys(nodeID string) (ret []*BlockAttributeViewKeys) {ret = append(ret, &BlockAttributeViewKeys{AvID: avID,AvName: getAttrViewName(attrView),+ CustomColors: attrView.CustomColors,BlockIDs: blockIDs,KeyValues: keyValues,ItemPositions: getAttributeViewItemPositions(attrView, itemID),@@ -3956,7 +3972,7 @@ func genAttrViewGroups(view *av.View, attrView *av.AttributeView) {if opt := groupKey.GetOption(groupValue); nil != opt {v.GroupVal.Text = nilv.GroupVal.Type = av.KeyTypeSelect- v.GroupVal.MSelect = []*av.ValueSelect{{Content: opt.Name, Color: opt.Color}}+ v.GroupVal.MSelect = []*av.ValueSelect{newAttrViewValueSelect(opt)}}} else if av.KeyTypeRelation == groupKey.Type {if relationDestAv != nil && groupValueDefault != groupValue {@@ -5975,7 +5991,7 @@ func fillDefaultValue(attrView *av.AttributeView, view, groupView *av.View, previf (av.KeyTypeSelect == newValue.Type || av.KeyTypeMSelect == newValue.Type) && 1 > len(newValue.MSelect) && groupValueDefault != groupView.GetGroupValue() {// 单选或多选类型的值可能需要从分组条件中获取默认值if opt := keyValues.Key.GetOption(groupView.GetGroupValue()); nil != opt {- newValue.MSelect = append(newValue.MSelect, &av.ValueSelect{Content: opt.Name, Color: opt.Color})+ newValue.MSelect = append(newValue.MSelect, newAttrViewValueSelect(opt))}}@@ -7841,7 +7857,7 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyIfor _, valOpt := range val.MSelect {if opt := key.GetOption(valOpt.Content); nil == opt {// 不存在的选项新建保存- color := av.FilterColorValue(valOpt.Color)+ color := attrView.FilterColorValue(valOpt.Color)if "" == color {color = fmt.Sprintf("%d", 1+rand.Intn(14))}@@ -8305,28 +8321,87 @@ func updateAttributeViewColumnOptions(operation *Operation) (err error) {for _, opt := range selectKey.Options {existingOptions[opt.Name] = opt}+ colorChanges := map[string]string{}for _, opt := range options {if existingOpt, exists := existingOptions[opt.Name]; exists {// 如果选项已经存在则更新颜色和描述- existingOpt.Color = av.FilterColorValue(opt.Color)+ newColor := attrView.FilterColorValue(opt.Color)+ if existingOpt.Color != newColor {+ colorChanges[existingOpt.Name] = newColor+ }+ existingOpt.Color = newColorexistingOpt.Desc = opt.Desc} else {// 如果选项不存在则添加新选项selectKey.Options = append(selectKey.Options, &av.SelectOption{Name: opt.Name,- Color: av.FilterColorValue(opt.Color),+ Color: attrView.FilterColorValue(opt.Color),Desc: opt.Desc,})}}sortAttributeViewColumnOptions(selectKey.Options, optionSorts)+ for name, color := range colorChanges {+ syncAttributeViewOptionColor(attrView, selectKey.ID, name, color)+ }regenAttrViewGroups(attrView)- err = av.SaveAttributeView(attrView)+ if err = av.SaveAttributeView(attrView); nil != err {+ return+ }+ if 0 == len(colorChanges) {+ return+ }++ for _, relatedAvID := range av.GetSrcAvIDs(attrView.ID) {+ if relatedAvID == attrView.ID {+ continue+ }+ relatedAttrView, parseErr := av.ParseAttributeView(relatedAvID)+ if nil != parseErr || nil == relatedAttrView {+ continue+ }+ changed := false+ for name, color := range colorChanges {+ changed = renameAttrViewOptionInFieldFilters(relatedAttrView, attrView.ID, selectKey.ID,+ name, name, color) || changed+ }+ if !changed {+ continue+ }+ if err = av.SaveAttributeView(relatedAttrView); nil != err {+ return+ }+ ReloadAttrView(relatedAvID)+ }return}+func syncAttributeViewOptionColor(attrView *av.AttributeView, keyID, name, color string) {+ attrView.RenameNewItemTemplateSelectOption(keyID, name, name, color)+ for _, keyValues := range attrView.KeyValues {+ if nil == keyValues || nil == keyValues.Key || keyID != keyValues.Key.ID {+ continue+ }+ for _, value := range keyValues.Values {+ if nil == value {+ continue+ }+ for _, selection := range value.MSelect {+ if nil != selection && name == selection.Content {+ selection.Color = color+ }+ }+ }+ break+ }+ for _, view := range attrView.Views {+ av.RenameSelectOptionInFilters(view.Filters, keyID, name, name, color)+ }+ renameAttrViewOptionInFieldFilters(attrView, attrView.ID, keyID, name, name, color)+}+func sortAttributeViewColumnOptions(options []*av.SelectOption, optionSorts map[string]int) {var sortableOptions []*av.SelectOptionfor _, opt := range options {@@ -8348,6 +8423,67 @@ func sortAttributeViewColumnOptions(options []*av.SelectOption, optionSorts map[}}+func (tx *Transaction) doSetAttrViewCustomColors(operation *Operation) (ret *TxErr) {+ if err := setAttrViewCustomColors(operation); nil != err {+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}+ }+ return+}++func setAttrViewCustomColors(operation *Operation) (err error) {+ attrView, err := avParseView(operation.AvID, operation.BlockID)+ if nil != err {+ return+ }+ if nil == operation.Data {+ return errors.New("attribute view custom colors must be an array")+ }++ data, err := gulu.JSON.MarshalJSON(operation.Data)+ if nil != err {+ return+ }+ colors := []*av.AttributeViewCustomColor{}+ if err = gulu.JSON.UnmarshalJSON(data, &colors); nil != err {+ return+ }+ colors, err = av.NormalizeAttributeViewCustomColors(colors, true)+ if nil != err {+ return+ }++ retainedIndexes := map[int]struct{}{}+ for _, color := range colors {+ retainedIndexes[color.Index] = struct{}{}+ }+ usedIndexes := map[int]struct{}{}+ for _, index := range attrView.UsedCustomColorIndexes() {+ usedIndexes[index] = struct{}{}+ }+ for _, oldColor := range attrView.CustomColors {+ if nil == oldColor {+ continue+ }+ if _, retained := retainedIndexes[oldColor.Index]; !retained {+ if _, used := usedIndexes[oldColor.Index]; used {+ return fmt.Errorf("attribute view custom color [%d] is still in use", oldColor.Index)+ }+ }+ }++ attrView.CustomColors = colors+ if err = avSaveView(attrView, operation.BlockID); nil != err {+ return+ }+ ReloadAttrView(attrView.ID)+ for _, relatedAvID := range av.GetSrcAvIDs(attrView.ID) {+ if relatedAvID != attrView.ID {+ ReloadAttrView(relatedAvID)+ }+ }+ return+}+func (tx *Transaction) doRemoveAttrViewColOption(operation *Operation) (ret *TxErr) {err := removeAttributeViewColumnOption(operation)if err != nil {@@ -8454,7 +8590,7 @@ func updateAttributeViewColumnOption(operation *Operation) (err error) {oldName := strings.TrimSpace(data["oldName"].(string))newName := strings.TrimSpace(data["newName"].(string))newDesc := strings.TrimSpace(data["newDesc"].(string))- newColor := av.FilterColorValue(data["newColor"].(string))+ newColor := attrView.FilterColorValue(data["newColor"].(string))found := falseif oldName != newName {diff --git a/kernel/model/attribute_view_custom_color_history_test.go b/kernel/model/attribute_view_custom_color_history_test.gonew file mode 100644index 0000000000..8a1070654a--- /dev/null+++ b/kernel/model/attribute_view_custom_color_history_test.go@@ -0,0 +1,114 @@+// SiYuan - From thought to insight, with agents+// 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.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "encoding/json"+ "os"+ "path/filepath"+ "sync"+ "sync/atomic"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+)++func TestLoadHistoryAttributeViewCustomColors(t *testing.T) {+ const avID = "20260824000000-target1"+ historyDir := t.TempDir()+ path := filepath.Join(historyDir, "storage", "av", avID+".json")+ if err := os.MkdirAll(filepath.Dir(path), 0755); nil != err {+ t.Fatal(err)+ }+ data, err := json.Marshal(&av.AttributeView{+ Spec: av.CurrentSpec,+ ID: avID,+ CustomColors: []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }},+ })+ if nil != err {+ t.Fatal(err)+ }+ if err = os.WriteFile(path, data, 0644); nil != err {+ t.Fatal(err)+ }++ colors, found := loadHistoryAttributeViewCustomColors(historyDir, avID)+ if !found || 1 != len(colors) || "#010203" != colors[0].Light.Color {+ t.Fatalf("unexpected historical palette: %+v, found %v", colors, found)+ }+ if _, found = loadHistoryAttributeViewCustomColors(historyDir, "20260824000001-missing"); found {+ t.Fatal("missing historical palette was reported as found")+ }+ if _, found = loadHistoryAttributeViewCustomColors(historyDir, "../target1"); found {+ t.Fatal("invalid related attribute view ID was accepted")+ }+}++func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(t *testing.T) {+ var calls atomic.Int32+ resolver := newCachedAttributeViewCustomColorResolver(+ func(string) ([]*av.AttributeViewCustomColor, bool) {+ calls.Add(1)+ return []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}, true+ },+ )++ const goroutines = 32+ var waitGroup sync.WaitGroup+ errs := make(chan string, goroutines)+ for i := 0; i < goroutines; i++ {+ waitGroup.Add(1)+ go func() {+ defer waitGroup.Done()+ colors, found := resolver("20260824000000-target1")+ if !found || 1 != len(colors) || "#0a0b0c" != colors[0].Dark.BackgroundColor {+ errs <- "resolver returned an invalid palette"+ }+ }()+ }+ waitGroup.Wait()+ close(errs)+ for err := range errs {+ t.Fatal(err)+ }+ if 1 != calls.Load() {+ t.Fatalf("palette loader called %d times, want 1", calls.Load())+ }++ secondCalls := atomic.Int32{}+ secondResolver := newCachedAttributeViewCustomColorResolver(+ func(string) ([]*av.AttributeViewCustomColor, bool) {+ secondCalls.Add(1)+ return nil, false+ },+ )+ if _, found := secondResolver("20260824000000-target1"); found || 1 != secondCalls.Load() {+ t.Fatal("separate request resolver reused another request cache")+ }+}diff --git a/kernel/model/attribute_view_default_test.go b/kernel/model/attribute_view_default_test.goindex 15c590a014..8917cdb62d 100644--- a/kernel/model/attribute_view_default_test.go+++ b/kernel/model/attribute_view_default_test.go@@ -154,6 +154,41 @@ func TestTopAddingDoesNotUseGroupedViewDefault(t *testing.T) {}}+func TestAddingDefaultValueResolvesCustomSelectColor(t *testing.T) {+ setupAttributeViewValidationTest(t)++ attrView := av.NewAttributeView("20260824150000-colors3")+ selectKey := attrView.KeyValues[1].Key+ selectKey.Options = []*av.SelectOption{{+ Name: "Custom", Color: "15",+ }}+ attrView.CustomColors = []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}+ view := attrView.Views[0]+ view.Filters = []*av.ViewFilter{{+ Column: selectKey.ID,+ Operator: av.FilterOperatorIsEqual,+ Value: &av.Value{Type: av.KeyTypeSelect, MSelect: []*av.ValueSelect{{+ Content: "Custom", Color: "15",+ }}},+ }}++ values := getAttrViewAddingBlockDefaultValues(attrView, view, view, "", "new-item", true, false)+ value := values[selectKey.ID]+ if nil == value || 1 != len(value.MSelect) || nil == value.MSelect[0].ResolvedColor {+ t.Fatalf("select filter default lost its resolved custom color: %+v", value)+ }+ if "#010203" != value.MSelect[0].ResolvedColor.Light.Color ||+ "#0a0b0c" != value.MSelect[0].ResolvedColor.Dark.BackgroundColor {+ t.Fatalf("unexpected resolved custom color: %+v", value.MSelect[0].ResolvedColor)+ }+}+func TestFillAttrViewAutoFillNowValuesOverridesExistingValue(t *testing.T) {const (itemID = "new-item"diff --git a/kernel/model/attribute_view_options_test.go b/kernel/model/attribute_view_options_test.goindex 996bf4c3d6..b711fe8f3d 100644--- a/kernel/model/attribute_view_options_test.go+++ b/kernel/model/attribute_view_options_test.go@@ -97,6 +97,132 @@ func TestUpdateAttributeViewColumnOptionsKeepsUnspecifiedOptionsInPlace(t *testiassertSelectOptionNames(t, updatedKey.Options, []string{"Second", "First", "Concurrent", "New"})}+func TestUpdateAttributeViewColumnOptionsSynchronizesOptionColorReferences(t *testing.T) {+ setupAttributeViewValidationTest(t)++ attrView := av.NewAttributeView("20260824120000-options")+ attrView.CustomColors = []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}+ selectKey := attrView.KeyValues[1].Key+ selectKey.Options = []*av.SelectOption{{Name: "Used", Color: "15"}}+ selectValue := func() *av.Value {+ return &av.Value{Type: av.KeyTypeSelect, MSelect: []*av.ValueSelect{{Content: "Used", Color: "15"}}}+ }+ attrView.KeyValues[1].Values = []*av.Value{selectValue()}+ attrView.Views[0].Filters = []*av.ViewFilter{{+ Combination: av.FilterCombinationAnd,+ Filters: []*av.ViewFilter{{Column: selectKey.ID, Value: selectValue()}},+ }}+ attrView.NewItemTemplates = []*av.NewItemTemplate{{+ FieldValues: map[string]*av.NewItemFieldValue{+ selectKey.ID: {Mode: av.NewItemFieldValueStatic, Value: selectValue()},+ },+ }}+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ operation := &Operation{AvID: attrView.ID, ID: selectKey.ID, Data: []*av.SelectOption{{Name: "Used", Color: "1"}}}+ if err := updateAttributeViewColumnOptions(operation); nil != err {+ t.Fatalf("update attribute view column options failed: %s", err)+ }++ parsed, err := av.ParseAttributeView(attrView.ID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ if parsed.UsesCustomColor(15) {+ t.Fatal("old option color remained referenced after a batch option update")+ }+ if "1" != parsed.KeyValues[1].Values[0].MSelect[0].Color ||+ "1" != parsed.Views[0].Filters[0].Filters[0].Value.MSelect[0].Color ||+ "1" != parsed.NewItemTemplates[0].FieldValues[selectKey.ID].Value.MSelect[0].Color {+ t.Fatal("batch option update did not synchronize persisted color references")+ }+ if err = setAttrViewCustomColors(&Operation{AvID: attrView.ID, Data: []*av.AttributeViewCustomColor{}}); nil != err {+ t.Fatalf("unused custom color could not be deleted after a batch option update: %s", err)+ }+}++func TestSetAttrViewCustomColorsRejectsDeletingUsedColor(t *testing.T) {+ setupAttributeViewValidationTest(t)++ attrView := av.NewAttributeView("20260824130000-colors1")+ attrView.CustomColors = []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}+ selectKey := attrView.KeyValues[1].Key+ selectKey.Options = []*av.SelectOption{{Name: "Used", Color: "15"}}+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ if err := setAttrViewCustomColors(&Operation{AvID: attrView.ID}); nil == err {+ t.Fatal("missing custom color array should fail")+ }++ operation := &Operation{AvID: attrView.ID, Data: []*av.AttributeViewCustomColor{}}+ if err := setAttrViewCustomColors(operation); nil == err {+ t.Fatal("deleting a referenced custom color should fail")+ }++ updated := []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#111111", BackgroundColor: "#222222"},+ Dark: av.AttributeViewColorTheme{Color: "#eeeeee", BackgroundColor: "#333333"},+ },+ }}+ operation.Data = updated+ if err := setAttrViewCustomColors(operation); nil != err {+ t.Fatalf("editing a referenced custom color should succeed: %s", err)+ }+ parsed, err := av.ParseAttributeView(attrView.ID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ if 1 != len(parsed.CustomColors) || "#111111" != parsed.CustomColors[0].Light.Color {+ t.Fatalf("custom palette update was not saved: %+v", parsed.CustomColors)+ }+}++func TestGenerateAttributeViewGroupsPreservesResolvedCustomColor(t *testing.T) {+ setupAttributeViewValidationTest(t)++ attrView := av.NewAttributeView("20260824140000-colors2")+ attrView.CustomColors = []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}+ selectKey := attrView.KeyValues[1].Key+ selectKey.Options = []*av.SelectOption{{Name: "Custom", Color: "15"}}+ attrView.ResolveDirectColors()+ view := attrView.Views[0]+ view.Group = &av.ViewGroup{Field: selectKey.ID, Method: av.GroupMethodValue}++ genAttrViewGroups(view, attrView)+ group := view.GetGroupByGroupValue("Custom")+ if nil == group || nil == group.GroupVal || 1 != len(group.GroupVal.MSelect) {+ t.Fatalf("custom color group was not generated: %+v", group)+ }+ resolved := group.GroupVal.MSelect[0].ResolvedColor+ if nil == resolved || "#010203" != resolved.Light.Color || "#0a0b0c" != resolved.Dark.BackgroundColor {+ t.Fatalf("custom color group lost its resolved color: %+v", group.GroupVal.MSelect[0])+ }+}+func assertSelectOptionNames(t *testing.T, options []*av.SelectOption, expected []string) {t.Helper()diff --git a/kernel/model/attribute_view_output.go b/kernel/model/attribute_view_output.goindex ef62030ded..3ebd0c175b 100644--- a/kernel/model/attribute_view_output.go+++ b/kernel/model/attribute_view_output.go@@ -20,10 +20,11 @@ import "github.com/siyuan-note/siyuan/kernel/av"// AttributeViewMetadata 描述面向命令行和工具调用方的数据库元数据。type AttributeViewMetadata struct {- ID string `json:"id"`- Name string `json:"name"`- Keys []*av.Key `json:"keys"`- Views []*av.ViewData `json:"views"`+ ID string `json:"id"`+ Name string `json:"name"`+ CustomColors []*av.AttributeViewCustomColor `json:"customColors"`+ Keys []*av.Key `json:"keys"`+ Views []*av.ViewData `json:"views"`}// NewAttributeViewMetadata 构造不包含数据库条目值的元数据。@@ -33,10 +34,11 @@ func NewAttributeViewMetadata(attrView *av.AttributeView) (ret *AttributeViewMet}ret = &AttributeViewMetadata{- ID: attrView.ID,- Name: attrView.Name,- Keys: []*av.Key{},- Views: []*av.ViewData{},+ ID: attrView.ID,+ Name: attrView.Name,+ CustomColors: attrView.CustomColors,+ Keys: []*av.Key{},+ Views: []*av.ViewData{},}for _, keyValues := range attrView.KeyValues {if nil != keyValues && nil != keyValues.Key {@@ -62,9 +64,10 @@ func NewAttributeViewMetadata(attrView *av.AttributeView) (ret *AttributeViewMet// AttributeViewKeys 描述数据库字段及其类型专属配置。type AttributeViewKeys struct {- ID string `json:"id"`- Name string `json:"name"`- Keys []*av.Key `json:"keys"`+ ID string `json:"id"`+ Name string `json:"name"`+ CustomColors []*av.AttributeViewCustomColor `json:"customColors"`+ Keys []*av.Key `json:"keys"`}// NewAttributeViewKeys 构造数据库字段结果。@@ -73,20 +76,21 @@ func NewAttributeViewKeys(attrView *av.AttributeView) (ret *AttributeViewKeys) {if nil == metadata {return}- ret = &AttributeViewKeys{ID: metadata.ID, Name: metadata.Name, Keys: metadata.Keys}+ ret = &AttributeViewKeys{ID: metadata.ID, Name: metadata.Name, CustomColors: metadata.CustomColors, Keys: metadata.Keys}return}// AttributeViewRenderData 描述经过指定视图筛选、排序、分组和分页后的数据库结果。type AttributeViewRenderData struct {- ID string `json:"id"`- Name string `json:"name"`- ViewID string `json:"viewID"`- ViewType av.LayoutType `json:"viewType"`- Query string `json:"query,omitempty"`- Page int `json:"page"`- PageSize int `json:"pageSize"`- View av.Viewable `json:"view"`+ ID string `json:"id"`+ Name string `json:"name"`+ CustomColors []*av.AttributeViewCustomColor `json:"customColors"`+ ViewID string `json:"viewID"`+ ViewType av.LayoutType `json:"viewType"`+ Query string `json:"query,omitempty"`+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+ View av.Viewable `json:"view"`}// NewAttributeViewRenderData 构造数据库渲染结果。@@ -95,14 +99,15 @@ func NewAttributeViewRenderData(attrView *av.AttributeView, view av.Viewable, qureturn}ret = &AttributeViewRenderData{- ID: attrView.ID,- Name: attrView.Name,- ViewID: view.GetID(),- ViewType: view.GetType(),- Query: query,- Page: page,- PageSize: pageSize,- View: view,+ ID: attrView.ID,+ Name: attrView.Name,+ CustomColors: attrView.CustomColors,+ ViewID: view.GetID(),+ ViewType: view.GetType(),+ Query: query,+ Page: page,+ PageSize: pageSize,+ View: view,}return}diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.goindex 5fa471d1e0..599a32520f 100644--- a/kernel/model/attribute_view_render.go+++ b/kernel/model/attribute_view_render.go@@ -26,6 +26,7 @@ import ("sort""strconv""strings"+ "sync""time""github.com/88250/gulu"@@ -1130,6 +1131,100 @@ func ResolveHistoryAttributeViewBoxID(avID, created string) (string, error) {return "", nil}+type attributeViewCustomColorPaletteCacheEntry struct {+ colors []*av.AttributeViewCustomColor+ found bool+}++// newCachedAttributeViewCustomColorResolver 将历史调色板解析限制在单次渲染请求内,并避免并发重复读取。+func newCachedAttributeViewCustomColorResolver(+ loader func(avID string) (colors []*av.AttributeViewCustomColor, found bool),+) func(avID string) (colors []*av.AttributeViewCustomColor, found bool) {+ cache := map[string]attributeViewCustomColorPaletteCacheEntry{}+ var lock sync.Mutex+ return func(avID string) (colors []*av.AttributeViewCustomColor, found bool) {+ lock.Lock()+ defer lock.Unlock()++ if entry, ok := cache[avID]; ok {+ colors, _ = av.NormalizeAttributeViewCustomColors(entry.colors, false)+ return colors, entry.found+ }+ colors, found = loader(avID)+ colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)+ cache[avID] = attributeViewCustomColorPaletteCacheEntry{colors: colors, found: found}+ colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)+ return+ }+}++func decodeHistoricalAttributeViewCustomColors(boxID, avID string, data []byte) (ret []*av.AttributeViewCustomColor, err error) {+ data, err = decryptHistoricalAttributeView(boxID, avID, data)+ if nil != err {+ return+ }+ attrView := &av.AttributeView{}+ if err = gulu.JSON.UnmarshalJSON(data, attrView); nil != err {+ return+ }+ if err = av.CheckSpec(attrView); nil != err {+ return+ }+ if err = attrView.NormalizeCustomColors(false); nil != err {+ return+ }+ ret = attrView.CustomColors+ return+}++func loadHistoryAttributeViewCustomColors(historyDir, avID string) (ret []*av.AttributeViewCustomColor, found bool) {+ if !ast.IsNodeIDPattern(avID) {+ return nil, false+ }+ type source struct {+ path string+ boxID string+ }+ var sources []source+ globalPath := filepath.Join(historyDir, "storage", "av", avID+".json")+ if gulu.File.IsExist(globalPath) {+ sources = append(sources, source{path: globalPath})+ }+ entries, _ := os.ReadDir(historyDir)+ for _, entry := range entries {+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {+ continue+ }+ candidate := filepath.Join(historyDir, entry.Name(), "storage", "av", avID+".json")+ if gulu.File.IsExist(candidate) {+ sources = append(sources, source{path: candidate, boxID: entry.Name()})+ }+ }+ if 1 != len(sources) {+ return nil, false+ }++ data, err := os.ReadFile(sources[0].path)+ if nil != err {+ logging.LogWarnf("read related history attribute view [%s] failed: %s", avID, err)+ return nil, false+ }+ ret, err = decodeHistoricalAttributeViewCustomColors(sources[0].boxID, avID, data)+ if nil != err {+ logging.LogWarnf("parse related history attribute view [%s] failed: %s", avID, err)+ return nil, false+ }+ return ret, true+}++func newHistoryAttributeViewCustomColorRenderContext(historyDir string) *av.CustomColorRenderContext {+ return &av.CustomColorRenderContext{ResolveRelatedCustomColors: newCachedAttributeViewCustomColorResolver(+ func(avID string) (colors []*av.AttributeViewCustomColor, found bool) {+ return loadHistoryAttributeViewCustomColors(historyDir, avID)+ },+ )}+}+func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID string) (viewable av.Viewable, attrView *av.AttributeView, err error) {if !ast.IsNodeIDPattern(avID) {err = ErrInvalidID@@ -1190,6 +1285,38 @@ func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID stringif err = av.CheckSpec(attrView); nil != err {return}+ _ = attrView.NormalizeCustomColors(false)+ attrView.ResolveDirectColors()+ attrView.CustomColorRenderContext = &av.CustomColorRenderContext{+ ResolveRelatedCustomColors: newCachedAttributeViewCustomColorResolver(+ func(targetAvID string) (colors []*av.AttributeViewCustomColor, found bool) {+ if !ast.IsNodeIDPattern(targetAvID) {+ return nil, false+ }+ var matches []*entity.File+ for _, file := range files {+ if strings.HasSuffix(file.Path, "/storage/av/"+targetAvID+".json") {+ matches = append(matches, file)+ }+ }+ if 1 != len(matches) {+ return nil, false+ }+ data, readErr := repo.OpenFile(matches[0])+ if nil != readErr {+ logging.LogWarnf("read related snapshot attribute view [%s] failed: %s", targetAvID, readErr)+ return nil, false+ }+ colors, parseErr := decodeHistoricalAttributeViewCustomColors(+ avBoxIDFromRepoPath(matches[0].Path), targetAvID, data)+ if nil != parseErr {+ logging.LogWarnf("parse related snapshot attribute view [%s] failed: %s", targetAvID, parseErr)+ return nil, false+ }+ return colors, true+ },+ ),+ }viewable, err = renderAttributeView(attrView, "", viewID, carrierViewID, "", 1, -1, nil, false, false, nil, "")return@@ -1221,21 +1348,24 @@ func RenderHistoryAttributeView(avID, viewID, carrierViewID, query string, page,}type historyAttributeViewSource struct {- path string- boxID string+ path string+ boxID string+ historyDir string}var sources []historyAttributeViewSourcefor _, historyDir := range matches {globalPath := filepath.Join(historyDir, "storage", "av", avID+".json")if gulu.File.IsExist(globalPath) {- sources = append(sources, historyAttributeViewSource{path: globalPath})+ sources = append(sources, historyAttributeViewSource{path: globalPath, historyDir: historyDir})}entries, _ := os.ReadDir(historyDir)for _, entry := range entries {if entry.IsDir() && ast.IsNodeIDPattern(entry.Name()) {candidate := filepath.Join(historyDir, entry.Name(), "storage", "av", avID+".json")if gulu.File.IsExist(candidate) {- sources = append(sources, historyAttributeViewSource{path: candidate, boxID: entry.Name()})+ sources = append(sources, historyAttributeViewSource{+ path: candidate, boxID: entry.Name(), historyDir: historyDir,+ })}}}@@ -1272,6 +1402,9 @@ func RenderHistoryAttributeView(avID, viewID, carrierViewID, query string, page,if err = av.CheckSpec(attrView); nil != err {return}+ _ = attrView.NormalizeCustomColors(false)+ attrView.ResolveDirectColors()+ attrView.CustomColorRenderContext = newHistoryAttributeViewCustomColorRenderContext(source.historyDir)viewable, err = renderAttributeView(attrView, "", viewID, carrierViewID, query, page, pageSize, groupPaging, false, false, nil, "")returndiff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.goindex 2eb8665d35..810c9e89b7 100644--- a/kernel/model/publish_access.go+++ b/kernel/model/publish_access.go@@ -1123,10 +1123,11 @@ func FilterBlockAttributeViewKeysByPublishAccess(c *gin.Context, publishAccess P}ret = append(ret, &BlockAttributeViewKeys{- AvID: blockAttributeViewKey.AvID,- AvName: blockAttributeViewKey.AvName,- BlockIDs: blockAttributeViewKey.BlockIDs,- KeyValues: keyValues,+ AvID: blockAttributeViewKey.AvID,+ AvName: blockAttributeViewKey.AvName,+ CustomColors: blockAttributeViewKey.CustomColors,+ BlockIDs: blockAttributeViewKey.BlockIDs,+ KeyValues: keyValues,})}returndiff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex 49a762175e..05227abc2a 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -372,6 +372,13 @@ func TestFilterBlockAttributeViewKeysByPublishAccess(t *testing.T) {newKeys := func(avID, blockID string) *BlockAttributeViewKeys {attrView := av.NewAttributeView(avID)attrView.Name = avID+ attrView.CustomColors = []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}blockKey := attrView.GetBlockKey()textKey := av.NewKey(ast.NewNodeID(), "Text", "", av.KeyTypeText)rowID := ast.NewNodeID()@@ -433,6 +440,9 @@ func TestFilterBlockAttributeViewKeysByPublishAccess(t *testing.T) {if 2 != len(blockAttributeViewKey.KeyValues) {t.Fatalf("unexpected block attribute view key values: %+v", blockAttributeViewKey.KeyValues)}+ if 1 != len(blockAttributeViewKey.CustomColors) || 15 != blockAttributeViewKey.CustomColors[0].Index {+ t.Fatalf("attribute view custom colors were not preserved: %+v", blockAttributeViewKey.CustomColors)+ }for _, keyValues := range blockAttributeViewKey.KeyValues {if 1 != len(keyValues.Values) {t.Fatalf("unexpected block attribute view key value count: %+v", keyValues)@@ -457,10 +467,11 @@ func newTestBlockAttributeViewKeys(attrView *av.AttributeView, blockIDs []string}}return &BlockAttributeViewKeys{- AvID: attrView.ID,- AvName: attrView.Name,- BlockIDs: blockIDs,- KeyValues: keyValues,+ AvID: attrView.ID,+ AvName: attrView.Name,+ CustomColors: attrView.CustomColors,+ BlockIDs: blockIDs,+ KeyValues: keyValues,}}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 846ed7c15e..899c87bb17 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -363,6 +363,8 @@ func performTx(tx *Transaction) (ret *TxErr) {ret = tx.doUpdateAttrViewColOption(op)case "setAttrViewColOptionDesc":ret = tx.doSetAttrViewColOptionDesc(op)+ case "setAttrViewCustomColors":+ ret = tx.doSetAttrViewCustomColors(op)case "setAttrViewColCalc":ret = tx.doSetAttrViewColCalc(op)case "updateAttrViewColNumberFormat":diff --git a/kernel/sql/av.go b/kernel/sql/av.goindex 450d691a84..dd4871b6dc 100644--- a/kernel/sql/av.go+++ b/kernel/sql/av.go@@ -557,13 +557,7 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectionvalue.Relation.Contents = nilrelKey, _ := attrView.GetKey(value.KeyID)if nil != relKey && nil != relKey.Relation {- destAv := cachedAttrViews[relKey.Relation.AvID]- if nil == destAv {- destAv, _ = av.ParseAttributeView(relKey.Relation.AvID)- if nil != destAv {- cachedAttrViews[relKey.Relation.AvID] = destAv- }- }+ destAv := loadRelatedAttributeView(attrView, relKey.Relation.AvID, cachedAttrViews)if nil != destAv {if !normalizedBlockRefSubtypes[destAv.ID] {fillAttributeViewBlockRefSubtypes(destAv, nil)@@ -607,13 +601,7 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectioncontinue}- destAv := cachedAttrViews[relKey.Relation.AvID]- if nil == destAv {- destAv, _ = av.ParseAttributeView(relKey.Relation.AvID)- if nil != destAv {- cachedAttrViews[relKey.Relation.AvID] = destAv- }- }+ destAv := loadRelatedAttributeView(attrView, relKey.Relation.AvID, cachedAttrViews)if nil == destAv {continue}@@ -666,13 +654,7 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectionbreak}- destAv := cachedAttrViews[relKey.Relation.AvID]- if nil == destAv {- destAv, _ = av.ParseAttributeView(relKey.Relation.AvID)- if nil != destAv {- cachedAttrViews[relKey.Relation.AvID] = destAv- }- }+ destAv := loadRelatedAttributeView(attrView, relKey.Relation.AvID, cachedAttrViews)if nil == destAv {break}@@ -683,7 +665,7 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collection}context := rollupRenderContexts[rollupKey.ID]- value.Rollup.BuildContents(destAv.KeyValues, destKey, relVal, rollupKey.Rollup.Calc, context)+ value.Rollup.BuildContents(destAv, destKey, relVal, rollupKey.Rollup.Calc, context)}}}@@ -704,6 +686,28 @@ func hasFilterConditions(filters []*av.ViewFilter) bool {return false}+// loadRelatedAttributeView 为历史和仓库快照渲染绑定请求级调色板,同时保持关联数据库的字段和值来源不变。+func loadRelatedAttributeView(source *av.AttributeView, avID string, cachedAttrViews map[string]*av.AttributeView) (ret *av.AttributeView) {+ if ret = cachedAttrViews[avID]; nil != ret {+ return+ }++ ret, _ = av.ParseAttributeView(avID)+ if nil == ret {+ return+ }+ applyRelatedCustomColorRenderContext(source, ret)+ cachedAttrViews[avID] = ret+ return+}++func applyRelatedCustomColorRenderContext(source, target *av.AttributeView) {+ if nil == source {+ return+ }+ source.ApplyRelatedCustomColorRenderContext(target)+}+func filterAttributeViewItemIDs(attrView *av.AttributeView, filters []*av.ViewFilter, depth *int,cachedAttrViews map[string]*av.AttributeView) (ret map[string]bool) {ret = map[string]bool{}@@ -763,13 +767,9 @@ func getFurtherCollections(attrView *av.AttributeView, cachedAttrViews map[strincontinue}- destAv := cachedAttrViews[relKey.Relation.AvID]+ destAv := loadRelatedAttributeView(attrView, relKey.Relation.AvID, cachedAttrViews)if nil == destAv {- destAv, _ = av.ParseAttributeView(relKey.Relation.AvID)- if nil == destAv {- continue- }- cachedAttrViews[relKey.Relation.AvID] = destAv+ continue}destKey, _ := destAv.GetKey(kv.Key.Rollup.KeyID)diff --git a/kernel/sql/av_custom_color_context_test.go b/kernel/sql/av_custom_color_context_test.gonew file mode 100644index 0000000000..dfdb67957f--- /dev/null+++ b/kernel/sql/av_custom_color_context_test.go@@ -0,0 +1,104 @@+// SiYuan - From thought to insight, with agents+// 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.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+)++func TestApplyRelatedCustomColorRenderContext(t *testing.T) {+ historicalColor := customColorForContextTest("#010203", "#040506", "#070809", "#0a0b0c")+ context := &av.CustomColorRenderContext{ResolveRelatedCustomColors: func(string) ([]*av.AttributeViewCustomColor, bool) {+ return []*av.AttributeViewCustomColor{historicalColor}, true+ }}+ source := &av.AttributeView{CustomColorRenderContext: context}+ target, key, value := relatedCustomColorTargetForContextTest()++ applyRelatedCustomColorRenderContext(source, target)++ if target.CustomColorRenderContext != context {+ t.Fatal("related render context was not propagated")+ }+ if target.KeyValues[0].Key != key || target.KeyValues[0].Values[0] != value || "Current value" != value.MSelect[0].Content {+ t.Fatal("applying a historical palette changed the current target value source")+ }+ if 1 != len(target.CustomColors) || "#010203" != target.CustomColors[0].Light.Color {+ t.Fatalf("unexpected historical palette: %+v", target.CustomColors)+ }+ if nil == key.Options[0].ResolvedColor || "#010203" != key.Options[0].ResolvedColor.Light.Color {+ t.Fatalf("option did not use the historical target palette: %+v", key.Options[0].ResolvedColor)+ }+ if nil == value.MSelect[0].ResolvedColor || "#0a0b0c" != value.MSelect[0].ResolvedColor.Dark.BackgroundColor {+ t.Fatalf("value did not use the historical target palette: %+v", value.MSelect[0].ResolvedColor)+ }+}++func TestApplyRelatedCustomColorRenderContextMissingPalette(t *testing.T) {+ target, key, value := relatedCustomColorTargetForContextTest()+ if nil == key.Options[0].ResolvedColor || nil == value.MSelect[0].ResolvedColor {+ t.Fatal("test target was not initialized with its current palette")+ }+ source := &av.AttributeView{CustomColorRenderContext: &av.CustomColorRenderContext{+ ResolveRelatedCustomColors: func(string) ([]*av.AttributeViewCustomColor, bool) { return nil, false },+ }}++ applyRelatedCustomColorRenderContext(source, target)++ if 0 != len(target.CustomColors) {+ t.Fatalf("missing historical palette retained current colors: %+v", target.CustomColors)+ }+ if nil != key.Options[0].ResolvedColor || nil != value.MSelect[0].ResolvedColor {+ t.Fatal("missing historical palette retained a derived current color")+ }+}++func TestApplyRelatedCustomColorRenderContextOrdinaryRenderDoesNotLeak(t *testing.T) {+ target, key, value := relatedCustomColorTargetForContextTest()+ applyRelatedCustomColorRenderContext(&av.AttributeView{}, target)++ if 1 != len(target.CustomColors) || "#111213" != target.CustomColors[0].Light.Color {+ t.Fatalf("ordinary render palette changed: %+v", target.CustomColors)+ }+ if nil == key.Options[0].ResolvedColor || nil == value.MSelect[0].ResolvedColor {+ t.Fatal("ordinary render lost its current derived color")+ }+}++func relatedCustomColorTargetForContextTest() (target *av.AttributeView, key *av.Key, value *av.Value) {+ currentColor := customColorForContextTest("#111213", "#141516", "#171819", "#1a1b1c")+ key = &av.Key{ID: "select", Type: av.KeyTypeSelect, Options: []*av.SelectOption{{Name: "Current", Color: "15"}}}+ value = &av.Value{Type: av.KeyTypeSelect, MSelect: []*av.ValueSelect{{Content: "Current value", Color: "15"}}}+ target = &av.AttributeView{+ ID: "target",+ CustomColors: []*av.AttributeViewCustomColor{currentColor},+ KeyValues: []*av.KeyValues{{Key: key, Values: []*av.Value{value}}},+ }+ target.ResolveDirectColors()+ return+}++func customColorForContextTest(lightColor, lightBackground, darkColor, darkBackground string) *av.AttributeViewCustomColor {+ return &av.AttributeViewCustomColor{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: lightColor, BackgroundColor: lightBackground},+ Dark: av.AttributeViewColorTheme{Color: darkColor, BackgroundColor: darkBackground},+ },+ }+}