Skip to content

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

:sparkles: Support sorting database date fields by start or end date https://github.com/siyuan-note/siyuan/issues/15681

Daniel4425d10619aa
diff --git a/app/src/protyle/render/av/sort.ts b/app/src/protyle/render/av/sort.ts
index 6f20680328..1f89bcb4b1 100644
--- a/app/src/protyle/render/av/sort.ts
+++ b/app/src/protyle/render/av/sort.ts
@@ -68,20 +68,32 @@ export const addSort = (options: {
};
export const bindSortsEvent = (protyle: IProtyle, menuElement: HTMLElement, data: IAV, blockID: string) => {
+ const fields = getFieldsByData(data);
menuElement.querySelectorAll("select").forEach((item: HTMLSelectElement) => {
item.addEventListener("change", () => {
const colId = item.parentElement.getAttribute("data-id");
const oldSort = JSON.parse(JSON.stringify(data.view.sorts));
- if (item.previousElementSibling.classList.contains("b3-menu__icon")) {
- data.view.sorts.find((sort: IAVSort) => {
- if (sort.column === colId) {
- sort.column = item.value;
- item.parentElement.setAttribute("data-id", item.value);
- return true;
- }
- });
- } else {
- data.view.sorts.find((sort: IAVSort) => sort.column === colId).order = item.value as "ASC" | "DESC";
+ const sort = data.view.sorts.find((sort: IAVSort) => sort.column === colId);
+ if (!sort) {
+ return;
+ }
+ let reRender = false;
+ if (item.dataset.type === "sortColumn") {
+ const oldColumn = fields.find((column) => column.id === sort.column);
+ const newColumn = fields.find((column) => column.id === item.value);
+ sort.column = item.value;
+ if (oldColumn?.type !== "date" || newColumn?.type !== "date") {
+ delete sort.dateEndpoint;
+ }
+ reRender = true;
+ } else if (item.dataset.type === "sortDateEndpoint") {
+ if (item.value === "end") {
+ sort.dateEndpoint = "end";
+ } else {
+ delete sort.dateEndpoint;
+ }
+ } else if (item.dataset.type === "sortOrder") {
+ sort.order = item.value as "ASC" | "DESC";
}
transaction(protyle, [{
action: "setAttrViewSorts",
@@ -94,6 +106,10 @@ export const bindSortsEvent = (protyle: IProtyle, menuElement: HTMLElement, data
data: oldSort,
blockID
}]);
+ if (reRender) {
+ menuElement.innerHTML = getSortsHTML(fields, data.view.sorts);
+ bindSortsEvent(protyle, menuElement, data, blockID);
+ }
});
});
};
@@ -108,13 +124,20 @@ export const getSortsHTML = (columns: IAVColumn[], sorts: IAVSort[]) => {
return sortHTML;
};
sorts.forEach((item: IAVSort) => {
+ const column = columns.find((column) => column.id === item.column);
+ const dateEndpointHTML = column?.type === "date" ? `
+ <span class="fn__space"></span>
+ <select class="b3-select" data-type="sortDateEndpoint" style="margin: 4px 0">
+ <option value="start" ${item.dateEndpoint !== "end" ? "selected" : ""}>${window.siyuan.languages.startDate}</option>
+ <option value="end" ${item.dateEndpoint === "end" ? "selected" : ""}>${window.siyuan.languages.endDate}</option>
+ </select>` : "";
html += `<button draggable="true" class="b3-menu__item" data-id="${item.column}">
<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
- <select class="b3-select fn__flex-1" style="margin: 4px 0">
+ <select class="b3-select fn__flex-1" data-type="sortColumn" style="margin: 4px 0">
${genSortItem(item.column)}
- </select>
+ </select>${dateEndpointHTML}
<span class="fn__space"></span>
- <select class="b3-select" style="margin: 4px 0">
+ <select class="b3-select" data-type="sortOrder" style="margin: 4px 0">
<option value="ASC" ${item.order === "ASC" ? "selected" : ""}>${window.siyuan.languages.asc}</option>
<option value="DESC" ${item.order === "DESC" ? "selected" : ""}>${window.siyuan.languages.desc}</option>
</select>
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index b37a204f90..2dd6866503 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -1144,7 +1144,8 @@ interface IAVGroup {
interface IAVSort {
column: string,
- order: "ASC" | "DESC"
+ order: "ASC" | "DESC",
+ dateEndpoint?: "start" | "end"
}
interface IAVColumn {
diff --git a/kernel/av/sort.go b/kernel/av/sort.go
index 2c83741185..55aa7b9f55 100644
--- a/kernel/av/sort.go
+++ b/kernel/av/sort.go
@@ -27,8 +27,9 @@ import (
// ViewSort 描述了视图排序规则的结构。
type ViewSort struct {
- Column string `json:"column"` // 字段(列)ID
- Order SortOrder `json:"order"` // 排序顺序
+ Column string `json:"column"` // 字段(列)ID
+ Order SortOrder `json:"order"` // 排序顺序
+ DateEndpoint DateEndpoint `json:"dateEndpoint,omitempty"` // 日期端点
}
type SortOrder string
@@ -46,8 +47,9 @@ func Sort(viewable Viewable, attrView *AttributeView) {
}
type FieldIndexSort struct {
- Index int
- Order SortOrder
+ Index int
+ Order SortOrder
+ DateEndpoint DateEndpoint
}
var fieldIndexSorts []*FieldIndexSort
@@ -55,7 +57,11 @@ func Sort(viewable Viewable, attrView *AttributeView) {
for _, s := range sorts {
for i, c := range fields {
if c.GetID() == s.Column {
- fieldIndexSorts = append(fieldIndexSorts, &FieldIndexSort{Index: i, Order: s.Order})
+ fieldIndexSorts = append(fieldIndexSorts, &FieldIndexSort{
+ Index: i,
+ Order: s.Order,
+ DateEndpoint: s.DateEndpoint,
+ })
break
}
}
@@ -128,19 +134,19 @@ func Sort(viewable Viewable, attrView *AttributeView) {
for _, fieldIndexSort := range fieldIndexSorts {
val1 := editedItems[i].GetValues()[fieldIndexSort.Index]
val2 := editedItems[j].GetValues()[fieldIndexSort.Index]
- if nil == val1 || val1.IsEmpty() {
- if nil != val2 && !val2.IsEmpty() {
+ if isSortValueEmpty(val1, fieldIndexSort.DateEndpoint) {
+ if !isSortValueEmpty(val2, fieldIndexSort.DateEndpoint) {
return false
}
sorted = false
continue
} else {
- if nil == val2 || val2.IsEmpty() {
+ if isSortValueEmpty(val2, fieldIndexSort.DateEndpoint) {
return true
}
}
- result := val1.Compare(val2, optionSortByIndex[fieldIndexSort.Index])
+ result := val1.compare(val2, optionSortByIndex[fieldIndexSort.Index], fieldIndexSort.DateEndpoint)
if 0 == result {
sorted = false
continue
@@ -178,7 +184,22 @@ func Sort(viewable Viewable, attrView *AttributeView) {
}
}
+func isSortValueEmpty(value *Value, dateEndpoint DateEndpoint) bool {
+ if nil == value {
+ return true
+ }
+ if KeyTypeDate == value.Type {
+ _, isNotEmpty := value.Date.GetByEndpoint(dateEndpoint)
+ return !isNotEmpty
+ }
+ return value.IsEmpty()
+}
+
func (value *Value) Compare(other *Value, optionSort map[string]int) int {
+ return value.compare(other, optionSort, DateEndpointStart)
+}
+
+func (value *Value) compare(other *Value, optionSort map[string]int, dateEndpoint DateEndpoint) int {
switch value.Type {
case KeyTypeBlock:
if nil != value.Block && nil != other.Block {
@@ -234,14 +255,13 @@ func (value *Value) Compare(other *Value, optionSort map[string]int) int {
}
case KeyTypeDate:
if nil != value.Date && nil != other.Date {
- if value.Date.IsNotEmpty {
- if !other.Date.IsNotEmpty {
+ valueContent, valueIsNotEmpty := value.Date.GetByEndpoint(dateEndpoint)
+ otherContent, otherIsNotEmpty := other.Date.GetByEndpoint(dateEndpoint)
+ if valueIsNotEmpty {
+ if !otherIsNotEmpty {
return -1
}
- valueContent := value.Date.Content
- otherContent := other.Date.Content
-
if value.Date.IsNotTime {
v := time.UnixMilli(valueContent)
valueContent = time.Date(v.Year(), v.Month(), v.Day(), 0, 0, 0, 0, time.Local).UnixMilli()
@@ -260,7 +280,7 @@ func (value *Value) Compare(other *Value, optionSort map[string]int) int {
return 0
}
- if !other.Date.IsNotEmpty {
+ if !otherIsNotEmpty {
return 1
}
return 0
diff --git a/kernel/av/sort_test.go b/kernel/av/sort_test.go
new file mode 100644
index 0000000000..63c720e7d1
--- /dev/null
+++ b/kernel/av/sort_test.go
@@ -0,0 +1,174 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package av
+
+import (
+ "slices"
+ "testing"
+ "time"
+)
+
+type dateSortTestValue struct {
+ start int64
+ end int64
+ hasEndDate bool
+ isNotTime bool
+ endNotEmpty bool
+}
+
+func TestDateEndpointSort(t *testing.T) {
+ values := map[string]dateSortTestValue{
+ "a": {start: 100, end: 400, hasEndDate: true, endNotEmpty: true},
+ "b": {start: 200, end: 300, hasEndDate: true, endNotEmpty: true},
+ }
+ tests := []struct {
+ name string
+ dateEndpoint DateEndpoint
+ want []string
+ }{
+ {name: "default start endpoint", want: []string{"a", "b"}},
+ {name: "explicit start endpoint", dateEndpoint: DateEndpointStart, want: []string{"a", "b"}},
+ {name: "end endpoint", dateEndpoint: DateEndpointEnd, want: []string{"b", "a"}},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ table := newDateSortTestTable(values, SortOrderAsc, test.dateEndpoint)
+ Sort(table, &AttributeView{})
+ assertDateSortRowIDs(t, table, test.want)
+ })
+ }
+}
+
+func TestDateEndpointSortFallbackAndEmpty(t *testing.T) {
+ t.Run("fallback to start endpoint", func(t *testing.T) {
+ table := newDateSortTestTable(map[string]dateSortTestValue{
+ "a": {start: 100},
+ "b": {start: 200, end: 50, hasEndDate: true, endNotEmpty: true},
+ }, SortOrderAsc, DateEndpointEnd)
+ Sort(table, &AttributeView{})
+ assertDateSortRowIDs(t, table, []string{"b", "a"})
+ })
+
+ for _, order := range []SortOrder{SortOrderAsc, SortOrderDesc} {
+ t.Run("empty end endpoint "+string(order), func(t *testing.T) {
+ table := newDateSortTestTable(map[string]dateSortTestValue{
+ "a": {start: 100, hasEndDate: true},
+ "b": {start: 200, end: 50, hasEndDate: true, endNotEmpty: true},
+ }, order, DateEndpointEnd)
+ Sort(table, &AttributeView{})
+ assertDateSortRowIDs(t, table, []string{"b", "a"})
+ })
+ }
+}
+
+func TestDateEndpointSortWithoutTime(t *testing.T) {
+ start := time.Date(2026, 7, 27, 0, 0, 0, 0, time.Local).UnixMilli()
+ table := newDateSortTestTable(map[string]dateSortTestValue{
+ "a": {
+ start: start,
+ end: time.Date(2026, 7, 28, 23, 0, 0, 0, time.Local).UnixMilli(),
+ hasEndDate: true,
+ isNotTime: true,
+ endNotEmpty: true,
+ },
+ "b": {
+ start: start,
+ end: time.Date(2026, 7, 28, 1, 0, 0, 0, time.Local).UnixMilli(),
+ hasEndDate: true,
+ isNotTime: true,
+ endNotEmpty: true,
+ },
+ }, SortOrderAsc, DateEndpointEnd)
+
+ Sort(table, &AttributeView{})
+ assertDateSortRowIDs(t, table, []string{"a", "b"})
+}
+
+func newDateSortTestTable(values map[string]dateSortTestValue, order SortOrder, dateEndpoint DateEndpoint) *Table {
+ const (
+ blockColumnID = "block"
+ dateColumnID = "date"
+ )
+ rows := make([]*TableRow, 0, len(values))
+ for _, id := range []string{"a", "b"} {
+ value := values[id]
+ createdAt := int64(1)
+ if "b" == id {
+ createdAt = 2
+ }
+ rows = append(rows, &TableRow{
+ ID: id,
+ Cells: []*TableCell{
+ {
+ BaseValue: &BaseValue{
+ ValueType: KeyTypeBlock,
+ Value: &Value{
+ Type: KeyTypeBlock,
+ CreatedAt: createdAt,
+ Block: &ValueBlock{Content: id},
+ },
+ },
+ },
+ {
+ BaseValue: &BaseValue{
+ ValueType: KeyTypeDate,
+ Value: &Value{
+ Type: KeyTypeDate,
+ CreatedAt: 1709740800000,
+ Date: &ValueDate{
+ Content: value.start,
+ IsNotEmpty: true,
+ Content2: value.end,
+ IsNotEmpty2: value.endNotEmpty,
+ HasEndDate: value.hasEndDate,
+ IsNotTime: value.isNotTime,
+ },
+ },
+ },
+ },
+ },
+ })
+ }
+
+ return &Table{
+ BaseInstance: &BaseInstance{
+ ID: "table",
+ Sorts: []*ViewSort{{
+ Column: dateColumnID,
+ Order: order,
+ DateEndpoint: dateEndpoint,
+ }},
+ },
+ Columns: []*TableColumn{
+ {BaseInstanceField: &BaseInstanceField{ID: blockColumnID, Type: KeyTypeBlock}},
+ {BaseInstanceField: &BaseInstanceField{ID: dateColumnID, Type: KeyTypeDate}},
+ },
+ Rows: rows,
+ }
+}
+
+func assertDateSortRowIDs(t *testing.T, table *Table, want []string) {
+ t.Helper()
+ got := make([]string, 0, len(table.Rows))
+ for _, row := range table.Rows {
+ got = append(got, row.ID)
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("unexpected row order: got %v, want %v", got, want)
+ }
+}
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 991dd2cf9a..3777a72b6e 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -4024,8 +4024,9 @@ func (tx *Transaction) doDuplicateAttrViewView(operation *Operation) (ret *TxErr
for _, s := range masterView.Sorts {
view.Sorts = append(view.Sorts, &av.ViewSort{
- Column: s.Column,
- Order: s.Order,
+ Column: s.Column,
+ Order: s.Order,
+ DateEndpoint: s.DateEndpoint,
})
}