From d7b0ab97bcee2e0cfadadc44b4d769fc599c1b66 Mon Sep 17 00:00:00 2001 From: Riyyi Date: Tue, 26 Nov 2024 00:08:51 +0100 Subject: [PATCH] Components: Implement multiple column sorting on data-grid --- README.org | 4 ++-- src/components/Todo/Browse.vue | 28 ++++++++++++++++++++-------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/README.org b/README.org index d673b91..233f0c0 100644 --- a/README.org +++ b/README.org @@ -26,8 +26,8 @@ $ bun run dev -o # automatically open in the browser Build for production: #+BEGIN_SRC sh -$ bun nuxi build # for server-side rendering or hybrid -$ bun nuxi generate # for static site generation +$ bun run build # for server-side rendering or hybrid +$ bun run generate # for static site generation #+END_SRC Locally preview production build: diff --git a/src/components/Todo/Browse.vue b/src/components/Todo/Browse.vue index 8ec088d..d8b8fd5 100644 --- a/src/components/Todo/Browse.vue +++ b/src/components/Todo/Browse.vue @@ -2,7 +2,7 @@
+ :sortMode="'multiple'" v-model:multiSortMeta="multiSortMeta"> @@ -22,6 +22,7 @@ import { useConfirm } from "primevue/useconfirm"; import { useToast } from "primevue/usetoast"; import { useTodoStore } from "@/stores/todoStore"; +import type { DataTableSortMeta } from "primevue/datatable"; import type { Todo } from "@/schemas/todo"; const confirm = useConfirm(); @@ -29,16 +30,27 @@ const store = useTodoStore(); const toast = useToast(); // Reactive bindings for sorting -const sortField = ref(""); -const sortOrder = ref(); +const multiSortMeta = ref([]); function sortTodos(): Todo[] { let todos: Todo[] = JSON.parse(JSON.stringify(store.todos)); // deep copy - if (sortField.value) { // string or null - todos = (sortOrder.value == 1) // 1 or -1 - ? todos.sort((a, b) => a[sortField.value as keyof Todo]?.localeCompare(b[sortField.value as keyof Todo] || "") || 0) - : todos.sort((a, b) => b[sortField.value as keyof Todo]?.localeCompare(a[sortField.value as keyof Todo] || "") || 0); + // Loop in reverse order to apply the sorting correctly + for (let i = multiSortMeta.value.length - 1; i >= 0; i--) { + + const sort: DataTableSortMeta = multiSortMeta.value[i]; + const value = (item: Todo): string => { + if (typeof sort.field === "string") { + return item[sort.field as keyof Todo] || ""; + } + else if (typeof sort.field === "function") { + return sort.field(item) || ""; + } + + return ""; + }; + + todos.sort((a, b) => sort.order! * value(a).localeCompare(value(b))); } return todos; @@ -75,7 +87,7 @@ const removeTodo = (id: String) => { }; -