Skip to content

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

:bug: Restore database option data when undoing deletion and merging https://github.com/siyuan-note/siyuan/issues/10907

Danielb2afb9ad1dc3
diff --git a/app/src/protyle/render/av/kanban/groupMenu.ts b/app/src/protyle/render/av/kanban/groupMenu.ts
index 9b1acd9130..80d7903790 100644
--- a/app/src/protyle/render/av/kanban/groupMenu.ts
+++ b/app/src/protyle/render/av/kanban/groupMenu.ts
@@ -53,6 +53,7 @@ export const openKanbanGroupMenu = (options: {
action: "removeAttrViewColOption",
id: colID,
avID,
+ blockID,
data: name,
}, {
action: "doUpdateUpdated",
@@ -62,6 +63,7 @@ export const openKanbanGroupMenu = (options: {
action: "updateAttrViewColOptions",
id: colID,
avID,
+ blockID,
data: colOptions,
}]);
},
@@ -121,6 +123,7 @@ export const openKanbanGroupMenu = (options: {
action: "updateAttrViewColOption",
id: colID,
avID,
+ blockID,
data: {
oldName: name,
newName: name,
@@ -136,6 +139,7 @@ export const openKanbanGroupMenu = (options: {
action: "updateAttrViewColOption",
id: colID,
avID,
+ blockID,
data: {
oldName: name,
newName: name,
diff --git a/app/src/protyle/render/av/optionUndo.test.ts b/app/src/protyle/render/av/optionUndo.test.ts
new file mode 100644
index 0000000000..ae6ce19794
--- /dev/null
+++ b/app/src/protyle/render/av/optionUndo.test.ts
@@ -0,0 +1,117 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const selectSource = readFileSync("src/protyle/render/av/select.ts", "utf8");
+const kanbanSource = readFileSync("src/protyle/render/av/kanban/groupMenu.ts", "utf8");
+const compile = (source: string) => transpileModule(source, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+const selectCode = compile(selectSource.slice(selectSource.indexOf("export const setColOption ="),
+ selectSource.indexOf("export const bindSelectEvent =")));
+const kanbanCode = compile(kanbanSource.slice(kanbanSource.indexOf("export const openKanbanGroupMenu =")));
+
+const setupOptionMenu = (kanban = false) => {
+ const options = [{name: "A", color: "1", desc: "Original"}, {name: "B", color: "2", desc: "Target"}];
+ const fields = [{id: "field", options}];
+ const input = {value: "A", select: () => {}};
+ const description = {value: "Original"};
+ const items: any[] = [];
+ const transactions: {operations: any[], inverse: any[]}[] = [];
+ let closeMenu: () => void;
+ const menuElement = {querySelector: (selector: string) => {
+ if (selector === ".b3-chips") {
+ return null;
+ }
+ return {scrollTop: 0, getAttribute: () => "field"};
+ }};
+ const blockElement = {
+ getAttribute: (name: string) => ({"data-node-id": "carrier", "data-av-id": "database", "data-av-type": "table"})[name],
+ querySelector: () => ({dataset: {groupOptions: JSON.stringify(options)}}),
+ };
+ const optionElement = {dataset: {name: "A", desc: "Original", color: "1", colId: "field", groupId: "group"}};
+ const target = {
+ ...optionElement,
+ parentElement: optionElement,
+ closest: () => optionElement,
+ getBoundingClientRect: () => ({left: 0, right: 0, bottom: 0, width: 0, height: 0}),
+ };
+ const exports: any = {};
+ runInNewContext(kanban ? kanbanCode : selectCode, {
+ exports,
+ Constants: {},
+ window: {siyuan: {languages: {}}},
+ Menu: class {
+ element = {querySelector: (selector: string) => selector === "input" ? input : description};
+ constructor(_id: string, onClose: () => void) {
+ closeMenu = onClose;
+ }
+ addItem(item: any) { items.push(item); }
+ addSeparator() {}
+ open() {}
+ },
+ hasClosestByClassName: () => menuElement,
+ getFieldsByData: () => fields,
+ getAVData: () => ({id: "database"}),
+ applyAVColorPalette: () => {},
+ getAVCustomColors: (): string[] => [],
+ getAVColorOrder: (): string[] => [],
+ getAVColorGridHTML: () => "",
+ escapeAriaLabel: (text: string) => text,
+ escapeAttr: (text: string) => text,
+ escapeHtml: (text: string) => text,
+ dayjs: () => ({format: () => "20260916120000"}),
+ confirmDialog: (_title: string, _text: string, confirm: () => void) => confirm(),
+ transaction: (_protyle: any, operations: any[], inverse: any[]) => transactions.push({operations, inverse}),
+ getEditHTML: () => "",
+ bindEditEvent: () => {},
+ });
+ if (kanban) {
+ exports.openKanbanGroupMenu({protyle: {}, blockElement, target});
+ } else {
+ exports.setColOption({}, {id: "database"}, target, blockElement, false);
+ }
+ return {options, input, description, items, transactions, closeMenu: () => closeMenu()};
+};
+
+for (const kanban of [false, true]) {
+ test(`${kanban ? "kanban group" : "select option"} deletion preserves the complete inverse and carrier`, () => {
+ const menu = setupOptionMenu(kanban);
+ const original = JSON.parse(JSON.stringify(menu.options));
+ menu.items.find(item => item.icon === "iconTrashcan").click();
+ const {operations, inverse} = menu.transactions[0];
+ assert.equal(operations[0].action, "removeAttrViewColOption");
+ assert.equal(inverse[0].action, "updateAttrViewColOptions");
+ for (const operation of [operations[0], inverse[0]]) {
+ assert.equal(operation.avID, "database");
+ assert.equal(operation.id, "field");
+ assert.equal(operation.blockID, "carrier");
+ }
+ if (!kanban) {
+ assert.deepEqual(menu.options.map(option => option.name), ["B"]);
+ menu.options[0].color = "3";
+ }
+ assert.deepEqual(JSON.parse(JSON.stringify(inverse[0].data)), original);
+ });
+}
+
+test("merging an option identifies its source and destination within the same database carrier", () => {
+ const menu = setupOptionMenu();
+ menu.input.value = "B";
+ menu.description.value = "Target";
+ menu.closeMenu();
+ const {operations, inverse} = menu.transactions[0];
+ for (const operation of [operations[0], inverse[0]]) {
+ assert.equal(operation.action, "updateAttrViewColOption");
+ assert.equal(operation.avID, "database");
+ assert.equal(operation.id, "field");
+ assert.equal(operation.blockID, "carrier");
+ }
+ assert.equal(operations[0].data.oldName, "A");
+ assert.equal(operations[0].data.newName, "B");
+ assert.equal(inverse[0].data.oldName, "B");
+ assert.equal(inverse[0].data.newName, "A");
+ assert.deepEqual(menu.options.map(option => option.name), ["A", "B"]);
+});
diff --git a/app/src/protyle/render/av/select.ts b/app/src/protyle/render/av/select.ts
index 705bdc1bc7..40d3dd8b67 100644
--- a/app/src/protyle/render/av/select.ts
+++ b/app/src/protyle/render/av/select.ts
@@ -189,6 +189,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
+ blockID,
data: {
newColor: color,
oldName: name,
@@ -203,6 +204,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
+ blockID,
data: {
newColor: color,
oldName: inputElement.value,
@@ -337,6 +339,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
action: "removeAttrViewColOption",
id: colId,
avID: data.id,
+ blockID,
data: newName,
}, {
action: "doUpdateUpdated",
@@ -346,7 +349,8 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
action: "updateAttrViewColOptions",
id: colId,
avID: data.id,
- data: colOptions
+ blockID,
+ data: colOptions.map(option => ({...option}))
}]);
colOptions.find((item, index) => {
if (item.name === newName) {
@@ -424,6 +428,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
+ blockID,
data: {
oldName: name,
newName: inputElement.value,
@@ -439,6 +444,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,
action: "updateAttrViewColOption",
id: colId,
avID: data.id,
+ blockID,
data: {
oldName: inputElement.value,
newName: name,
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 6a1ec002e2..99de2210eb 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -8681,6 +8681,12 @@ func getNodeByBlockID(tx *Transaction, blockID string) (node *ast.Node, tree *pa
}
func (tx *Transaction) doUpdateAttrViewColOptions(operation *Operation) (ret *TxErr) {
+ if operation.attributeViewFields != nil {
+ if err := tx.replayAttributeViewFields(operation); err != nil {
+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
+ }
+ return nil
+ }
err := updateAttributeViewColumnOptions(operation)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
@@ -8919,212 +8925,21 @@ func setAttrViewCustomColors(operation *Operation) (err error) {
}
func (tx *Transaction) doRemoveAttrViewColOption(operation *Operation) (ret *TxErr) {
- err := removeAttributeViewColumnOption(operation)
+ err := tx.mutateAttributeViewOption(operation, true)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
}
return
}
-func removeAttributeViewColumnOption(operation *Operation) (err error) {
- attrView, err := av.ParseAttributeView(operation.AvID)
- if err != nil {
- return
- }
-
- optName := operation.Data.(string)
-
- key, err := attrView.GetKey(operation.ID)
- if err != nil {
- return
- }
-
- for i, opt := range key.Options {
- if optName == opt.Name {
- key.Options = append(key.Options[:i], key.Options[i+1:]...)
- break
- }
- }
- attrView.RemoveNewItemTemplateSelectOption(operation.ID, optName)
-
- for _, keyValues := range attrView.KeyValues {
- if keyValues.Key.ID != operation.ID {
- continue
- }
-
- for _, value := range keyValues.Values {
- if nil == value || nil == value.MSelect {
- continue
- }
-
- for i, opt := range value.MSelect {
- if optName == opt.Content {
- value.MSelect = append(value.MSelect[:i], value.MSelect[i+1:]...)
- break
- }
- }
- }
- break
- }
-
- // 如果存在选项对应的过滤条件,则删除过滤条件中设置的选项值 https://github.com/siyuan-note/siyuan/issues/15536
- for _, view := range attrView.Views {
- view.Filters = av.RemoveSelectOptionFromFilters(view.Filters, operation.ID, optName)
- if 0 == len(view.Filters) {
- // 保持 spec 5 根组不变量
- view.Filters = []*av.ViewFilter{{Combination: av.FilterCombinationAnd}}
- }
- }
- removeAttrViewOptionFromFieldFilters(attrView, attrView.ID, operation.ID, optName)
-
- regenAttrViewGroups(attrView)
- if err = av.SaveAttributeView(attrView); nil != err {
- return
- }
-
- for _, relatedAvID := range av.GetSrcAvIDs(attrView.ID) {
- if relatedAvID == attrView.ID {
- continue
- }
- relatedAv, parseErr := av.ParseAttributeView(relatedAvID)
- if nil != parseErr || nil == relatedAv ||
- !removeAttrViewOptionFromFieldFilters(relatedAv, attrView.ID, operation.ID, optName) {
- continue
- }
- if err = av.SaveAttributeView(relatedAv); nil != err {
- return
- }
- ReloadAttrView(relatedAvID)
- }
- return
-}
-
func (tx *Transaction) doUpdateAttrViewColOption(operation *Operation) (ret *TxErr) {
- err := updateAttributeViewColumnOption(operation)
+ err := tx.mutateAttributeViewOption(operation, false)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
}
return
}
-func updateAttributeViewColumnOption(operation *Operation) (err error) {
- attrView, err := av.ParseAttributeView(operation.AvID)
- if err != nil {
- return
- }
-
- key, err := attrView.GetKey(operation.ID)
- if err != nil {
- return
- }
-
- data := operation.Data.(map[string]any)
-
- rename := false
- oldName := strings.TrimSpace(data["oldName"].(string))
- newName := strings.TrimSpace(data["newName"].(string))
- newDesc := strings.TrimSpace(data["newDesc"].(string))
- newColor := attrView.FilterColorValue(data["newColor"].(string))
-
- found := false
- if oldName != newName {
- rename = true
-
- for _, opt := range key.Options {
- if newName == opt.Name { // 如果选项已经存在则直接使用
- found = true
- newColor = opt.Color
- newDesc = opt.Desc
- break
- }
- }
- }
- if rename {
- attrView.RenameNewItemTemplateSelectOption(operation.ID, oldName, newName, newColor)
- }
-
- if !found {
- for i, opt := range key.Options {
- if oldName == opt.Name {
- key.Options[i].Name = newName
- key.Options[i].Color = newColor
- key.Options[i].Desc = newDesc
- break
- }
- }
- }
-
- // 如果存在选项对应的值,需要更新值中的选项
- for _, keyValues := range attrView.KeyValues {
- if keyValues.Key.ID != operation.ID {
- continue
- }
-
- for _, value := range keyValues.Values {
- if nil == value || nil == value.MSelect {
- continue
- }
-
- found = false
- for _, opt := range value.MSelect {
- if newName == opt.Content {
- found = true
- break
- }
- }
- if found && rename {
- idx := -1
- for i, opt := range value.MSelect {
- if oldName == opt.Content {
- idx = i
- break
- }
- }
- if 0 <= idx {
- value.MSelect = util.RemoveElem(value.MSelect, idx)
- }
- } else {
- for i, opt := range value.MSelect {
- if oldName == opt.Content {
- value.MSelect[i].Content = newName
- value.MSelect[i].Color = newColor
- break
- }
- }
- }
- }
- break
- }
-
- // 如果存在选项对应的过滤条件,需要更新过滤条件中设置的选项值
- // Database select field filters follow option editing changes https://github.com/siyuan-note/siyuan/issues/10881
- for _, view := range attrView.Views {
- av.RenameSelectOptionInFilters(view.Filters, key.ID, oldName, newName, newColor)
- }
- renameAttrViewOptionInFieldFilters(attrView, attrView.ID, key.ID, oldName, newName, newColor)
-
- regenAttrViewGroups(attrView)
- if err = av.SaveAttributeView(attrView); nil != err {
- return
- }
-
- for _, relatedAvID := range av.GetSrcAvIDs(attrView.ID) {
- if relatedAvID == attrView.ID {
- continue
- }
- relatedAv, parseErr := av.ParseAttributeView(relatedAvID)
- if nil != parseErr || nil == relatedAv ||
- !renameAttrViewOptionInFieldFilters(relatedAv, attrView.ID, key.ID, oldName, newName, newColor) {
- continue
- }
- if err = av.SaveAttributeView(relatedAv); nil != err {
- return
- }
- ReloadAttrView(relatedAvID)
- }
- return
-}
-
func (tx *Transaction) doSetAttrViewColOptionDesc(operation *Operation) (ret *TxErr) {
err := setAttributeViewColumnOptionDesc(operation)
if err != nil {
diff --git a/kernel/model/attribute_view_field_changes.go b/kernel/model/attribute_view_field_changes.go
index 9b3f5f54f8..8d7d4cf2b7 100644
--- a/kernel/model/attribute_view_field_changes.go
+++ b/kernel/model/attribute_view_field_changes.go
@@ -25,7 +25,7 @@ import (
"sort"
)
-// 只记录字段删除实际改变的片段;带稳定 ID 的集合按元素合并,其他列表整体检查冲突。
+// 只记录字段操作实际改变的片段;带稳定标识的集合按元素合并,其他列表整体检查冲突。
type attributeViewFieldChange struct {
before, after any
beforeExists, afterExists bool
@@ -47,11 +47,15 @@ func attributeViewFieldJSON(value any) (any, error) {
return ret, err
}
-func attributeViewFieldElementID(value any) string {
+func attributeViewFieldElementID(value any, container string) string {
object, ok := value.(map[string]any)
if !ok {
return ""
}
+ if container == "options" {
+ name, _ := object["name"].(string)
+ return name
+ }
if key, ok := object["key"].(map[string]any); ok {
object = key
}
@@ -59,11 +63,11 @@ func attributeViewFieldElementID(value any) string {
return id
}
-func attributeViewFieldElements(values []any) (map[string]any, []string, bool) {
+func attributeViewFieldElements(values []any, container string) (map[string]any, []string, bool) {
ret := map[string]any{}
var order []string
for _, value := range values {
- id := attributeViewFieldElementID(value)
+ id := attributeViewFieldElementID(value, container)
if id == "" || ret[id] != nil {
return nil, nil, false
}
@@ -160,8 +164,8 @@ func diffAttributeViewFieldData(before, after any, beforeExists, afterExists boo
if !beforeIsSlice || !afterIsSlice {
return change
}
- oldElements, oldOrder, oldOK := attributeViewFieldElements(beforeSlice)
- newElements, newOrder, newOK := attributeViewFieldElements(afterSlice)
+ oldElements, oldOrder, oldOK := attributeViewFieldElements(beforeSlice, container)
+ newElements, newOrder, newOK := attributeViewFieldElements(afterSlice, container)
if !oldOK || !newOK {
return change
}
@@ -221,7 +225,7 @@ func (change *attributeViewFieldChange) apply(current any, exists, undo bool) (a
if !exists || !ok {
return nil, false, conflict
}
- elements, _, valid := attributeViewFieldElements(values)
+ elements, _, valid := attributeViewFieldElements(values, change.container)
if !valid {
return nil, false, conflict
}
@@ -239,7 +243,7 @@ func (change *attributeViewFieldChange) apply(current any, exists, undo bool) (a
}
result := make([]any, 0, len(values))
for _, value := range values {
- if updated, keep := elements[attributeViewFieldElementID(value)]; keep {
+ if updated, keep := elements[attributeViewFieldElementID(value, change.container)]; keep {
result = append(result, updated)
}
}
@@ -248,12 +252,12 @@ func (change *attributeViewFieldChange) apply(current any, exists, undo bool) (a
order = change.beforeOrder
}
for index, id := range order {
- if elements[id] == nil || slices.ContainsFunc(result, func(value any) bool { return attributeViewFieldElementID(value) == id }) {
+ if elements[id] == nil || slices.ContainsFunc(result, func(value any) bool { return attributeViewFieldElementID(value, change.container) == id }) {
continue
}
position := -1
for previous := index - 1; previous >= 0; previous-- {
- if found := slices.IndexFunc(result, func(value any) bool { return attributeViewFieldElementID(value) == order[previous] }); found >= 0 {
+ if found := slices.IndexFunc(result, func(value any) bool { return attributeViewFieldElementID(value, change.container) == order[previous] }); found >= 0 {
position = found + 1
break
}
diff --git a/kernel/model/attribute_view_fields.go b/kernel/model/attribute_view_fields.go
index 8fe717c990..99365b09b4 100644
--- a/kernel/model/attribute_view_fields.go
+++ b/kernel/model/attribute_view_fields.go
@@ -26,11 +26,12 @@ import (
"github.com/siyuan-note/siyuan/kernel/av"
)
-// 字段快照只包含本次删除的变化,不进入接口响应或数据库持久化格式。
+// 字段快照只包含本次操作的变化,不进入接口响应或数据库持久化格式。
type attributeViewFieldsSnapshot struct {
avID, keyID, blockID, boxID string
changes map[string]*attributeViewFieldChange
relationValues map[string]map[string]attributeViewRelationValues
+ fieldTypes map[string]map[string]av.KeyType
}
type attributeViewRelationValues map[string][]string
@@ -229,12 +230,21 @@ func (tx *Transaction) replayAttributeViewFields(op *Operation) error {
if !tx.isReplay || op.AvID != state.avID || op.ID != state.keyID {
return errors.New("invalid database field replay")
}
+ if len(state.changes) == 0 {
+ return nil
+ }
before, after := map[string]*av.AttributeView{}, map[string]*av.AttributeView{}
for _, id := range sortedAttributeViewFieldKeys(state.changes) {
current, err := tx.readAttributeViewForMutation(id, state.blockID, state.boxID)
if err != nil {
return err
}
+ for keyID, typ := range state.fieldTypes[id] {
+ key, keyErr := current.GetKey(keyID)
+ if keyErr != nil || key.Type != typ {
+ return fmt.Errorf("database field [%s] changed after the operation", keyID)
+ }
+ }
// 恢复双向定义时,另一端的单向值必须仍与删除时一致。
for keyID, expected := range state.relationValues[id] {
kv, keyErr := current.GetKeyValues(keyID)
diff --git a/kernel/model/attribute_view_option_undo.go b/kernel/model/attribute_view_option_undo.go
new file mode 100644
index 0000000000..0e275afb34
--- /dev/null
+++ b/kernel/model/attribute_view_option_undo.go
@@ -0,0 +1,320 @@
+// 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"
+ "errors"
+ "strings"
+
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// 删除和合并选项共用字段变化快照,恢复实际改变的值、筛选条件、模板默认值和分组状态。
+func (tx *Transaction) mutateAttributeViewOption(op *Operation, remove bool) error {
+ if op.attributeViewFields != nil {
+ return tx.replayAttributeViewFields(op)
+ }
+ var inverse *Operation
+ if tx.fromAPI && !tx.isReplay {
+ action := "updateAttrViewColOption"
+ if remove {
+ action = "updateAttrViewColOptions"
+ }
+ for _, undo := range tx.UndoOperations {
+ if undo.Action == action && undo.AvID == op.AvID && undo.ID == op.ID && undo.attributeViewFields == nil {
+ inverse = undo
+ break
+ }
+ }
+ }
+ blockID := op.BlockID
+ if blockID == "" {
+ for _, operation := range tx.DoOperations {
+ if operation.Action == "doUpdateUpdated" {
+ blockID = operation.ID
+ break
+ }
+ }
+ }
+ if _, err := avParseView(op.AvID, blockID); err != nil {
+ return err
+ }
+ state := &attributeViewFieldsSnapshot{avID: op.AvID, keyID: op.ID, blockID: blockID,
+ boxID: av.GetAVBoxID(op.AvID), changes: map[string]*attributeViewFieldChange{}}
+ source, err := tx.readAttributeViewForMutation(op.AvID, blockID, state.boxID)
+ if err != nil {
+ return err
+ }
+ key, err := source.GetKey(op.ID)
+ if err != nil {
+ return err
+ }
+ state.fieldTypes = map[string]map[string]av.KeyType{source.ID: {key.ID: key.Type}}
+ before := map[string]*av.AttributeView{}
+ views := map[string]*av.AttributeView{source.ID: source}
+ // 写入前读取所有关联数据库,缺失的旧关联可以跳过,损坏或认证失败必须终止。
+ for _, id := range av.GetSrcAvIDs(source.ID) {
+ if views[id] != nil {
+ continue
+ }
+ related, readErr := tx.readAttributeViewForMutation(id, blockID, state.boxID)
+ if errors.Is(readErr, av.ErrViewNotFound) {
+ continue
+ }
+ if readErr != nil {
+ return readErr
+ }
+ views[id] = related
+ }
+ for id, view := range views {
+ before[id], err = cloneAttributeViewForFieldMutation(view)
+ if err != nil {
+ return err
+ }
+ }
+ if remove {
+ err = removeAttributeViewColumnOptionValues(source, op)
+ } else {
+ err = updateAttributeViewColumnOptionValues(source, op)
+ }
+ if err != nil {
+ return err
+ }
+ for id, view := range views {
+ if id == source.ID {
+ continue
+ }
+ // 源数据库中的字段筛选已经随选项值一并更新。
+ changed := false
+ if remove {
+ changed = removeAttrViewOptionFromFieldFilters(view, source.ID, key.ID, op.Data.(string))
+ } else {
+ var data struct {
+ OldName string `json:"oldName"`
+ NewName string `json:"newName"`
+ }
+ encoded, _ := json.Marshal(op.Data)
+ if err = json.Unmarshal(encoded, &data); err != nil {
+ return err
+ }
+ oldName, newName := strings.TrimSpace(data.OldName), strings.TrimSpace(data.NewName)
+ option := key.GetOption(newName)
+ if option != nil {
+ changed = renameAttrViewOptionInFieldFilters(view, source.ID, key.ID, oldName, newName, option.Color)
+ }
+ }
+ if !changed {
+ delete(views, id)
+ delete(before, id)
+ }
+ }
+ regenAttrViewGroups(source)
+ if err = tx.saveAttributeViewFieldChanges(state, before, views); err != nil {
+ return err
+ }
+ if inverse != nil {
+ for id := range views {
+ persisted, readErr := tx.readAttributeViewForMutation(id, blockID, state.boxID)
+ if readErr != nil {
+ return readErr
+ }
+ oldJSON, jsonErr := attributeViewFieldJSON(before[id])
+ if jsonErr != nil {
+ return jsonErr
+ }
+ newJSON, jsonErr := attributeViewFieldJSON(persisted)
+ if jsonErr != nil {
+ return jsonErr
+ }
+ if change := diffAttributeViewFields(oldJSON, newJSON, true, true); change != nil {
+ state.changes[id] = change
+ }
+ }
+ op.attributeViewFields, op.BlockID = state, blockID
+ inverse.attributeViewFields, inverse.attributeViewFieldUndo, inverse.BlockID = state, true, blockID
+ }
+ return nil
+}
+
+func removeAttributeViewColumnOption(operation *Operation) (err error) {
+ tx := &Transaction{trees: map[string]*parse.Tree{}}
+ defer func() { tx.finishAttributeViewMutation(err != nil) }()
+ return tx.mutateAttributeViewOption(operation, true)
+}
+
+func updateAttributeViewColumnOption(operation *Operation) (err error) {
+ tx := &Transaction{trees: map[string]*parse.Tree{}}
+ defer func() { tx.finishAttributeViewMutation(err != nil) }()
+ return tx.mutateAttributeViewOption(operation, false)
+}
+
+func removeAttributeViewColumnOptionValues(attrView *av.AttributeView, operation *Operation) (err error) {
+ optName, ok := operation.Data.(string)
+ if !ok {
+ return errors.New("invalid database option name")
+ }
+
+ key, err := attrView.GetKey(operation.ID)
+ if err != nil {
+ return
+ }
+
+ for i, opt := range key.Options {
+ if optName == opt.Name {
+ key.Options = append(key.Options[:i], key.Options[i+1:]...)
+ break
+ }
+ }
+ attrView.RemoveNewItemTemplateSelectOption(operation.ID, optName)
+
+ for _, keyValues := range attrView.KeyValues {
+ if keyValues.Key.ID != operation.ID {
+ continue
+ }
+
+ for _, value := range keyValues.Values {
+ if nil == value || nil == value.MSelect {
+ continue
+ }
+
+ for i, opt := range value.MSelect {
+ if optName == opt.Content {
+ value.MSelect = append(value.MSelect[:i], value.MSelect[i+1:]...)
+ break
+ }
+ }
+ }
+ break
+ }
+
+ // 如果存在选项对应的过滤条件,则删除过滤条件中设置的选项值 https://github.com/siyuan-note/siyuan/issues/15536
+ for _, view := range attrView.Views {
+ view.Filters = av.RemoveSelectOptionFromFilters(view.Filters, operation.ID, optName)
+ if 0 == len(view.Filters) {
+ // 保持 spec 5 根组不变量
+ view.Filters = []*av.ViewFilter{{Combination: av.FilterCombinationAnd}}
+ }
+ }
+ removeAttrViewOptionFromFieldFilters(attrView, attrView.ID, operation.ID, optName)
+
+ return nil
+}
+
+func updateAttributeViewColumnOptionValues(attrView *av.AttributeView, operation *Operation) (err error) {
+ key, err := attrView.GetKey(operation.ID)
+ if err != nil {
+ return
+ }
+
+ var data struct {
+ OldName string `json:"oldName"`
+ NewName string `json:"newName"`
+ NewDesc string `json:"newDesc"`
+ NewColor string `json:"newColor"`
+ }
+ encoded, err := json.Marshal(operation.Data)
+ if err != nil {
+ return err
+ }
+ if err = json.Unmarshal(encoded, &data); err != nil {
+ return err
+ }
+ oldName, newName := strings.TrimSpace(data.OldName), strings.TrimSpace(data.NewName)
+ newDesc, newColor := strings.TrimSpace(data.NewDesc), attrView.FilterColorValue(data.NewColor)
+ rename := oldName != newName
+
+ found := false
+ if oldName != newName {
+ rename = true
+
+ for _, opt := range key.Options {
+ if newName == opt.Name { // 如果选项已经存在则直接使用
+ found = true
+ newColor = opt.Color
+ newDesc = opt.Desc
+ break
+ }
+ }
+ }
+ if rename {
+ attrView.RenameNewItemTemplateSelectOption(operation.ID, oldName, newName, newColor)
+ }
+
+ if !found {
+ for i, opt := range key.Options {
+ if oldName == opt.Name {
+ key.Options[i].Name = newName
+ key.Options[i].Color = newColor
+ key.Options[i].Desc = newDesc
+ break
+ }
+ }
+ }
+
+ // 如果存在选项对应的值,需要更新值中的选项
+ for _, keyValues := range attrView.KeyValues {
+ if keyValues.Key.ID != operation.ID {
+ continue
+ }
+
+ for _, value := range keyValues.Values {
+ if nil == value || nil == value.MSelect {
+ continue
+ }
+
+ found = false
+ for _, opt := range value.MSelect {
+ if newName == opt.Content {
+ found = true
+ break
+ }
+ }
+ if found && rename {
+ idx := -1
+ for i, opt := range value.MSelect {
+ if oldName == opt.Content {
+ idx = i
+ break
+ }
+ }
+ if 0 <= idx {
+ value.MSelect = util.RemoveElem(value.MSelect, idx)
+ }
+ } else {
+ for i, opt := range value.MSelect {
+ if oldName == opt.Content {
+ value.MSelect[i].Content = newName
+ value.MSelect[i].Color = newColor
+ break
+ }
+ }
+ }
+ }
+ break
+ }
+
+ // 如果存在选项对应的过滤条件,需要更新过滤条件中设置的选项值
+ for _, view := range attrView.Views {
+ av.RenameSelectOptionInFilters(view.Filters, key.ID, oldName, newName, newColor)
+ }
+ renameAttrViewOptionInFieldFilters(attrView, attrView.ID, key.ID, oldName, newName, newColor)
+
+ return nil
+}
diff --git a/kernel/model/attribute_view_option_undo_fts5_test.go b/kernel/model/attribute_view_option_undo_fts5_test.go
new file mode 100644
index 0000000000..15f42f4a4b
--- /dev/null
+++ b/kernel/model/attribute_view_option_undo_fts5_test.go
@@ -0,0 +1,391 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAttributeViewOptionUndoRedo(t *testing.T) {
+ for _, action := range []string{"delete", "merge", "rename"} {
+ for _, typ := range []av.KeyType{av.KeyTypeSelect, av.KeyTypeMSelect} {
+ t.Run(action+"/"+string(typ), func(t *testing.T) {
+ fixture, source, peer, tx := setupAttributeViewOptionUndoTest(t, action, typ)
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ entry := GlobalUndoLog.Peek(fixture.sourceID)
+ if entry == nil {
+ t.Fatal("option operation did not enter the undo log")
+ }
+ data, err := json.Marshal(tx)
+ if err != nil || strings.Contains(string(data), "Private template") {
+ t.Fatalf("private option snapshot leaked into response: %s, %v", data, err)
+ }
+ after, peerAfter := readAttributeViewItemsTest(t, source.ID), readAttributeViewItemsTest(t, peer.ID)
+ field, _ := after.GetKeyValues(tx.DoOperations[0].ID)
+ want := [][]string{{}, {"B"}, {"B"}, {"C"}}
+ if action != "delete" {
+ name := "B"
+ if action == "rename" {
+ name = "Renamed"
+ }
+ want[0] = []string{name}
+ if typ == av.KeyTypeSelect {
+ want[2] = []string{name}
+ } else if action == "rename" {
+ want[2] = []string{name, "B"}
+ }
+ } else if typ == av.KeyTypeSelect {
+ want[2] = nil
+ }
+ for i, value := range field.Values {
+ var got []string
+ for _, option := range value.MSelect {
+ got = append(got, option.Content)
+ }
+ if !slices.Equal(got, want[i]) {
+ t.Fatalf("unexpected option values at item %d: want %v, got %v", i, want[i], got)
+ }
+ }
+ if action == "delete" && field.Key.GetOption("A") != nil {
+ t.Fatal("deleted option definition remains")
+ }
+ if action == "merge" && field.Key.GetOption("B").Desc != "Target description" {
+ t.Fatal("merge changed the target option definition")
+ }
+ for cycle := 0; cycle < 3; cycle++ {
+ replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())
+ assertAttributeViewFieldsTest(t, source, readAttributeViewItemsTest(t, source.ID))
+ assertAttributeViewFieldsTest(t, peer, readAttributeViewItemsTest(t, peer.ID))
+ // 渲染会刷新派生字段,不能因此阻止下一次重做。
+ rendered := readAttributeViewItemsTest(t, source.ID)
+ for _, view := range rendered.Views {
+ sql.RenderView(rendered, view, "", false)
+ }
+ if err = av.SaveAttributeView(rendered); err != nil {
+ t.Fatal(err)
+ }
+ replayAttributeViewFieldsTest(t, entry.DoOperationsForReplay())
+ assertAttributeViewFieldsTest(t, after, readAttributeViewItemsTest(t, source.ID))
+ assertAttributeViewFieldsTest(t, peerAfter, readAttributeViewItemsTest(t, peer.ID))
+ }
+ })
+ }
+ }
+}
+
+func TestAttributeViewOptionDeleteLastUndo(t *testing.T) {
+ fixture, source, peer, tx := setupAttributeViewOptionUndoTest(t, "delete", av.KeyTypeMSelect)
+ field, _ := source.GetKeyValues(tx.DoOperations[0].ID)
+ field.Key.Options = field.Key.Options[:1]
+ for _, value := range field.Values {
+ value.MSelect = optionUndoSelections("A")
+ }
+ regenAttrViewGroups(source)
+ if err := av.SaveAttributeView(source); err != nil {
+ t.Fatal(err)
+ }
+ source = readAttributeViewItemsTest(t, source.ID)
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ entry := GlobalUndoLog.Peek(fixture.sourceID)
+ for cycle := 0; cycle < 2; cycle++ {
+ deleted := readAttributeViewItemsTest(t, source.ID)
+ key, _ := deleted.GetKey(field.Key.ID)
+ if len(key.Options) != 0 {
+ t.Fatal("last option was not deleted")
+ }
+ replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())
+ assertAttributeViewFieldsTest(t, source, readAttributeViewItemsTest(t, source.ID))
+ assertAttributeViewFieldsTest(t, peer, readAttributeViewItemsTest(t, peer.ID))
+ replayAttributeViewFieldsTest(t, entry.DoOperationsForReplay())
+ }
+}
+
+func TestAttributeViewOptionUndoPreservesOtherEdits(t *testing.T) {
+ for _, action := range []string{"delete", "merge"} {
+ t.Run(action, func(t *testing.T) {
+ fixture, source, _, tx := setupAttributeViewOptionUndoTest(t, action, av.KeyTypeMSelect)
+ for _, view := range source.Views {
+ view.Group, view.Groups = nil, nil
+ }
+ if err := av.SaveAttributeView(source); err != nil {
+ t.Fatal(err)
+ }
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ current := readAttributeViewItemsTest(t, source.ID)
+ for _, view := range []*av.AttributeView{source, current} {
+ view.Name = "New database name"
+ view.KeyValues[2].Values[0].Text.Content = "Later text edit"
+ field, _ := view.GetKeyValues(tx.DoOperations[0].ID)
+ field.Key.Options = append(field.Key.Options, &av.SelectOption{Name: "Later", Color: "4"})
+ field.Values[1].MSelect = optionUndoSelections("C")
+ }
+ if err := av.SaveAttributeView(current); err != nil {
+ t.Fatal(err)
+ }
+ replayAttributeViewFieldsTest(t, GlobalUndoLog.Peek(fixture.sourceID).UndoOperationsForReplay())
+ assertAttributeViewFieldsTest(t, source, readAttributeViewItemsTest(t, source.ID))
+ })
+ }
+}
+
+func TestAttributeViewOptionReplayConflict(t *testing.T) {
+ for _, conflict := range []string{"value", "option", "type", "item", "relatedFilter"} {
+ t.Run(conflict, func(t *testing.T) {
+ fixture, source, peer, tx := setupAttributeViewOptionUndoTest(t, "delete", av.KeyTypeMSelect)
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ source, peer = readAttributeViewItemsTest(t, source.ID), readAttributeViewItemsTest(t, peer.ID)
+ field, _ := source.GetKeyValues(tx.DoOperations[0].ID)
+ switch conflict {
+ case "value":
+ field.Values[0].MSelect = optionUndoSelections("C")
+ case "option":
+ field.Key.Options = append(field.Key.Options, &av.SelectOption{Name: "A", Color: "4"})
+ case "type":
+ field.Key.Type = av.KeyTypeText
+ case "item":
+ field.Values = field.Values[1:]
+ case "relatedFilter":
+ peer.KeyValues[2].Key.Relation.CandidateFilters = fieldFilterRoot(fieldFilterLeaf(source.GetBlockKey().ID))
+ }
+ for _, view := range []*av.AttributeView{source, peer} {
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := PerformTxSync(&Transaction{DoOperations: GlobalUndoLog.Peek(fixture.sourceID).UndoOperationsForReplay(), isReplay: true}); err == nil {
+ t.Fatal("conflicting option replay succeeded")
+ }
+ assertAttributeViewFieldsTest(t, source, readAttributeViewItemsTest(t, source.ID))
+ assertAttributeViewFieldsTest(t, peer, readAttributeViewItemsTest(t, peer.ID))
+ })
+ }
+}
+
+func TestAttributeViewOptionWriteFailure(t *testing.T) {
+ for _, action := range []string{"delete", "merge"} {
+ for _, undo := range []bool{false, true} {
+ t.Run(action+map[bool]string{false: "/apply", true: "/undo"}[undo], func(t *testing.T) {
+ fixture, source, peer, tx := setupAttributeViewOptionUndoTest(t, action, av.KeyTypeMSelect)
+ if undo {
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ tx = &Transaction{DoOperations: GlobalUndoLog.Peek(fixture.sourceID).UndoOperationsForReplay(), isReplay: true}
+ }
+ source, peer = readAttributeViewItemsTest(t, source.ID), readAttributeViewItemsTest(t, peer.ID)
+ tx.writeTransactionTree = func(*parse.Tree) error { return errors.New("injected option write failure") }
+ if err := PerformTxSync(tx); err == nil || !strings.Contains(err.Error(), "injected option write failure") {
+ t.Fatalf("unexpected write result: %v", err)
+ }
+ assertAttributeViewFieldsTest(t, source, readAttributeViewItemsTest(t, source.ID))
+ assertAttributeViewFieldsTest(t, peer, readAttributeViewItemsTest(t, peer.ID))
+ })
+ }
+ }
+}
+
+func TestAttributeViewOptionEncryptedReplay(t *testing.T) {
+ for _, action := range []string{"delete", "merge"} {
+ t.Run(action, func(t *testing.T) {
+ _, source, peer, tx := setupAttributeViewOptionUndoTest(t, action, av.KeyTypeMSelect)
+ boxID := ast.NewNodeID()
+ dek := bytes.Repeat([]byte{0x64}, 32)
+ markRuntimeEncryptedBox(boxID)
+ setDEKForTest(boxID, dek)
+ t.Cleanup(func() {
+ for _, view := range []*av.AttributeView{source, peer} {
+ av.SetAVBoxID(view.ID, "")
+ }
+ forgetRuntimeEncryptedBox(boxID)
+ encryptedBoxLifecycles.Delete(boxID)
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, boxID)
+ cachedDEKsLock.Unlock()
+ })
+ for _, view := range []*av.AttributeView{source, peer} {
+ av.SetAVBoxID(view.ID, boxID)
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(filepath.Join(util.DataDir, "storage", "av", view.ID+".json")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ tx.DoOperations[0].BlockID, tx.UndoOperations[0].BlockID = "", ""
+ for _, view := range []*av.AttributeView{source, peer} {
+ av.UpsertAvBackRel(view.ID, source.ID)
+ }
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ if tx.DoOperations[0].attributeViewFields.changes[peer.ID] == nil {
+ t.Fatal("encrypted related filters were not included in the snapshot")
+ }
+ replayAttributeViewFieldsTest(t, cloneOperations(tx.UndoOperations))
+ for _, view := range []*av.AttributeView{source, peer} {
+ restored, err := av.ParseAttributeViewForIndexInBox(view.ID, boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertAttributeViewFieldsTest(t, view, restored)
+ if _, err = os.Stat(filepath.Join(util.DataDir, "storage", "av", view.ID+".json")); !os.IsNotExist(err) {
+ t.Fatalf("option replay produced plaintext: %v", err)
+ }
+ }
+ replayAttributeViewFieldsTest(t, cloneOperations(tx.DoOperations))
+ for _, failure := range []string{"locked", "corruptedPeer"} {
+ t.Run(failure, func(t *testing.T) {
+ if failure == "locked" {
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, boxID)
+ cachedDEKsLock.Unlock()
+ defer setDEKForTest(boxID, dek)
+ } else {
+ path := filepath.Join(util.DataDir, boxID, "storage", "av", peer.ID+".json")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data[len(data)-1] ^= 1
+ if err = os.WriteFile(path, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ciphertexts := map[string][]byte{}
+ for _, view := range []*av.AttributeView{source, peer} {
+ path := filepath.Join(util.DataDir, boxID, "storage", "av", view.ID+".json")
+ data, err := os.ReadFile(path)
+ if err != nil || !util.IsCiphertext(data) {
+ t.Fatalf("database was not encrypted: %v", err)
+ }
+ ciphertexts[path] = data
+ }
+ cache.ClearAVCache()
+ if err := PerformTxSync(&Transaction{DoOperations: cloneOperations(tx.UndoOperations), isReplay: true}); err == nil {
+ t.Fatal("option replay accepted inaccessible encrypted data")
+ }
+ for path, expected := range ciphertexts {
+ actual, err := os.ReadFile(path)
+ if err != nil || !bytes.Equal(actual, expected) {
+ t.Fatalf("failed replay changed encrypted data: %v", err)
+ }
+ }
+ })
+ }
+ })
+ }
+}
+
+func optionUndoSelections(names ...string) []*av.ValueSelect {
+ ret := make([]*av.ValueSelect, 0, len(names))
+ for _, name := range names {
+ ret = append(ret, &av.ValueSelect{Content: name, Color: map[string]string{"A": "1", "B": "2", "C": "3"}[name]})
+ }
+ return ret
+}
+
+func setupAttributeViewOptionUndoTest(t *testing.T, action string, typ av.KeyType) (*fileOperationTestFixture, *av.AttributeView, *av.AttributeView, *Transaction) {
+ t.Helper()
+ fixture, source, _, _ := setupAttributeViewItemsTest(t, false)
+ util.AttrViewLangs["en"]["gallery"], util.AttrViewLangs["en"]["kanban"] = "Gallery", "Kanban"
+ var field *av.KeyValues
+ for _, kv := range source.KeyValues {
+ if kv.Key.Type == typ && len(kv.Values) != 0 {
+ field = kv
+ break
+ }
+ }
+ field.Key.Name = "Options"
+ field.Key.Options = []*av.SelectOption{{Name: "A", Color: "1", Desc: "Original description"},
+ {Name: "B", Color: "2", Desc: "Target description"}, {Name: "C", Color: "3"}}
+ selections := [][]string{{"A"}, {"B"}, {"A", "B"}, {"C"}}
+ if typ == av.KeyTypeSelect {
+ selections[2] = []string{"A"}
+ }
+ for i, value := range field.Values {
+ value.MSelect = optionUndoSelections(selections[i]...)
+ }
+ optionFilter := func(names ...string) *av.ViewFilter {
+ return &av.ViewFilter{Column: field.Key.ID, Operator: av.FilterOperatorContains,
+ Value: &av.Value{Type: typ, MSelect: optionUndoSelections(names...)}}
+ }
+ source.Views = append(source.Views, av.NewGalleryView(), av.NewKanbanView())
+ for _, view := range source.Views {
+ view.Filters = fieldFilterRoot(&av.ViewFilter{Combination: av.FilterCombinationOr,
+ Filters: []*av.ViewFilter{optionFilter("A"), optionFilter("A", "B")}}, optionFilter("B"))
+ view.Group = &av.ViewGroup{Field: field.Key.ID, Method: av.GroupMethodValue}
+ if view.Table != nil {
+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.Key.ID}})
+ }
+ if view.Gallery != nil {
+ view.Gallery.CardFields = []*av.ViewGalleryCardField{{BaseField: &av.BaseField{ID: field.Key.ID}}}
+ }
+ if view.Kanban != nil {
+ view.Kanban.Fields = []*av.ViewKanbanField{{BaseField: &av.BaseField{ID: field.Key.ID}}}
+ }
+ }
+ for _, names := range [][]string{{"A"}, {"A", "B"}, {"B"}} {
+ source.NewItemTemplates = append(source.NewItemTemplates, &av.NewItemTemplate{ID: ast.NewNodeID(), Name: "Private template",
+ TargetType: av.NewItemTargetDetached, FieldValues: map[string]*av.NewItemFieldValue{
+ field.Key.ID: {Mode: av.NewItemFieldValueStatic, Value: &av.Value{Type: typ, MSelect: optionUndoSelections(names...)}},
+ }})
+ }
+ peer := av.NewAttributeView(ast.NewNodeID())
+ for _, view := range []*av.AttributeView{source, peer} {
+ relationID := ast.NewNodeID()
+ view.KeyValues = append(view.KeyValues,
+ &av.KeyValues{Key: &av.Key{ID: relationID, Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: source.ID, CandidateFilters: fieldFilterRoot(optionFilter("A"), optionFilter("A", "B"))}}},
+ &av.KeyValues{Key: &av.Key{ID: ast.NewNodeID(), Type: av.KeyTypeRollup,
+ Rollup: &av.Rollup{RelationKeyID: relationID, KeyID: field.Key.ID, Filters: fieldFilterRoot(optionFilter("A"))}}})
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ av.UpsertAvBackRel(view.ID, source.ID)
+ }
+ regenAttrViewGroups(source)
+ for _, view := range source.Views {
+ for i, group := range view.Groups {
+ group.GroupFolded, group.GroupSort = true, i+2
+ slices.Reverse(group.GroupItemIDs)
+ }
+ }
+ if err := av.SaveAttributeView(source); err != nil {
+ t.Fatal(err)
+ }
+ op := &Operation{Action: "removeAttrViewColOption", ID: field.Key.ID, AvID: source.ID, BlockID: fixture.sourceID, Data: "A"}
+ inverse := &Operation{Action: "updateAttrViewColOptions", ID: field.Key.ID, AvID: source.ID, BlockID: fixture.sourceID, Data: field.Key.Options}
+ if action != "delete" {
+ name := "B"
+ if action == "rename" {
+ name = "Renamed"
+ }
+ op.Action, inverse.Action = "updateAttrViewColOption", "updateAttrViewColOption"
+ op.Data = map[string]any{"oldName": "A", "newName": name, "newColor": "1", "newDesc": "Changed"}
+ inverse.Data = map[string]any{"oldName": name, "newName": "A", "newColor": "1", "newDesc": "Original description"}
+ }
+ return fixture, readAttributeViewItemsTest(t, source.ID), readAttributeViewItemsTest(t, peer.ID),
+ &Transaction{DoOperations: []*Operation{op}, UndoOperations: []*Operation{inverse}, fromAPI: true}
+}