@garagem-ai/site-sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,297 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { usePathname, useRouter, useSearchParams } from "next/navigation";
5
+
6
+ import { getSearchUi, queryListings } from "../fetchers";
7
+ import { coerceSiteId, normalizeBaseUrl } from "../internal/url";
8
+ import {
9
+ applyPathFilter,
10
+ buildQueryListingsParams,
11
+ canonicalizeSearchHref,
12
+ clearStagedPathFilters,
13
+ hrefForAppliedChange,
14
+ hrefForPathFilters,
15
+ readPublicSearch,
16
+ type LocationNameTables,
17
+ } from "../search-engine";
18
+ import type { SearchPathFilters, SearchUi } from "../types";
19
+ import type {
20
+ PublicSearchState,
21
+ SiteIdInput,
22
+ UsePublicSearchOptions,
23
+ } from "./types";
24
+
25
+ async function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {
26
+ const value = typeof siteId === "function" ? siteId() : siteId;
27
+ return coerceSiteId(value);
28
+ }
29
+
30
+ function currentHref(pathname: string, search: string): string {
31
+ return search ? `${pathname}?${search}` : pathname;
32
+ }
33
+
34
+ export function usePublicSearch(
35
+ options: UsePublicSearchOptions
36
+ ): PublicSearchState {
37
+ const { siteId, baseUrl } = options;
38
+ const router = useRouter();
39
+ const pathname = usePathname() || "/imoveis";
40
+ const searchParams = useSearchParams();
41
+ const search = searchParams.toString();
42
+
43
+ const siteIdRef = useRef(siteId);
44
+ siteIdRef.current = siteId;
45
+ const siteIdToken = typeof siteId === "string" ? siteId : null;
46
+
47
+ const [catalogId, setCatalogId] = useState<string | null>(null);
48
+ const [schema, setSchema] = useState<SearchUi | null>(null);
49
+ const [listings, setListings] = useState<PublicSearchState["listings"]>([]);
50
+ const [page, setPage] = useState(1);
51
+ const [total, setTotal] = useState(0);
52
+ const [totalPages, setTotalPages] = useState(1);
53
+ const [loading, setLoading] = useState(true);
54
+ const [qDraft, setQDraft] = useState("");
55
+ const [staged, setStaged] = useState<SearchPathFilters>({});
56
+
57
+ const parsed = useMemo(
58
+ () => readPublicSearch(pathname, search, schema?.dictionary),
59
+ [pathname, search, schema?.dictionary]
60
+ );
61
+
62
+ useEffect(() => {
63
+ setQDraft(parsed.applied.query || "");
64
+ }, [parsed.applied.query]);
65
+
66
+ const resetStagedFromUrl = useCallback(() => {
67
+ setStaged({ ...parsed.pathFilters });
68
+ }, [parsed.pathFilters]);
69
+
70
+ useEffect(() => {
71
+ setStaged({ ...parsed.pathFilters });
72
+ }, [parsed.pathFilters]);
73
+
74
+ const locationsRef = useRef<LocationNameTables | null>(null);
75
+
76
+ useEffect(() => {
77
+ if (!schema) return;
78
+ const canonical = canonicalizeSearchHref(
79
+ pathname,
80
+ search,
81
+ schema.dictionary
82
+ );
83
+ if (canonical) router.replace(canonical);
84
+ }, [pathname, search, schema, router]);
85
+
86
+ useEffect(() => {
87
+ let active = true;
88
+ setCatalogId(null);
89
+ setSchema(null);
90
+ setListings([]);
91
+ setLoading(true);
92
+ resolveSiteIdInput(siteIdRef.current)
93
+ .then((id) => {
94
+ if (active) setCatalogId(id);
95
+ })
96
+ .catch(() => {
97
+ if (active) setLoading(false);
98
+ });
99
+ return () => {
100
+ active = false;
101
+ };
102
+ }, [baseUrl, siteIdToken]);
103
+
104
+ useEffect(() => {
105
+ if (!catalogId) return;
106
+ const id = catalogId;
107
+ let active = true;
108
+ locationsRef.current = null;
109
+ setSchema(null);
110
+ setListings([]);
111
+ setLoading(true);
112
+ async function loadSchema() {
113
+ try {
114
+ const nextSchema = await getSearchUi({ siteId: id, baseUrl });
115
+ if (!active) return;
116
+ let locations: LocationNameTables | null = null;
117
+ if (nextSchema.locationsPath.startsWith("/")) {
118
+ try {
119
+ const response = await fetch(
120
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
121
+ );
122
+ if (response.ok) {
123
+ locations = (await response.json()) as LocationNameTables;
124
+ }
125
+ } catch {
126
+ locations = null;
127
+ }
128
+ }
129
+ if (!active) return;
130
+ locationsRef.current = locations;
131
+ setSchema(nextSchema);
132
+ } catch {
133
+ if (active) {
134
+ locationsRef.current = null;
135
+ setSchema(null);
136
+ setLoading(false);
137
+ }
138
+ }
139
+ }
140
+ loadSchema();
141
+ return () => {
142
+ active = false;
143
+ };
144
+ }, [baseUrl, catalogId]);
145
+
146
+ useEffect(() => {
147
+ if (!schema || !catalogId) return;
148
+ const currentSchema = schema;
149
+ const id = catalogId;
150
+ let active = true;
151
+ async function loadListings() {
152
+ setLoading(true);
153
+ try {
154
+ const { pathFilters, applied } = readPublicSearch(
155
+ pathname,
156
+ search,
157
+ currentSchema.dictionary
158
+ );
159
+ const response = await queryListings({
160
+ siteId: id,
161
+ baseUrl,
162
+ params: buildQueryListingsParams(
163
+ pathFilters,
164
+ applied,
165
+ currentSchema,
166
+ locationsRef.current
167
+ ),
168
+ });
169
+ if (!active) return;
170
+ setListings(response.listings || []);
171
+ setPage(response.page || 1);
172
+ setTotal(response.total || 0);
173
+ setTotalPages(response.totalPages || 1);
174
+ } catch {
175
+ if (active) {
176
+ setListings([]);
177
+ setPage(1);
178
+ setTotal(0);
179
+ setTotalPages(1);
180
+ }
181
+ } finally {
182
+ if (active) setLoading(false);
183
+ }
184
+ }
185
+ loadListings();
186
+ return () => {
187
+ active = false;
188
+ };
189
+ }, [pathname, search, baseUrl, schema, catalogId]);
190
+
191
+ const go = useCallback(
192
+ (href: string) => {
193
+ if (href && href !== currentHref(pathname, search)) router.push(href);
194
+ },
195
+ [pathname, search, router]
196
+ );
197
+
198
+ const applyFilter = useCallback(
199
+ (filterId: string, value: unknown) => {
200
+ if (!schema) return;
201
+ go(
202
+ hrefForPathFilters(
203
+ pathname,
204
+ search,
205
+ schema.dictionary,
206
+ applyPathFilter(parsed.pathFilters, filterId, value)
207
+ )
208
+ );
209
+ },
210
+ [go, pathname, search, schema, parsed.pathFilters]
211
+ );
212
+
213
+ const stageFilter = useCallback((filterId: string, value: unknown) => {
214
+ setStaged((current) => applyPathFilter(current, filterId, value));
215
+ }, []);
216
+
217
+ const applyStaged = useCallback(() => {
218
+ if (!schema) return;
219
+ go(hrefForPathFilters(pathname, search, schema.dictionary, staged));
220
+ }, [go, pathname, search, schema, staged]);
221
+
222
+ const clearStaged = useCallback(() => {
223
+ setStaged((current) => clearStagedPathFilters(current));
224
+ }, []);
225
+
226
+ const submitQuery = useCallback(() => {
227
+ if (!schema) return;
228
+ go(
229
+ hrefForAppliedChange(pathname, search, schema.dictionary, {
230
+ type: "query",
231
+ query: qDraft,
232
+ })
233
+ );
234
+ }, [go, pathname, search, schema, qDraft]);
235
+
236
+ const clearQuery = useCallback(() => {
237
+ setQDraft("");
238
+ if (!schema) return;
239
+ go(
240
+ hrefForAppliedChange(pathname, search, schema.dictionary, {
241
+ type: "query",
242
+ query: "",
243
+ })
244
+ );
245
+ }, [go, pathname, search, schema]);
246
+
247
+ const setSort = useCallback(
248
+ (sort: string | null) => {
249
+ if (!schema) return;
250
+ go(
251
+ hrefForAppliedChange(pathname, search, schema.dictionary, {
252
+ type: "sort",
253
+ sort,
254
+ })
255
+ );
256
+ },
257
+ [go, pathname, search, schema]
258
+ );
259
+
260
+ const hrefForPage = useCallback(
261
+ (nextPage: number) => {
262
+ if (!schema) return pathname;
263
+ return hrefForAppliedChange(pathname, search, schema.dictionary, {
264
+ type: "page",
265
+ page: nextPage,
266
+ });
267
+ },
268
+ [pathname, search, schema]
269
+ );
270
+
271
+ return {
272
+ schema,
273
+ listings,
274
+ page,
275
+ total,
276
+ totalPages,
277
+ loading,
278
+ pathname,
279
+ search,
280
+ pathFilters: parsed.pathFilters,
281
+ applied: parsed.applied,
282
+ qDraft,
283
+ setQDraft,
284
+ staged,
285
+ setStaged,
286
+ resetStagedFromUrl,
287
+ applyFilter,
288
+ stageFilter,
289
+ applyStaged,
290
+ clearStaged,
291
+ submitQuery,
292
+ clearQuery,
293
+ setSort,
294
+ hrefForPage,
295
+ go,
296
+ };
297
+ }
@@ -0,0 +1,404 @@
1
+ import {
2
+ composeSearchPublicHref,
3
+ parseAppliedSearchQuery,
4
+ reduceAppliedSearchQuery,
5
+ } from "./applied-query";
6
+ import { pathLocationToFilterInput } from "./loc-params";
7
+ import {
8
+ composeSearchPublicPath,
9
+ parseSearchPublicPath,
10
+ pathFiltersToQueryFilters,
11
+ } from "./path";
12
+ import { parseGroupedInteger } from "./presentation";
13
+ import type {
14
+ AppliedSearchChange,
15
+ AppliedSearchQuery,
16
+ QueryListingsParams,
17
+ SearchPathFilters,
18
+ SearchUi,
19
+ SearchUiDictionary,
20
+ SearchUiFilter,
21
+ SearchUiOption,
22
+ } from "./types";
23
+
24
+ const PATH_FILTER_IDS: Record<string, keyof SearchPathFilters> = {
25
+ listing_type: "listingType",
26
+ property_type: "propertyType",
27
+ property_bedrooms: "bedrooms",
28
+ property_bathrooms: "bathrooms",
29
+ property_suites: "suites",
30
+ property_parking_spots: "parkingSpots",
31
+ price: "price",
32
+ property_area_total: "area",
33
+ propertyFeatures: "propertyFeatures",
34
+ buildingAmenities: "buildingAmenities",
35
+ };
36
+
37
+ /** Query keys that must never encode filters (Editor/Studio path contract). */
38
+ export const FORBIDDEN_SEARCH_QUERY_KEYS = [
39
+ "tipo",
40
+ "quartos",
41
+ "tipo-imovel",
42
+ "banheiros",
43
+ "vagas",
44
+ ] as const;
45
+
46
+ /** Default option: omit `ordenar` (API has no relevance token). */
47
+ export const SEARCH_SORT_RELEVANCE = {
48
+ id: "",
49
+ label: "Mais relevantes",
50
+ } as const;
51
+
52
+ export function searchSortOptions(
53
+ sorts: Array<{ id: string; label: string }> | undefined
54
+ ): Array<{ id: string; label: string }> {
55
+ const fromApi = (sorts || []).filter((sort) => sort.id);
56
+ return [
57
+ { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },
58
+ ...fromApi,
59
+ ];
60
+ }
61
+
62
+ /** Toolbar: price + bedrooms first and required when the schema has them. */
63
+ export const TOOLBAR_PRIMARY_FILTER_IDS = [
64
+ "price",
65
+ "property_bedrooms",
66
+ ] as const;
67
+
68
+ const HIDDEN_FILTER_IDS = new Set(["property_suites"]);
69
+
70
+ function toFiniteNumber(value: unknown): number | undefined {
71
+ if (value === "" || value == null) return undefined;
72
+ const n = Number(value);
73
+ return Number.isFinite(n) ? n : undefined;
74
+ }
75
+
76
+ function pathnameOnly(pathname: string): string {
77
+ return String(pathname || "").split(/[?#]/)[0] || "/";
78
+ }
79
+
80
+ export function isListingDetailPath(pathname: string): boolean {
81
+ const parts = pathnameOnly(pathname).split("/").filter(Boolean);
82
+ const last = parts[parts.length - 1] || "";
83
+ return last.toLowerCase().startsWith("id-");
84
+ }
85
+
86
+ export function readPublicSearch(
87
+ pathname: string,
88
+ search: string,
89
+ dictionary?: SearchUiDictionary
90
+ ): { pathFilters: SearchPathFilters; applied: AppliedSearchQuery } {
91
+ const pathFilters =
92
+ parseSearchPublicPath(pathnameOnly(pathname), dictionary) || {};
93
+ const applied = parseAppliedSearchQuery(search || "");
94
+ return { pathFilters, applied };
95
+ }
96
+
97
+ function lookupDisplay(
98
+ table: Record<string, string> | undefined,
99
+ slug: string | undefined
100
+ ): string | undefined {
101
+ if (!slug || !table) return slug;
102
+ return table[slug] || table[String(slug).toLowerCase()] || slug;
103
+ }
104
+
105
+ export type LocationNameTables = {
106
+ states?: Record<string, string>;
107
+ cities?: Record<string, string>;
108
+ neighborhoods?: Record<string, string>;
109
+ streets?: Record<string, string>;
110
+ };
111
+
112
+ export function displayPathLocation(
113
+ location: SearchPathFilters["location"],
114
+ values?: LocationNameTables | null
115
+ ): SearchPathFilters["location"] | null {
116
+ if (!location) return null;
117
+ const table = values || {};
118
+ return {
119
+ state: lookupDisplay(table.states, location.state),
120
+ city: lookupDisplay(table.cities, location.city),
121
+ neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),
122
+ street: lookupDisplay(table.streets, location.street),
123
+ };
124
+ }
125
+
126
+ export function buildQueryListingsParams(
127
+ pathFilters: SearchPathFilters,
128
+ applied: AppliedSearchQuery,
129
+ schema: Pick<SearchUi, "defaultLimit"> | { defaultLimit?: number } | null,
130
+ locationValues?: LocationNameTables | null
131
+ ): QueryListingsParams {
132
+ const filters = pathFiltersToQueryFilters(pathFilters || {});
133
+ const locations: Array<{ type: string; value: string }> = [];
134
+ const displayed = displayPathLocation(pathFilters?.location, locationValues);
135
+ const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;
136
+ if (pathLoc) locations.push(pathLoc);
137
+ for (const value of applied?.loc || []) {
138
+ locations.push({ type: "loc", value });
139
+ }
140
+ const params: QueryListingsParams = {
141
+ page: applied?.page || 1,
142
+ limit: schema?.defaultLimit || 12,
143
+ filters,
144
+ };
145
+ if (applied?.sort) params.sort = applied.sort;
146
+ const hasLocation = locations.length > 0;
147
+ if (applied?.query && !hasLocation) params.q = applied.query;
148
+ if (hasLocation) params.location = locations;
149
+ return params;
150
+ }
151
+
152
+ export function applyPathFilter(
153
+ pathFilters: SearchPathFilters,
154
+ filterId: string,
155
+ value: unknown
156
+ ): SearchPathFilters {
157
+ const next: SearchPathFilters = { ...(pathFilters || {}) };
158
+ const key = PATH_FILTER_IDS[filterId];
159
+ if (!key) return next;
160
+ if (value === "" || value == null) {
161
+ delete next[key];
162
+ return next;
163
+ }
164
+ if (key === "price" || key === "area") {
165
+ const range = (value || {}) as { min?: unknown; max?: unknown };
166
+ const parse = key === "price" ? parseGroupedInteger : toFiniteNumber;
167
+ const min = parse(range.min);
168
+ const max = parse(range.max);
169
+ if (min == null && max == null) {
170
+ delete next[key];
171
+ return next;
172
+ }
173
+ next[key] = {
174
+ ...(min != null ? { min } : {}),
175
+ ...(max != null ? { max } : {}),
176
+ };
177
+ return next;
178
+ }
179
+ if (key === "propertyFeatures" || key === "buildingAmenities") {
180
+ const current = Array.isArray(next[key]) ? [...next[key]] : [];
181
+ const id = String(value);
182
+ const i = current.indexOf(id);
183
+ if (i >= 0) current.splice(i, 1);
184
+ else current.push(id);
185
+ if (current.length) next[key] = current;
186
+ else delete next[key];
187
+ return next;
188
+ }
189
+ if (key === "propertyType") {
190
+ const id = String(value);
191
+ const current = Array.isArray(next.propertyType)
192
+ ? [...next.propertyType]
193
+ : next.propertyType
194
+ ? [String(next.propertyType)]
195
+ : [];
196
+ const i = current.indexOf(id);
197
+ if (i >= 0) current.splice(i, 1);
198
+ else current.push(id);
199
+ if (current.length === 0) delete next.propertyType;
200
+ else if (current.length === 1) next.propertyType = current[0];
201
+ else next.propertyType = current;
202
+ return next;
203
+ }
204
+ if (key === "listingType") {
205
+ const id = String(value);
206
+ if (next.listingType === id) delete next.listingType;
207
+ else next.listingType = id;
208
+ return next;
209
+ }
210
+ if (
211
+ key === "bedrooms" ||
212
+ key === "bathrooms" ||
213
+ key === "suites" ||
214
+ key === "parkingSpots"
215
+ ) {
216
+ const n = Number(value);
217
+ if (!Number.isFinite(n)) {
218
+ delete next[key];
219
+ return next;
220
+ }
221
+ if (next[key] === n) delete next[key];
222
+ else next[key] = n;
223
+ return next;
224
+ }
225
+ return next;
226
+ }
227
+
228
+ export function pathFilterValue(
229
+ pathFilters: SearchPathFilters | undefined,
230
+ filterId: string
231
+ ): string {
232
+ const key = PATH_FILTER_IDS[filterId];
233
+ const value = pathFilters && key ? pathFilters[key] : undefined;
234
+ if (value == null) return "";
235
+ if (Array.isArray(value)) return value[0] != null ? String(value[0]) : "";
236
+ if (typeof value === "object") return "";
237
+ return String(value);
238
+ }
239
+
240
+ export function pathFilterHasOption(
241
+ pathFilters: SearchPathFilters | undefined,
242
+ filterId: string,
243
+ optionId: string
244
+ ): boolean {
245
+ const key = PATH_FILTER_IDS[filterId];
246
+ const value = pathFilters && key ? pathFilters[key] : undefined;
247
+ if (value == null) return false;
248
+ if (Array.isArray(value)) return value.map(String).includes(optionId);
249
+ if (typeof value === "object") return false;
250
+ return String(value) === optionId;
251
+ }
252
+
253
+ export function publicSearchHref(
254
+ pathFilters: SearchPathFilters,
255
+ applied: AppliedSearchQuery,
256
+ dictionary?: SearchUiDictionary,
257
+ existingSearch?: string
258
+ ): string {
259
+ const pathname = composeSearchPublicPath(pathFilters || {}, dictionary);
260
+ return composeSearchPublicHref(pathname, applied || {}, existingSearch);
261
+ }
262
+
263
+ export function hrefForPathFilters(
264
+ pathname: string,
265
+ search: string,
266
+ dictionary: SearchUiDictionary | undefined,
267
+ nextPathFilters: SearchPathFilters
268
+ ): string {
269
+ const { applied } = readPublicSearch(pathname, search, dictionary);
270
+ const nextApplied = reduceAppliedSearchQuery(applied, {
271
+ type: "applyFilters",
272
+ });
273
+ return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);
274
+ }
275
+
276
+ export function hrefForAppliedChange(
277
+ pathname: string,
278
+ search: string,
279
+ dictionary: SearchUiDictionary | undefined,
280
+ change: AppliedSearchChange
281
+ ): string {
282
+ const { pathFilters, applied } = readPublicSearch(
283
+ pathname,
284
+ search,
285
+ dictionary
286
+ );
287
+ let nextPath = pathFilters;
288
+ if (change && change.type === "query") {
289
+ nextPath = { ...pathFilters };
290
+ delete nextPath.location;
291
+ }
292
+ const nextApplied = reduceAppliedSearchQuery(applied, change);
293
+ return publicSearchHref(nextPath, nextApplied, dictionary, search);
294
+ }
295
+
296
+ function currentSearchHref(pathname: string, search: string): string {
297
+ const path = pathnameOnly(pathname);
298
+ const qs = search.replace(/^\?/, "");
299
+ return qs ? `${path}?${qs}` : path;
300
+ }
301
+
302
+ /** Canonical href if the current URL is out of generation order; otherwise null. */
303
+ export function canonicalizeSearchHref(
304
+ pathname: string,
305
+ search: string,
306
+ dictionary?: SearchUiDictionary
307
+ ): string | null {
308
+ const { pathFilters, applied } = readPublicSearch(
309
+ pathname,
310
+ search,
311
+ dictionary
312
+ );
313
+ const href = publicSearchHref(pathFilters, applied, dictionary, search);
314
+ if (href === currentSearchHref(pathname, search)) return null;
315
+ return href;
316
+ }
317
+
318
+ export function searchHrefUsesLegacyFilterQuery(href: string): boolean {
319
+ const query = href.split("?")[1] || "";
320
+ const params = new URLSearchParams(query);
321
+ return FORBIDDEN_SEARCH_QUERY_KEYS.some((key) => params.has(key));
322
+ }
323
+
324
+ /**
325
+ * Drop staged filters. Location always stays until apply.
326
+ * `keepFilterIds` keeps toolbar-primary filters (price, bedrooms) so Limpar
327
+ * in the extra-filters dialog does not wipe values already on the toolbar.
328
+ */
329
+ export function clearStagedPathFilters(
330
+ current: SearchPathFilters,
331
+ keepFilterIds: readonly string[] = []
332
+ ): SearchPathFilters {
333
+ const next: SearchPathFilters = current.location
334
+ ? { location: current.location }
335
+ : {};
336
+ for (const id of keepFilterIds) {
337
+ const key = PATH_FILTER_IDS[id];
338
+ if (!key || key === "location") continue;
339
+ const value = current[key];
340
+ if (value != null) Object.assign(next, { [key]: value });
341
+ }
342
+ return next;
343
+ }
344
+
345
+ export function visibleSearchFilters(
346
+ schema: SearchUi | null
347
+ ): SearchUiFilter[] {
348
+ if (!schema?.filters) return [];
349
+ return schema.filters.filter((filter) => {
350
+ if (HIDDEN_FILTER_IDS.has(filter.id)) return false;
351
+ if (filter.id === "listing_type" && (filter.options?.length ?? 0) <= 1) {
352
+ return false;
353
+ }
354
+ return true;
355
+ });
356
+ }
357
+
358
+ export function toolbarFilterIds(schema: SearchUi | null): string[] {
359
+ const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));
360
+ return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));
361
+ }
362
+
363
+ export function countOptionLabel(
364
+ option: Pick<SearchUiOption, "label">
365
+ ): string {
366
+ const label = String(option?.label ?? "");
367
+ if (/^[1-9]\d*$/.test(label)) return `${label}+`;
368
+ return label;
369
+ }
370
+
371
+ export function countFacetChoices(
372
+ options: SearchUiOption[] | undefined
373
+ ): Array<{ id: string; label: string }> {
374
+ const list = options || [];
375
+ const zero = list.find((o) => o.id === "0" || o.label === "Studio");
376
+ const isStudio = Boolean(
377
+ zero && /studio/i.test(String(zero.label)) && zero.id === "0"
378
+ );
379
+ const max = isStudio ? 3 : 4;
380
+ const out: Array<{ id: string; label: string }> = [];
381
+ if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });
382
+ for (let n = 1; n <= max; n += 1) {
383
+ const option = list.find((o) => o.id === String(n));
384
+ out.push({
385
+ id: String(n),
386
+ label: countOptionLabel(option || { label: String(n) }),
387
+ });
388
+ }
389
+ return out;
390
+ }
391
+
392
+ export function paginationPages(
393
+ currentPage: number,
394
+ totalPages: number,
395
+ padding: number
396
+ ): number[] {
397
+ if (totalPages < 1) return [];
398
+ const current = Math.min(Math.max(1, currentPage), totalPages);
399
+ const start = Math.max(1, current - padding);
400
+ const end = Math.min(totalPages, current + padding);
401
+ const pages: number[] = [];
402
+ for (let i = start; i <= end; i += 1) pages.push(i);
403
+ return pages;
404
+ }