Skip to content

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

:recycle: Reduce attribute view type dispatch duplication

Jeffrey Chen71218bfe17ef
diff --git a/kernel/av/av_fix_test.go b/kernel/av/av_fix_test.go
index 7cb1cf5022..732179f803 100644
--- a/kernel/av/av_fix_test.go
+++ b/kernel/av/av_fix_test.go
@@ -29,12 +29,16 @@ func TestUpgradeSpec6CardConfiguration(t *testing.T) {
Spec: 5,
Views: []*View{{
Gallery: &LayoutGallery{
- CardSize: CardSizeSmall,
- CardAspectRatio: CardAspectRatio3_4,
+ CardSettings: CardSettings{
+ CardSize: CardSizeSmall,
+ CardAspectRatio: CardAspectRatio3_4,
+ },
},
Kanban: &LayoutKanban{
- CardSize: CardSizeLarge,
- CardAspectRatio: CardAspectRatio2_3,
+ CardSettings: CardSettings{
+ CardSize: CardSizeLarge,
+ CardAspectRatio: CardAspectRatio2_3,
+ },
},
}},
}
diff --git a/kernel/av/calc.go b/kernel/av/calc.go
index 4261406985..e024cc7f34 100644
--- a/kernel/av/calc.go
+++ b/kernel/av/calc.go
@@ -99,25 +99,25 @@ func Calc(viewable Viewable, attrView *AttributeView) {
func calcField(collection Collection, field Field, fieldIndex int, attrView *AttributeView) {
switch field.GetType() {
case KeyTypeBlock:
- calcFieldBlock(collection, field, fieldIndex)
+ calcFieldByScalarContent(collection, field, fieldIndex, countBlockValues, countBlockUniqueValues)
case KeyTypeText:
- calcFieldText(collection, field, fieldIndex)
+ calcFieldByScalarContent(collection, field, fieldIndex, countTextValues, countTextUniqueValues)
+ case KeyTypeURL:
+ calcFieldByScalarContent(collection, field, fieldIndex, countURLValues, countURLUniqueValues)
+ case KeyTypeEmail:
+ calcFieldByScalarContent(collection, field, fieldIndex, countEmailValues, countEmailUniqueValues)
+ case KeyTypePhone:
+ calcFieldByScalarContent(collection, field, fieldIndex, countPhoneValues, countPhoneUniqueValues)
+ case KeyTypeSelect:
+ calcFieldByScalarContent(collection, field, fieldIndex, countSelectValues, countSelectUniqueValues)
case KeyTypeNumber:
calcFieldNumber(collection, field, fieldIndex)
case KeyTypeDate:
calcFieldDate(collection, field, fieldIndex)
- case KeyTypeSelect:
- calcFieldSelect(collection, field, fieldIndex)
case KeyTypeMSelect:
calcFieldMSelect(collection, field, fieldIndex)
- case KeyTypeURL:
- calcFieldURL(collection, field, fieldIndex)
- case KeyTypeEmail:
- calcFieldEmail(collection, field, fieldIndex)
case KeyTypeLocation:
calcFieldLocation(collection, field, fieldIndex)
- case KeyTypePhone:
- calcFieldPhone(collection, field, fieldIndex)
case KeyTypeMAsset:
calcFieldMAsset(collection, field, fieldIndex)
case KeyTypeTemplate:
@@ -491,93 +491,6 @@ func calcFieldMSelect(collection Collection, field Field, fieldIndex int) {
}
}
-func calcFieldSelect(collection Collection, field Field, fieldIndex int) {
- calc := field.GetCalc()
- switch calc.Operator {
- case CalcOperatorCountAll:
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(len(collection.GetItems())), NumberFormatNone)}
- case CalcOperatorCountValues:
- countValues := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].MSelect && 0 < len(values[fieldIndex].MSelect) && nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
- countValues++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues), NumberFormatNone)}
- case CalcOperatorCountUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].MSelect && 0 < len(values[fieldIndex].MSelect) && nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
- if _, ok := uniqueValues[values[fieldIndex].MSelect[0].Content]; !ok {
- uniqueValues[values[fieldIndex].MSelect[0].Content] = true
- countUniqueValues++
- }
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues), NumberFormatNone)}
- case CalcOperatorCountEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].MSelect || 1 > len(values[fieldIndex].MSelect) || nil == values[fieldIndex].MSelect[0] || "" == values[fieldIndex].MSelect[0].Content {
- countEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty), NumberFormatNone)}
- case CalcOperatorCountNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].MSelect && 0 < len(values[fieldIndex].MSelect) && nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
- countNotEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty), NumberFormatNone)}
- case CalcOperatorPercentEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].MSelect || 1 > len(values[fieldIndex].MSelect) || nil == values[fieldIndex].MSelect[0] || "" == values[fieldIndex].MSelect[0].Content {
- countEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].MSelect && 0 < len(values[fieldIndex].MSelect) && nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
- countNotEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].MSelect && 0 < len(values[fieldIndex].MSelect) && nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
- if _, ok := uniqueValues[values[fieldIndex].MSelect[0].Content]; !ok {
- uniqueValues[values[fieldIndex].MSelect[0].Content] = true
- countUniqueValues++
- }
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorTemplate:
- calcFieldByTemplate(collection, field, fieldIndex)
- }
-}
-
func calcFieldDate(collection Collection, field Field, fieldIndex int) {
calc := field.GetCalc()
switch calc.Operator {
@@ -891,435 +804,181 @@ func calcFieldNumber(collection Collection, field Field, fieldIndex int) {
}
}
-func calcFieldText(collection Collection, field Field, fieldIndex int) {
- calc := field.GetCalc()
- switch calc.Operator {
- case CalcOperatorCountAll:
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(len(collection.GetItems())), NumberFormatNone)}
- case CalcOperatorCountValues:
- countValues := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
- countValues++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues), NumberFormatNone)}
- case CalcOperatorCountUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
- if !uniqueValues[values[fieldIndex].Text.Content] {
- uniqueValues[values[fieldIndex].Text.Content] = true
- countUniqueValues++
- }
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues), NumberFormatNone)}
- case CalcOperatorCountEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Text || "" == values[fieldIndex].Text.Content {
- countEmpty++
- }
+// calcScalarContent 返回单值字段用于统计的内容,空串表示该条目没有值。
+// 单值内容字段都只有一处内容来源,集中在这里分派,新增类型只需要在这里登记。
+// countBlockValues 统计块引用字段有内容的条目数。
+func countBlockValues(items []Item, fieldIndex int) int {
+ count := 0
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
+ count++
}
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty), NumberFormatNone)}
- case CalcOperatorCountNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
- countNotEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty), NumberFormatNone)}
- case CalcOperatorPercentEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Text || "" == values[fieldIndex].Text.Content {
- countEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
- countNotEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
- if !uniqueValues[values[fieldIndex].Text.Content] {
- uniqueValues[values[fieldIndex].Text.Content] = true
- countUniqueValues++
- }
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorTemplate:
- calcFieldByTemplate(collection, field, fieldIndex)
}
+ return count
}
-func calcFieldURL(collection Collection, field Field, fieldIndex int) {
- calc := field.GetCalc()
- switch calc.Operator {
- case CalcOperatorCountAll:
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(len(collection.GetItems())), NumberFormatNone)}
- case CalcOperatorCountValues:
- countValues := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
- countValues++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues), NumberFormatNone)}
- case CalcOperatorCountUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
- if !uniqueValues[values[fieldIndex].URL.Content] {
- uniqueValues[values[fieldIndex].URL.Content] = true
- countUniqueValues++
- }
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues), NumberFormatNone)}
- case CalcOperatorCountEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].URL || "" == values[fieldIndex].URL.Content {
- countEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty), NumberFormatNone)}
- case CalcOperatorCountNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
- countNotEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty), NumberFormatNone)}
- case CalcOperatorPercentEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].URL || "" == values[fieldIndex].URL.Content {
- countEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
- countNotEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
- if !uniqueValues[values[fieldIndex].URL.Content] {
- uniqueValues[values[fieldIndex].URL.Content] = true
- countUniqueValues++
- }
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues)/float64(len(collection.GetItems())), NumberFormatPercent)}
+// countBlockUniqueValues 统计块引用字段不同内容的个数。
+func countBlockUniqueValues(items []Item, fieldIndex int) int {
+ unique := map[string]struct{}{}
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
+ unique[values[fieldIndex].Block.Content] = struct{}{}
}
- case CalcOperatorTemplate:
- calcFieldByTemplate(collection, field, fieldIndex)
}
+ return len(unique)
}
-func calcFieldEmail(collection Collection, field Field, fieldIndex int) {
- calc := field.GetCalc()
- switch calc.Operator {
- case CalcOperatorCountAll:
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(len(collection.GetItems())), NumberFormatNone)}
- case CalcOperatorCountValues:
- countValues := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
- countValues++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues), NumberFormatNone)}
- case CalcOperatorCountUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
- if !uniqueValues[values[fieldIndex].Email.Content] {
- uniqueValues[values[fieldIndex].Email.Content] = true
- countUniqueValues++
- }
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues), NumberFormatNone)}
- case CalcOperatorCountEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Email || "" == values[fieldIndex].Email.Content {
- countEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty), NumberFormatNone)}
- case CalcOperatorCountNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
- countNotEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty), NumberFormatNone)}
- case CalcOperatorPercentEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Email || "" == values[fieldIndex].Email.Content {
- countEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
+// countTextValues 统计文本字段有内容的条目数。
+func countTextValues(items []Item, fieldIndex int) int {
+ count := 0
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
+ count++
}
- case CalcOperatorPercentNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
- countNotEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorPercentUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
- if !uniqueValues[values[fieldIndex].Email.Content] {
- uniqueValues[values[fieldIndex].Email.Content] = true
- countUniqueValues++
- }
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues)/float64(len(collection.GetItems())), NumberFormatPercent)}
- }
- case CalcOperatorTemplate:
- calcFieldByTemplate(collection, field, fieldIndex)
}
+ return count
}
-func calcFieldPhone(collection Collection, field Field, fieldIndex int) {
- calc := field.GetCalc()
- switch calc.Operator {
- case CalcOperatorCountAll:
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(len(collection.GetItems())), NumberFormatNone)}
- case CalcOperatorCountValues:
- countValues := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
- countValues++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues), NumberFormatNone)}
- case CalcOperatorCountUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
- if !uniqueValues[values[fieldIndex].Phone.Content] {
- uniqueValues[values[fieldIndex].Phone.Content] = true
- countUniqueValues++
- }
- }
+// countTextUniqueValues 统计文本字段不同内容的个数。
+func countTextUniqueValues(items []Item, fieldIndex int) int {
+ unique := map[string]struct{}{}
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Text && "" != values[fieldIndex].Text.Content {
+ unique[values[fieldIndex].Text.Content] = struct{}{}
}
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues), NumberFormatNone)}
- case CalcOperatorCountEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Phone || "" == values[fieldIndex].Phone.Content {
- countEmpty++
- }
+ }
+ return len(unique)
+}
+
+// countURLValues 统计链接字段有内容的条目数。
+func countURLValues(items []Item, fieldIndex int) int {
+ count := 0
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
+ count++
}
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty), NumberFormatNone)}
- case CalcOperatorCountNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
- countNotEmpty++
- }
+ }
+ return count
+}
+
+// countURLUniqueValues 统计链接字段不同内容的个数。
+func countURLUniqueValues(items []Item, fieldIndex int) int {
+ unique := map[string]struct{}{}
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].URL && "" != values[fieldIndex].URL.Content {
+ unique[values[fieldIndex].URL.Content] = struct{}{}
}
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty), NumberFormatNone)}
- case CalcOperatorPercentEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Phone || "" == values[fieldIndex].Phone.Content {
- countEmpty++
- }
+ }
+ return len(unique)
+}
+
+// countEmailValues 统计邮箱字段有内容的条目数。
+func countEmailValues(items []Item, fieldIndex int) int {
+ count := 0
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
+ count++
}
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
+ }
+ return count
+}
+
+// countEmailUniqueValues 统计邮箱字段不同内容的个数。
+func countEmailUniqueValues(items []Item, fieldIndex int) int {
+ unique := map[string]struct{}{}
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Email && "" != values[fieldIndex].Email.Content {
+ unique[values[fieldIndex].Email.Content] = struct{}{}
}
- case CalcOperatorPercentNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
- countNotEmpty++
- }
+ }
+ return len(unique)
+}
+
+// countPhoneValues 统计电话字段有内容的条目数。
+func countPhoneValues(items []Item, fieldIndex int) int {
+ count := 0
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
+ count++
}
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
+ }
+ return count
+}
+
+// countPhoneUniqueValues 统计电话字段不同内容的个数。
+func countPhoneUniqueValues(items []Item, fieldIndex int) int {
+ unique := map[string]struct{}{}
+ for _, item := range items {
+ values := item.GetValues()
+ if fieldIndex < len(values) && nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
+ unique[values[fieldIndex].Phone.Content] = struct{}{}
}
- case CalcOperatorPercentUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Phone && "" != values[fieldIndex].Phone.Content {
- if !uniqueValues[values[fieldIndex].Phone.Content] {
- uniqueValues[values[fieldIndex].Phone.Content] = true
- countUniqueValues++
- }
- }
+ }
+ return len(unique)
+}
+
+// countSelectValues 统计单选字段有内容的条目数,内容取第一个选项。
+func countSelectValues(items []Item, fieldIndex int) int {
+ count := 0
+ for _, item := range items {
+ values := item.GetValues()
+ if 0 < len(values) && fieldIndex < len(values) && nil != values[fieldIndex] && 0 < len(values[fieldIndex].MSelect) &&
+ nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
+ count++
}
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues)/float64(len(collection.GetItems())), NumberFormatPercent)}
+ }
+ return count
+}
+
+// countSelectUniqueValues 统计单选字段不同内容的个数,内容取第一个选项。
+func countSelectUniqueValues(items []Item, fieldIndex int) int {
+ unique := map[string]struct{}{}
+ for _, item := range items {
+ values := item.GetValues()
+ if 0 < len(values) && fieldIndex < len(values) && nil != values[fieldIndex] && 0 < len(values[fieldIndex].MSelect) &&
+ nil != values[fieldIndex].MSelect[0] && "" != values[fieldIndex].MSelect[0].Content {
+ unique[values[fieldIndex].MSelect[0].Content] = struct{}{}
}
- case CalcOperatorTemplate:
- calcFieldByTemplate(collection, field, fieldIndex)
}
+ return len(unique)
}
-func calcFieldBlock(collection Collection, field Field, fieldIndex int) {
+// calcFieldByScalarContent 汇总单值内容字段。各类型的内容来源不同,由调用方给出计数函数,
+// 算子分派与占比分母在此统一;条目集合只取一次,避免占比算子重复构造条目列表。
+func calcFieldByScalarContent(collection Collection, field Field, fieldIndex int,
+ countValues, countUniqueValues func([]Item, int) int) {
calc := field.GetCalc()
+ items := collection.GetItems()
+ total := len(items)
switch calc.Operator {
case CalcOperatorCountAll:
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(len(collection.GetItems())), NumberFormatNone)}
- case CalcOperatorCountValues:
- countValues := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
- countValues++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues), NumberFormatNone)}
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(total), NumberFormatNone)}
+ case CalcOperatorCountValues, CalcOperatorCountNotEmpty:
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues(items, fieldIndex)), NumberFormatNone)}
case CalcOperatorCountUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
- if !uniqueValues[values[fieldIndex].Block.Content] {
- uniqueValues[values[fieldIndex].Block.Content] = true
- countUniqueValues++
- }
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues), NumberFormatNone)}
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues(items, fieldIndex)), NumberFormatNone)}
case CalcOperatorCountEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Block || "" == values[fieldIndex].Block.Content {
- countEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty), NumberFormatNone)}
- case CalcOperatorCountNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
- countNotEmpty++
- }
- }
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty), NumberFormatNone)}
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(total-countValues(items, fieldIndex)), NumberFormatNone)}
case CalcOperatorPercentEmpty:
- countEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil == values[fieldIndex] || nil == values[fieldIndex].Block || "" == values[fieldIndex].Block.Content {
- countEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
+ if 0 < total {
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(total-countValues(items, fieldIndex))/float64(total), NumberFormatPercent)}
}
case CalcOperatorPercentNotEmpty:
- countNotEmpty := 0
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
- countNotEmpty++
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countNotEmpty)/float64(len(collection.GetItems())), NumberFormatPercent)}
+ if 0 < total {
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(countValues(items, fieldIndex))/float64(total), NumberFormatPercent)}
}
case CalcOperatorPercentUniqueValues:
- countUniqueValues := 0
- uniqueValues := map[string]bool{}
- for _, item := range collection.GetItems() {
- values := item.GetValues()
- if nil != values[fieldIndex] && nil != values[fieldIndex].Block && "" != values[fieldIndex].Block.Content {
- if !uniqueValues[values[fieldIndex].Block.Content] {
- uniqueValues[values[fieldIndex].Block.Content] = true
- countUniqueValues++
- }
- }
- }
- if 0 < len(collection.GetItems()) {
- calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues)/float64(len(collection.GetItems())), NumberFormatPercent)}
+ if 0 < total {
+ calc.Result = &Value{Number: NewFormattedValueNumber(float64(countUniqueValues(items, fieldIndex))/float64(total), NumberFormatPercent)}
}
case CalcOperatorTemplate:
calcFieldByTemplate(collection, field, fieldIndex)
diff --git a/kernel/av/calc_scalar_content_test.go b/kernel/av/calc_scalar_content_test.go
new file mode 100644
index 0000000000..8329c1cd9d
--- /dev/null
+++ b/kernel/av/calc_scalar_content_test.go
@@ -0,0 +1,156 @@
+// SiYuan - https://github.com/siyuan-note/siyuan
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package av
+
+import (
+ "math"
+ "testing"
+)
+
+// scalarContentTypes 是共用单值内容统计口径的字段类型。
+var scalarContentTypes = []KeyType{
+ KeyTypeBlock, KeyTypeText, KeyTypeURL, KeyTypeEmail, KeyTypePhone, KeyTypeSelect,
+}
+
+// scalarContentValue 按类型构造只带内容的字段值,用于验证统计口径与类型无关。
+func scalarContentValue(t *testing.T, typ KeyType, content string) *Value {
+ t.Helper()
+ value := &Value{Type: typ}
+ switch typ {
+ case KeyTypeBlock:
+ value.Block = &ValueBlock{Content: content}
+ case KeyTypeText:
+ value.Text = &ValueText{Content: content}
+ case KeyTypeURL:
+ value.URL = &ValueURL{Content: content}
+ case KeyTypeEmail:
+ value.Email = &ValueEmail{Content: content}
+ case KeyTypePhone:
+ value.Phone = &ValuePhone{Content: content}
+ case KeyTypeSelect:
+ value.MSelect = []*ValueSelect{{Content: content}}
+ default:
+ t.Fatalf("类型 %s 不是单值内容字段", typ)
+ }
+ return value
+}
+
+// scalarContentTable 构造单列表格,nil 表示该行缺少字段值。
+func scalarContentTable(t *testing.T, typ KeyType, contents []*string) *Table {
+ t.Helper()
+ column := &TableColumn{BaseInstanceField: &BaseInstanceField{ID: "field", Type: typ}}
+ table := &Table{BaseInstance: &BaseInstance{}, Columns: []*TableColumn{column}}
+ for _, content := range contents {
+ cell := &TableCell{BaseValue: &BaseValue{}}
+ if nil != content {
+ cell.Value = scalarContentValue(t, typ, *content)
+ }
+ table.Rows = append(table.Rows, &TableRow{Cells: []*TableCell{cell}})
+ }
+ return table
+}
+
+func textPointer(text string) *string {
+ return &text
+}
+
+// TestScalarContentCalc 固定单值内容字段各算子的结果。五种取值形态覆盖有内容、
+// 重复内容、空内容和缺少值,避免归并时把空值判定或计数单位改错。
+func TestScalarContentCalc(t *testing.T) {
+ contents := []*string{textPointer("甲"), textPointer("乙"), textPointer("甲"), textPointer(""), nil}
+ const (
+ total = 5
+ values = 3
+ uniqueValues = 2
+ empty = 2
+ )
+
+ tests := []struct {
+ operator CalcOperator
+ want float64
+ format NumberFormat
+ }{
+ {CalcOperatorCountAll, total, NumberFormatNone},
+ {CalcOperatorCountValues, values, NumberFormatNone},
+ {CalcOperatorCountNotEmpty, values, NumberFormatNone},
+ {CalcOperatorCountUniqueValues, uniqueValues, NumberFormatNone},
+ {CalcOperatorCountEmpty, empty, NumberFormatNone},
+ {CalcOperatorPercentEmpty, float64(empty) / total, NumberFormatPercent},
+ {CalcOperatorPercentNotEmpty, float64(values) / total, NumberFormatPercent},
+ {CalcOperatorPercentUniqueValues, float64(uniqueValues) / total, NumberFormatPercent},
+ }
+
+ for _, typ := range scalarContentTypes {
+ t.Run(string(typ), func(t *testing.T) {
+ for _, test := range tests {
+ t.Run(string(test.operator), func(t *testing.T) {
+ table := scalarContentTable(t, typ, contents)
+ column := table.Columns[0]
+ column.Calc = &FieldCalc{Operator: test.operator}
+ calcField(table, column, 0, nil)
+
+ if nil == column.Calc.Result || nil == column.Calc.Result.Number {
+ t.Fatalf("算子 %s 没有产生结果", test.operator)
+ }
+ if math.Abs(column.Calc.Result.Number.Content-test.want) > 1e-10 {
+ t.Fatalf("结果 = %v,期望 %v", column.Calc.Result.Number.Content, test.want)
+ }
+ if test.format != column.Calc.Result.Number.Format {
+ t.Fatalf("格式 = %v,期望 %v", column.Calc.Result.Number.Format, test.format)
+ }
+ })
+ }
+ })
+ }
+}
+
+// TestScalarContentCalcEmptyCollection 空集合的占比算子不产生结果,与计数算子区分开。
+func TestScalarContentCalcEmptyCollection(t *testing.T) {
+ for _, typ := range scalarContentTypes {
+ t.Run(string(typ), func(t *testing.T) {
+ table := scalarContentTable(t, typ, nil)
+ column := table.Columns[0]
+ for _, operator := range []CalcOperator{CalcOperatorPercentEmpty, CalcOperatorPercentNotEmpty, CalcOperatorPercentUniqueValues} {
+ column.Calc = &FieldCalc{Operator: operator}
+ calcField(table, column, 0, nil)
+ if nil != column.Calc.Result {
+ t.Fatalf("空集合的 %s 应无结果,实际 %v", operator, column.Calc.Result.Number.Content)
+ }
+ }
+ column.Calc = &FieldCalc{Operator: CalcOperatorCountAll}
+ calcField(table, column, 0, nil)
+ if nil == column.Calc.Result || 0 != column.Calc.Result.Number.Content {
+ t.Fatalf("空集合的 Count all 应为 0")
+ }
+ })
+ }
+}
+
+// BenchmarkScalarContentCount 固定单值内容统计的开销,归并后仍应是按条目一次遍历。
+func BenchmarkScalarContentCount(b *testing.B) {
+ contents := make([]*string, 10000)
+ for i := range contents {
+ text := "值"
+ if 0 == i%3 {
+ text = ""
+ }
+ contents[i] = &text
+ }
+ table := &Table{BaseInstance: &BaseInstance{}, Columns: []*TableColumn{{BaseInstanceField: &BaseInstanceField{ID: "field", Type: KeyTypeText}}}}
+ for _, content := range contents {
+ table.Rows = append(table.Rows, &TableRow{Cells: []*TableCell{{BaseValue: &BaseValue{Value: &Value{Type: KeyTypeText, Text: &ValueText{Content: *content}}}}}})
+ }
+ column := table.Columns[0]
+
+ for _, operator := range []CalcOperator{CalcOperatorCountValues, CalcOperatorCountEmpty, CalcOperatorCountUniqueValues} {
+ b.Run(string(operator), func(b *testing.B) {
+ column.Calc = &FieldCalc{Operator: operator}
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ calcField(table, column, 0, nil)
+ }
+ })
+ }
+}
diff --git a/kernel/av/card_settings_test.go b/kernel/av/card_settings_test.go
new file mode 100644
index 0000000000..00c6237d63
--- /dev/null
+++ b/kernel/av/card_settings_test.go
@@ -0,0 +1,129 @@
+// SiYuan - https://github.com/siyuan-note/siyuan
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package av
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+// 卡片布局和看板布局把共有的封面与卡片设置收进嵌入结构,持久化字段必须保持扁平:
+// 旧文件是扁平 JSON,前端和插件按顶层字段名读写,出现嵌套对象就是格式变更。
+
+func TestCardSettingsMarshalStaysFlat(t *testing.T) {
+ keys := []string{
+ "spec", "id", "showIcon", "wrapField",
+ "coverFrom", "coverFromAssetKeyID", "cardAspectRatio", "cardAspectRatioValue",
+ "cardSize", "cardWidth", "cardLayout", "fitImage", "displayFieldName", "displayEmptyFields",
+ "fields",
+ }
+ for _, test := range []struct {
+ name string
+ value any
+ }{
+ {"gallery", func() *LayoutGallery {
+ gallery := NewLayoutGallery()
+ gallery.CoverFromAssetKeyID = "asset"
+ return gallery
+ }()},
+ {"kanban", func() *LayoutKanban {
+ kanban := NewLayoutKanban()
+ kanban.CoverFromAssetKeyID = "asset"
+ return kanban
+ }()},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ data, err := json.Marshal(test.value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded map[string]json.RawMessage
+ if err = json.Unmarshal(data, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range keys {
+ if _, found := decoded[key]; !found {
+ t.Fatalf("序列化结果缺少顶层字段 %q:%s", key, data)
+ }
+ }
+ for _, nested := range []string{"CardSettings", "cardSettings", "BaseLayout", "baseLayout"} {
+ if _, found := decoded[nested]; found {
+ t.Fatalf("嵌入结构不得出现在持久化字段中:%q", nested)
+ }
+ }
+ })
+ }
+}
+
+func TestCardSettingsUnmarshalLegacyFlatJSON(t *testing.T) {
+ const galleryJSON = `{"spec":0,"id":"g","showIcon":true,"wrapField":true,` +
+ `"coverFrom":2,"coverFromAssetKeyID":"asset","cardAspectRatio":5,"cardAspectRatioValue":1.5,` +
+ `"cardSize":2,"cardWidth":300,"cardLayout":1,"fitImage":true,"displayFieldName":true,` +
+ `"displayEmptyFields":true,"fields":[]}`
+ var gallery LayoutGallery
+ if err := json.Unmarshal([]byte(galleryJSON), &gallery); err != nil {
+ t.Fatal(err)
+ }
+ if CoverFromAssetField != gallery.CoverFrom || "asset" != gallery.CoverFromAssetKeyID {
+ t.Fatalf("封面设置未按扁平字段还原:%+v", gallery.CardSettings)
+ }
+ if 300 != gallery.CardWidth || CardLayoutCompact != gallery.CardLayout || !gallery.FitImage {
+ t.Fatalf("卡片设置未按扁平字段还原:%+v", gallery.CardSettings)
+ }
+ if !gallery.DisplayFieldName || !gallery.DisplayEmptyFields || 2 != gallery.CardSize {
+ t.Fatalf("显示设置未按扁平字段还原:%+v", gallery.CardSettings)
+ }
+
+ // 往返一次后字节保持不变,确认内嵌结构没有引入格式漂移。
+ encoded, err := json.Marshal(&gallery)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var again LayoutGallery
+ if err = json.Unmarshal(encoded, &again); err != nil {
+ t.Fatal(err)
+ }
+ second, err := json.Marshal(&again)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(encoded) != string(second) {
+ t.Fatalf("往返不稳定:\n%s\n%s", encoded, second)
+ }
+}
+
+func TestViewAccessorsCoverCardAndBaseLayouts(t *testing.T) {
+ gallery := &View{LayoutType: LayoutTypeGallery, Gallery: NewLayoutGallery()}
+ if cards := gallery.GetCardSettings(); nil == cards || cards != &gallery.Gallery.CardSettings {
+ t.Fatal("卡片视图应返回自己的卡片设置")
+ }
+ if base := gallery.GetBaseLayout(); nil == base || base != gallery.Gallery.BaseLayout {
+ t.Fatal("卡片视图应返回自己的基础设置")
+ }
+
+ kanban := &View{LayoutType: LayoutTypeKanban, Kanban: NewLayoutKanban()}
+ if cards := kanban.GetCardSettings(); nil == cards || cards != &kanban.Kanban.CardSettings {
+ t.Fatal("看板视图应返回自己的卡片设置")
+ }
+
+ table := &View{LayoutType: LayoutTypeTable, Table: NewLayoutTable()}
+ if nil != table.GetCardSettings() {
+ t.Fatal("表格视图没有卡片设置")
+ }
+ if base := table.GetBaseLayout(); nil == base || base != table.Table.BaseLayout {
+ t.Fatal("表格视图的基础设置来自表格布局")
+ }
+
+ list := &View{LayoutType: LayoutTypeList, List: NewLayoutList()}
+ if base := list.GetBaseLayout(); nil == base {
+ t.Fatal("列表视图的基础设置来自表格布局")
+ }
+
+ // 布局缺失时返回 nil,调用方用默认值,不因为字段缺失而崩溃。
+ broken := &View{LayoutType: LayoutTypeGallery}
+ if nil != broken.GetCardSettings() || nil != broken.GetBaseLayout() {
+ t.Fatal("缺少布局数据时应返回 nil")
+ }
+}
diff --git a/kernel/av/dispatch_coverage_test.go b/kernel/av/dispatch_coverage_test.go
new file mode 100644
index 0000000000..ff822a7ace
--- /dev/null
+++ b/kernel/av/dispatch_coverage_test.go
@@ -0,0 +1,233 @@
+// SiYuan - https://github.com/siyuan-note/siyuan
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package av
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// 字段类型分派都是全枚举 switch:漏掉一种类型既不会编译失败,也不会被现有用例发现,
+// 只会静默返回零值。本文件把「必须显式处理每种类型」写成断言,让遗漏变成失败。
+//
+// 期望集合全部从字段能力表推导,不在此处抄一份类型清单,避免新增类型时两处都要改。
+
+// nonStoredKeyTypes 声明不落在 Value 上的字段类型。
+// 行号是渲染期按段落序号生成的计算列,不参与取值、置值、判空和默认值分派。
+var nonStoredKeyTypes = []KeyType{KeyTypeLineNumber}
+
+// typeDispatch 描述一个必须逐类型分支的函数,以及它应覆盖的类型集合。
+type typeDispatch struct {
+ file string
+ function string
+ expect []KeyType
+ reason string
+}
+
+func TestTypeDispatchCoversDeclaredCases(t *testing.T) {
+ stored := keyTypesWithout(nonStoredKeyTypes...)
+ sortable := keyTypesWhere(func(capability KeyCapability) bool { return capability.Sortable })
+ filterable := keyTypesWhere(func(capability KeyCapability) bool { return capability.Filterable })
+ // 汇总值在 Value.Filter 中先解包成目标类型的值再比较,不会以 Rollup 身份进入 filter。
+ filterableValues := keyTypesExcept(filterable, KeyTypeRollup)
+ // 生成字段与行号在 GetAffectValue 开头按能力分组提前返回,不参与默认值构造。
+ filterDefaults := keyTypesWhere(func(capability KeyCapability) bool {
+ return capability.Filterable && capability.Groups&KeyGroupNoFilterDefault == 0
+ })
+
+ dispatches := []typeDispatch{
+ {"value.go", "String", stored, "每种存储值都必须有文本表示"},
+ {"value.go", "isEmpty", stored, "每种存储值都必须能判断空值与空白"},
+ {"value.go", "SetValByType", stored, "每种存储值都必须能按类型写入"},
+ {"value.go", "GetValByType", stored, "每种存储值都必须能按类型读取"},
+ {"value.go", "GetAttributeViewDefaultValue", stored, "每种存储值都必须有默认值构造"},
+ {"calc.go", "calcField", sortable, "不可排序的字段不参与汇总"},
+ {"sort.go", "compare", sortable, "每种可排序字段都必须能比较"},
+ {"filter.go", "filter", filterableValues, "每种可筛选字段都必须能比较取值"},
+ {"filter.go", "GetAffectValue", filterDefaults, "可筛选且非生成字段才构造筛选默认值"},
+ }
+
+ files := avPackageFiles(t)
+ values := keyTypeConstantValues(t, files)
+ for _, dispatch := range dispatches {
+ t.Run(dispatch.file+":"+dispatch.function, func(t *testing.T) {
+ actual := keyTypeCaseValues(t, files, values, dispatch.file, dispatch.function)
+ expect := make([]string, 0, len(dispatch.expect))
+ for _, typ := range dispatch.expect {
+ expect = append(expect, string(typ))
+ }
+ sort.Strings(expect)
+ if missing := difference(expect, actual); 0 < len(missing) {
+ t.Fatalf("%s 未处理 %s:%s", dispatch.reason, dispatch.function, strings.Join(missing, ", "))
+ }
+ if extra := difference(actual, expect); 0 < len(extra) {
+ t.Fatalf("%s 不应处理 %s:%s", dispatch.reason, dispatch.function, strings.Join(extra, ", "))
+ }
+ })
+ }
+}
+
+// keyTypesWithout 返回除排除项外的全部声明类型,保持声明顺序。
+func keyTypesWithout(excluded ...KeyType) []KeyType {
+ return keyTypesExcept(KeyTypes(), excluded...)
+}
+
+func keyTypesExcept(all []KeyType, excluded ...KeyType) []KeyType {
+ skip := map[KeyType]bool{}
+ for _, typ := range excluded {
+ skip[typ] = true
+ }
+ ret := make([]KeyType, 0, len(all))
+ for _, typ := range all {
+ if !skip[typ] {
+ ret = append(ret, typ)
+ }
+ }
+ return ret
+}
+
+func keyTypesWhere(match func(capability KeyCapability) bool) []KeyType {
+ var ret []KeyType
+ for _, typ := range KeyTypes() {
+ if match(GetKeyCapability(typ)) {
+ ret = append(ret, typ)
+ }
+ }
+ return ret
+}
+
+// avPackageFiles 解析 av 包的非测试源码,供分派断言复用。
+func avPackageFiles(t *testing.T) map[string]*ast.File {
+ t.Helper()
+ packages, err := parser.ParseDir(token.NewFileSet(), ".", func(file os.FileInfo) bool {
+ return !strings.HasSuffix(file.Name(), "_test.go")
+ }, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ files := map[string]*ast.File{}
+ for name, file := range packages["av"].Files {
+ files[filepath.Base(name)] = file
+ }
+ return files
+}
+
+// keyTypeConstantValues 建立字段类型常量标识符到协议值的映射,用于把 AST 分支换算成能力表取值。
+func keyTypeConstantValues(t *testing.T, files map[string]*ast.File) map[string]string {
+ t.Helper()
+ values := map[string]string{}
+ for _, file := range files {
+ for _, declaration := range file.Decls {
+ group, ok := declaration.(*ast.GenDecl)
+ if !ok || token.CONST != group.Tok {
+ continue
+ }
+ for _, spec := range group.Specs {
+ value := spec.(*ast.ValueSpec)
+ if 1 != len(value.Names) || 1 != len(value.Values) {
+ continue
+ }
+ if !strings.HasPrefix(value.Names[0].Name, "KeyType") {
+ continue
+ }
+ literal, ok := value.Values[0].(*ast.BasicLit)
+ if !ok || token.STRING != literal.Kind {
+ t.Fatalf("字段类型常量 %s 必须声明字面量协议值", value.Names[0].Name)
+ }
+ text, err := strconv.Unquote(literal.Value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values[value.Names[0].Name] = text
+ }
+ }
+ }
+ if len(values) != len(KeyTypes()) {
+ t.Fatalf("字段类型常量数量 %d 与能力表 %d 不一致", len(values), len(KeyTypes()))
+ }
+ return values
+}
+
+// keyTypeCaseValues 返回函数体内所有 case 分支出现的字段类型协议值,去重后排序。
+func keyTypeCaseValues(t *testing.T, files map[string]*ast.File, values map[string]string, fileName, funcName string) []string {
+ t.Helper()
+ file, found := files[fileName]
+ if !found {
+ t.Fatalf("源文件 %s 不存在", fileName)
+ }
+ var body *ast.BlockStmt
+ for _, declaration := range file.Decls {
+ function, ok := declaration.(*ast.FuncDecl)
+ if !ok || function.Name.Name != funcName || nil == function.Body {
+ continue
+ }
+ body = function.Body
+ break
+ }
+ if nil == body {
+ t.Fatalf("函数 %s 不在 %s 中", funcName, fileName)
+ }
+
+ names := map[string]bool{}
+ ast.Inspect(body, func(node ast.Node) bool {
+ clause, ok := node.(*ast.CaseClause)
+ if !ok {
+ return true
+ }
+ for _, expression := range clause.List {
+ if name := keyTypeConstantName(expression); "" != name {
+ names[name] = true
+ }
+ }
+ return true
+ })
+ ret := make([]string, 0, len(names))
+ for name := range names {
+ value, found := values[name]
+ if !found {
+ t.Fatalf("%s 使用了未声明协议值的常量 %s", funcName, name)
+ }
+ ret = append(ret, value)
+ }
+ sort.Strings(ret)
+ return ret
+}
+
+// keyTypeConstantName 只接受本包的字段类型常量标识符,忽略其他分支条件。
+func keyTypeConstantName(expression ast.Expr) string {
+ switch value := expression.(type) {
+ case *ast.Ident:
+ if strings.HasPrefix(value.Name, "KeyType") {
+ return value.Name
+ }
+ case *ast.SelectorExpr:
+ if strings.HasPrefix(value.Sel.Name, "KeyType") {
+ return value.Sel.Name
+ }
+ }
+ return ""
+}
+
+// difference 返回 left 中不在 right 里的元素,两者均需已排序。
+func difference(left, right []string) []string {
+ present := map[string]bool{}
+ for _, item := range right {
+ present[item] = true
+ }
+ var ret []string
+ for _, item := range left {
+ if !present[item] {
+ ret = append(ret, item)
+ }
+ }
+ return ret
+}
diff --git a/kernel/av/layout.go b/kernel/av/layout.go
index 4378141b1b..14cb189bb5 100644
--- a/kernel/av/layout.go
+++ b/kernel/av/layout.go
@@ -80,18 +80,45 @@ type BaseInstance struct {
GroupHidden int `json:"groupHidden"` // 分组是否隐藏,0:显示,1:空白隐藏,2:手动隐藏
}
-func NewViewBaseInstance(view *View) *BaseInstance {
- showIcon, wrapField := true, false
+// GetBaseLayout 返回当前布局的基础设置,布局缺失时返回 nil。
+// 表格、列表和日历共用表格布局的基础设置。
+func (view *View) GetBaseLayout() *BaseLayout {
switch view.LayoutType {
case LayoutTypeTable, LayoutTypeList, LayoutTypeCalendar:
- showIcon = view.GetTableLayout().ShowIcon
- wrapField = view.GetTableLayout().WrapField
+ if table := view.GetTableLayout(); nil != table {
+ return table.BaseLayout
+ }
case LayoutTypeGallery:
- showIcon = view.Gallery.ShowIcon
- wrapField = view.Gallery.WrapField
+ if nil != view.Gallery {
+ return view.Gallery.BaseLayout
+ }
case LayoutTypeKanban:
- showIcon = view.Kanban.ShowIcon
- wrapField = view.Kanban.WrapField
+ if nil != view.Kanban {
+ return view.Kanban.BaseLayout
+ }
+ }
+ return nil
+}
+
+// GetCardSettings 返回卡片类布局共有的卡片设置,其他布局返回 nil。
+func (view *View) GetCardSettings() *CardSettings {
+ switch view.LayoutType {
+ case LayoutTypeGallery:
+ if nil != view.Gallery {
+ return &view.Gallery.CardSettings
+ }
+ case LayoutTypeKanban:
+ if nil != view.Kanban {
+ return &view.Kanban.CardSettings
+ }
+ }
+ return nil
+}
+
+func NewViewBaseInstance(view *View) *BaseInstance {
+ showIcon, wrapField := true, false
+ if base := view.GetBaseLayout(); nil != base {
+ showIcon, wrapField = base.ShowIcon, base.WrapField
}
return &BaseInstance{
ConditionalColors: view.EffectiveConditionalColors(),
diff --git a/kernel/av/layout_card.go b/kernel/av/layout_card.go
index 971ef18d39..24e6b01720 100644
--- a/kernel/av/layout_card.go
+++ b/kernel/av/layout_card.go
@@ -27,3 +27,30 @@ const (
func (layout CardLayout) IsValid() bool {
return CardLayoutList <= layout && layout <= CardLayoutCompact
}
+
+// CardSettings 描述卡片类布局(卡片、看板)共有的封面与卡片设置。
+// 各布局内嵌这份结构,持久化字段保持扁平,旧文件照常读写。
+type CardSettings struct {
+ CoverFrom CoverFrom `json:"coverFrom"` // 封面来源,0:无,1:内容图,2:资源字段
+ CoverFromAssetKeyID string `json:"coverFromAssetKeyID,omitempty"` // 资源字段 ID,CoverFrom 为 2 时有效
+ CardAspectRatio CardAspectRatio `json:"cardAspectRatio"` // 卡片宽高比
+ CardAspectRatioValue float64 `json:"cardAspectRatioValue"` // 卡片宽高比实际值,宽除以高
+ CardSize CardSize `json:"cardSize"` // 卡片大小,0:小卡片,1:中卡片,2:大卡片
+ CardWidth int `json:"cardWidth"` // 卡片宽度,单位为像素
+ CardLayout CardLayout `json:"cardLayout"` // 卡片字段布局
+ FitImage bool `json:"fitImage"` // 是否适应封面图片大小
+ DisplayFieldName bool `json:"displayFieldName"` // 是否显示字段名称
+ DisplayEmptyFields bool `json:"displayEmptyFields"` // 是否显示空字段
+}
+
+// NewCardSettings 返回卡片类布局共有的默认设置。
+func NewCardSettings() CardSettings {
+ return CardSettings{
+ CoverFrom: CoverFromContentImage,
+ CardAspectRatio: CardAspectRatio16_9,
+ CardAspectRatioValue: CardAspectRatioValueByPreset(CardAspectRatio16_9),
+ CardSize: CardSizeMedium,
+ CardWidth: CardWidthBySize(CardSizeMedium),
+ CardLayout: CardLayoutList,
+ }
+}
diff --git a/kernel/av/layout_gallery.go b/kernel/av/layout_gallery.go
index 1fa784afaa..36ca726f04 100644
--- a/kernel/av/layout_gallery.go
+++ b/kernel/av/layout_gallery.go
@@ -23,17 +23,7 @@ import (
// LayoutGallery 描述了卡片布局的结构。
type LayoutGallery struct {
*BaseLayout
-
- CoverFrom CoverFrom `json:"coverFrom"` // 封面来源,0:无,1:内容图,2:资源字段
- CoverFromAssetKeyID string `json:"coverFromAssetKeyID,omitempty"` // 资源字段 ID,CoverFrom 为 2 时有效
- CardAspectRatio CardAspectRatio `json:"cardAspectRatio"` // 卡片宽高比
- CardAspectRatioValue float64 `json:"cardAspectRatioValue"` // 卡片宽高比实际值,宽除以高
- CardSize CardSize `json:"cardSize"` // 卡片大小,0:小卡片,1:中卡片,2:大卡片
- CardWidth int `json:"cardWidth"` // 卡片宽度,单位为像素
- CardLayout CardLayout `json:"cardLayout"` // 卡片字段布局
- FitImage bool `json:"fitImage"` // 是否适应封面图片大小
- DisplayFieldName bool `json:"displayFieldName"` // 是否显示字段名称
- DisplayEmptyFields bool `json:"displayEmptyFields"` // 是否显示空字段
+ CardSettings
CardFields []*ViewGalleryCardField `json:"fields"` // 卡片字段
@@ -48,12 +38,7 @@ func NewLayoutGallery() *LayoutGallery {
ID: ast.NewNodeID(),
ShowIcon: true,
},
- CoverFrom: CoverFromContentImage,
- CardAspectRatio: CardAspectRatio16_9,
- CardAspectRatioValue: CardAspectRatioValueByPreset(CardAspectRatio16_9),
- CardSize: CardSizeMedium,
- CardWidth: CardWidthBySize(CardSizeMedium),
- CardLayout: CardLayoutList,
+ CardSettings: NewCardSettings(),
}
}
diff --git a/kernel/av/layout_kanban.go b/kernel/av/layout_kanban.go
index 9d7dfe73ce..5325883dcf 100644
--- a/kernel/av/layout_kanban.go
+++ b/kernel/av/layout_kanban.go
@@ -23,17 +23,7 @@ import (
// LayoutKanban 描述了看板视图的结构。
type LayoutKanban struct {
*BaseLayout
-
- CoverFrom CoverFrom `json:"coverFrom"` // 封面来源,0:无,1:内容图,2:资源字段
- CoverFromAssetKeyID string `json:"coverFromAssetKeyID,omitempty"` // 资源字段 ID,CoverFrom 为 2 时有效
- CardAspectRatio CardAspectRatio `json:"cardAspectRatio"` // 卡片宽高比
- CardAspectRatioValue float64 `json:"cardAspectRatioValue"` // 卡片宽高比实际值,宽除以高
- CardSize CardSize `json:"cardSize"` // 卡片大小,0:小卡片,1:中卡片,2:大卡片
- CardWidth int `json:"cardWidth"` // 卡片宽度,单位为像素
- CardLayout CardLayout `json:"cardLayout"` // 卡片字段布局
- FitImage bool `json:"fitImage"` // 是否适应封面图片大小
- DisplayFieldName bool `json:"displayFieldName"` // 是否显示字段名称
- DisplayEmptyFields bool `json:"displayEmptyFields"` // 是否显示空字段
+ CardSettings
FillColBackgroundColor bool `json:"fillColBackgroundColor"` // 是否填充列背景颜色
@@ -47,12 +37,7 @@ func NewLayoutKanban() *LayoutKanban {
ID: ast.NewNodeID(),
ShowIcon: true,
},
- CoverFrom: CoverFromContentImage,
- CardAspectRatio: CardAspectRatio16_9,
- CardAspectRatioValue: CardAspectRatioValueByPreset(CardAspectRatio16_9),
- CardSize: CardSizeMedium,
- CardWidth: CardWidthBySize(CardSizeMedium),
- CardLayout: CardLayoutList,
+ CardSettings: NewCardSettings(),
}
}
diff --git a/kernel/av/value.go b/kernel/av/value.go
index e2aaef8e1e..bd872f3e11 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -237,136 +237,42 @@ func (value *Value) IsEdited() bool {
return value.CreatedAt != value.UpdatedAt
}
-func (value *Value) IsBlank() bool {
- if nil == value {
- return true
- }
-
- switch value.Type {
- case KeyTypeBlock:
- if nil == value.Block {
- return true
- }
- return "" == strings.TrimSpace(value.Block.Content)
- case KeyTypeText:
- if nil == value.Text {
- return true
- }
- return "" == strings.TrimSpace(value.Text.Content)
- case KeyTypeNumber:
- if nil == value.Number {
- return true
- }
- return !value.Number.IsNotEmpty
- case KeyTypeDate:
- if nil == value.Date {
- return true
- }
- return !value.Date.IsNotEmpty
- case KeyTypeSelect:
- if 1 > len(value.MSelect) {
- return true
- }
- return "" == strings.TrimSpace(value.MSelect[0].Content)
- case KeyTypeMSelect:
- return 1 > len(value.MSelect)
- case KeyTypeURL:
- if nil == value.URL {
- return true
- }
- return "" == strings.TrimSpace(value.URL.Content)
- case KeyTypeEmail:
- if nil == value.Email {
- return true
- }
- return "" == strings.TrimSpace(value.Email.Content)
- case KeyTypeLocation:
- return value.Location.IsEmpty()
- case KeyTypePhone:
- if nil == value.Phone {
- return true
- }
- return "" == strings.TrimSpace(value.Phone.Content)
- case KeyTypeMAsset:
- return 1 > len(value.MAsset)
- case KeyTypeTemplate:
- if nil == value.Template {
- return true
- }
- return "" == strings.TrimSpace(value.Template.Content)
- case KeyTypeCreated:
- if nil == value.Created {
- return true
- }
- return !value.Created.IsNotEmpty
- case KeyTypeUpdated:
- if nil == value.Updated {
- return true
- }
- return !value.Updated.IsNotEmpty
- case KeyTypeCheckbox:
- if nil == value.Checkbox {
- return true
- }
- return false // 复选框不会为空
- case KeyTypeRelation:
- return 1 > len(value.Relation.Contents)
- case KeyTypeRollup:
- return 1 > len(value.Rollup.Contents)
+// isBlankContent 判断内容是否为空,trimSpace 为真时忽略首尾空白。
+func isBlankContent(content string, trimSpace bool) bool {
+ if trimSpace {
+ return "" == strings.TrimSpace(content)
}
- return false
+ return "" == content
}
-func (value *Value) IsEmpty() bool {
+// isEmpty 判断值是否为空。IsEmpty 按原始内容比较,IsBlank 额外忽略首尾空白;
+// 生成字段的模板内容始终按去空白后比较。
+func (value *Value) isEmpty(trimSpace bool) bool {
if nil == value {
return true
}
switch value.Type {
case KeyTypeBlock:
- if nil == value.Block {
- return true
- }
- return "" == value.Block.Content
+ return nil == value.Block || isBlankContent(value.Block.Content, trimSpace)
case KeyTypeText:
- if nil == value.Text {
- return true
- }
- return "" == value.Text.Content
+ return nil == value.Text || isBlankContent(value.Text.Content, trimSpace)
case KeyTypeNumber:
- if nil == value.Number {
- return true
- }
- return !value.Number.IsNotEmpty
+ return nil == value.Number || !value.Number.IsNotEmpty
case KeyTypeDate:
- if nil == value.Date {
- return true
- }
- return !value.Date.IsNotEmpty
+ return nil == value.Date || !value.Date.IsNotEmpty
case KeyTypeSelect:
- if 1 > len(value.MSelect) {
- return true
- }
- return "" == value.MSelect[0].Content
+ return 1 > len(value.MSelect) || nil == value.MSelect[0] || isBlankContent(value.MSelect[0].Content, trimSpace)
case KeyTypeMSelect:
return 1 > len(value.MSelect)
case KeyTypeURL:
- if nil == value.URL {
- return true
- }
- return "" == value.URL.Content
+ return nil == value.URL || isBlankContent(value.URL.Content, trimSpace)
case KeyTypeEmail:
- if nil == value.Email {
- return true
- }
- return "" == value.Email.Content
+ return nil == value.Email || isBlankContent(value.Email.Content, trimSpace)
case KeyTypeLocation:
return value.Location.IsEmpty()
case KeyTypePhone:
- if nil == value.Phone {
- return true
- }
- return "" == value.Phone.Content
+ return nil == value.Phone || isBlankContent(value.Phone.Content, trimSpace)
case KeyTypeMAsset:
return 1 > len(value.MAsset)
case KeyTypeTemplate:
@@ -375,28 +281,29 @@ func (value *Value) IsEmpty() bool {
}
return "" == strings.TrimSpace(value.Template.Content)
case KeyTypeCreated:
- if nil == value.Created {
- return true
- }
- return !value.Created.IsNotEmpty
+ return nil == value.Created || !value.Created.IsNotEmpty
case KeyTypeUpdated:
- if nil == value.Updated {
- return true
- }
- return !value.Updated.IsNotEmpty
+ return nil == value.Updated || !value.Updated.IsNotEmpty
case KeyTypeCheckbox:
- if nil == value.Checkbox {
- return true
- }
- return false // 复选框不会为空
+ return nil == value.Checkbox // 复选框不会为空
case KeyTypeRelation:
- return 1 > len(value.Relation.Contents)
+ return nil == value.Relation || 1 > len(value.Relation.Contents)
case KeyTypeRollup:
- return 1 > len(value.Rollup.Contents)
+ return nil == value.Rollup || 1 > len(value.Rollup.Contents)
}
return false
}
+// IsBlank 判断值是否为空,忽略内容首尾空白。
+func (value *Value) IsBlank() bool {
+ return value.isEmpty(true)
+}
+
+// IsEmpty 判断值是否为空,按原始内容比较。
+func (value *Value) IsEmpty() bool {
+ return value.isEmpty(false)
+}
+
func (value *Value) SetValByType(typ KeyType, val any) {
switch typ {
case KeyTypeBlock:
diff --git a/kernel/av/value_empty_test.go b/kernel/av/value_empty_test.go
new file mode 100644
index 0000000000..4886189985
--- /dev/null
+++ b/kernel/av/value_empty_test.go
@@ -0,0 +1,95 @@
+// SiYuan - https://github.com/siyuan-note/siyuan
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package av
+
+import "testing"
+
+// IsEmpty 与 IsBlank 共用同一套类型分派,两者的唯一差别是内容首尾空白:
+// 只有空白的值 IsBlank 视为空、IsEmpty 视为有内容;模板内容两者都按去空白后比较。
+func TestValueEmptyAndBlank(t *testing.T) {
+ tests := []struct {
+ name string
+ value *Value
+ empty bool
+ blank bool
+ }{
+ {"nil value", nil, true, true},
+
+ {"block filled", &Value{Type: KeyTypeBlock, Block: &ValueBlock{Content: "块"}}, false, false},
+ {"block blank", &Value{Type: KeyTypeBlock, Block: &ValueBlock{Content: " "}}, false, true},
+ {"block missing", &Value{Type: KeyTypeBlock}, true, true},
+
+ {"text filled", &Value{Type: KeyTypeText, Text: &ValueText{Content: "字"}}, false, false},
+ {"text blank", &Value{Type: KeyTypeText, Text: &ValueText{Content: " "}}, false, true},
+ {"text missing", &Value{Type: KeyTypeText}, true, true},
+
+ {"url blank", &Value{Type: KeyTypeURL, URL: &ValueURL{Content: " "}}, false, true},
+ {"email blank", &Value{Type: KeyTypeEmail, Email: &ValueEmail{Content: " "}}, false, true},
+ {"phone blank", &Value{Type: KeyTypePhone, Phone: &ValuePhone{Content: " "}}, false, true},
+
+ {"number empty", &Value{Type: KeyTypeNumber, Number: &ValueNumber{IsNotEmpty: false}}, true, true},
+ {"number filled", &Value{Type: KeyTypeNumber, Number: &ValueNumber{Content: 0, IsNotEmpty: true}}, false, false},
+ {"date empty", &Value{Type: KeyTypeDate, Date: &ValueDate{IsNotEmpty: false}}, true, true},
+
+ {"select missing", &Value{Type: KeyTypeSelect}, true, true},
+ {"select blank", &Value{Type: KeyTypeSelect, MSelect: []*ValueSelect{{Content: " "}}}, false, true},
+ {"select nil option", &Value{Type: KeyTypeSelect, MSelect: []*ValueSelect{nil}}, true, true},
+ {"select filled", &Value{Type: KeyTypeSelect, MSelect: []*ValueSelect{{Content: "甲"}}}, false, false},
+ {"mselect empty", &Value{Type: KeyTypeMSelect}, true, true},
+ {"mselect filled", &Value{Type: KeyTypeMSelect, MSelect: []*ValueSelect{{Content: "甲"}}}, false, false},
+
+ {"mAsset empty", &Value{Type: KeyTypeMAsset}, true, true},
+ {"mAsset filled", &Value{Type: KeyTypeMAsset, MAsset: []*ValueAsset{{Content: "a.png"}}}, false, false},
+
+ // 模板内容始终按去空白后比较,空白模板在两种判定下都是空值。
+ {"template blank", &Value{Type: KeyTypeTemplate, Template: &ValueTemplate{Content: " "}}, true, true},
+ {"template filled", &Value{Type: KeyTypeTemplate, Template: &ValueTemplate{Content: "x"}}, false, false},
+
+ {"created missing", &Value{Type: KeyTypeCreated}, true, true},
+ {"created filled", &Value{Type: KeyTypeCreated, Created: &ValueCreated{Content: 1, IsNotEmpty: true}}, false, false},
+ {"updated missing", &Value{Type: KeyTypeUpdated}, true, true},
+
+ {"checkbox missing", &Value{Type: KeyTypeCheckbox}, true, true},
+ {"checkbox unchecked", &Value{Type: KeyTypeCheckbox, Checkbox: &ValueCheckbox{}}, false, false},
+
+ {"relation missing", &Value{Type: KeyTypeRelation}, true, true},
+ {"relation empty", &Value{Type: KeyTypeRelation, Relation: &ValueRelation{}}, true, true},
+ {"rollup missing", &Value{Type: KeyTypeRollup}, true, true},
+
+ {"location missing", &Value{Type: KeyTypeLocation}, true, true},
+
+ // 未知类型既不是空值也不是空白,保留原有回退结果。
+ {"unknown", &Value{Type: KeyType("unknown")}, false, false},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if got := test.value.IsEmpty(); got != test.empty {
+ t.Fatalf("IsEmpty = %v,期望 %v", got, test.empty)
+ }
+ if got := test.value.IsBlank(); got != test.blank {
+ t.Fatalf("IsBlank = %v,期望 %v", got, test.blank)
+ }
+ })
+ }
+}
+
+// TestValueBlankKeepsEmptyContract 断言空白判定包含空值判定:
+// 空值在两种口径下都必须为空,否则过滤与排序会得到互相矛盾的结果。
+func TestValueBlankKeepsEmptyContract(t *testing.T) {
+ values := []*Value{
+ {Type: KeyTypeBlock}, {Type: KeyTypeText, Text: &ValueText{}},
+ {Type: KeyTypeNumber}, {Type: KeyTypeDate}, {Type: KeyTypeSelect},
+ {Type: KeyTypeMSelect}, {Type: KeyTypeURL}, {Type: KeyTypeEmail},
+ {Type: KeyTypePhone}, {Type: KeyTypeMAsset}, {Type: KeyTypeTemplate},
+ {Type: KeyTypeCreated}, {Type: KeyTypeUpdated}, {Type: KeyTypeCheckbox},
+ {Type: KeyTypeRelation}, {Type: KeyTypeRollup},
+ }
+ for _, value := range values {
+ if value.IsEmpty() && !value.IsBlank() {
+ t.Fatalf("类型 %s 的 IsEmpty 为真但 IsBlank 为假", value.Type)
+ }
+ }
+}
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 78021ea941..3c4b7123c9 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -1342,16 +1342,12 @@ func setAttrViewCardAspectRatio(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.CardAspectRatio = ratio
- view.Gallery.CardAspectRatioValue = av.CardAspectRatioValueByPreset(ratio)
- case av.LayoutTypeKanban:
- view.Kanban.CardAspectRatio = ratio
- view.Kanban.CardAspectRatioValue = av.CardAspectRatioValueByPreset(ratio)
}
+ cards.CardAspectRatio = ratio
+ cards.CardAspectRatioValue = av.CardAspectRatioValueByPreset(ratio)
err = av.SaveAttributeView(attrView)
return
@@ -1383,14 +1379,11 @@ func setAttrViewCardAspectRatioValue(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.CardAspectRatioValue = ratio
- case av.LayoutTypeKanban:
- view.Kanban.CardAspectRatioValue = ratio
}
+ cards.CardAspectRatioValue = ratio
err = av.SaveAttributeView(attrView)
return
@@ -1586,19 +1579,8 @@ func changeAttrViewLayout(attrView *av.AttributeView, view *av.View, newLayout a
}
view.Table = av.NewLayoutTable()
- switch oldLayout {
- case av.LayoutTypeList, av.LayoutTypeCalendar:
- for _, id := range oldFields {
- view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: id}})
- }
- case av.LayoutTypeGallery:
- for _, field := range view.Gallery.CardFields {
- view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.ID}})
- }
- case av.LayoutTypeKanban:
- for _, field := range view.Kanban.Fields {
- view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.ID}})
- }
+ for _, id := range oldFields {
+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: id}})
}
case av.LayoutTypeGallery:
if oldLayout == av.LayoutTypeList && view.Name == av.GetAttributeViewI18n("list") || view.Name == av.GetAttributeViewI18n("table") || view.Name == av.GetAttributeViewI18n("kanban") {
@@ -1610,15 +1592,8 @@ func changeAttrViewLayout(attrView *av.AttributeView, view *av.View, newLayout a
}
view.Gallery = av.NewLayoutGallery()
- switch oldLayout {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- for _, id := range oldFields {
- view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: id}})
- }
- case av.LayoutTypeKanban:
- for _, field := range view.Kanban.Fields {
- view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: field.ID}})
- }
+ for _, id := range oldFields {
+ view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: id}})
}
case av.LayoutTypeKanban:
if oldLayout == av.LayoutTypeList && view.Name == av.GetAttributeViewI18n("list") || view.Name == av.GetAttributeViewI18n("table") || view.Name == av.GetAttributeViewI18n("gallery") {
@@ -1630,15 +1605,8 @@ func changeAttrViewLayout(attrView *av.AttributeView, view *av.View, newLayout a
}
view.Kanban = av.NewLayoutKanban()
- switch oldLayout {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- for _, id := range oldFields {
- view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: id}})
- }
- case av.LayoutTypeGallery:
- for _, field := range view.Gallery.CardFields {
- view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: field.ID}})
- }
+ for _, id := range oldFields {
+ view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: id}})
}
if !view.IsGroupView() {
@@ -1711,14 +1679,11 @@ func setAttrViewShowIcon(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- view.GetTableLayout().ShowIcon = operation.Data.(bool)
- case av.LayoutTypeGallery:
- view.Gallery.ShowIcon = operation.Data.(bool)
- case av.LayoutTypeKanban:
- view.Kanban.ShowIcon = operation.Data.(bool)
+ base := view.GetBaseLayout()
+ if nil == base {
+ return
}
+ base.ShowIcon = operation.Data.(bool)
err = av.SaveAttributeView(attrView)
return
@@ -1743,14 +1708,11 @@ func setAttrViewFitImage(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.FitImage = operation.Data.(bool)
- case av.LayoutTypeKanban:
- view.Kanban.FitImage = operation.Data.(bool)
}
+ cards.FitImage = operation.Data.(bool)
err = av.SaveAttributeView(attrView)
return
@@ -1791,15 +1753,12 @@ func setAttrViewDisplayFieldName(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList:
- return
- case av.LayoutTypeCalendar:
+ if cards := view.GetCardSettings(); nil != cards {
+ cards.DisplayFieldName = operation.Data.(bool)
+ } else if av.LayoutTypeCalendar == view.LayoutType {
view.Calendar.Settings.DisplayFieldName = operation.Data.(bool)
- case av.LayoutTypeGallery:
- view.Gallery.DisplayFieldName = operation.Data.(bool)
- case av.LayoutTypeKanban:
- view.Kanban.DisplayFieldName = operation.Data.(bool)
+ } else {
+ return
}
err = av.SaveAttributeView(attrView)
@@ -1817,14 +1776,11 @@ func setAttrViewDisplayEmptyFields(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.DisplayEmptyFields = operation.Data.(bool)
- case av.LayoutTypeKanban:
- view.Kanban.DisplayEmptyFields = operation.Data.(bool)
}
+ cards.DisplayEmptyFields = operation.Data.(bool)
err = av.SaveAttributeView(attrView)
return
@@ -1841,14 +1797,10 @@ func setAttrViewFillColBackgroundColor(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- return
- case av.LayoutTypeGallery:
+ if av.LayoutTypeKanban != view.LayoutType || nil == view.Kanban {
return
- case av.LayoutTypeKanban:
- view.Kanban.FillColBackgroundColor = operation.Data.(bool)
}
+ view.Kanban.FillColBackgroundColor = operation.Data.(bool)
err = av.SaveAttributeView(attrView)
return
@@ -1882,16 +1834,12 @@ func setAttrViewCardSize(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.CardSize = size
- view.Gallery.CardWidth = av.CardWidthBySize(size)
- case av.LayoutTypeKanban:
- view.Kanban.CardSize = size
- view.Kanban.CardWidth = av.CardWidthBySize(size)
}
+ cards.CardSize = size
+ cards.CardWidth = av.CardWidthBySize(size)
err = av.SaveAttributeView(attrView)
return
@@ -1924,14 +1872,11 @@ func setAttrViewCardWidth(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.CardWidth = width
- case av.LayoutTypeKanban:
- view.Kanban.CardWidth = width
}
+ cards.CardWidth = width
err = av.SaveAttributeView(attrView)
return
@@ -1963,14 +1908,11 @@ func setAttrViewCardLayout(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeGallery:
- view.Gallery.CardLayout = layout
- case av.LayoutTypeKanban:
- view.Kanban.CardLayout = layout
- default:
+ cards := view.GetCardSettings()
+ if nil == cards {
return av.ErrWrongLayoutType
}
+ cards.CardLayout = layout
err = av.SaveAttributeView(attrView)
return
@@ -2065,14 +2007,11 @@ func setAttrViewCoverFromAssetKeyID(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.CoverFromAssetKeyID = operation.KeyID
- case av.LayoutTypeKanban:
- view.Kanban.CoverFromAssetKeyID = operation.KeyID
}
+ cards.CoverFromAssetKeyID = operation.KeyID
err = av.SaveAttributeView(attrView)
return
@@ -2097,14 +2036,11 @@ func setAttrViewCoverFrom(operation *Operation) (err error) {
return
}
- switch view.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ cards := view.GetCardSettings()
+ if nil == cards {
return
- case av.LayoutTypeGallery:
- view.Gallery.CoverFrom = av.CoverFrom(operation.Data.(float64))
- case av.LayoutTypeKanban:
- view.Kanban.CoverFrom = av.CoverFrom(operation.Data.(float64))
}
+ cards.CoverFrom = av.CoverFrom(operation.Data.(float64))
err = av.SaveAttributeView(attrView)
return
@@ -4288,15 +4224,8 @@ func setAttrViewGroupStates(view *av.View, groupStates map[string]*GroupState) {
groupView.GroupHidden = state.Hidden
groupView.GroupSort = state.Sort
if groupView.LayoutType == state.LayoutType && state.LayoutID != "" {
- switch groupView.LayoutType {
- case av.LayoutTypeTable:
- groupView.Table.ID = state.LayoutID
- case av.LayoutTypeList:
- groupView.List.ID = state.LayoutID
- case av.LayoutTypeGallery:
- groupView.Gallery.ID = state.LayoutID
- case av.LayoutTypeKanban:
- groupView.Kanban.ID = state.LayoutID
+ if layout := groupView.GetBaseLayout(); nil != layout {
+ layout.ID = state.LayoutID
}
}
@@ -4340,23 +4269,12 @@ func setAttrViewGroupStates(view *av.View, groupStates map[string]*GroupState) {
}
}
+// attrViewGroupLayoutID 返回可分组的布局 ID,日历不参与分组。
func attrViewGroupLayoutID(view *av.View) string {
switch view.LayoutType {
- case av.LayoutTypeTable:
- if view.Table != nil {
- return view.Table.ID
- }
- case av.LayoutTypeList:
- if view.List != nil {
- return view.List.ID
- }
- case av.LayoutTypeGallery:
- if view.Gallery != nil {
- return view.Gallery.ID
- }
- case av.LayoutTypeKanban:
- if view.Kanban != nil {
- return view.Kanban.ID
+ case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeGallery, av.LayoutTypeKanban:
+ if layout := view.GetBaseLayout(); nil != layout {
+ return layout.ID
}
}
return ""
@@ -5242,63 +5160,42 @@ func addAttrViewViewNamed(avID, viewID, blockID, name string, layout av.LayoutTy
layout = av.LayoutTypeTable
}
+ fieldIDs := attributeViewFieldIDs(firstView)
+ // 表格类布局之间复制字段时保留列宽和对齐,其他来源只带字段顺序。
+ var tableColumns []*av.ViewTableColumn
+ switch firstView.LayoutType {
+ case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
+ if table := firstView.GetTableLayout(); nil != table {
+ tableColumns = table.Columns
+ }
+ }
+
var view *av.View
switch layout {
case av.LayoutTypeCalendar:
view = av.NewCalendarView()
- view.Calendar = newAttributeViewCalendarLayout(attrView, attributeViewFieldIDs(firstView))
+ view.Calendar = newAttributeViewCalendarLayout(attrView, fieldIDs)
case av.LayoutTypeList:
view = av.NewListView()
- view.List = newAttributeViewListLayout(attrView, attributeViewFieldIDs(firstView))
+ view.List = newAttributeViewListLayout(attrView, fieldIDs)
case av.LayoutTypeTable:
view = av.NewTableView()
- switch firstView.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- for _, col := range firstView.GetTableLayout().Columns {
- view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{
- BaseField: &av.BaseField{ID: col.ID}, Width: col.Width, Align: col.Align,
- })
- }
- case av.LayoutTypeGallery:
- for _, field := range firstView.Gallery.CardFields {
- view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.ID}})
- }
- case av.LayoutTypeKanban:
- for _, field := range firstView.Kanban.Fields {
- view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: field.ID}})
+ for i, id := range fieldIDs {
+ column := &av.ViewTableColumn{BaseField: &av.BaseField{ID: id}}
+ if i < len(tableColumns) && nil != tableColumns[i] {
+ column.Width, column.Align = tableColumns[i].Width, tableColumns[i].Align
}
+ view.Table.Columns = append(view.Table.Columns, column)
}
case av.LayoutTypeGallery:
view = av.NewGalleryView()
- switch firstView.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- for _, col := range firstView.GetTableLayout().Columns {
- view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: col.ID}})
- }
- case av.LayoutTypeGallery:
- for _, field := range firstView.Gallery.CardFields {
- view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: field.ID}})
- }
- case av.LayoutTypeKanban:
- for _, field := range firstView.Kanban.Fields {
- view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: field.ID}})
- }
+ for _, id := range fieldIDs {
+ view.Gallery.CardFields = append(view.Gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: id}})
}
case av.LayoutTypeKanban:
view = av.NewKanbanView()
- switch firstView.LayoutType {
- case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
- for _, col := range firstView.GetTableLayout().Columns {
- view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: col.ID}})
- }
- case av.LayoutTypeGallery:
- for _, field := range firstView.Gallery.CardFields {
- view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: field.ID}})
- }
- case av.LayoutTypeKanban:
- for _, field := range firstView.Kanban.Fields {
- view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: field.ID}})
- }
+ for _, id := range fieldIDs {
+ view.Kanban.Fields = append(view.Kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: id}})
}
default:
err = av.ErrWrongLayoutType
diff --git a/kernel/model/attribute_view_field_ids_test.go b/kernel/model/attribute_view_field_ids_test.go
new file mode 100644
index 0000000000..dfa9fdf24b
--- /dev/null
+++ b/kernel/model/attribute_view_field_ids_test.go
@@ -0,0 +1,54 @@
+// SiYuan - https://github.com/siyuan-note/siyuan
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package model
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+// attributeViewFieldIDs 是切换布局和新建视图时唯一的字段顺序来源。
+// 这两种操作都改为「先取一次字段顺序,再按目标布局重新包装」,
+// 因此五种布局必须给出同一顺序,否则切换后字段会错位。
+func TestAttributeViewFieldIDsAgreesAcrossLayouts(t *testing.T) {
+ want := []string{"a", "b", "c"}
+
+ table := &av.LayoutTable{BaseLayout: &av.BaseLayout{}}
+ for _, id := range want {
+ table.Columns = append(table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: id}})
+ }
+ gallery := &av.LayoutGallery{BaseLayout: &av.BaseLayout{}}
+ for _, id := range want {
+ gallery.CardFields = append(gallery.CardFields, &av.ViewGalleryCardField{BaseField: &av.BaseField{ID: id}})
+ }
+ kanban := &av.LayoutKanban{BaseLayout: &av.BaseLayout{}}
+ for _, id := range want {
+ kanban.Fields = append(kanban.Fields, &av.ViewKanbanField{BaseField: &av.BaseField{ID: id}})
+ }
+
+ for _, test := range []struct {
+ name string
+ view *av.View
+ }{
+ {"table", &av.View{LayoutType: av.LayoutTypeTable, Table: table}},
+ {"list", &av.View{LayoutType: av.LayoutTypeList, List: table}},
+ {"calendar", &av.View{LayoutType: av.LayoutTypeCalendar, Calendar: &av.LayoutCalendar{LayoutTable: table}}},
+ {"gallery", &av.View{LayoutType: av.LayoutTypeGallery, Gallery: gallery}},
+ {"kanban", &av.View{LayoutType: av.LayoutTypeKanban, Kanban: kanban}},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ if got := attributeViewFieldIDs(test.view); !reflect.DeepEqual(got, want) {
+ t.Fatalf("字段顺序 = %v,期望 %v", got, want)
+ }
+ })
+ }
+
+ // 布局数据缺失时返回 nil,调用方据此得到空字段列表而不是崩溃。
+ if got := attributeViewFieldIDs(&av.View{LayoutType: av.LayoutTypeGallery}); 0 != len(got) {
+ t.Fatalf("缺少布局数据时应返回空列表,实际 %v", got)
+ }
+}
diff --git a/kernel/model/attribute_view_list.go b/kernel/model/attribute_view_list.go
index 967ef9b74f..c3b9c6289b 100644
--- a/kernel/model/attribute_view_list.go
+++ b/kernel/model/attribute_view_list.go
@@ -51,7 +51,7 @@ func cloneAttributeViewLayouts(target, source *av.View) (err error) {
return
}
-// attributeViewFieldIDs 按当前布局的字段顺序返回字段 ID。
+// attributeViewFieldIDs 按当前布局的字段顺序返回字段 ID,布局数据缺失时返回空列表。
func attributeViewFieldIDs(view *av.View) (ret []string) {
switch view.LayoutType {
case av.LayoutTypeTable, av.LayoutTypeList, av.LayoutTypeCalendar:
@@ -61,12 +61,16 @@ func attributeViewFieldIDs(view *av.View) (ret []string) {
}
}
case av.LayoutTypeGallery:
- for _, field := range view.Gallery.CardFields {
- ret = append(ret, field.ID)
+ if nil != view.Gallery {
+ for _, field := range view.Gallery.CardFields {
+ ret = append(ret, field.ID)
+ }
}
case av.LayoutTypeKanban:
- for _, field := range view.Kanban.Fields {
- ret = append(ret, field.ID)
+ if nil != view.Kanban {
+ for _, field := range view.Kanban.Fields {
+ ret = append(ret, field.ID)
+ }
}
}
return