urlState.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. export const SEARCH_SCOPE = Object.freeze({
  2. SINGLE: "single",
  3. MULTI: "multi",
  4. ALL: "all",
  5. });
  6. // Backend constraint (app/api/search/route.js): limit must be 50..200.
  7. // We expose a strict allowed set in the UI to keep URLs predictable and avoid 400s.
  8. export const SEARCH_LIMITS = Object.freeze([50, 100, 200]);
  9. export const DEFAULT_SEARCH_LIMIT = 100;
  10. /**
  11. * Read a query parameter from either:
  12. * - URLSearchParams (client-side `useSearchParams()`)
  13. * - Next.js server `searchParams` object (plain object with string or string[])
  14. *
  15. * @param {any} searchParams
  16. * @param {string} key
  17. * @returns {string|null}
  18. */
  19. function readParam(searchParams, key) {
  20. if (!searchParams) return null;
  21. // URLSearchParams-like object: has .get()
  22. if (typeof searchParams.get === "function") {
  23. const value = searchParams.get(key);
  24. return typeof value === "string" ? value : null;
  25. }
  26. // Next.js server searchParams: plain object
  27. const raw = searchParams[key];
  28. if (Array.isArray(raw)) {
  29. return typeof raw[0] === "string" ? raw[0] : null;
  30. }
  31. return typeof raw === "string" ? raw : null;
  32. }
  33. function normalizeTrimmedOrNull(value) {
  34. if (typeof value !== "string") return null;
  35. const s = value.trim();
  36. return s ? s : null;
  37. }
  38. function uniqueStable(items) {
  39. const out = [];
  40. const seen = new Set();
  41. for (const it of items) {
  42. const s = String(it);
  43. if (!s) continue;
  44. if (seen.has(s)) continue;
  45. seen.add(s);
  46. out.push(s);
  47. }
  48. return out;
  49. }
  50. /**
  51. * Parse comma-separated branches param (branches=NL01,NL02).
  52. *
  53. * @param {string|null} raw
  54. * @returns {string[]}
  55. */
  56. export function parseBranchesCsv(raw) {
  57. const s = typeof raw === "string" ? raw.trim() : "";
  58. if (!s) return [];
  59. const parts = s
  60. .split(",")
  61. .map((x) => String(x).trim())
  62. .filter(Boolean);
  63. return uniqueStable(parts);
  64. }
  65. /**
  66. * Serialize branches as comma-separated string.
  67. *
  68. * @param {string[]|null|undefined} branches
  69. * @returns {string|null}
  70. */
  71. export function serializeBranchesCsv(branches) {
  72. if (!Array.isArray(branches) || branches.length === 0) return null;
  73. const cleaned = uniqueStable(
  74. branches.map((b) => String(b).trim()).filter(Boolean)
  75. );
  76. return cleaned.length > 0 ? cleaned.join(",") : null;
  77. }
  78. function normalizeLimit(raw) {
  79. const s = normalizeTrimmedOrNull(raw);
  80. if (!s) return DEFAULT_SEARCH_LIMIT;
  81. if (!/^\d+$/.test(s)) return DEFAULT_SEARCH_LIMIT;
  82. const n = Number(s);
  83. if (!Number.isInteger(n)) return DEFAULT_SEARCH_LIMIT;
  84. return SEARCH_LIMITS.includes(n) ? n : DEFAULT_SEARCH_LIMIT;
  85. }
  86. /**
  87. * Parse search URL state from query params.
  88. *
  89. * Precedence (robust + shareable):
  90. * 1) scope=all -> ALL
  91. * 2) scope=multi OR branches=... -> MULTI
  92. * 3) branch=... or fallback routeBranch -> SINGLE
  93. *
  94. * Notes:
  95. * - For SINGLE we default to the route branch if branch param is missing.
  96. * - For MULTI/ALL we intentionally return branch=null (UI is route-context but API scope is not single).
  97. * - limit is restricted to SEARCH_LIMITS for predictable UX and to avoid backend 400s.
  98. *
  99. * @param {URLSearchParams|Record<string, any>|any} searchParams
  100. * @param {{ routeBranch?: string|null }=} options
  101. * @returns {{
  102. * q: string|null,
  103. * scope: "single"|"multi"|"all",
  104. * branch: string|null,
  105. * branches: string[],
  106. * limit: number,
  107. * from: string|null,
  108. * to: string|null
  109. * }}
  110. */
  111. export function parseSearchUrlState(searchParams, { routeBranch = null } = {}) {
  112. const q = normalizeTrimmedOrNull(readParam(searchParams, "q"));
  113. const scopeRaw = normalizeTrimmedOrNull(readParam(searchParams, "scope"));
  114. const branchRaw = normalizeTrimmedOrNull(readParam(searchParams, "branch"));
  115. const branches = parseBranchesCsv(readParam(searchParams, "branches"));
  116. const limit = normalizeLimit(readParam(searchParams, "limit"));
  117. const from = normalizeTrimmedOrNull(readParam(searchParams, "from"));
  118. const to = normalizeTrimmedOrNull(readParam(searchParams, "to"));
  119. let scope = SEARCH_SCOPE.SINGLE;
  120. if (scopeRaw === "all") {
  121. scope = SEARCH_SCOPE.ALL;
  122. } else if (scopeRaw === "multi" || branches.length > 0) {
  123. scope = SEARCH_SCOPE.MULTI;
  124. }
  125. if (scope === SEARCH_SCOPE.SINGLE) {
  126. const fallbackRouteBranch = normalizeTrimmedOrNull(routeBranch);
  127. const branch = branchRaw || fallbackRouteBranch || null;
  128. return {
  129. q,
  130. scope,
  131. branch,
  132. branches: [],
  133. limit,
  134. from,
  135. to,
  136. };
  137. }
  138. if (scope === SEARCH_SCOPE.MULTI) {
  139. return {
  140. q,
  141. scope,
  142. branch: null,
  143. branches,
  144. limit,
  145. from,
  146. to,
  147. };
  148. }
  149. // ALL
  150. return {
  151. q,
  152. scope: SEARCH_SCOPE.ALL,
  153. branch: null,
  154. branches: [],
  155. limit,
  156. from,
  157. to,
  158. };
  159. }
  160. /**
  161. * Serialize search URL state into a stable query string (no leading "?").
  162. *
  163. * Stable param ordering:
  164. * - q
  165. * - scope
  166. * - branch
  167. * - branches
  168. * - limit
  169. * - from
  170. * - to
  171. *
  172. * @param {{
  173. * q?: string|null,
  174. * scope?: "single"|"multi"|"all"|string|null,
  175. * branch?: string|null,
  176. * branches?: string[]|null,
  177. * limit?: number|null,
  178. * from?: string|null,
  179. * to?: string|null
  180. * }} state
  181. * @returns {string}
  182. */
  183. export function serializeSearchUrlState(state) {
  184. const s = state || {};
  185. const params = new URLSearchParams();
  186. const q = normalizeTrimmedOrNull(s.q);
  187. const from = normalizeTrimmedOrNull(s.from);
  188. const to = normalizeTrimmedOrNull(s.to);
  189. const limit =
  190. Number.isInteger(s.limit) && SEARCH_LIMITS.includes(s.limit)
  191. ? s.limit
  192. : DEFAULT_SEARCH_LIMIT;
  193. if (q) params.set("q", q);
  194. // Scope: we only emit what the UI needs for shareability.
  195. if (s.scope === SEARCH_SCOPE.ALL) {
  196. params.set("scope", "all");
  197. } else if (s.scope === SEARCH_SCOPE.MULTI) {
  198. params.set("scope", "multi");
  199. const csv = serializeBranchesCsv(s.branches);
  200. if (csv) params.set("branches", csv);
  201. } else {
  202. // SINGLE
  203. const branch = normalizeTrimmedOrNull(s.branch);
  204. if (branch) params.set("branch", branch);
  205. }
  206. // Only include non-default limit to keep URLs shorter.
  207. if (limit !== DEFAULT_SEARCH_LIMIT) {
  208. params.set("limit", String(limit));
  209. }
  210. // from/to are additive for RHL-025. We allow carrying them already.
  211. if (from) params.set("from", from);
  212. if (to) params.set("to", to);
  213. return params.toString();
  214. }