@garagem-ai/site-sdk 0.10.0 → 0.11.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.
- package/README.md +7 -7
- package/dist/index.d.mts +17 -7
- package/dist/index.d.ts +17 -7
- package/dist/index.js +76 -60
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +75 -60
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +58 -54
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +58 -54
- package/dist/react.mjs.map +1 -1
- package/dist/{types-photo-search-DIoV75SN.d.mts → types-photo-search-Bmf1f1-Y.d.mts} +455 -419
- package/dist/{types-photo-search-DIoV75SN.d.ts → types-photo-search-Bmf1f1-Y.d.ts} +455 -419
- package/package.json +3 -3
- package/src/index.ts +2 -0
- package/src/listing-detail.ts +1 -0
- package/src/map-search.ts +89 -60
- package/src/react/use-map-search.ts +6 -2
- package/src/search-engine.ts +5 -0
- package/src/studio-contract.ts +21 -8
- package/src/types-maps.ts +17 -1
- package/src/types-market.ts +4 -0
- package/src/types.ts +10 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@garagem-ai/site-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Typed, runtime-agnostic SDK for building custom real estate sites against the Garagem platform. Drop into any Next.js (or other JS) project to fetch listings, sites and CMS data.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"dev": "tsup --watch",
|
|
49
49
|
"test": "vitest run",
|
|
50
50
|
"test:watch": "vitest",
|
|
51
|
-
"typecheck": "tsgo --noEmit",
|
|
51
|
+
"typecheck": "bash ../../scripts/checks/run-tsgo.sh --noEmit",
|
|
52
52
|
"lint": "eslint ."
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"@types/react": "19.1.4",
|
|
59
59
|
"eslint": "^9.0.0",
|
|
60
60
|
"jsdom": "^26.1.0",
|
|
61
|
-
"next": "16.4.
|
|
61
|
+
"next": "16.4.2",
|
|
62
62
|
"react": "19.2.1",
|
|
63
63
|
"react-dom": "19.2.1",
|
|
64
64
|
"tsup": "^8.0.1",
|
package/src/index.ts
CHANGED
|
@@ -342,6 +342,7 @@ export {
|
|
|
342
342
|
MAP_VIEWPORT_DEBOUNCE_MS,
|
|
343
343
|
capMapPage,
|
|
344
344
|
capMapPageSize,
|
|
345
|
+
clusterBuckets,
|
|
345
346
|
clusterPins,
|
|
346
347
|
isMapBounds,
|
|
347
348
|
isMapPolygon,
|
|
@@ -384,6 +385,7 @@ export type {
|
|
|
384
385
|
TravelTimeOptions,
|
|
385
386
|
TravelTimesOptions,
|
|
386
387
|
MapBounds,
|
|
388
|
+
MapBucket,
|
|
387
389
|
MapPin,
|
|
388
390
|
MapPinCluster,
|
|
389
391
|
MapPolygon,
|
package/src/listing-detail.ts
CHANGED
|
@@ -104,6 +104,7 @@ function overlayKind(
|
|
|
104
104
|
src: string
|
|
105
105
|
): "video" | "tour" | null {
|
|
106
106
|
if (type === "image" || type === "photo") return null;
|
|
107
|
+
if (/\.(mp4|webm|ogg|mov)(\?|#|$)/i.test(src)) return "video";
|
|
107
108
|
const host = new URL(src).hostname.toLowerCase();
|
|
108
109
|
if (
|
|
109
110
|
type === "tour" ||
|
package/src/map-search.ts
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Pins copy `listing.location.coordinates` as the API returned them.
|
|
10
10
|
* Those values are already masked. Nothing here adds precision.
|
|
11
|
+
*
|
|
12
|
+
* When the matches do not fit on page 1, the route also returns weighted
|
|
13
|
+
* location buckets. Cluster those instead of the page's pins, so the
|
|
14
|
+
* badges add up to `total` rather than to one page.
|
|
11
15
|
*/
|
|
12
16
|
|
|
13
17
|
import { queryListings, type FetchLike } from "./fetchers";
|
|
@@ -24,10 +28,12 @@ import type {
|
|
|
24
28
|
Listing,
|
|
25
29
|
QueryListingsFilters,
|
|
26
30
|
QueryListingsParams,
|
|
31
|
+
QueryListingsResult,
|
|
27
32
|
RequestNextOptions,
|
|
28
33
|
} from "./types";
|
|
29
34
|
import type {
|
|
30
35
|
MapBounds,
|
|
36
|
+
MapBucket,
|
|
31
37
|
MapPin,
|
|
32
38
|
MapPinCluster,
|
|
33
39
|
MapPolygon,
|
|
@@ -80,6 +86,8 @@ export interface MapSearchResult {
|
|
|
80
86
|
pageSize: number;
|
|
81
87
|
total: number;
|
|
82
88
|
totalPages: number;
|
|
89
|
+
/** Empty when page 1 holds every match. */
|
|
90
|
+
buckets: MapBucket[];
|
|
83
91
|
}
|
|
84
92
|
|
|
85
93
|
export type MapSearchListenerEvent =
|
|
@@ -171,6 +179,7 @@ export function emptyMapSearchResult(
|
|
|
171
179
|
pageSize,
|
|
172
180
|
total: 0,
|
|
173
181
|
totalPages: 0,
|
|
182
|
+
buckets: [],
|
|
174
183
|
};
|
|
175
184
|
}
|
|
176
185
|
|
|
@@ -193,18 +202,19 @@ export function mapSearchPins(listings: readonly Listing[]): MapPin[] {
|
|
|
193
202
|
}
|
|
194
203
|
|
|
195
204
|
function listingsResult(
|
|
196
|
-
|
|
197
|
-
meta: { page?: number; limit?: number; total?: number; totalPages?: number },
|
|
205
|
+
result: Partial<QueryListingsResult>,
|
|
198
206
|
requestedPageSize: number
|
|
199
207
|
): MapSearchResult {
|
|
208
|
+
const listings = result.listings ?? [];
|
|
200
209
|
return {
|
|
201
210
|
pins: mapSearchPins(listings),
|
|
202
211
|
cards: listings.map((listing) => toListingCardModel(listing)),
|
|
203
212
|
listings,
|
|
204
|
-
page:
|
|
205
|
-
pageSize:
|
|
206
|
-
total:
|
|
207
|
-
totalPages:
|
|
213
|
+
page: result.page ?? 1,
|
|
214
|
+
pageSize: result.limit ?? requestedPageSize,
|
|
215
|
+
total: result.total ?? listings.length,
|
|
216
|
+
totalPages: result.totalPages ?? 0,
|
|
217
|
+
buckets: result.buckets ?? [],
|
|
208
218
|
};
|
|
209
219
|
}
|
|
210
220
|
|
|
@@ -215,6 +225,7 @@ function searchParams(
|
|
|
215
225
|
const params: QueryListingsParams = {
|
|
216
226
|
page: capMapPage(options.page),
|
|
217
227
|
limit: capMapPageSize(options.pageSize),
|
|
228
|
+
buckets: true,
|
|
218
229
|
};
|
|
219
230
|
if (options.q !== undefined) params.q = options.q;
|
|
220
231
|
if (options.sort !== undefined) params.sort = options.sort;
|
|
@@ -240,7 +251,7 @@ async function runMapSearch(
|
|
|
240
251
|
publishableKey: options.publishableKey,
|
|
241
252
|
next: options.next,
|
|
242
253
|
});
|
|
243
|
-
return listingsResult(result
|
|
254
|
+
return listingsResult(result, pageSize);
|
|
244
255
|
}
|
|
245
256
|
|
|
246
257
|
export async function searchListingsInBounds(
|
|
@@ -277,9 +288,12 @@ export function mapClusterCellDegrees(zoom: number): number {
|
|
|
277
288
|
return 360 / 2 ** clampZoom(zoom) / 4;
|
|
278
289
|
}
|
|
279
290
|
|
|
280
|
-
|
|
291
|
+
type GridPoint = { id: string; lat: number; lng: number };
|
|
292
|
+
|
|
293
|
+
function usablePoint(point: GridPoint): boolean {
|
|
281
294
|
return (
|
|
282
|
-
finitePair(
|
|
295
|
+
finitePair(point.lat, point.lng) !== null &&
|
|
296
|
+
!(point.lat === 0 && point.lng === 0)
|
|
283
297
|
);
|
|
284
298
|
}
|
|
285
299
|
|
|
@@ -287,73 +301,88 @@ function usablePin(pin: MapPin): boolean {
|
|
|
287
301
|
* The finest precision any member shows. A masked `-23.600` prints as
|
|
288
302
|
* `-23.6`, so the coarsest member would round the centroid kilometres away.
|
|
289
303
|
*/
|
|
290
|
-
function groupPrecision(group: readonly
|
|
304
|
+
function groupPrecision(group: readonly GridPoint[]): number {
|
|
291
305
|
let max = 0;
|
|
292
|
-
for (const
|
|
306
|
+
for (const point of group) {
|
|
293
307
|
max = Math.max(
|
|
294
308
|
max,
|
|
295
|
-
coordinateDecimals(
|
|
296
|
-
coordinateDecimals(
|
|
309
|
+
coordinateDecimals(point.lat),
|
|
310
|
+
coordinateDecimals(point.lng)
|
|
297
311
|
);
|
|
298
312
|
}
|
|
299
313
|
return max;
|
|
300
314
|
}
|
|
301
315
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
316
|
+
/**
|
|
317
|
+
* Grid cells at this zoom. A cell with one member keeps that member's id
|
|
318
|
+
* and coordinates. A larger cell is centred on the weighted centroid,
|
|
319
|
+
* rounded to the members' own precision so clustering cannot invent
|
|
320
|
+
* decimals.
|
|
321
|
+
*/
|
|
322
|
+
function gridCells<T extends GridPoint>(
|
|
323
|
+
points: readonly T[],
|
|
324
|
+
zoom: number,
|
|
325
|
+
weight: (point: T) => number
|
|
326
|
+
): Array<MapPinCluster & { members: T[] }> {
|
|
327
|
+
const cell = mapClusterCellDegrees(zoom);
|
|
328
|
+
const groups = new Map<string, T[]>();
|
|
329
|
+
for (const point of points) {
|
|
330
|
+
if (!usablePoint(point)) continue;
|
|
331
|
+
const key = `${Math.floor(point.lat / cell)}:${Math.floor(point.lng / cell)}`;
|
|
332
|
+
const list = groups.get(key);
|
|
333
|
+
if (list) list.push(point);
|
|
334
|
+
else groups.set(key, [point]);
|
|
335
|
+
}
|
|
336
|
+
return [...groups]
|
|
337
|
+
.map(([key, members]) => {
|
|
338
|
+
const count = members.reduce((sum, point) => sum + weight(point), 0);
|
|
339
|
+
const only = members.length === 1 ? members[0] : undefined;
|
|
340
|
+
const center =
|
|
341
|
+
only ??
|
|
342
|
+
coarsenCoordinates(
|
|
343
|
+
{
|
|
344
|
+
lat: members.reduce((sum, p) => sum + p.lat * weight(p), 0) / count,
|
|
345
|
+
lng: members.reduce((sum, p) => sum + p.lng * weight(p), 0) / count,
|
|
346
|
+
},
|
|
347
|
+
groupPrecision(members)
|
|
348
|
+
);
|
|
349
|
+
return {
|
|
350
|
+
id: only?.id ?? key,
|
|
351
|
+
lat: center.lat,
|
|
352
|
+
lng: center.lng,
|
|
353
|
+
count,
|
|
354
|
+
pinIds: [],
|
|
355
|
+
pin: null,
|
|
356
|
+
members,
|
|
357
|
+
};
|
|
358
|
+
})
|
|
359
|
+
.sort((a, b) => a.id.localeCompare(b.id));
|
|
314
360
|
}
|
|
315
361
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
pin,
|
|
324
|
-
|
|
362
|
+
/** Headless grid cluster of one page of pins. */
|
|
363
|
+
export function clusterPins(
|
|
364
|
+
pins: readonly MapPin[],
|
|
365
|
+
zoom: number
|
|
366
|
+
): MapPinCluster[] {
|
|
367
|
+
return gridCells(pins, zoom, () => 1).map(({ members, ...cluster }) => ({
|
|
368
|
+
...cluster,
|
|
369
|
+
pinIds: members.map((pin) => pin.id),
|
|
370
|
+
pin: members.length === 1 ? (members[0] ?? null) : null,
|
|
371
|
+
}));
|
|
325
372
|
}
|
|
326
373
|
|
|
327
374
|
/**
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
* cannot invent extra decimals.
|
|
375
|
+
* Grid cluster of location buckets. Counts add up, so a cell's badge is
|
|
376
|
+
* the real total of its buckets. Bucket cells carry no pins.
|
|
331
377
|
*/
|
|
332
|
-
export function
|
|
333
|
-
|
|
378
|
+
export function clusterBuckets(
|
|
379
|
+
buckets: readonly MapBucket[],
|
|
334
380
|
zoom: number
|
|
335
381
|
): MapPinCluster[] {
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
if (!usablePin(pin)) continue;
|
|
341
|
-
const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
|
|
342
|
-
const list = groups.get(key);
|
|
343
|
-
if (list) list.push(pin);
|
|
344
|
-
else groups.set(key, [pin]);
|
|
345
|
-
}
|
|
346
|
-
const clusters: MapPinCluster[] = [];
|
|
347
|
-
for (const [key, group] of groups) {
|
|
348
|
-
const only = group[0];
|
|
349
|
-
clusters.push(
|
|
350
|
-
group.length === 1 && only
|
|
351
|
-
? singleCluster(only)
|
|
352
|
-
: multiCluster(key, group)
|
|
353
|
-
);
|
|
354
|
-
}
|
|
355
|
-
clusters.sort((a, b) => a.id.localeCompare(b.id));
|
|
356
|
-
return clusters;
|
|
382
|
+
const weighted = buckets.filter((bucket) => bucket.count > 0);
|
|
383
|
+
return gridCells(weighted, zoom, (bucket) => bucket.count).map(
|
|
384
|
+
({ members: _members, ...cluster }) => cluster
|
|
385
|
+
);
|
|
357
386
|
}
|
|
358
387
|
|
|
359
388
|
type MapArea =
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
4
4
|
|
|
5
5
|
import {
|
|
6
|
+
clusterBuckets,
|
|
6
7
|
clusterPins,
|
|
7
8
|
emptyMapSearchResult,
|
|
8
9
|
MAP_VIEWPORT_DEBOUNCE_MS,
|
|
@@ -93,8 +94,11 @@ export function useMapSearch(options: UseMapSearchOptions): UseMapSearchResult {
|
|
|
93
94
|
}, [key]);
|
|
94
95
|
|
|
95
96
|
const clusters = useMemo(
|
|
96
|
-
() =>
|
|
97
|
-
|
|
97
|
+
() =>
|
|
98
|
+
result.buckets.length > 0
|
|
99
|
+
? clusterBuckets(result.buckets, zoom)
|
|
100
|
+
: clusterPins(result.pins, zoom),
|
|
101
|
+
[result.buckets, result.pins, zoom]
|
|
98
102
|
);
|
|
99
103
|
|
|
100
104
|
return { ...result, clusters, loading, error };
|
package/src/search-engine.ts
CHANGED
|
@@ -363,6 +363,11 @@ export function toolbarFilterIds(schema: SearchUi | null): string[] {
|
|
|
363
363
|
return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));
|
|
364
364
|
}
|
|
365
365
|
|
|
366
|
+
/**
|
|
367
|
+
* The zero option's label is schema data: "Studio" only for
|
|
368
|
+
* `property_bedrooms`, "0" for the other count filters. Never derive it from
|
|
369
|
+
* `option.id`.
|
|
370
|
+
*/
|
|
366
371
|
export function countOptionLabel(
|
|
367
372
|
option: Pick<SearchUiOption, "label">
|
|
368
373
|
): string {
|
package/src/studio-contract.ts
CHANGED
|
@@ -22,11 +22,11 @@ export const STUDIO_SDK_CONTRACT = {
|
|
|
22
22
|
* prompt-safe lists. Do not bump here until that tarball is on npm.
|
|
23
23
|
* Phone mask helpers shipped in 0.6.0. Map search
|
|
24
24
|
* (`useMapSearch`, `searchListingsInBounds`) shipped in 0.9.0 — 0.7.0
|
|
25
|
-
* does not export them.
|
|
26
|
-
* (`visibleSearchFilters` / `toolbarFilterIds`)
|
|
27
|
-
* remain on this pin.
|
|
25
|
+
* does not export them. Property registration shipped in 0.10.0.
|
|
26
|
+
* Search filter helpers (`visibleSearchFilters` / `toolbarFilterIds`)
|
|
27
|
+
* shipped in 0.4.12 and remain on this pin.
|
|
28
28
|
*/
|
|
29
|
-
minNpmVersion: "0.
|
|
29
|
+
minNpmVersion: "0.10.0",
|
|
30
30
|
/** Historical: older tarballs inject card CSS when those components mount. */
|
|
31
31
|
selfInjectSince: "0.4.2",
|
|
32
32
|
chromeStrategy: "app-owned" as const,
|
|
@@ -138,6 +138,8 @@ export const STUDIO_SDK_CONTRACT = {
|
|
|
138
138
|
"toolbarFilterIds",
|
|
139
139
|
"paginationPages",
|
|
140
140
|
"hrefWithExplicitPage",
|
|
141
|
+
"countOptionLabel",
|
|
142
|
+
"countFacetChoices",
|
|
141
143
|
] as const,
|
|
142
144
|
/**
|
|
143
145
|
* Main-package helpers in git / newer tarballs but not required on
|
|
@@ -160,6 +162,12 @@ export const STUDIO_SDK_CONTRACT = {
|
|
|
160
162
|
* pin sentence does not name it.
|
|
161
163
|
*/
|
|
162
164
|
mapsSince: "0.9.0",
|
|
165
|
+
/**
|
|
166
|
+
* `useMapSearch` returns weighted location buckets (`map.buckets`, and
|
|
167
|
+
* `map.clusters` built from them) when the matches overflow one page.
|
|
168
|
+
* The map-search guidance teaches bucket clicks only from this pin on.
|
|
169
|
+
*/
|
|
170
|
+
mapBucketsSince: "0.11.0",
|
|
163
171
|
mapsExports: [
|
|
164
172
|
"listingStaticMapUrl",
|
|
165
173
|
"listingStreetViewUrl",
|
|
@@ -239,7 +247,7 @@ export function studioSellerLeadSdkInstruction(
|
|
|
239
247
|
): string {
|
|
240
248
|
if (!isSellerLeadOnPin(pin)) return "";
|
|
241
249
|
const names = STUDIO_SDK_CONTRACT.sellerLeadExports.join(", ");
|
|
242
|
-
return `Property registration (\`/anunciar-imovel\`, client component): import ${names}, isValidPhone, toE164 from \`${STUDIO_SDK_PACKAGE}\`. Address: load Maps JS only through \`<script src="https://maps.fndn.ai/sdk.js?callback=initPlaces" async defer />\` (Places is included; never a Google key, never \`maps.googleapis.com\`), then \`google.maps.places.Autocomplete\` with \`componentRestrictions: { country: "br" }\` and pt-BR. Picking a suggestion fills fullAddress, street, number, neighborhood, city, state (the 2-letter code), postalCode, latitude and longitude from the place;
|
|
250
|
+
return `Property registration (\`/anunciar-imovel\`, client component): import ${names}, isValidPhone, toE164 from \`${STUDIO_SDK_PACKAGE}\`. Address: load Maps JS only through \`<script src="https://maps.fndn.ai/sdk.js?callback=initPlaces" async defer />\` (Places is included; never a Google key, never \`maps.googleapis.com\`), then \`google.maps.places.Autocomplete\` with \`componentRestrictions: { country: "br" }\` and pt-BR. Picking a suggestion fills fullAddress, street, number, neighborhood, city, state (the 2-letter code), postalCode, country, latitude and longitude from the place and replaces every one of those values. Show CEP, Rua, Número, Bairro, Cidade, Estado and País as editable inputs bound to postalCode, street, number, neighborhood, city, state and country; the visitor can edit every value submitSellerLead sends. Latitude and longitude come from \`place.geometry.location.lat()\` and \`.lng()\`, are stored on the address and sent, and they are not inputs. A typed address without a suggestion is not enough. The visitor confirms number or "Sem número", bloco/torre or "Não tem", unidade or "Não tem" (noNumber, noBlocoTorre, noUnidade). Block the next group while \`sellerAddressErrors(address)\` has keys and show each message on its field. Owner: name, email and phone are all required — \`isValidName\`, \`isValidEmail\`, the phone mask with \`isValidPhone(toE164(phone))\`. Photos: \`await uploadSellerLeadPhoto({ siteId, baseUrl: GARAGEM_API_BASE, file, publishableKey })\` per file (JPG/PNG/WEBP, 10MB, up to 30), keep the returned URLs. Photo session: \`const schedule = sellerPhotoSchedule(config)\` and \`slotsForDate(schedule, day)\` for the hours. Submit once with \`await submitSellerLead({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey, owner: { name, email, phone }, address, property: { businessType, saleValue, rentValue, condoFee, totalArea, bedrooms, bathrooms, suites, parkingSpaces }, photos, photoSession: { date, time }, photoSchedule: schedule })\` (omit what the visitor did not fill). Errors are \`LeadSubmitError\`: \`duplicate_property\` → "Este imóvel já está cadastrado. Nossa equipe entrará em contato."; \`invalid_address\` → ask to pick the address again; anything else → a retry message. Disable the submit while pending and show a success state after it resolves. Never POST the leads webhook by hand.`;
|
|
243
251
|
}
|
|
244
252
|
|
|
245
253
|
/** Whether the pinned tarball carries the photo-search surface. */
|
|
@@ -431,7 +439,7 @@ export function studioAmenityInstruction(): string {
|
|
|
431
439
|
export function studioSearchInstruction(): string {
|
|
432
440
|
const reactNames = STUDIO_SDK_CONTRACT.reactExports.join(", ");
|
|
433
441
|
const libNames = STUDIO_SDK_CONTRACT.searchExports.join(", ");
|
|
434
|
-
return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Prefetch \`getSearchUi\` + \`queryListings\` on the server page. \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE, search: searchFromServer, initial })\` where \`searchFromServer\` is \`new URLSearchParams(await searchParams).toString()\` — never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file — heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app — do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` — never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range “Atualizar” on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / “Mais relevantes” — map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give “Mais recentes” (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton only for a slot whose content is still unknown, never as a Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (“Mais relevantes” when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu — Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Preço is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de imóvel, características and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no “Aplicar”; the footer stages then applyStaged. Never read \`staged[filter.id]\` — path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set — never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
|
|
442
|
+
return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Prefetch \`getSearchUi\` + \`queryListings\` on the server page. \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE, search: searchFromServer, initial })\` where \`searchFromServer\` is \`new URLSearchParams(await searchParams).toString()\` — never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file — heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app — do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` — never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range “Atualizar” on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / “Mais relevantes” — map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give “Mais recentes” (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton only for a slot whose content is still unknown, never as a Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (“Mais relevantes” when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu — Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Preço is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de imóvel, características and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no “Aplicar”; the footer stages then applyStaged. Never read \`staged[filter.id]\` — path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set — never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Count-button text is \`countOptionLabel(option)\`; never map id \`"0"\` to "Studio" (only bedrooms gets that label, from the schema). Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
|
|
435
443
|
}
|
|
436
444
|
|
|
437
445
|
/** Whether the Studio pin already carries the maps helpers. */
|
|
@@ -460,7 +468,12 @@ export function studioMapSearchInstruction(
|
|
|
460
468
|
options: { pin?: string } = {}
|
|
461
469
|
): string {
|
|
462
470
|
if (!mapsExportsPublished(options.pin)) return "";
|
|
463
|
-
|
|
471
|
+
const pin = options.pin ?? STUDIO_SDK_CONTRACT.minNpmVersion;
|
|
472
|
+
const buckets =
|
|
473
|
+
compareSemver(pin, STUDIO_SDK_CONTRACT.mapBucketsSince) >= 0
|
|
474
|
+
? " When the matches do not fit on one page, the hook builds `map.clusters` from location buckets whose counts add up to `map.total`; render them as they come and never fetch or merge more pages. A cluster with empty `pinIds` is a bucket: draw it as a cluster, and on click center the map on `cluster.lat`/`cluster.lng` and zoom in two levels — the next viewport search returns finer buckets or the listings themselves."
|
|
475
|
+
: "";
|
|
476
|
+
return `Map search on \`/imoveis\` (list and map of the same query). The list stays: keep \`usePublicSearch\` for the list, including its sort and pagination. The visitor switches on the same page. \`?modo=mapa\` is the map — read it on first paint. The list is the URL without \`modo\`; do not write \`modo=lista\` or \`modo=grade\`. Choosing the map sets \`modo=mapa\` and drops \`page\`. Choosing the list removes \`modo\`. On the map, hide sort and pagination. Do not add a map pager. The heading stays. Filters apply to both. Load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` — never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`, never \`maps.googleapis.com\`, never \`@vis.gl/react-google-maps\`. From \`${STUDIO_SDK_PACKAGE}/react\` import useMapSearch; it fetches, debounces, and clusters. \`const map = useMapSearch({ siteId, baseUrl: GARAGEM_API_BASE, bounds, zoom, q, sort, location, filters, publishableKey })\` with the same q, sort, location, filters, and publishableKey as the list. Pass the map's current zoom on every zoom change, including after a cluster click. Changing zoom recomputes \`map.clusters\` and does not refetch; a bounds change refetches. Do not send filter_by, vector_query, or nl_query from the browser. Request page 1 and pageSize at most 100. Do not walk totalPages. Pins are the masked coordinates the API returned — plot them as returned, never geocode the street. Render \`map.clusters\` with \`google.maps.Marker\` (no map id needed), in two styles that never look alike. A cluster (\`count > 1\`) is a filled circle in the brand color with a white border and the white count as its label. A listing (\`count === 1\` with \`cluster.pin\`) is a white rounded-rectangle chip with a brand-color border, labelled with the short price in the brand color ("R$ 850 mil", "R$ 1,2 mi"; "Consulte" when the price is null or 0): \`icon: { path: "M-34,-12 h68 a6,6 0 0 1 6,6 v12 a6,6 0 0 1 -6,6 h-68 a6,6 0 0 1 -6,-6 v-12 a6,6 0 0 1 6,-6 z", fillColor: "#ffffff", fillOpacity: 1, strokeColor: brand, strokeWeight: 1.5, scale: 1, labelOrigin: new google.maps.Point(0, 0) }\`. Never draw a listing as a dot or a circle, and never without its price. Clicking a listing selects it and shows its card. The card content is \`toListingCardModel(map.listings.find((listing) => listing.id === pin.id))\` and shows, in order: a large cover (\`coverSrc\`, aspect 4/3, full card width), title, \`priceLabel\`, \`locationLabel\`, then the facts that are present: \`bedrooms\` quartos, \`bathrooms\` banheiros, \`parkingSpaces\` vagas, \`areaM2\` m². Title and price alone are incomplete. On a wide screen the card opens next to its pin, never at the bottom of the map, where it falls below the viewport when the page is scrolled. Use one \`google.maps.InfoWindow\` and open it on the clicked marker: \`infoWindow.open({ map: googleMap, anchor: marker })\`. Its content is a div that React fills with \`createPortal\`. The InfoWindow pans the map so the card is in view. On a narrow screen the same card sits in a bottom sheet across the map width. Dismissing it leaves the pins. While \`map.loading\` the map is \`aria-busy\` with a visible progress indicator and the previous pins stay mounted. Clicking a cluster opens its members: \`const members = map.pins.filter((pin) => cluster.pinIds.includes(pin.id))\`, then \`fitBounds\` a LatLngBounds of their coordinates with about 64px padding, so the listings land inside the new view and split into chips. Do not step the zoom around \`cluster.lat\`/\`cluster.lng\`: that point is approximate and the area around it can come back empty. When every member has the same coordinates, or the map is already at zoom 18, do not zoom: open a small list of those listings, each with its price and a link. Layout, top to bottom: query, heading, toolbar, then the view. Lista and Mapa are icon buttons with the site tooltip and \`aria-label\` “Lista” / “Mapa”, not icon-plus-text. On desktop the toolbar is one row: featured filters on the left, and the list/map toggle immediately beside the sort select on the right. On a narrow screen the filters stay in one horizontal scroll that does not wrap, and the toggle plus the sort sit together on the row below that scroll. That row fits the viewport and never widens the page; sort may truncate. On the map the sort is hidden, so the toggle keeps that place beside where the sort was. In map mode the map fills the remaining viewport height, with a minimum of about 240px. Keep the hook's 400ms viewport debounce. A drawn polygon is not required. Do not add a separate /mapa route, a regions page, or a map on the listing page. Do not call Street View or travel time inside the map search.${buckets}`;
|
|
464
477
|
}
|
|
465
478
|
|
|
466
479
|
/** True when the pinned tarball ships the market-data helpers. */
|
|
@@ -485,7 +498,7 @@ export function studioMarketInstruction(
|
|
|
485
498
|
return `Market data: import ${names} from \`${STUDIO_SDK_PACKAGE}\`. **IPTU module required.** Every helper returns \`{ available: false, reason }\` (HTTP 200, never a throw) unless the site's organization has the IPTU module (\`iptu_itbi_integration\`) and the city is covered — most sites get \`available: false\`. ALWAYS render these blocks conditionally: \`if (!result.available) return null\` (omit the whole section, heading included); never a placeholder, never “dados indisponíveis”, never a local fallback number. The payloads carry only aggregates and a trimmed estimate — never render, request, or invent cadastral ids, IPTU lookups, ITBI transactions, comparables, or addresses from market data. Reasons are codes (\`module_not_enabled\`, \`city_unsupported\`, \`no_data\`, \`rate_limited\`, …) — do not print them. Three blocks (all optional, design is free):
|
|
486
499
|
- Neighborhood summary (listing detail, optionally search heading): \`const summary = await ${summary}({ siteId, baseUrl: GARAGEM_API_BASE, query: { city: listing.location.city, neighborhood: listing.location.neighborhood } })\`. Render \`summary.pricePerSqmFormatted.p25\` / \`.p50\` / \`.p75\` (strings, already \`R$ X/m²\`) and \`summary.sampleSize\` (“com base em N vendas”); omit the sample line when null.
|
|
487
500
|
- Listing market position (listing detail, near the price): \`const position = await ${position}({ siteId, baseUrl: GARAGEM_API_BASE, listingId: listing.id })\`. Copy comes from the helpers only: \`${positionLabel}(position)\` (“8% abaixo da mediana do bairro”) and \`${bandLabel}(position)\` (“Na faixa do bairro, abaixo da mediana”); both return \`null\` when unavailable — hide the line on \`null\`. Show \`position.listingPricePerSqmFormatted\` vs \`position.medianPricePerSqmFormatted\` if a comparison row is wanted. Do not compute the percent in the app.
|
|
488
|
-
- Visitor price estimate (\`/anunciar\` or
|
|
501
|
+
- Visitor price estimate (its own page, never \`/anunciar\` or \`/anunciar-imovel\`, client component): an address suggestion fills editable fields for city, bairro, área (m²), quartos, banheiros, vagas, tipo; latitude and longitude come from the suggestion and are not inputs. On submit \`const input = { city, neighborhood, areaSqm, bedrooms, bathrooms, parkingSpots, propertyType, latitude, longitude }; const estimate = await ${estimate}({ siteId, baseUrl: GARAGEM_API_BASE, input })\`. Render \`estimate.estimatedPriceFormatted\` with the range \`estimate.rangeLowFormatted\` – \`estimate.rangeHighFormatted\` and \`estimate.confidenceLabel\` mapped to pt-BR (alta / média / baixa). When \`available\` is false show \`estimate.message\` (pt-BR, already written) and the contact CTA. It is rate limited per visitor — disable the submit while pending. Never call it on page load.
|
|
489
502
|
Fetch on the server page (\`next: { revalidate: 900 }\`) for the summary and position; the estimate is a user action. Resolve \`siteId\` the same way as every other SDK call.`;
|
|
490
503
|
}
|
|
491
504
|
|
package/src/types-maps.ts
CHANGED
|
@@ -264,7 +264,23 @@ export interface MapPin {
|
|
|
264
264
|
coverImage: string | null;
|
|
265
265
|
}
|
|
266
266
|
|
|
267
|
-
/**
|
|
267
|
+
/**
|
|
268
|
+
* Location group returned when the matches do not fit on one page. It sits
|
|
269
|
+
* on one of its own listings (masked like a pin) and `count` is the group's
|
|
270
|
+
* real total, so bucket counts add up to the search total.
|
|
271
|
+
*/
|
|
272
|
+
export interface MapBucket {
|
|
273
|
+
/** Location path, e.g. `SP · São Paulo · Pinheiros`. */
|
|
274
|
+
id: string;
|
|
275
|
+
lat: number;
|
|
276
|
+
lng: number;
|
|
277
|
+
count: number;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* One grid cell. `count === 1` keeps the pin's own coordinates. A cell of
|
|
282
|
+
* buckets has empty `pinIds` and a null `pin`.
|
|
283
|
+
*/
|
|
268
284
|
export interface MapPinCluster {
|
|
269
285
|
id: string;
|
|
270
286
|
lat: number;
|
package/src/types-market.ts
CHANGED
|
@@ -116,6 +116,10 @@ export interface PriceEstimateInput {
|
|
|
116
116
|
parkingSpots?: number;
|
|
117
117
|
propertyType?: MarketPropertyType;
|
|
118
118
|
listingType?: MarketListingType;
|
|
119
|
+
/** From the address suggestion. Not a form field. */
|
|
120
|
+
latitude?: number;
|
|
121
|
+
/** From the address suggestion. Not a form field. */
|
|
122
|
+
longitude?: number;
|
|
119
123
|
}
|
|
120
124
|
|
|
121
125
|
export type PriceEstimateConfidence = "high" | "medium" | "low";
|
package/src/types.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* additive changes only, never breaking.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import type { MapBucket } from "./types-maps";
|
|
10
|
+
|
|
9
11
|
/** Sale/rental indicator. The API may return additional string values; consumers should branch defensively. */
|
|
10
12
|
export type ListingBusinessType = "sale" | "rental" | (string & {});
|
|
11
13
|
|
|
@@ -287,6 +289,8 @@ export interface QueryListingsParams {
|
|
|
287
289
|
};
|
|
288
290
|
/** Drawn area as `[lat, lng]` pairs, not GeoJSON `[lng, lat]`. */
|
|
289
291
|
polygon?: Array<[number, number]>;
|
|
292
|
+
/** Map search: return `buckets` when the matches do not fit on page 1. */
|
|
293
|
+
buckets?: boolean;
|
|
290
294
|
}
|
|
291
295
|
|
|
292
296
|
export interface QueryListingsResult {
|
|
@@ -295,6 +299,12 @@ export interface QueryListingsResult {
|
|
|
295
299
|
limit: number;
|
|
296
300
|
total: number;
|
|
297
301
|
totalPages: number;
|
|
302
|
+
/**
|
|
303
|
+
* Present only when `buckets` was requested, the matches overflow, and
|
|
304
|
+
* `total` counts one listing per match (no property collapse or partner
|
|
305
|
+
* listings). Otherwise map the page's pins.
|
|
306
|
+
*/
|
|
307
|
+
buckets?: MapBucket[];
|
|
298
308
|
}
|
|
299
309
|
|
|
300
310
|
/**
|