urlState.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 normalizeBranchId(value) {
  39. if (typeof value !== "string") return null;
  40. const trimmed = value.trim();
  41. if (!trimmed) return null;
  42. // Keep it lenient (fail-open): uppercase for consistency.
  43. // Validation is enforced later (backend + error mapping).
  44. return trimmed.toUpperCase();
  45. }
  46. function toBranchNumber(branchId) {
  47. const m = /^NL(\d+)$/i.exec(String(branchId || "").trim());
  48. if (!m) return null;
  49. const n = Number(m[1]);
  50. return Number.isInteger(n) ? n : null;
  51. }
  52. function compareBranchIds(a, b) {
  53. const aa = String(a || "");
  54. const bb = String(b || "");
  55. const na = toBranchNumber(aa);
  56. const nb = toBranchNumber(bb);
  57. // Prefer numeric ordering for NLxx patterns when possible.
  58. if (na !== null && nb !== null) return na - nb;
  59. // Stable fallback:
  60. // - valid NL<num> come before unknown shapes
  61. // - otherwise lexicographic
  62. if (na !== null && nb === null) return -1;
  63. if (na === null && nb !== null) return 1;
  64. return aa.localeCompare(bb, "en");
  65. }
  66. function uniqueSorted(items) {
  67. const cleaned = [];
  68. for (const it of Array.isArray(items) ? items : []) {
  69. const id = normalizeBranchId(String(it));
  70. if (!id) continue;
  71. cleaned.push(id);
  72. }
  73. const unique = Array.from(new Set(cleaned));
  74. unique.sort(compareBranchIds);
  75. return unique;
  76. }
  77. /**
  78. * Parse comma-separated branches param (branches=NL01,NL02).
  79. *
  80. * @param {string|null} raw
  81. * @returns {string[]}
  82. */
  83. export function parseBranchesCsv(raw) {
  84. const s = typeof raw === "string" ? raw.trim() : "";
  85. if (!s) return [];
  86. return uniqueSorted(
  87. s
  88. .split(",")
  89. .map((x) => String(x).trim())
  90. .filter(Boolean)
  91. );
  92. }
  93. /**
  94. * Serialize branches as comma-separated string.
  95. *
  96. * @param {string[]|null|undefined} branches
  97. * @returns {string|null}
  98. */
  99. export function serializeBranchesCsv(branches) {
  100. if (!Array.isArray(branches) || branches.length === 0) return null;
  101. const cleaned = uniqueSorted(branches);
  102. return cleaned.length > 0 ? cleaned.join(",") : null;
  103. }
  104. function normalizeLimit(raw) {
  105. const s = normalizeTrimmedOrNull(raw);
  106. if (!s) return DEFAULT_SEARCH_LIMIT;
  107. if (!/^\d+$/.test(s)) return DEFAULT_SEARCH_LIMIT;
  108. const n = Number(s);
  109. if (!Number.isInteger(n)) return DEFAULT_SEARCH_LIMIT;
  110. return SEARCH_LIMITS.includes(n) ? n : DEFAULT_SEARCH_LIMIT;
  111. }
  112. /**
  113. * Parse search URL state from query params.
  114. *
  115. * Precedence:
  116. * 1) scope=all -> ALL
  117. * 2) scope=multi OR branches=... -> MULTI
  118. * 3) otherwise -> SINGLE (routeBranch is the source of truth)
  119. *
  120. * @param {URLSearchParams|Record<string, any>|any} searchParams
  121. * @param {{ routeBranch?: string|null }=} options
  122. * @returns {{
  123. * q: string|null,
  124. * scope: "single"|"multi"|"all",
  125. * branch: string|null,
  126. * branches: string[],
  127. * limit: number,
  128. * from: string|null,
  129. * to: string|null
  130. * }}
  131. */
  132. export function parseSearchUrlState(searchParams, { routeBranch = null } = {}) {
  133. const q = normalizeTrimmedOrNull(readParam(searchParams, "q"));
  134. const scopeRaw = normalizeTrimmedOrNull(readParam(searchParams, "scope"));
  135. const branchRaw = normalizeBranchId(readParam(searchParams, "branch"));
  136. const branches = parseBranchesCsv(readParam(searchParams, "branches"));
  137. const limit = normalizeLimit(readParam(searchParams, "limit"));
  138. const from = normalizeTrimmedOrNull(readParam(searchParams, "from"));
  139. const to = normalizeTrimmedOrNull(readParam(searchParams, "to"));
  140. let scope = SEARCH_SCOPE.SINGLE;
  141. if (scopeRaw === "all") {
  142. scope = SEARCH_SCOPE.ALL;
  143. } else if (scopeRaw === "multi" || branches.length > 0) {
  144. scope = SEARCH_SCOPE.MULTI;
  145. }
  146. if (scope === SEARCH_SCOPE.SINGLE) {
  147. const fallbackRouteBranch = normalizeBranchId(routeBranch);
  148. const branch = branchRaw || fallbackRouteBranch || null;
  149. return {
  150. q,
  151. scope,
  152. branch,
  153. branches: [],
  154. limit,
  155. from,
  156. to,
  157. };
  158. }
  159. if (scope === SEARCH_SCOPE.MULTI) {
  160. return {
  161. q,
  162. scope,
  163. branch: null,
  164. branches,
  165. limit,
  166. from,
  167. to,
  168. };
  169. }
  170. // ALL
  171. return {
  172. q,
  173. scope: SEARCH_SCOPE.ALL,
  174. branch: null,
  175. branches: [],
  176. limit,
  177. from,
  178. to,
  179. };
  180. }
  181. /**
  182. * Serialize search URL state into a stable query string (no leading "?").
  183. *
  184. * Stable param ordering:
  185. * - q
  186. * - scope
  187. * - branches
  188. * - limit
  189. * - from
  190. * - to
  191. *
  192. * SINGLE policy:
  193. * - We do NOT emit `branch=` because the path segment `/:branch/search` is the source of truth.
  194. *
  195. * @param {{
  196. * q?: string|null,
  197. * scope?: "single"|"multi"|"all"|string|null,
  198. * branch?: string|null,
  199. * branches?: string[]|null,
  200. * limit?: number|null,
  201. * from?: string|null,
  202. * to?: string|null
  203. * }} state
  204. * @returns {string}
  205. */
  206. export function serializeSearchUrlState(state) {
  207. const s = state || {};
  208. const params = new URLSearchParams();
  209. const q = normalizeTrimmedOrNull(s.q);
  210. const from = normalizeTrimmedOrNull(s.from);
  211. const to = normalizeTrimmedOrNull(s.to);
  212. const limit =
  213. Number.isInteger(s.limit) && SEARCH_LIMITS.includes(s.limit)
  214. ? s.limit
  215. : DEFAULT_SEARCH_LIMIT;
  216. if (q) params.set("q", q);
  217. // Scope: we only emit what the UI needs for shareability.
  218. if (s.scope === SEARCH_SCOPE.ALL) {
  219. params.set("scope", "all");
  220. } else if (s.scope === SEARCH_SCOPE.MULTI) {
  221. params.set("scope", "multi");
  222. const csv = serializeBranchesCsv(s.branches);
  223. if (csv) params.set("branches", csv);
  224. } else {
  225. // SINGLE: no `branch=` in URL (path is SoT)
  226. }
  227. // Only include non-default limit to keep URLs shorter.
  228. if (limit !== DEFAULT_SEARCH_LIMIT) {
  229. params.set("limit", String(limit));
  230. }
  231. // from/to are additive for RHL-025. We allow carrying them already.
  232. if (from) params.set("from", from);
  233. if (to) params.set("to", to);
  234. return params.toString();
  235. }