diff --git a/booklore-ui/src/app/features/book/service/sort.service.ts b/booklore-ui/src/app/features/book/service/sort.service.ts index 75e26156a..70da1c33f 100644 --- a/booklore-ui/src/app/features/book/service/sort.service.ts +++ b/booklore-ui/src/app/features/book/service/sort.service.ts @@ -7,7 +7,48 @@ import {SortDirection, SortOption} from "../model/sort.model"; }) export class SortService { - private readonly fieldExtractors: Record any> = { + private naturalCompare(a: string, b: string): number { + if (a == null && b == null) return 0; + if (a == null) return 1; + if (b == null) return -1; + + const aStr = a.toString(); + const bStr = b.toString(); + + const chunkRegex = /(\d+|\D+)/g; + + const aChunks = aStr.match(chunkRegex) || [aStr]; + const bChunks = bStr.match(chunkRegex) || [bStr]; + + const maxLength = Math.max(aChunks.length, bChunks.length); + + for (let i = 0; i < maxLength; i++) { + const aChunk = aChunks[i] || ''; + const bChunk = bChunks[i] || ''; + + if (aChunk === '' && bChunk === '') continue; + + const aIsNumeric = /^\d+$/.test(aChunk); + const bIsNumeric = /^\d+$/.test(bChunk); + + if (aIsNumeric && bIsNumeric) { + const aNum = parseInt(aChunk, 10); + const bNum = parseInt(bChunk, 10); + if (aNum !== bNum) { + return aNum - bNum; + } + } else { + const comparison = aChunk.localeCompare(bChunk); + if (comparison !== 0) { + return comparison; + } + } + } + + return aChunks.length - bChunks.length; + } + + private readonly fieldExtractors: Record unknown> = { title: (book) => (book.seriesCount ? (book.metadata?.seriesName?.toLowerCase() || null) : null) ?? (book.metadata?.title?.toLowerCase() || null), titleSeries: (book) => { @@ -20,7 +61,10 @@ export class SortService { return [title, Number.MAX_SAFE_INTEGER]; }, author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null, - publishedDate: (book) => book.metadata?.publishedDate === null ? null : new Date(book.metadata?.publishedDate!).getTime(), + publishedDate: (book) => { + const date = book.metadata?.publishedDate; + return date === null || date === undefined ? null : new Date(date).getTime(); + }, publisher: (book) => book.metadata?.publisher || null, pageCount: (book) => book.metadata?.pageCount || null, rating: (book) => book.metadata?.rating || null, @@ -60,10 +104,11 @@ export class SortService { let result: number; if (Array.isArray(aValue) && Array.isArray(bValue)) { - const nameCompare = aValue[0]?.localeCompare?.(bValue[0]) ?? 0; + // For titleSeries: [seriesName, seriesNumber] + const nameCompare = this.naturalCompare(aValue[0] || '', bValue[0] || ''); result = nameCompare !== 0 ? nameCompare : (aValue[1] - bValue[1]); } else if (typeof aValue === 'string' && typeof bValue === 'string') { - result = aValue.localeCompare(bValue); + result = this.naturalCompare(aValue, bValue); } else if (typeof aValue === 'number' && typeof bValue === 'number') { result = aValue - bValue; } else {