@realadvisor-sites/kit-react 0.0.0-stage → 0.3.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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +210 -2
  3. package/bin/sites-kit-react.mjs +26 -0
  4. package/client/index.ts +21 -0
  5. package/client/islands.ts +33 -0
  6. package/components/ConsentBanner.tsx +25 -0
  7. package/components/Document.tsx +170 -0
  8. package/components/EnquiryForm.tsx +107 -0
  9. package/components/Island.tsx +39 -0
  10. package/components/LanguageSwitch.tsx +24 -0
  11. package/components/LegalContent.tsx +30 -0
  12. package/components/ListingsMap.tsx +76 -0
  13. package/components/ListingsPager.tsx +25 -0
  14. package/components/ListingsSearch.tsx +294 -0
  15. package/components/RaImage.tsx +107 -0
  16. package/components/SafeHtml.tsx +30 -0
  17. package/components/form/Button.tsx +22 -0
  18. package/components/form/Combobox.tsx +34 -0
  19. package/components/form/Input.tsx +24 -0
  20. package/components/form/Select.tsx +30 -0
  21. package/components/index.ts +15 -0
  22. package/env.d.ts +36 -0
  23. package/lib/image.ts +36 -0
  24. package/lib/records.ts +17 -0
  25. package/lib/search.ts +37 -0
  26. package/package.json +63 -4
  27. package/server/data.ts +82 -0
  28. package/server/enquiry.ts +9 -0
  29. package/server/entry.server.tsx +54 -0
  30. package/server/fixture-client.ts +2 -0
  31. package/server/kit.ts +52 -0
  32. package/server/security.ts +32 -0
  33. package/server/seo.ts +39 -0
  34. package/server/worker.ts +146 -0
  35. package/styles/consent.css +6 -0
  36. package/styles/kit.css +21 -0
  37. package/styles/map.css +58 -0
  38. package/styles/pager.css +14 -0
  39. package/styles/search.css +162 -0
  40. package/tools/check-deploy.mjs +280 -0
  41. package/tools/preview.mjs +77 -0
  42. package/vite.d.mts +2 -0
  43. package/vite.mjs +180 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RealAdvisor SA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,211 @@
1
- # Temporary Holding Version
1
+ # @realadvisor/sites-kit-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The React Router version of the RealAdvisor sites kit: React Router 7
4
+ (framework mode, SSR) on a Cloudflare Worker, with the same guarantees as the
5
+ Astro kit (`@realadvisor/sites-kit`). It reuses the Astro kit for every rule,
6
+ string and browser script it can (`lib/` format, i18n, legal, search, seo,
7
+ image, env, render-error; `client/` enquiry, consent, combobox, listings
8
+ search and map; the check:deploy rules; `AGENTS.md` / `DESIGN.md` still
9
+ apply) and adds only what React needs. Reference site:
10
+ `examples/react/studio-vey`.
11
+
12
+ | Import | What |
13
+ | --- | --- |
14
+ | `@realadvisor/sites-kit-react/vite` | `sitesKit({ inlineCss? })`: `virtual:sites-kit/site` (site.json), the site's bundled browser script, `build/client/_headers`, build settings. `inlineCss: true` (opt-in): the Worker inlines each page's built stylesheets as `<style>` (no render-blocking CSS request; style-src already allows it). |
15
+ | `…/worker` | `createSiteWorker(build)`: env, 301s, cross-site form check, per-request CSP nonce, full render before answering (500 never a cut 200), 404/410, security headers. |
16
+ | `…/entry.server` | `renderToReadableStream` with the nonce, waits for `allReady`. |
17
+ | `…/server/data` | `siteClient({ fixture })`: one `SitesClient` (SDK interface), live with SITES_API_URL + SITES_API_KEY, else the fixture. |
18
+ | `…/server/kit` | `kitData()` for the root loader (mode, analytics id, Turnstile key, SITE_URL), `canonical(request)`, `pageLocale(request)`. |
19
+ | `…/server/enquiry` | `enquiryAction(request, sites)`: the Astro `/api/enquiry` contract, sent through the SDK's `handleEnquiry`. |
20
+ | `…/server/seo` | `sitemap(paths)`, `robots()`, `legalPaths()`, `notFound(gone?)`. |
21
+ | `…/components/*` | `Document` (`KitProvider`, `KitScripts`, `Seo`, `JsonLd`, `NonceContext`, `usePageLocale`, `useGone`), `SafeHtml` (`sanitized()`), `RaImage`, `EnquiryForm`, `LegalContent`, `ConsentBanner`, `ListingsSearch`, `ListingsMap`, `ListingsPager`, `Island`, `LanguageSwitch`, `form/*`. Same markup, classes and `data-*` hooks as the Astro components. |
22
+ | `…/lib/*` | `records` (`agencyOf`, `price(l, locale)`, `listingRef`), `search` (`searchListings`), `image` (`imgUrl` with crop). |
23
+ | `…/client` | `kit()` (loads each browser part only where the page has it), `islands({...})`. |
24
+ | `…/styles/*` | `kit.css`: every kit part's CSS (the Astro kit's form.css, search, pager, map, consent), same tokens; or the parts one by one. Import order: see CSS order. |
25
+ | `sites-kit-react check deploy` | The deploy gate (`pnpm check:deploy`). |
26
+ | `sites-kit-react preview --port N` | `pnpm preview`: build/ on `wrangler dev`, restarted when a new build lands (plain `wrangler dev --config build/server/wrangler.json` keeps serving the build it started with). |
27
+
28
+ ## Scripts and the CSP nonce
29
+
30
+ Approved for React Router sites only (2026-11-11): a per-request nonce in
31
+ `script-src`; everything else is the Astro kit's `lib/security.mjs`.
32
+
33
+ - The Worker makes 16 random bytes (base64) per request, passes them as
34
+ `loadContext.nonce` and writes `script-src 'self' 'nonce-…' <kit hosts>`
35
+ on HTML responses only. Static files get the kit's headers from
36
+ `build/client/_headers` (no nonce).
37
+ - `entry.server` passes it to `renderToReadableStream({ nonce })`,
38
+ `<ServerRouter nonce>` and `NonceContext`; `<KitScripts>` gives it to
39
+ `<Scripts>`, `<ScrollRestoration>` and the site script; `<JsonLd>` too.
40
+ - **Static by default.** A route renders HTML plus one bundled module
41
+ (`app/client.ts`: `kit()`, the site's small behaviours, `islands()`); no
42
+ React Router runtime, no inline script. A route that needs full hydration
43
+ exports `handle = { hydrate: true }`: then React Router's scripts render,
44
+ all with the nonce, and `app/entry.client.tsx` imports `./client`.
45
+ - **Islands (opt-in)**: `<Island name component props when>` renders a
46
+ component on the server and hydrates it alone; `islands({ Name: () =>
47
+ import(...) })` in app/client.ts loads React (~90 KB) only on a page that
48
+ has one. Use it for real React interactivity only: small behaviours (tabs,
49
+ menus, lightboxes) are plain functions in app/client.ts, as on Astro
50
+ (studio-vey: menu, offer tabs, gallery, ~5 KB). Props are JSON; never
51
+ import server code into an island.
52
+ - Pages that the search script updates (`ListingsSearch`) stay static.
53
+ - **Bytes, as on Astro.** `kit()` loads each kit part (enquiry, consent,
54
+ combobox, search, map) only on a page that renders it, as its own chunk,
55
+ when the page loads. Vite wraps every dynamic `import()` of the browser
56
+ build in its ~2 KB preload helper (`build.modulePreload: false` does not
57
+ remove it): the kit's plugin replaces it with a ~300-byte one (same
58
+ contract: a chunk's CSS first, its imports preloaded). A page without a kit
59
+ part loads the site chunk only (studio-vey: menu, tabs, gallery); a site
60
+ with no behaviours of its own ships well under 1 KB.
61
+
62
+ ## A site
63
+
64
+ ```
65
+ site.json, wrangler.jsonc (main: workers/app.ts), vite.config.ts, react-router.config.ts
66
+ workers/app.ts createSiteWorker(() => import('virtual:react-router/server-build'))
67
+ app/entry.server.tsx export { default, streamTimeout } from '@realadvisor/sites-kit-react/entry.server'
68
+ app/root.tsx loader { kit: await kitData() }, <KitProvider>, <ConsentBanner>, <KitScripts>, ErrorBoundary -> 404/410 page
69
+ app/client.ts kit(); islands({...}); site behaviours
70
+ app/lib/data.server.ts export const sites = siteClient({ fixture })
71
+ app/routes/api.enquiry.ts export const action = ({ request }) => enquiryAction(request, sites)
72
+ app/routes/sitemap.ts, robots.ts, legal.tsx, privacy.tsx, 404.tsx (splat)
73
+ ```
74
+
75
+ tsconfig `include` lists `node_modules/@realadvisor/sites-kit-react/env.d.ts`.
76
+ Rules for loaders: read data only through `sites`, throw `notFound()` (404)
77
+ or `notFound(true)` (410), keep loader data to what the page renders.
78
+ `dangerouslySetInnerHTML` only with `sanitizeHtml(...)` written inside it, or
79
+ `sanitized()` in the loader and `<SafeHtml html={…}>` in the page (check:deploy).
80
+
81
+ ### Recipe: root.tsx
82
+
83
+ ```tsx
84
+ import './styles/global.css'; // 1. the site's CSS first
85
+ import '@realadvisor/sites-kit-react/styles/kit.css'; // 2. then the kit's (Astro order)
86
+ import { KitProvider, KitScripts, usePageLocale } from '@realadvisor/sites-kit-react/components/Document';
87
+ import { ConsentBanner } from '@realadvisor/sites-kit-react/components/ConsentBanner';
88
+ import NotFound, { ServerError } from './routes/404';
89
+
90
+ export function Layout({ children }) {
91
+ const data = useRouteLoaderData('root');
92
+ return (
93
+ <html lang={usePageLocale()}> {/* the path's language: /fr/… -> fr-CH */}
94
+ <head>…<Meta /><Links /></head>
95
+ <body>
96
+ <KitProvider value={data?.kit}>{children}<ConsentBanner /></KitProvider>
97
+ <KitScripts />
98
+ </body>
99
+ </html>
100
+ );
101
+ }
102
+ export function ErrorBoundary() {
103
+ const error = useRouteError();
104
+ if (isRouteErrorResponse(error) && (error.status === 404 || error.status === 410)) return <NotFound />;
105
+ return <ServerError />;
106
+ }
107
+ // routes/404.tsx
108
+ export default function NotFound() {
109
+ const gone = useGone(); // never a prop: React Router drops a route default export's props
110
+ …
111
+ }
112
+ ```
113
+
114
+ ### Languages
115
+
116
+ A multi-language site lists its locales in site.json (`locales`, the default
117
+ first; the others under `/fr/…`, `/en/…`). The page's locale comes from its
118
+ path: `usePageLocale()` in components, `pageLocale(request)` in loaders.
119
+ `Seo` (og:locale), `ConsentBanner`, `EnquiryForm`, `ListingsSearch`,
120
+ `ListingsPager` and `ListingsMap` default to it; `<html lang>` takes
121
+ `usePageLocale()`. `searchListings(pool, params, { url: request })` sorts the
122
+ facets in the page's language (or pass `locale`).
123
+
124
+ ### Prices and currency
125
+
126
+ `formatPrice(listing, { locale })` and `price(record, locale)` (lib/records)
127
+ write the listing's own `currency` with the page's words ("/ mois", "Price on
128
+ request"): the country's currency in the country's form (`CHF 1'250'000`,
129
+ `1 250 000 €`), another one in the page language's (`€1,250,000` on an
130
+ English page of a Swiss site). `formatAmount(n, { currency, locale })` for a
131
+ bare amount. The search's price filter works in one currency (`currency`,
132
+ else the one most of the pool is in): amounts are never converted, so a
133
+ listing in another currency is left out of a price filter and of the price
134
+ steps. An agency with CHF and EUR listings filters in one of them, or leaves
135
+ `price` out of `filters`.
136
+
137
+ ### CSS order
138
+
139
+ Astro writes CSS in import order: a layout that imports its global.css and
140
+ then the kit's ConsentBanner (the template, halderhof, clairval…) gets the
141
+ kit's form.css after the site's, so the kit wins at equal specificity
142
+ (`--control-h: 48px`, `.enquiry form { gap }`); a layout that imports the
143
+ kit's components first (quartier-zinnober, ballatoio…) gets the opposite.
144
+ The React kit keeps that rule: import `styles/kit.css` once in root.tsx,
145
+ **after the site's global CSS** for a new site, or at the place the Astro
146
+ layout imports ConsentBanner for a port. The kit's plugin turns the import
147
+ into one import per part (no `@import`, which the CSS bundler would hoist to
148
+ the top of the bundle), so the rules sit exactly there. Do not restate the
149
+ kit's values in a later stylesheet to fix the order: move the import. Theme
150
+ the kit with its tokens (`--accent`, `--line`, `--radius-btn`…) or with
151
+ selectors scoped to the part (`.enquiry { … }`).
152
+
153
+ ### Images
154
+
155
+ `RaImage` adds an AVIF `<source>` (and so a `<picture>`) to the `priority`
156
+ image only, as the Astro kit: a lazy photo is a plain `<img>`, so CSS that
157
+ sizes `.card > img` holds. `avif` forces it either way. `data-*` attributes
158
+ go on the `<img>` (`data-hero`).
159
+
160
+ ### Loader data and the client chunk
161
+
162
+ Loaders run on the server only. A page component that imports a fixture or
163
+ a data helper, though, compiles it (the whole fixture JSON) into the route's
164
+ client chunk, which `check:deploy`'s secret scan reads and a hydrated route
165
+ downloads. Read fixture-only fields (the API does not have them yet) in the
166
+ loader and pass them as an `extras` object:
167
+
168
+ ```ts
169
+ // routes/listing.tsx
170
+ export async function loader({ params }) {
171
+ const listing = await sites.listing(params.slug);
172
+ if (!listing) throw notFound(true);
173
+ return { listing, extras: listingExtras(listing.id) }; // fixture only: energy class, year built
174
+ }
175
+ ```
176
+
177
+ Never import `app/data/fixture.json` or `*.server.ts` into a component.
178
+
179
+ ### Porting an Astro site
180
+
181
+ - **Whitespace**: JSX drops the line break between inline elements that
182
+ Astro keeps as a space: `<strong>{n}</strong>{' '}<span>rooms</span>`.
183
+ Compare the text, not only the screenshot.
184
+ - **Specificity**: Astro's scoped styles (`.card[data-astro-cid-x]`) beat the
185
+ global CSS that the port turns them into. Scope a page's styles by a page
186
+ class on `<main>` (`.page-listing .facts { … }`) instead of raising
187
+ selectors one by one.
188
+ - **CSS order**: kit.css where the Astro layout imports the kit's
189
+ components (above); a port does not restate the kit's values.
190
+ - **404 / 410**: `useGone()` in the 404 page (above).
191
+ - **Images**: `RaImage` = Astro's (AVIF on the priority image only, `data-*`).
192
+
193
+ ## check:deploy
194
+
195
+ `pnpm check:deploy` builds, serves `build/` with wrangler and runs the Astro
196
+ kit's rules (imported from `kit/tools/check-deploy.mjs`) on one page
197
+ of every route in the sitemap, the map view of every search page, legal
198
+ pages and three missing pages, plus: one nonce per response, new per
199
+ request, on every `<script>`, CSP otherwise equal to the kit's, `_headers`
200
+ on static files, the enquiry endpoint contract, `dangerouslySetInnerHTML`
201
+ in `app/`, secrets in `build/`. The browser tools of the Astro kit work on a
202
+ running React site: `sites-kit screenshot --url …`, `sites-kit test map --url … --path /kaufen`.
203
+
204
+ ## Develop
205
+
206
+ `pnpm preview` (`sites-kit-react preview`) restarts wrangler on each `pnpm
207
+ build`; a site still on `wrangler dev --config build/server/wrangler.json`
208
+ must be restarted by hand after a build.
209
+
210
+ Sites install the kit as `file:../../kit-react` (pnpm hard-links it): run
211
+ `pnpm install` in the site after adding a file to the kit.
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The React kit's tools, run from the site root (the site's package scripts):
4
+ *
5
+ * sites-kit-react check deploy [--no-build] the deploy gate (pnpm check:deploy)
6
+ * sites-kit-react preview [--port N] build/ on wrangler dev, restarted on each new build (pnpm preview)
7
+ *
8
+ * The other tools are the Astro kit's (`sites-kit screenshot --url …`,
9
+ * `sites-kit test map --url …`): they drive a running site, whatever builds it.
10
+ */
11
+ import { spawn } from 'node:child_process';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ const TOOLS = { 'check deploy': 'check-deploy.mjs', preview: 'preview.mjs' };
15
+ const argv = process.argv.slice(2);
16
+ const one = TOOLS[argv[0]] && argv[0] === 'preview';
17
+ const [first, second, ...rest] = one ? [argv[0], undefined, ...argv.slice(1)] : argv;
18
+ const tool = one ? TOOLS.preview : TOOLS[`${first} ${second}`];
19
+ if (!tool) {
20
+ console.error(`${first ? `Unknown command: ${[first, second].filter(Boolean).join(' ')}\n` : ''}Commands:\n${Object.keys(TOOLS).map((k) => ` sites-kit-react ${k}`).join('\n')}`);
21
+ process.exit(first ? 2 : 0);
22
+ }
23
+ const child = spawn(process.execPath, [fileURLToPath(new URL(`../tools/${tool}`, import.meta.url)), ...rest], { stdio: 'inherit' });
24
+ // pnpm stops a script with a signal: pass it on, so `preview` takes wrangler down with it.
25
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => child.kill(sig));
26
+ child.on('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The kit's browser side, for app/client.ts:
3
+ *
4
+ * import { kit, islands } from '@realadvisor/sites-kit-react/client';
5
+ * kit();
6
+ * islands({ Gallery: () => import('./components/Gallery') });
7
+ *
8
+ * kit() loads each part only on a page that has it (one small module each,
9
+ * the same files as the Astro kit): enquiry form, consent banner, combobox,
10
+ * listing search (with its map) or a map alone.
11
+ */
12
+ export { islands } from './islands';
13
+
14
+ export function kit() {
15
+ const has = (sel: string) => !!document.querySelector(sel);
16
+ if (has('[data-enquiry]')) void import('@realadvisor/sites-kit/client/enquiry');
17
+ if (has('[data-consent]')) void import('@realadvisor/sites-kit/client/consent');
18
+ if (has('[data-combobox]')) void import('@realadvisor/sites-kit/client/combobox');
19
+ if (has('[data-rs-root]')) void import('@realadvisor/sites-kit/client/listings-search');
20
+ else if (has('[data-ra-map]')) void import('@realadvisor/sites-kit/client/listings-map');
21
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Hydrates the [data-island] roots that <Island> rendered: each with its own
3
+ * React root, the server's useId prefix and its JSON props. React loads only
4
+ * on a page that has an island, and only when the first one is due.
5
+ */
6
+ import type { ComponentType } from 'react';
7
+
8
+ type Loader = () => Promise<{ default: ComponentType<any> }>;
9
+
10
+ export function islands(loaders: Record<string, Loader>) {
11
+ for (const el of document.querySelectorAll<HTMLElement>('[data-island]:not([data-hydrated])')) {
12
+ const load = loaders[el.dataset.island!];
13
+ if (!load) continue;
14
+ const go = () => void hydrate(el, load);
15
+ if (el.dataset.when === 'load') go();
16
+ else if (el.dataset.when === 'idle') ('requestIdleCallback' in window ? requestIdleCallback(go) : setTimeout(go, 200));
17
+ else {
18
+ const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && (io.disconnect(), go()), { rootMargin: '200px' });
19
+ io.observe(el.firstElementChild ?? el);
20
+ }
21
+ }
22
+ }
23
+
24
+ async function hydrate(el: HTMLElement, load: Loader) {
25
+ if (el.dataset.hydrated) return;
26
+ el.dataset.hydrated = 'pending';
27
+ const [{ createElement }, { hydrateRoot }, { default: C }] = await Promise.all([import('react'), import('react-dom/client'), load()]);
28
+ hydrateRoot(el, createElement(C, JSON.parse(el.dataset.props ?? '{}')), {
29
+ identifierPrefix: el.dataset.prefix,
30
+ onRecoverableError: (e) => console.error('[island]', el.dataset.island, e),
31
+ });
32
+ el.dataset.hydrated = 'true';
33
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Analytics consent (port of ConsentBanner.astro; the browser side is the
3
+ * Astro kit's client/consent.ts). Renders only when ANALYTICS_ID is set;
4
+ * GA4 loads only after "Accept". Keep both buttons equal in weight.
5
+ */
6
+ import { lang, privacyPath, t } from '@realadvisor/sites-kit/i18n';
7
+ import { useKit, usePageLocale } from './Document';
8
+
9
+ /** `locale`: default the page's (from its path), as the rest of the page. */
10
+ export function ConsentBanner({ locale: localeProp }: { locale?: string }) {
11
+ const { analyticsId } = useKit();
12
+ const pathLocale = usePageLocale();
13
+ if (!analyticsId) return null;
14
+ const locale = localeProp ?? pathLocale;
15
+ const l = lang(locale);
16
+ return (
17
+ <div className="consent" role="region" aria-label="Cookies" hidden data-consent={analyticsId}>
18
+ <p>{t('consentText', {}, l)} <a href={privacyPath(locale)}>{t('privacyLink', {}, l)}</a></p>
19
+ <div className="consent-actions">
20
+ <button type="button" className="btn btn--secondary" data-choice="denied">{t('decline', {}, l)}</button>
21
+ <button type="button" className="btn btn--secondary" data-choice="granted">{t('accept', {}, l)}</button>
22
+ </div>
23
+ </div>
24
+ );
25
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Document parts every root.tsx uses: the request nonce, the kit settings
3
+ * (mode, analytics, Turnstile), the scripts, the SEO head and JSON-LD.
4
+ *
5
+ * export function Layout({ children }) {
6
+ * const data = useRouteLoaderData<typeof loader>('root');
7
+ * return (
8
+ * <html lang={usePageLocale()}>
9
+ * <head><meta charSet="utf-8" /><meta name="viewport" … /><Meta /><Links /></head>
10
+ * <body>
11
+ * <KitProvider value={data?.kit}>{children}<ConsentBanner /></KitProvider>
12
+ * <KitScripts />
13
+ * </body>
14
+ * </html>
15
+ * );
16
+ * }
17
+ *
18
+ * Scripts: a route is static HTML plus the site's one bundled script
19
+ * (app/client.ts: kit behaviours, islands) unless its `handle` says
20
+ * `{ hydrate: true }`; then React Router's own scripts render, with the
21
+ * request nonce (the CSP allows no other inline script).
22
+ */
23
+ import { createContext, useContext, type ReactNode } from 'react';
24
+ import { isRouteErrorResponse, Scripts, ScrollRestoration, useLocation, useMatches, useRouteError } from 'react-router';
25
+ import { localeOfPath } from '@realadvisor/sites-kit/i18n';
26
+ import client from 'virtual:sites-kit-react/client';
27
+ import { safeJsonLd } from '@realadvisor/sites-kit/seo';
28
+
29
+ /** The request's CSP nonce (server only; the browser hides it). */
30
+ export const NonceContext = createContext<string | undefined>(undefined);
31
+ export const useNonce = () => useContext(NonceContext);
32
+
33
+ /** What the kit parts need from the request: from `kitData()` in the root loader. */
34
+ export type KitData = {
35
+ /** `preview` unless SITE_MODE says production: previews never send enquiries. */
36
+ mode: 'production' | 'preview';
37
+ /** GA4 id: the consent banner shows only when set. */
38
+ analyticsId?: string;
39
+ /** Turnstile site key for EnquiryForm (`fixture`: a stand-in that never loads Turnstile). */
40
+ turnstileSiteKey: string | null;
41
+ /** Public origin (SITE_URL): canonical, OG and sitemap URLs. */
42
+ siteUrl: string;
43
+ };
44
+
45
+ const DEFAULT: KitData = { mode: 'preview', turnstileSiteKey: null, siteUrl: 'https://example.realadvisor.site' };
46
+ const KitContext = createContext<KitData>(DEFAULT);
47
+ export const useKit = () => useContext(KitContext);
48
+ export function KitProvider({ value, children }: { value?: KitData; children: ReactNode }) {
49
+ return <KitContext.Provider value={value ?? DEFAULT}>{children}</KitContext.Provider>;
50
+ }
51
+
52
+ /**
53
+ * The page's locale from its path: site.json `locales`, the default one on
54
+ * unprefixed URLs, `/fr/…` for fr-CH and so on (the Astro kit's localeOfPath).
55
+ * For `<html lang>`, og:locale (Seo), the consent banner, the enquiry form
56
+ * and the listings search, which all default to it. Loaders: `pageLocale(request)`
57
+ * from `…/server/kit`.
58
+ */
59
+ export function usePageLocale(): string {
60
+ return localeOfPath(useLocation().pathname);
61
+ }
62
+
63
+ type Handle = { hydrate?: boolean } | undefined;
64
+
65
+ /** True when a matched route asks for React hydration (`export const handle = { hydrate: true }`). */
66
+ export function useHydrate(): boolean {
67
+ return useMatches().some((m) => (m.handle as Handle)?.hydrate === true);
68
+ }
69
+
70
+ /**
71
+ * End of <body>. Static routes: the site's bundled script (a file: 'self'),
72
+ * nothing inline. Hydrated routes: React Router's scripts with the nonce
73
+ * (app/entry.client.tsx imports app/client.ts itself there).
74
+ */
75
+ export function KitScripts() {
76
+ const nonce = useNonce();
77
+ const hydrate = useHydrate();
78
+ if (hydrate) {
79
+ return (
80
+ <>
81
+ <ScrollRestoration nonce={nonce} />
82
+ <Scripts nonce={nonce} />
83
+ </>
84
+ );
85
+ }
86
+ if (!client.src) return null;
87
+ return (
88
+ <>
89
+ {client.preload.map((href) => (
90
+ <link key={href} rel="modulepreload" href={href} />
91
+ ))}
92
+ <script type="module" src={client.src} nonce={nonce} />
93
+ </>
94
+ );
95
+ }
96
+
97
+ /**
98
+ * The 404 / 410 page: read the status from the route error, never from a
99
+ * prop. React Router wraps a route module's default export and drops the
100
+ * props it is given, so `<NotFound gone />` from the root ErrorBoundary
101
+ * arrives without `gone` when NotFound is routes/404.tsx's default export.
102
+ *
103
+ * export default function NotFound() {
104
+ * const gone = useGone(); // true on a 410 (`throw notFound(true)`)
105
+ * ...
106
+ * }
107
+ * // root.tsx
108
+ * export function ErrorBoundary() {
109
+ * const error = useRouteError();
110
+ * if (isRouteErrorResponse(error) && (error.status === 404 || error.status === 410)) return <NotFound />;
111
+ * ...
112
+ * }
113
+ */
114
+ export function useErrorStatus(): number | undefined {
115
+ const error = useRouteError();
116
+ return isRouteErrorResponse(error) ? error.status : undefined;
117
+ }
118
+ /** True when the page answers a 410 (a listing that left the site). */
119
+ export const useGone = () => useErrorStatus() === 410;
120
+
121
+ /** JSON-LD (escaped by the kit's safeJsonLd, so data never closes the tag). */
122
+ export function JsonLd({ data }: { data: unknown }) {
123
+ const nonce = useNonce();
124
+ return <script type="application/ld+json" nonce={nonce} dangerouslySetInnerHTML={{ __html: safeJsonLd(data) }} />;
125
+ }
126
+
127
+ export type SeoProps = {
128
+ title: string;
129
+ description: string;
130
+ /** Absolute URL, about 1200x630: the page's main photo. */
131
+ image?: string;
132
+ jsonLd?: object | object[];
133
+ noindex?: boolean;
134
+ /** Every language version of this page: hreflang links (and x-default = the first). */
135
+ alternates?: { lang: string; href: string }[];
136
+ /** The page's locale (og:locale). Default: the path's (`usePageLocale()`). */
137
+ locale?: string;
138
+ /** Canonical URL (canonicalUrl() of the request URL on SITE_URL). */
139
+ canonical: string;
140
+ themeColor?: string;
141
+ };
142
+
143
+ /**
144
+ * Title, description, canonical, hreflang, robots, Open Graph and JSON-LD.
145
+ * React 19 hoists the tags into <head> wherever the page renders it.
146
+ */
147
+ export function Seo({ title, description, image, jsonLd, noindex, alternates, locale: localeProp, canonical, themeColor }: SeoProps) {
148
+ const pathLocale = usePageLocale();
149
+ const locale = localeProp ?? pathLocale;
150
+ const base = new URL(canonical).origin;
151
+ return (
152
+ <>
153
+ <title>{title}</title>
154
+ <meta name="description" content={description} />
155
+ <link rel="canonical" href={canonical} />
156
+ {alternates?.map((a) => <link key={a.lang} rel="alternate" hrefLang={a.lang} href={new URL(a.href, base).href} />)}
157
+ {alternates?.[0] && <link rel="alternate" hrefLang="x-default" href={new URL(alternates[0].href, base).href} />}
158
+ {noindex && <meta name="robots" content="noindex" />}
159
+ <meta property="og:type" content="website" />
160
+ <meta property="og:title" content={title} />
161
+ <meta property="og:description" content={description} />
162
+ <meta property="og:url" content={canonical} />
163
+ <meta property="og:locale" content={locale.replace('-', '_')} />
164
+ {image && <meta property="og:image" content={image} />}
165
+ <meta name="twitter:card" content={image ? 'summary_large_image' : 'summary'} />
166
+ {themeColor && <meta name="theme-color" content={themeColor} />}
167
+ {jsonLd && <JsonLd data={jsonLd} />}
168
+ </>
169
+ );
170
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * THE enquiry form (port of EnquiryForm.astro: same markup, same fields, same
3
+ * browser script @realadvisor/sites-kit/client/enquiry, same /api/enquiry
4
+ * contract). Every form that sends a message to the agency is this one.
5
+ *
6
+ * <EnquiryForm listingId={l.id} agentId={l.agent?.id} agentName={l.agent?.first_name} message={…} />
7
+ * <EnquiryForm id="valuation" contactReason="valuation" />
8
+ * <EnquiryForm developmentId={dev.id} units={unitOptions(dev.units)} />
9
+ *
10
+ * Turnstile site key and preview mode come from the root loader (kitData()).
11
+ */
12
+ import { useLocation } from 'react-router';
13
+ import { FIXTURE_TURNSTILE_SITE_KEY } from '@realadvisor/sites-sdk';
14
+ import { t as tr, lang, localeOfPath, privacyPath, type StringKey } from '@realadvisor/sites-kit/i18n';
15
+ import { useKit } from './Document';
16
+ import { Input } from './form/Input';
17
+ import { Button } from './form/Button';
18
+ import { Select } from './form/Select';
19
+
20
+ export type EnquiryFormProps = {
21
+ /** Unique per page when the page has two forms. */
22
+ id?: string;
23
+ listingId?: string;
24
+ agentId?: string;
25
+ /** First name in the success message. */
26
+ agentName?: string;
27
+ developmentId?: string;
28
+ lotId?: string;
29
+ units?: Array<{ value: string; label: string }>;
30
+ selectedUnit?: string;
31
+ contactReason?: 'buy' | 'sell' | 'valuation' | 'other';
32
+ message?: string;
33
+ submitLabel?: string;
34
+ locale?: string;
35
+ className?: string;
36
+ };
37
+
38
+ export function EnquiryForm(props: EnquiryFormProps) {
39
+ const { id = 'enquiry', listingId, agentId, agentName, developmentId, lotId, units, selectedUnit, message, submitLabel, className } = props;
40
+ const { pathname } = useLocation();
41
+ const kit = useKit();
42
+ const contactReason = props.contactReason ?? (developmentId ? 'buy' : undefined);
43
+ const locale = props.locale ?? localeOfPath(pathname);
44
+ const t = (key: StringKey, vars: Record<string, string> = {}) => tr(key, vars, lang(locale));
45
+ const success = agentName ? t('sentBy', { name: agentName }) : t('sent');
46
+ const f = (name: string) => `${id}-${name}`;
47
+ const unitSelect = !!developmentId && !lotId && !!units && units.length > 0;
48
+ const siteKey = kit.mode === 'preview' ? null : kit.turnstileSiteKey;
49
+ return (
50
+ <div className={['enquiry', className].filter(Boolean).join(' ')} id={id} data-enquiry="">
51
+ <p className="enquiry-status" role="status" aria-live="polite" tabIndex={-1} hidden data-status=""></p>
52
+ <form
53
+ method="post"
54
+ action="/api/enquiry"
55
+ noValidate
56
+ data-msg-sent={success}
57
+ data-msg-preview={t('preview')}
58
+ data-msg-error={t('error')}
59
+ data-msg-required={t('required')}
60
+ data-msg-email={t('invalidEmail')}
61
+ data-msg-unit={t('unitRequired')}
62
+ data-msg-sending={t('sending')}
63
+ data-msg-verify={t('verifyFailed')}
64
+ data-msg-rejected={t('rejected')}
65
+ >
66
+ {listingId && <input type="hidden" name="listingId" value={listingId} />}
67
+ {agentId && <input type="hidden" name="agentId" value={agentId} />}
68
+ {developmentId && <input type="hidden" name="developmentId" value={developmentId} />}
69
+ {developmentId && lotId && <input type="hidden" name="lotId" value={lotId} />}
70
+ {!listingId && !lotId && contactReason && <input type="hidden" name="contactReason" value={contactReason} />}
71
+ <input type="hidden" name="locale" value={locale} />
72
+ <input type="hidden" name="idempotencyKey" defaultValue={crypto.randomUUID()} data-idempotency="" />
73
+ <input type="hidden" name="redirect" defaultValue={`#${id}`} data-redirect="" />
74
+ <div className="enquiry-grid">
75
+ <div>
76
+ <Input id={f('name')} label={`${t('name')} *`} name="name" required maxLength={100} autoComplete="name" aria-describedby={f('name-err')} />
77
+ <p className="field-error" id={f('name-err')} hidden></p>
78
+ </div>
79
+ <div>
80
+ <Input id={f('email')} label={`${t('email')} *`} name="email" type="email" required maxLength={200} autoComplete="email" aria-describedby={f('email-err')} />
81
+ <p className="field-error" id={f('email-err')} hidden></p>
82
+ </div>
83
+ <div>
84
+ <Input id={f('phone')} label={`${t('phone')} ${t('optional')}`} name="phone" type="tel" maxLength={40} autoComplete="tel" />
85
+ </div>
86
+ {unitSelect && (
87
+ <div className="enquiry-full">
88
+ <Select id={f('lot')} label={`${t('unitOfInterest')} *`} name="lotId" options={units!} value={selectedUnit} placeholder={t('chooseUnit')} required aria-describedby={f('lot-err')} />
89
+ <p className="field-error" id={f('lot-err')} hidden></p>
90
+ </div>
91
+ )}
92
+ <div className="enquiry-full">
93
+ <Input id={f('message')} label={`${t('message')} *`} name="message" multiline required maxLength={5000} value={message} aria-describedby={f('message-err')} />
94
+ <p className="field-error" id={f('message-err')} hidden></p>
95
+ </div>
96
+ </div>
97
+ {siteKey && (
98
+ <div className="enquiry-turnstile" data-turnstile={siteKey === FIXTURE_TURNSTILE_SITE_KEY ? 'fixture' : 'live'} data-sitekey={siteKey} data-lang={lang(locale)}></div>
99
+ )}
100
+ <Button type="submit">{submitLabel ?? t('send')}</Button>
101
+ <p className="enquiry-note">{t('privacyNote')} <a href={privacyPath(locale)}>{t('privacyLink')}</a></p>
102
+ </form>
103
+ </div>
104
+ );
105
+ }
106
+
107
+ export default EnquiryForm;