@garagem-ai/site-sdk 0.3.0 → 0.4.1

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,483 @@
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
+ const FEMININE_HEADING =
393
+ /(casa|cobertura|kitnet|loja|sala|fazenda|chácara|chacara)s?$/i;
394
+
395
+ function pluralizePt(label: string): string {
396
+ const text = label.trim();
397
+ if (!text || /s$/i.test(text)) return text;
398
+ if (/il$/i.test(text)) return `${text.slice(0, -1)}is`;
399
+ if (/m$/i.test(text)) return `${text.slice(0, -1)}ns`;
400
+ return `${text}s`;
401
+ }
402
+
403
+ function headingLocationSuffix(
404
+ location: SearchPathFilters["location"] | null
405
+ ): string {
406
+ if (!location) return "";
407
+ if (location.street && location.neighborhood) {
408
+ return `${location.street}, ${location.neighborhood}`;
409
+ }
410
+ if (location.neighborhood && location.city) {
411
+ return `${location.neighborhood}, ${location.city}`;
412
+ }
413
+ if (location.city && location.state) {
414
+ return `${location.city} - ${location.state}`;
415
+ }
416
+ return (
417
+ location.city ||
418
+ location.neighborhood ||
419
+ location.street ||
420
+ location.state ||
421
+ ""
422
+ );
423
+ }
424
+
425
+ /**
426
+ * SEO H1 for a search URL. Must stay stable for the same path — never
427
+ * include the hit count (Google treats a changing H1 on one URL as
428
+ * volatile). Count is rendered in a sibling `<span>`.
429
+ */
430
+ export function searchResultsHeading(
431
+ pathFilters: SearchPathFilters,
432
+ dictionary?: SearchUiDictionary | null,
433
+ locationNames?: LocationNameTables | null
434
+ ): string {
435
+ const types = ([] as string[])
436
+ .concat(pathFilters.propertyType || [])
437
+ .filter(Boolean);
438
+ let noun = "Imóveis";
439
+ let found = "encontrados";
440
+ if (types.length === 1) {
441
+ const id = String(types[0]);
442
+ const option = dictionary?.propertyTypes?.find(
443
+ (entry) => entry.id === id || entry.slug === id
444
+ );
445
+ const label = option?.label;
446
+ if (label) {
447
+ noun = pluralizePt(label.charAt(0).toUpperCase() + label.slice(1));
448
+ if (FEMININE_HEADING.test(id) || FEMININE_HEADING.test(label)) {
449
+ found = "encontradas";
450
+ }
451
+ }
452
+ }
453
+ const place = locationNames
454
+ ? headingLocationSuffix(
455
+ displayPathLocation(pathFilters.location, locationNames)
456
+ )
457
+ : "";
458
+ if (place) return `${noun} ${found} em ${place}`;
459
+ return `${noun} ${found}`;
460
+ }
461
+
462
+ /**
463
+ * Next App Router does not navigate when the href is unchanged. Canonical
464
+ * URLs omit `page=1`, so pagination must still emit `?page=1` on the link.
465
+ */
466
+ export function hrefWithExplicitPage(href: string, page: number): string {
467
+ if (page !== 1 || /(?:\?|&)page=/.test(href)) return href;
468
+ return href.includes("?") ? `${href}&page=1` : `${href}?page=1`;
469
+ }
470
+
471
+ export function paginationPages(
472
+ currentPage: number,
473
+ totalPages: number,
474
+ padding: number
475
+ ): number[] {
476
+ if (totalPages < 1) return [];
477
+ const current = Math.min(Math.max(1, currentPage), totalPages);
478
+ const start = Math.max(1, current - padding);
479
+ const end = Math.min(totalPages, current + padding);
480
+ const pages: number[] = [];
481
+ for (let i = start; i <= end; i += 1) pages.push(i);
482
+ return pages;
483
+ }