resultsSorting.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. export const SEARCH_RESULTS_SORT = Object.freeze({
  2. RELEVANCE: "relevance",
  3. DATE_DESC: "date_desc",
  4. FILENAME_ASC: "filename_asc",
  5. });
  6. function pad2(value) {
  7. return String(value || "").padStart(2, "0");
  8. }
  9. /**
  10. * Build an ISO-like date key (YYYY-MM-DD) from a search item.
  11. *
  12. * Note:
  13. * - The backend guarantees year/month/day for search items.
  14. * - We still keep this defensive to avoid runtime crashes on malformed items.
  15. *
  16. * @param {any} item
  17. * @returns {string}
  18. */
  19. export function toSearchItemIsoDateKey(item) {
  20. const y = String(item?.year || "");
  21. const m = pad2(item?.month);
  22. const d = pad2(item?.day);
  23. return `${y}-${m}-${d}`;
  24. }
  25. /**
  26. * Format the search item date as German UI string: DD.MM.YYYY
  27. *
  28. * @param {any} item
  29. * @returns {string}
  30. */
  31. export function formatSearchItemDateDe(item) {
  32. const y = String(item?.year || "");
  33. const m = pad2(item?.month);
  34. const d = pad2(item?.day);
  35. return `${d}.${m}.${y}`;
  36. }
  37. /**
  38. * Sort search items according to the selected sort mode.
  39. *
  40. * Policy:
  41. * - RELEVANCE: keep backend order (we return a shallow copy to avoid accidental mutation)
  42. * - DATE_DESC: newest date first, then filename asc (stable & predictable)
  43. * - FILENAME_ASC: filename asc
  44. *
  45. * @param {any[]} items
  46. * @param {"relevance"|"date_desc"|"filename_asc"|string} sortMode
  47. * @returns {any[]}
  48. */
  49. export function sortSearchItems(items, sortMode) {
  50. const arr = Array.isArray(items) ? [...items] : [];
  51. if (sortMode === SEARCH_RESULTS_SORT.RELEVANCE) return arr;
  52. if (sortMode === SEARCH_RESULTS_SORT.DATE_DESC) {
  53. return arr.sort((a, b) => {
  54. const da = toSearchItemIsoDateKey(a);
  55. const db = toSearchItemIsoDateKey(b);
  56. if (da !== db) return da < db ? 1 : -1;
  57. const fa = String(a?.filename || "");
  58. const fb = String(b?.filename || "");
  59. return fa.localeCompare(fb, "de");
  60. });
  61. }
  62. if (sortMode === SEARCH_RESULTS_SORT.FILENAME_ASC) {
  63. return arr.sort((a, b) =>
  64. String(a?.filename || "").localeCompare(String(b?.filename || ""), "de")
  65. );
  66. }
  67. // Unknown sort mode => fail-safe to backend order.
  68. return arr;
  69. }