The minimalistic document archiving platform.
feat(documents): add sorting to documents list (#1090)
Corentin Thomasset5ea8ca3e8720
diff --git a/.changeset/mean-garlics-lick.md b/.changeset/mean-garlics-lick.mdnew file mode 100644index 00000000..7bf1382d--- /dev/null+++ b/.changeset/mean-garlics-lick.md@@ -0,0 +1,5 @@+---+"@papra/app": patch+---++Added sorting option in the documents list, allowing to sort documents by name, or creation date, in ascending or descending order.diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.tsindex eaaefbb6..bde12cf3 100644--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts@@ -261,6 +261,8 @@ const inMemoryApiMock: Record<string, { handler: any }> = {pageIndex = 0,pageSize = 5,searchQuery: rawSearchQuery = '',+ sortField = 'createdAt',+ sortOrder = 'desc',} = query ?? {};const organization = await organizationStorage.getItem(organizationId);@@ -294,8 +296,32 @@ const inMemoryApiMock: Record<string, { handler: any }> = {const filteredDocuments = searchDemoDocuments({ query: searchQuery, documents: documentsWithTagsAndProperties as unknown as Document[] });+ const getSortValue = (document: Document) => {+ if (sortField === 'name') {+ return document.name?.toLowerCase() ?? '';+ }+ if (sortField === 'documentDate') {+ return document.documentDate ? new Date(document.documentDate).getTime() : 0;+ }+ if (sortField === 'updatedAt') {+ return document.updatedAt ? new Date(document.updatedAt).getTime() : 0;+ }+ return document.createdAt ? new Date(document.createdAt).getTime() : 0;+ };++ const sortDirection = sortOrder === 'asc' ? 1 : -1;const paginatedDocuments = filteredDocuments- .toSorted((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())+ .toSorted((a, b) => {+ const av = getSortValue(a);+ const bv = getSortValue(b);+ if (av < bv) {+ return -1 * sortDirection;+ }+ if (av > bv) {+ return 1 * sortDirection;+ }+ return 0;+ }).slice(pageIndex * pageSize, (pageIndex + 1) * pageSize);return {diff --git a/apps/papra-client/src/modules/documents/components/documents-list.component.tsx b/apps/papra-client/src/modules/documents/components/documents-list.component.tsxindex 379821b3..e3752b74 100644--- a/apps/papra-client/src/modules/documents/components/documents-list.component.tsx+++ b/apps/papra-client/src/modules/documents/components/documents-list.component.tsx@@ -1,4 +1,4 @@-import type { ColumnDef, RowSelectionState } from '@tanstack/solid-table';+import type { ColumnDef, RowSelectionState, SortingState } from '@tanstack/solid-table';import type { Accessor, Component, Setter } from 'solid-js';import type { Document } from '../documents.types';import type { Pagination } from '@/modules/shared/pagination/pagination.types';@@ -54,6 +54,7 @@ export const createdAtColumn: ColumnDef<Document> = {return <span class="hidden sm:block">{t('documents.list.table.headers.created')}</span>;},accessorKey: 'createdAt',+ enableSorting: true,cell: data => <RelativeTime class="text-muted-foreground hidden sm:block" date={data.getValue<Date>()} />,};@@ -72,6 +73,7 @@ export const standardActionsColumn: ColumnDef<Document> = {return <span class="block text-right">{t('documents.list.table.headers.actions')}</span>;},id: 'actions',+ enableSorting: false,cell: data => (<div class="flex items-center justify-end"><DocumentManagementDropdown document={data.row.original} />@@ -85,6 +87,7 @@ export const tagsColumn: ColumnDef<Document> = {return <span class="hidden sm:block">{t('documents.list.table.headers.tags')}</span>;},accessorKey: 'tags',+ enableSorting: false,cell: data => (<DocumentTagsListtags={data.getValue<Tag[]>()}@@ -107,6 +110,8 @@ export const DocumentsPaginatedList: Component<{enableBatchSelection?: boolean;getRowSelection?: Accessor<RowSelectionState>;setRowSelection?: Setter<RowSelectionState>;+ getSorting?: Accessor<SortingState>;+ setSorting?: Setter<SortingState>;}> = (props) => {const { t } = useI18n();const table = createSolidTable({@@ -118,7 +123,9 @@ export const DocumentsPaginatedList: Component<{...(props.enableBatchSelection ? [selectionColumn] : []),{header: () => t('documents.list.table.headers.file-name'),- id: 'fileName',+ id: 'name',+ accessorFn: row => row.name,+ enableSorting: true,cell: data => (<div class="overflow-hidden flex gap-4 items-center max-w-500px"><div class="bg-muted flex items-center justify-center p-2 rounded-lg">@@ -161,7 +168,9 @@ export const DocumentsPaginatedList: Component<{getPaginationRowModel: getPaginationRowModel(),onPaginationChange: props.setPagination,onRowSelectionChange: props.setRowSelection,+ onSortingChange: props.setSorting,enableRowSelection: props.enableBatchSelection ?? false,+ enableSorting: Boolean(props.setSorting),state: {get pagination() {return props.getPagination?.();@@ -169,8 +178,12 @@ export const DocumentsPaginatedList: Component<{get rowSelection() {return props.getRowSelection?.() ?? {};},+ get sorting() {+ return props.getSorting?.() ?? [];+ },},manualPagination: true,+ manualSorting: true,});return (@@ -186,12 +199,31 @@ export const DocumentsPaginatedList: Component<{{(header) => {return (<TableHead>- {header.isPlaceholder- ? null- : flexRender(- header.column.columnDef.header,- header.getContext(),- )}+ <Show+ when={!header.isPlaceholder}+ >+ <Show+ when={header.column.getCanSort()}+ fallback={flexRender(header.column.columnDef.header, header.getContext())}+ >+ <button+ type="button"+ class="flex items-center gap-1 cursor-pointer select-none"+ onClick={header.column.getToggleSortingHandler()}+ >+ {flexRender(header.column.columnDef.header, header.getContext())}+ <Show when={header.column.getIsSorted() === 'asc'}>+ <div class="i-tabler-arrow-up size-3.5" />+ </Show>+ <Show when={header.column.getIsSorted() === 'desc'}>+ <div class="i-tabler-arrow-down size-3.5" />+ </Show>+ <Show when={!header.column.getIsSorted()}>+ <div class="i-tabler-arrows-sort size-3.5 opacity-40" />+ </Show>+ </button>+ </Show>+ </Show></TableHead>);}}diff --git a/apps/papra-client/src/modules/documents/documents.constants.ts b/apps/papra-client/src/modules/documents/documents.constants.tsindex a7b57020..397d8608 100644--- a/apps/papra-client/src/modules/documents/documents.constants.ts+++ b/apps/papra-client/src/modules/documents/documents.constants.ts@@ -12,3 +12,12 @@ export const DOCUMENT_ACTIVITY_EVENT_LIST = Object.values(DOCUMENT_ACTIVITY_EVENexport const MAX_CONCURRENT_DOCUMENT_UPLOADS = 3;export const DEFAULT_DOCUMENT_ICON = 'i-tabler-file';++export const DOCUMENT_SEARCH_SORT_FIELDS = ['createdAt', 'updatedAt', 'name', 'documentDate'] as const;+export type DocumentSearchSortField = (typeof DOCUMENT_SEARCH_SORT_FIELDS)[number];++export const DOCUMENT_SEARCH_SORT_ORDERS = ['asc', 'desc'] as const;+export type DocumentSearchSortOrder = (typeof DOCUMENT_SEARCH_SORT_ORDERS)[number];++export const DEFAULT_DOCUMENT_SEARCH_SORT_FIELD: DocumentSearchSortField = 'createdAt';+export const DEFAULT_DOCUMENT_SEARCH_SORT_ORDER: DocumentSearchSortOrder = 'desc';diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.tsindex 1685160e..0b8ab996 100644--- a/apps/papra-client/src/modules/documents/documents.services.ts+++ b/apps/papra-client/src/modules/documents/documents.services.ts@@ -1,4 +1,5 @@import type { AsDto } from '../shared/http/http-client.types';+import type { DocumentSearchSortField, DocumentSearchSortOrder } from './documents.constants';import type { Document, DocumentActivity } from './documents.types';import { apiClient } from '../shared/http/api-client';import { coerceDates, getFormData } from '../shared/http/http-client.models';@@ -26,11 +27,15 @@ export async function fetchOrganizationDocuments({pageIndex,pageSize,searchQuery,+ sortField,+ sortOrder,}: {organizationId: string;pageIndex: number;pageSize: number;searchQuery?: string;+ sortField?: DocumentSearchSortField;+ sortOrder?: DocumentSearchSortOrder;}) {const {documents,@@ -45,6 +50,8 @@ export async function fetchOrganizationDocuments({searchQuery,pageIndex,pageSize,+ sortField,+ sortOrder,},});diff --git a/apps/papra-client/src/modules/documents/pages/documents.page.tsx b/apps/papra-client/src/modules/documents/pages/documents.page.tsxindex 2b7707f7..3e86763f 100644--- a/apps/papra-client/src/modules/documents/pages/documents.page.tsx+++ b/apps/papra-client/src/modules/documents/pages/documents.page.tsx@@ -1,6 +1,7 @@-import type { RowSelectionState } from '@tanstack/solid-table';-import type { Component } from 'solid-js';+import type { RowSelectionState, SortingState } from '@tanstack/solid-table';+import type { Component, Setter } from 'solid-js';import type { BatchTargetFilter } from '../documents-batch.services';+import type { DocumentSearchSortField, DocumentSearchSortOrder } from '../documents.constants';import { useParams } from '@solidjs/router';import { keepPreviousData, useMutation, useQuery } from '@tanstack/solid-query';import { createEffect, createMemo, createSignal, on, Show, Suspense } from 'solid-js';@@ -9,6 +10,7 @@ import { useConfirmModal } from '@/modules/shared/confirm';import { createParamSynchronizedPagination } from '@/modules/shared/pagination/query-synchronized-pagination';import { queryClient } from '@/modules/shared/query/query-client';import { createParamSynchronizedSignal } from '@/modules/shared/signals/params';+import { resolveSetterValue } from '@/modules/shared/signals/setters';import { cn } from '@/modules/shared/style/cn';import { useDebounce } from '@/modules/shared/utils/timing';import { Button } from '@/modules/ui/components/button';@@ -18,6 +20,12 @@ import { DocumentUploadArea } from '../components/document-upload-area.componentimport { DocumentsBatchTagDialog } from '../components/documents-batch-tag-dialog.component';import { createdAtColumn, DocumentsPaginatedList, standardActionsColumn, tagsColumn } from '../components/documents-list.component';import { batchTrashDocuments, batchUpdateDocumentTags } from '../documents-batch.services';+import {+ DEFAULT_DOCUMENT_SEARCH_SORT_FIELD,+ DEFAULT_DOCUMENT_SEARCH_SORT_ORDER,+ DOCUMENT_SEARCH_SORT_FIELDS,+ DOCUMENT_SEARCH_SORT_ORDERS,+} from '../documents.constants';import { fetchOrganizationDocuments } from '../documents.services';export const DocumentsPage: Component = () => {@@ -31,11 +39,39 @@ export const DocumentsPage: Component = () => {const [getSelectAllMatchingQuery, setSelectAllMatchingQuery] = createSignal(false);const [getTagDialogOpen, setTagDialogOpen] = createSignal(false);+ const [getSortField, setSortField] = createParamSynchronizedSignal<DocumentSearchSortField>({+ paramKey: 'sortField',+ defaultValue: DEFAULT_DOCUMENT_SEARCH_SORT_FIELD,+ deserialize: value => (DOCUMENT_SEARCH_SORT_FIELDS.includes(value as DocumentSearchSortField) ? (value as DocumentSearchSortField) : DEFAULT_DOCUMENT_SEARCH_SORT_FIELD),+ });+ const [getSortOrder, setSortOrder] = createParamSynchronizedSignal<DocumentSearchSortOrder>({+ paramKey: 'sortOrder',+ defaultValue: DEFAULT_DOCUMENT_SEARCH_SORT_ORDER,+ deserialize: value => (DOCUMENT_SEARCH_SORT_ORDERS.includes(value as DocumentSearchSortOrder) ? (value as DocumentSearchSortOrder) : DEFAULT_DOCUMENT_SEARCH_SORT_ORDER),+ });++ const getSorting = (): SortingState => [{ id: getSortField(), desc: getSortOrder() === 'desc' }];++ const setSorting: Setter<SortingState> = (valueOrUpdater) => {+ const next = resolveSetterValue(valueOrUpdater, getSorting());+ const first = next[0];+ if (!first) {+ setSortField(DEFAULT_DOCUMENT_SEARCH_SORT_FIELD);+ setSortOrder(DEFAULT_DOCUMENT_SEARCH_SORT_ORDER);+ return next;+ }+ setSortField(first.id as DocumentSearchSortField);+ setSortOrder(first.desc ? 'desc' : 'asc');+ return next;+ };+const documentsQuery = useQuery(() => ({- queryKey: ['organizations', params.organizationId, 'documents', getPagination(), debouncedSearchQuery()],+ queryKey: ['organizations', params.organizationId, 'documents', getPagination(), debouncedSearchQuery(), getSortField(), getSortOrder()],queryFn: () => fetchOrganizationDocuments({organizationId: params.organizationId,searchQuery: debouncedSearchQuery(),+ sortField: getSortField(),+ sortOrder: getSortOrder(),...getPagination(),}),placeholderData: keepPreviousData,@@ -324,6 +360,8 @@ export const DocumentsPage: Component = () => {enableBatchSelectiongetRowSelection={getRowSelection}setRowSelection={setRowSelection}+ getSorting={getSorting}+ setSorting={setSorting}extraColumns={[tagsColumn,createdAtColumn,