@sevenfold/setto-client 0.49.0 → 0.50.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/dist/pages/head.d.ts +36 -0
- package/dist/setto-client.js +19 -2
- package/dist/setto-client.js.map +1 -1
- package/dist/vite/pages.d.ts +68 -0
- package/dist/vite/plugin.d.ts +10 -0
- package/dist/vite/static.d.ts +13 -2
- package/dist/vite.js +269 -75
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/setto-client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setto-client.js","sources":["../src/lib/languages.ts","../src/lib/supabase.ts","../src/modules/forms/api.ts","../src/lib/api.ts","../src/lib/nested-resource.ts","../src/lib/i18n-store.ts","../src/lib/language-routing.ts","../src/lib/image-paths.ts","../src/lib/asset-store.ts","../src/lib/theme-store.ts","../src/pages/manifest.ts","../src/lib/page-store.ts","../src/pages/bundled.ts","../src/lib/use-site-access.ts","../src/lib/visitor-view.ts","../src/chrome.tsx","../src/lib/urls.ts","../src/edit-mode/constants.ts","../src/edit-mode/document-layout.ts","../src/edit-mode/setto-mark.tsx","../src/edit-mode/toolbar-fallback.tsx","../src/edit-mode/mount.tsx","../src/modules/chat/settings.ts","../src/modules/chat/index.ts","../src/provider.tsx","../src/LanguageSwitcher.tsx","../src/guest-edit.tsx","../src/lib/link-context.ts","../src/edit-mode/link-action-chip.tsx","../src/lib/place-caret-at-point.ts","../src/lib/use-coarse-pointer.ts","../src/T.tsx","../src/section-context.tsx","../src/theme-target-utils.ts","../src/use-section-theme.ts","../src/SettoSection.tsx","../src/SettoBlock.tsx","../src/edit-mode/floating-popover.tsx","../src/SettoIcon.tsx","../src/lib/media.ts","../src/lib/optimized-image.ts","../src/SettoImage.tsx","../src/SettoRepeater.tsx","../src/pages/SettoPage.tsx","../src/blog/contract.ts","../src/blog/data.ts","../src/blog/strings.ts","../src/blog/render.tsx","../src/blog/SettoBlog.tsx","../src/modules/forms/fields.ts","../src/modules/forms/SettoForm.tsx","../src/modules/forms/index.ts","../src/modules/domain/index.ts","../src/modules/index.ts","../src/SettoVideo.tsx","../src/lib/map-location.ts","../src/SettoMap.tsx","../src/SettoAnimation.tsx","../src/edit-mode/auth-gate.tsx","../src/admin/styles.ts","../src/admin/App.tsx","../src/block-tree/registry.ts","../src/block-tree/validate.ts","../src/block-tree/SettoBlockTree.tsx","../src/block-tree/extract-keys.ts"],"sourcesContent":["/**\n * Which languages a site speaks, and which one a visitor is reading.\n *\n * Every Setto site has been Norwegian-only, not because the machinery could\n * not hold more — `I18nStore` has taken a language argument since the\n * beginning and the publish path already serialises one bundle per language —\n * but because nothing ever told a site it had a second one, and nothing gave a\n * visitor a way to ask for it.\n *\n * The choice is deliberately per browser and not per URL. A path prefix\n * (`/en/…`) is the better answer for search engines and the wrong answer for\n * this pipeline today: every site is a single-page app whose routes the agent\n * writes, and quietly doubling every route is not a thing to do to thirteen\n * live sites in one release. Recorded here rather than hidden: when these\n * sites want to be found in two languages, this is the decision to revisit.\n */\n\nconst STORAGE_KEY = 'setto.lang';\n\n/** Norwegian is the floor: every site has it, and it is what the agent writes. */\nexport const DEFAULT_LANGUAGE = 'no';\n\n/**\n * Language names in their own language, because a switcher that says\n * \"Norwegian\" to a Norwegian is written for the wrong person.\n */\nconst ENDONYMS: Record<string, string> = {\n no: 'Norsk',\n nb: 'Norsk',\n nn: 'Nynorsk',\n en: 'English',\n sv: 'Svenska',\n da: 'Dansk',\n de: 'Deutsch',\n fr: 'Français',\n es: 'Español',\n it: 'Italiano',\n nl: 'Nederlands',\n pl: 'Polski',\n pt: 'Português',\n fi: 'Suomi',\n is: 'Íslenska',\n lt: 'Lietuvių',\n uk: 'Українська',\n ru: 'Русский',\n ar: 'العربية',\n tr: 'Türkçe',\n so: 'Soomaali',\n ti: 'ትግርኛ',\n th: 'ไทย',\n vi: 'Tiếng Việt',\n zh: '中文',\n ja: '日本語',\n};\n\n/** «Norsk», or the tag itself when we have no name for it. */\nexport function languageName(tag: string): string {\n const base = tag.toLowerCase().split('-')[0] ?? tag;\n return ENDONYMS[base] ?? tag.toUpperCase();\n}\n\n/**\n * The languages this site actually speaks, primary first, no duplicates.\n *\n * A configured list that forgets to include the primary language is a site\n * whose own copy is unreachable, so the primary is inserted rather than\n * trusted.\n */\nexport function siteLanguages(\n configured: readonly string[] | undefined,\n primary: string = DEFAULT_LANGUAGE,\n): string[] {\n const out = [primary];\n for (const tag of configured ?? []) {\n if (tag && !out.includes(tag)) out.push(tag);\n }\n return out;\n}\n\n/** What this browser last chose here, if anything. */\nexport function readStoredLanguage(): string | null {\n try {\n return window.localStorage.getItem(STORAGE_KEY);\n } catch {\n // A browser with site data blocked still gets a language, just not a memory.\n return null;\n }\n}\n\nexport function storeLanguage(tag: string): void {\n try {\n window.localStorage.setItem(STORAGE_KEY, tag);\n } catch {\n // Same.\n }\n}\n\n/**\n * The language to open in.\n *\n * Their own previous choice first — it is the only signal that is definitely\n * about this site. Then what the browser asks for, matched on the base tag so\n * `en-GB` finds `en`. Then the site's primary, which is always present.\n *\n * Note what is *not* here: no geolocation, and no guessing from a domain. A\n * Norwegian abroad is still Norwegian, and a site that decides it knows better\n * than `Accept-Language` is a site people fight with.\n */\nexport function pickInitialLanguage(\n available: readonly string[],\n browserLanguages: readonly string[] = typeof navigator === 'undefined'\n ? []\n : (navigator.languages ?? [navigator.language]),\n stored: string | null = null,\n): string {\n const fallback = available[0] ?? DEFAULT_LANGUAGE;\n if (stored && available.includes(stored)) return stored;\n\n for (const wanted of browserLanguages) {\n const base = wanted.toLowerCase().split('-')[0];\n if (!base) continue;\n const hit = available.find((tag) => tag.toLowerCase().split('-')[0] === base);\n if (hit) return hit;\n /*\n * Norwegian is three tags for one language. A browser asking for `nb`\n * should be given `no`, which is what every Setto bundle is named, or the\n * site opens in English for a Norwegian.\n */\n if ((base === 'nb' || base === 'nn' || base === 'no') && available.includes('no')) {\n return 'no';\n }\n }\n return fallback;\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\n\nexport interface SupabaseConnection {\n url: string;\n anonKey: string;\n}\n\n/**\n * Where supabase-js keeps the session for this project, in `localStorage`.\n * Per project URL so a host site with a Supabase of its own never collides,\n * and so local `supabase start` sessions stay apart from production ones.\n */\nexport function supabaseStorageKey(url: string): string {\n return `setto-auth-${url}`;\n}\n\n/**\n * One client per Supabase project, fetched only when somebody needs it.\n *\n * supabase-js is about 200 kB of the bundle every visitor of every site\n * downloaded, and a visitor is never signed in: the client was created, read\n * an empty `localStorage` and did nothing else for the whole visit. So the\n * library is a separate chunk now, loaded the first time something asks —\n * a stored session, the `/setto` page, a sign-in arriving in the URL, an\n * editor's chrome, or the visitor chat joining its Realtime channel.\n */\nexport interface SupabaseLoader {\n /** The client once it has loaded, otherwise null. */\n readonly client: SupabaseClient | null;\n /** True while the library is being fetched. */\n readonly loading: boolean;\n /**\n * The client, loading it on first call. Memoised: every caller gets the\n * same client. A failed fetch (a stale chunk after a deploy, a dropped\n * connection) rejects, and the next call tries again.\n */\n load(): Promise<SupabaseClient>;\n}\n\nconst loaders = new Map<string, SupabaseLoader>();\n\nexport function supabaseLoader(config: SupabaseConnection): SupabaseLoader {\n const key = `${config.url}\\n${config.anonKey}`;\n const existing = loaders.get(key);\n if (existing) return existing;\n\n let client: SupabaseClient | null = null;\n let pending: Promise<SupabaseClient> | null = null;\n\n const loader: SupabaseLoader = {\n get client() {\n return client;\n },\n get loading() {\n return pending !== null && client === null;\n },\n load() {\n if (client) return Promise.resolve(client);\n pending ??= import('@supabase/supabase-js').then(\n ({ createClient }) => {\n client = createClient(config.url, config.anonKey, {\n auth: {\n persistSession: true,\n autoRefreshToken: true,\n storageKey: supabaseStorageKey(config.url),\n },\n });\n return client;\n },\n (error: unknown) => {\n pending = null;\n throw error;\n },\n );\n return pending;\n },\n };\n loaders.set(key, loader);\n return loader;\n}\n\n/** The client for this project, loading supabase-js on first call. */\nexport function loadSupabase(config: SupabaseConnection): Promise<SupabaseClient> {\n return supabaseLoader(config).load();\n}\n\n/** True when `localStorage` holds anything supabase-js wrote for this project. */\nexport function hasStoredSession(url: string, storage: Pick<Storage, 'length' | 'key'> | null): boolean {\n if (!storage) return false;\n const prefix = supabaseStorageKey(url);\n try {\n for (let i = 0; i < storage.length; i += 1) {\n if (storage.key(i)?.startsWith(prefix)) return true;\n }\n } catch {\n // Storage that throws (blocked cookies, private mode) holds no session.\n }\n return false;\n}\n\n/**\n * A sign-in arriving in the address: the implicit-flow fragment GoTrue and\n * setto-server's handoffs append (`#access_token=…&refresh_token=…`, which is\n * also how the support account's «Rediger» lands), an auth error, or an\n * invite/recovery callback. supabase-js reads and clears these itself\n * (`detectSessionInUrl`), so the client must exist on such a page.\n */\nexport function hasAuthInUrl(hash: string, search: string): boolean {\n const fragment = new URLSearchParams(hash.replace(/^#/, ''));\n if (\n fragment.has('access_token') ||\n fragment.has('refresh_token') ||\n fragment.has('error_description') ||\n fragment.has('error_code')\n ) {\n return true;\n }\n const query = new URLSearchParams(search);\n return query.has('error_description') || query.has('error_code');\n}\n\n/**\n * Whether this page load can have a signed-in person on it, and so needs\n * supabase-js from the start: a session stored for this project, the\n * `/setto` page (the sign-in and the dashboard), or a sign-in in the URL.\n * Anything else is a visitor, whose answer — no session — is known without it.\n */\nexport function needsSupabaseAtStart(\n config: SupabaseConnection,\n env: {\n pathname: string;\n hash: string;\n search: string;\n storage: Pick<Storage, 'length' | 'key'> | null;\n },\n): boolean {\n // The same test as `isAdminRoute` in urls.ts, which decides what `/setto` renders.\n if (env.pathname.startsWith('/setto')) return true;\n if (hasAuthInUrl(env.hash, env.search)) return true;\n return hasStoredSession(config.url, env.storage);\n}\n\n/** `localStorage`, or null where reading it throws. */\nexport function browserStorage(): Storage | null {\n try {\n return typeof window === 'undefined' ? null : window.localStorage;\n } catch {\n return null;\n }\n}\n","import type { ApiRequest } from '../../lib/api';\n\n/** The forms row of `site_module_settings` as the server reports it, with the defaults resolved. */\nexport interface FormSettings {\n /** Addresses the owner chose; empty means \"use the defaults\". */\n recipients: string[];\n /** The site owners' addresses — where mail goes when `recipients` is empty. */\n defaultRecipients: string[];\n /** What a submission would be sent to right now. */\n effectiveRecipients: string[];\n updatedAt: string | null;\n}\n\n/** A row of `form_submissions`, read through Supabase RLS in the dashboard. */\nexport interface FormSubmissionRow {\n id: string;\n site_id: string;\n form_id: string;\n data: Record<string, unknown>;\n labels: Record<string, string>;\n field_order: string[];\n meta: {\n page?: string;\n title?: string;\n referer?: string;\n userAgent?: string;\n ip?: string;\n /** Milliseconds from the visitor's first interaction to submit; absent for API clients. */\n elapsed?: number;\n recipientSource?: 'settings' | 'owners' | 'none';\n };\n email_status: 'pending' | 'sent' | 'failed' | 'skipped';\n email_error: string | null;\n recipients: string[];\n created_at: string;\n}\n\nexport function createFormsApi(request: ApiRequest) {\n const base = (siteId: string) => `/sites/${encodeURIComponent(siteId)}/forms`;\n return {\n getSettings(siteId: string): Promise<FormSettings> {\n return request<FormSettings>(`${base(siteId)}/settings`, {}, 'getFormSettings');\n },\n saveSettings(siteId: string, recipients: string[]): Promise<FormSettings> {\n return request<FormSettings>(\n `${base(siteId)}/settings`,\n { method: 'PUT', body: { recipients } },\n 'saveFormSettings',\n );\n },\n deleteSubmission(siteId: string, id: string): Promise<void> {\n return request<void>(\n `${base(siteId)}/submissions/${encodeURIComponent(id)}`,\n { method: 'DELETE' },\n 'deleteSubmission',\n );\n },\n };\n}\n\nexport type FormsApi = ReturnType<typeof createFormsApi>;\n","import type { SupabaseClient } from '@supabase/supabase-js';\nimport { createFormsApi } from '../modules/forms/api';\nimport type { ContentFile, PublishFile, PublishResult } from '../types';\nimport type { AssetDraft } from './asset-store';\n\n/**\n * The client a call should read its token from: the one already loaded, the\n * one being loaded, or null when nobody on this page has needed supabase-js\n * yet — which means nobody is signed in (see `lib/supabase.ts`).\n */\nexport type SupabaseSource = SupabaseClient | (() => Promise<SupabaseClient | null>);\n\n/** Returns a fresh access token from the current Supabase session. */\nasync function bearer(source: SupabaseSource): Promise<string> {\n const sb = typeof source === 'function' ? await source() : source;\n if (!sb) throw new Error('not_authenticated');\n const { data } = await sb.auth.getSession();\n const token = data.session?.access_token;\n if (!token) throw new Error('not_authenticated');\n return token;\n}\n\nasync function parseJson<T>(res: Response): Promise<T> {\n const contentType = res.headers.get('content-type') ?? '';\n if (!contentType.includes('application/json')) {\n const text = await res.text();\n throw new Error(\n `expected JSON from ${res.url}, got ${contentType || 'unknown content-type'}: ${text.slice(0, 120)}`,\n );\n }\n return (await res.json()) as T;\n}\n\nasync function asError(res: Response, fallback: string): Promise<Error> {\n try {\n const body = await parseJson<{ error?: unknown; detail?: unknown }>(res);\n const detail =\n body.error != null\n ? String(body.error)\n : body.detail != null\n ? String(body.detail)\n : fallback;\n return new Error(`${fallback}: ${res.status} ${detail}`);\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('expected JSON')) {\n return new Error(`${fallback}: ${res.status} ${err.message}`);\n }\n return new Error(`${fallback}: ${res.status}`);\n }\n}\n\n/**\n * One authenticated JSON call against setto-server. Modules build their api\n * segment on this (see `modules/forms/api.ts`) rather than on `fetch`, so\n * bearer handling and error shaping stay in one place.\n */\nexport type ApiRequest = <T>(\n path: string,\n init?: { method?: string; body?: unknown },\n label?: string,\n) => Promise<T>;\n\nexport function createApi(args: { apiUrl: string; supabase: SupabaseSource }) {\n // Public chat already normalizes this boundary. Authenticated dashboard calls\n // must do the same: a configured `https://api.setto.no/` otherwise turns\n // `/sites/...` into `//sites/...`, which some proxies reject before Hono.\n const apiUrl = args.apiUrl.replace(/\\/+$/, '');\n const { supabase } = args;\n\n const request: ApiRequest = async <T,>(\n path: string,\n init: { method?: string; body?: unknown } = {},\n label = `${init.method ?? 'GET'} ${path}`,\n ): Promise<T> => {\n const token = await bearer(supabase);\n const res = await fetch(`${apiUrl}${path}`, {\n method: init.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n body: init.body !== undefined ? JSON.stringify(init.body) : undefined,\n });\n if (!res.ok) throw await asError(res, `${label} failed`);\n if (res.status === 204) return undefined as T;\n return parseJson<T>(res);\n };\n\n return {\n request,\n forms: createFormsApi(request),\n\n async getContent(siteId: string): Promise<{ files: ContentFile[] }> {\n const token = await bearer(supabase);\n const res = await fetch(`${apiUrl}/sites/${encodeURIComponent(siteId)}/content`, {\n headers: { Authorization: `Bearer ${token}` },\n });\n if (!res.ok) throw await asError(res, 'getContent failed');\n return parseJson<{ files: ContentFile[] }>(res);\n },\n\n async publish(\n siteId: string,\n files: PublishFile[],\n options?: { message?: string; assets?: AssetDraft[] },\n ): Promise<PublishResult> {\n const token = await bearer(supabase);\n const assets = options?.assets ?? [];\n\n if (assets.length === 0) {\n const res = await fetch(`${apiUrl}/sites/${encodeURIComponent(siteId)}/publish`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({ files, message: options?.message }),\n });\n if (!res.ok) throw await asError(res, 'publish failed');\n return parseJson<PublishResult>(res);\n }\n\n const form = new FormData();\n form.append(\n 'manifest',\n JSON.stringify({\n files,\n assets: assets.map((a) => ({ path: a.repoPath })),\n message: options?.message,\n }),\n );\n assets.forEach((asset, index) => {\n form.append(`asset_${index}`, asset.file, asset.file.name);\n });\n\n const res = await fetch(`${apiUrl}/sites/${encodeURIComponent(siteId)}/publish`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: form,\n });\n if (!res.ok) throw await asError(res, 'publish failed');\n return parseJson<PublishResult>(res);\n },\n\n async expireStaleDeployments(siteId: string): Promise<{ expired: number }> {\n const token = await bearer(supabase);\n const res = await fetch(\n `${apiUrl}/sites/${encodeURIComponent(siteId)}/deployments/expire-stale`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n },\n );\n if (!res.ok) throw await asError(res, 'expireStaleDeployments failed');\n return parseJson<{ expired: number }>(res);\n },\n\n async cancelDeployment(siteId: string, deploymentId: string): Promise<void> {\n const token = await bearer(supabase);\n const res = await fetch(\n `${apiUrl}/sites/${encodeURIComponent(siteId)}/deployments/${encodeURIComponent(deploymentId)}/cancel`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n },\n );\n if (!res.ok) throw await asError(res, 'cancelDeployment failed');\n },\n\n /** Request a password-reset email (link goes via setto-server, then site /setto). */\n async requestPasswordReset(siteId: string, email: string): Promise<void> {\n const res = await fetch(\n `${apiUrl}/sites/${encodeURIComponent(siteId)}/auth/password-reset`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n },\n );\n if (!res.ok) throw await asError(res, 'requestPasswordReset failed');\n },\n };\n}\n\nexport type SettoApi = ReturnType<typeof createApi>;\n","/*\n * Segments that name the object machinery rather than content.\n *\n * The keys these helpers walk come from locale JSON, and `JSON.parse` keeps\n * `\"__proto__\"` as an ordinary own key, so a locale file can carry one. Walked\n * with a plain `obj[part]`, `__proto__` lands on `Object.prototype` and\n * `constructor` on `Object`: a removal of `__proto__.toString` would delete a\n * method every object on the page shares, in the editor's browser. No Setto\n * key is ever named like this, so they are refused outright, and the walk\n * below follows own properties only for the same reason.\n */\nconst UNSAFE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);\n\n/** True for a single key segment that may be read or written. */\nexport function isSafeSegment(segment: string): boolean {\n return !UNSAFE_SEGMENTS.has(segment);\n}\n\n/** True when every segment of a dotted key may be read or written. */\nexport function isSafeKey(key: string): boolean {\n return key.split('.').every(isSafeSegment);\n}\n\n/** Reads a dotted key path from a nested object. */\nexport function getNested(obj: unknown, key: string): unknown {\n if (!obj || typeof obj !== 'object') return undefined;\n if (!isSafeKey(key)) return undefined;\n const parts = key.split('.');\n let cur: unknown = obj;\n for (const part of parts) {\n if (!cur || typeof cur !== 'object') return undefined;\n if (!Object.prototype.hasOwnProperty.call(cur, part)) return undefined;\n cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\n/** Sets a dotted key path on a nested object (mutates in place). */\nexport function setNested(obj: Record<string, unknown>, key: string, value: unknown): void {\n if (!isSafeKey(key)) return;\n const parts = key.split('.');\n let cur = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n const next = Object.prototype.hasOwnProperty.call(cur, part) ? cur[part] : undefined;\n if (!next || typeof next !== 'object') {\n cur[part] = {};\n }\n cur = cur[part] as Record<string, unknown>;\n }\n cur[parts[parts.length - 1]!] = value;\n}\n\n/**\n * Deletes a dotted key path from a nested object (mutates in place).\n *\n * Parents left empty by the deletion go too. Deleting the last leaf of\n * `form.kontakt.fields.3` used to leave `\"3\": {}` behind, which published as\n * a phantom list item and rendered as an empty field.\n */\nexport function deleteNested(obj: Record<string, unknown>, key: string): void {\n if (!isSafeKey(key)) return;\n const parts = key.split('.');\n const chain: Record<string, unknown>[] = [obj];\n let cur: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (!Object.prototype.hasOwnProperty.call(cur, part)) return;\n const next = cur[part];\n if (!next || typeof next !== 'object') return;\n cur = next as Record<string, unknown>;\n chain.push(cur);\n }\n delete cur[parts[parts.length - 1]!];\n for (let i = chain.length - 1; i > 0; i--) {\n if (Object.keys(chain[i]!).length > 0) break;\n delete chain[i - 1]![parts[i - 1]!];\n }\n}\n\n/** Collects all dotted keys under a prefix from a nested object. */\nexport function collectKeysUnder(obj: unknown, prefix: string): string[] {\n const base = getNested(obj, prefix);\n if (!base || typeof base !== 'object' || Array.isArray(base)) return [];\n return Object.keys(base as Record<string, unknown>).filter(isSafeSegment).sort(compareListKeys);\n}\n\nexport function compareListKeys(a: string, b: string): number {\n const na = Number(a);\n const nb = Number(b);\n if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;\n return a.localeCompare(b);\n}\n","import type { i18n as I18nType } from 'i18next';\nimport {\n collectKeysUnder,\n compareListKeys,\n deleteNested,\n getNested,\n isSafeKey,\n isSafeSegment,\n} from './nested-resource';\n\n/**\n * Tracks an in-memory layer of edits on top of a loaded i18next instance.\n *\n * On disk, a site has one JSON file per language under `content_paths`. At\n * runtime, i18next holds those JSONs as resource bundles in\n * `i18n.store.data[lng].translation`.\n *\n * The draft store mutates the resource bundles directly so the page re-renders\n * with the editor's text immediately. When the user publishes, we serialise\n * the merged resource bundles back to JSON and POST them to setto-server.\n */\nexport interface DraftEntry {\n /** Dotted key path, e.g. 'hero.headline'. */\n key: string;\n /** Language code, e.g. 'no'. */\n lng: string;\n /** Value before any edits in this session — used for diff and revert. */\n original: string;\n /** Current draft value. */\n current: string;\n /**\n * The key did not exist before this session (a list item the editor added).\n * Reverting deletes it instead of writing an empty string back, which would\n * leave a blank item on the page.\n */\n created?: boolean;\n /**\n * The key existed and the editor deleted it (a list item they removed).\n * Without this a removal was invisible to the draft count: an editor who\n * only deleted a FAQ entry had nothing to publish.\n */\n removed?: boolean;\n}\n\nexport interface I18nStoreSnapshot {\n /** All edits made in this session, keyed by `${lng}::${key}`. */\n drafts: Map<string, DraftEntry>;\n /** Bumps every time the store changes; React components subscribe to this. */\n version: number;\n}\n\n/** Stable empty snapshot for useSyncExternalStore when the store is not ready. */\nexport const EMPTY_I18N_STORE_SNAPSHOT: I18nStoreSnapshot = {\n drafts: new Map(),\n version: 0,\n};\n\ntype Listener = (snap: I18nStoreSnapshot) => void;\n\nexport class I18nStore {\n private drafts = new Map<string, DraftEntry>();\n private version = 0;\n private listeners = new Set<Listener>();\n /** Stable namespace used by react-i18next defaults. */\n private ns: string;\n private i18n: I18nType;\n /** >0 while a batch is running; consumers are notified once at the end. */\n private batchDepth = 0;\n /** Cached reference — useSyncExternalStore requires referential stability. */\n private cachedSnapshot: I18nStoreSnapshot = {\n drafts: this.drafts,\n version: 0,\n };\n\n constructor(i18n: I18nType, options?: { namespace?: string }) {\n this.i18n = i18n;\n this.ns = options?.namespace ?? 'translation';\n }\n\n snapshot(): I18nStoreSnapshot {\n return this.cachedSnapshot;\n }\n\n /**\n * Put a locale file into i18next as the published baseline.\n *\n * Same reason as `languages`: the editor chrome cannot reach the live\n * i18next instance from its own bundle, and this store already holds it.\n * Deep and overwriting, which is what seeding a baseline means — the file\n * from the repository is the truth, and any draft on top of it lives here,\n * not in i18next.\n */\n addBaselineBundle(lng: string, resources: Record<string, unknown>): void {\n this.i18n.addResourceBundle(lng, this.ns, resources, true, true);\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Returns the current rendered value for a key in a given language,\n * reading through any draft layer.\n */\n get(key: string, lng: string): string {\n const id = `${lng}::${key}`;\n const draft = this.drafts.get(id);\n if (draft) return draft.current;\n return String(this.i18n.getResource(lng, this.ns, key) ?? '');\n }\n\n /** Returns the original (pre-edit) value for a key. */\n original(key: string, lng: string): string {\n const id = `${lng}::${key}`;\n const draft = this.drafts.get(id);\n if (draft) return draft.original;\n return String(this.i18n.getResource(lng, this.ns, key) ?? '');\n }\n\n /**\n * Records an edit. Mutates the live i18next bundle so consumers re-render.\n * If the value is set back to the original, the draft entry is cleared.\n */\n set(key: string, lng: string, value: string): void {\n // `__proto__` and its kin are machinery, never content; see nested-resource.\n if (!isSafeKey(key)) return;\n const id = `${lng}::${key}`;\n const existing = this.drafts.get(id);\n const resource = this.i18n.getResource(lng, this.ns, key) as unknown;\n const original = existing?.original ?? String(resource ?? '');\n const created = existing ? existing.created === true : resource === undefined;\n\n if (value === original && !created) {\n this.drafts.delete(id);\n } else {\n this.drafts.set(id, { key, lng, original, current: value, ...(created ? { created } : {}) });\n }\n\n this.i18n.addResource(lng, this.ns, key, value);\n this.notify();\n }\n\n /**\n * Deletes a key from the bundle. A key that was created this session simply\n * disappears; one that was on disk is kept as a removal draft so the\n * deletion counts as a change and reverts cleanly.\n */\n delete(key: string, lng: string): void {\n if (!isSafeKey(key)) return;\n const id = `${lng}::${key}`;\n const existing = this.drafts.get(id);\n const resource = this.i18n.getResource(lng, this.ns, key) as unknown;\n if (existing?.created) {\n this.drafts.delete(id);\n } else if (existing || resource !== undefined) {\n const original = existing?.original ?? String(resource ?? '');\n this.drafts.set(id, { key, lng, original, current: '', removed: true });\n }\n this.deleteFromBundle(lng, key);\n this.notify();\n }\n\n /** Resets a single draft back to its original value. */\n revert(key: string, lng: string): void {\n const id = `${lng}::${key}`;\n const draft = this.drafts.get(id);\n if (!draft) return;\n this.restore(draft);\n this.drafts.delete(id);\n this.notify();\n }\n\n /** Resets every draft. */\n revertAll(): void {\n for (const draft of this.drafts.values()) this.restore(draft);\n this.drafts.clear();\n this.notify();\n }\n\n /** Marks the current state as the new baseline (after a successful publish). */\n commit(): void {\n this.drafts.clear();\n this.bump();\n }\n\n /** Number of pending draft entries across all languages. */\n size(): number {\n return this.drafts.size;\n }\n\n /** Returns sorted item keys under a list prefix, e.g. `faq.items` → ['1','2',…]. */\n getListKeys(prefix: string, lng: string): string[] {\n const bundle = this.i18n.getResourceBundle(lng, this.ns) as Record<string, unknown> | undefined;\n return collectKeysUnder(bundle, prefix);\n }\n\n /**\n * Adds a new list item under `prefix` with the given field defaults.\n * Adds the same key across all loaded languages.\n */\n addListItem(prefix: string, _lng: string, template: Record<string, string>): string {\n const langs = this.languages(_lng);\n const allKeys = langs.flatMap((l) => this.getListKeys(prefix, l));\n const numeric = allKeys.map(Number).filter((n) => !Number.isNaN(n));\n const nextKey = numeric.length > 0 ? String(Math.max(...numeric) + 1) : '1';\n\n this.batch(() => {\n for (const lang of langs) {\n for (const [field, value] of Object.entries(template)) {\n this.set(`${prefix}.${nextKey}.${field}`, lang, value);\n }\n }\n });\n return nextKey;\n }\n\n /** Removes a list item and all nested keys under `prefix.itemKey` in every language. */\n removeListItem(prefix: string, itemKey: string, _lng: string): void {\n this.batch(() => {\n for (const lang of this.languages(_lng)) {\n for (const leaf of this.leavesUnder(`${prefix}.${itemKey}`, lang)) {\n this.delete(leaf, lang);\n }\n }\n });\n }\n\n /**\n * Moves a list item one step up or down by swapping its values with its\n * neighbour's, in every language. Items keep their numeric keys and the keys\n * keep their order; only the contents trade places. That is what makes the\n * move a set of ordinary drafts — publish, revert and the change count all\n * work without knowing a move happened.\n */\n moveListItem(prefix: string, itemKey: string, direction: -1 | 1, _lng: string): boolean {\n const keys = this.getListKeys(prefix, _lng).sort(compareListKeys);\n const index = keys.indexOf(itemKey);\n const targetIndex = index + direction;\n if (index < 0 || targetIndex < 0 || targetIndex >= keys.length) return false;\n const other = keys[targetIndex]!;\n\n this.batch(() => {\n for (const lang of this.languages(_lng)) {\n const a = `${prefix}.${itemKey}`;\n const b = `${prefix}.${other}`;\n const fieldsA = this.leavesUnder(a, lang).map((k) => k.slice(a.length + 1));\n const fieldsB = this.leavesUnder(b, lang).map((k) => k.slice(b.length + 1));\n const fields = [...new Set([...fieldsA, ...fieldsB])];\n const valuesA = new Map(fields.map((f) => [f, this.valueOrUndefined(`${a}.${f}`, lang)]));\n const valuesB = new Map(fields.map((f) => [f, this.valueOrUndefined(`${b}.${f}`, lang)]));\n for (const f of fields) {\n this.setOrDelete(`${a}.${f}`, lang, valuesB.get(f));\n this.setOrDelete(`${b}.${f}`, lang, valuesA.get(f));\n }\n }\n });\n return true;\n }\n\n /** Re-sorts list keys after removal (optional compaction — not used by default). */\n sortListKeys(prefix: string, lng: string): string[] {\n return this.getListKeys(prefix, lng).sort(compareListKeys);\n }\n\n /**\n * Serialises the full resource bundle per language as it currently looks in\n * i18next (with drafts applied). Used as the payload for /publish.\n *\n * The caller maps language → file path via `sites.content_paths`.\n */\n serialiseBundles(): Record<string, unknown> {\n const langs = this.i18n.languages?.length ? this.i18n.languages : ['no', 'en'];\n const out: Record<string, unknown> = {};\n for (const lng of langs) {\n const bundle = this.i18n.getResourceBundle(lng, this.ns);\n if (bundle) out[lng] = bundle;\n }\n return out;\n }\n\n /** Runs `fn` and notifies consumers once, however many edits it makes. */\n batch(fn: () => void): void {\n this.batchDepth += 1;\n try {\n fn();\n } finally {\n this.batchDepth -= 1;\n }\n if (this.batchDepth === 0) this.notify();\n }\n\n /**\n * Every language this site has content for, in i18next's own order.\n *\n * Public because the editor chrome needs it and cannot get it the usual way:\n * that code runs in a second bundle whose `react-i18next` is a different\n * module instance from the host's, so its `useTranslation` finds no\n * initialised i18next and reports no languages at all. This store is the\n * host's own object, handed across by reference, and it already holds the\n * live instance.\n *\n * Deduplicated, because i18next appends its fallback chain and every caller\n * was doing that itself.\n */\n languages(fallback: string): string[] {\n return this.i18n.languages?.length ? Array.from(new Set(this.i18n.languages)) : [fallback];\n }\n\n private valueOrUndefined(key: string, lng: string): string | undefined {\n const resource = this.i18n.getResource(lng, this.ns, key) as unknown;\n return resource === undefined ? undefined : String(resource);\n }\n\n private setOrDelete(key: string, lng: string, value: string | undefined): void {\n if (value === undefined) {\n if (this.i18n.getResource(lng, this.ns, key) !== undefined) this.delete(key, lng);\n } else {\n this.set(key, lng, value);\n }\n }\n\n /** Every string key under `prefix`, nested to any depth. */\n private leavesUnder(prefix: string, lng: string): string[] {\n const bundle = (this.i18n.getResourceBundle(lng, this.ns) ?? {}) as Record<string, unknown>;\n const node = getNested(bundle, prefix);\n const out: string[] = [];\n const walk = (value: unknown, path: string) => {\n if (value && typeof value === 'object') {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (isSafeSegment(k)) walk(v, `${path}.${k}`);\n }\n } else if (value !== undefined) {\n out.push(path);\n }\n };\n walk(node, prefix);\n return out;\n }\n\n private deleteFromBundle(lng: string, key: string): void {\n const bundle = (this.i18n.getResourceBundle(lng, this.ns) ?? {}) as Record<string, unknown>;\n deleteNested(bundle, key);\n this.i18n.addResourceBundle(lng, this.ns, bundle, true, true);\n }\n\n private restore(draft: DraftEntry): void {\n if (draft.created) {\n this.deleteFromBundle(draft.lng, draft.key);\n } else {\n this.i18n.addResource(draft.lng, this.ns, draft.key, draft.original);\n }\n }\n\n private notify(): void {\n if (this.batchDepth > 0) return;\n // Trigger consumers of useTranslation to re-render. i18next exposes\n // languageChanged for this but a manual emit is simpler and side-effect-free.\n this.i18n.emit('languageChanged', this.i18n.language);\n this.bump();\n }\n\n private bump(): void {\n this.version += 1;\n this.cachedSnapshot = { drafts: this.drafts, version: this.version };\n for (const fn of this.listeners) fn(this.cachedSnapshot);\n }\n}\n","/**\n * The language lives in the URL.\n *\n * It did not, for one release: the choice was kept per browser in\n * `localStorage`, which is invisible to a search engine and unshareable\n * between people. A Norwegian plumber who wants to be found in English cannot\n * be, if the English version has no address. So the primary language stays at\n * the root — `/`, `/priser` — and every other language takes a prefix:\n * `/en`, `/en/priser`.\n *\n * Primary at the root rather than `/no/…` deliberately: every Setto site alive\n * today has its Norwegian pages at the root, they are linked to and indexed\n * there, and moving them would trade a real thing for a tidy one.\n *\n * The routes themselves never learn about this. `BrowserRouter` takes the\n * prefix as its `basename`, so a site's own `/priser` keeps matching whether\n * the visitor is at `/priser` or `/en/priser` — which matters because those\n * routes are written per site by the build agent, and a scheme that required\n * it to think about languages is a scheme that would be got wrong.\n */\n\nimport { DEFAULT_LANGUAGE } from './languages';\n\nexport interface LanguageRoute {\n /** The language this URL is in. */\n language: string;\n /** `''` for the primary language, `/en` otherwise. Feed to `basename`. */\n basename: string;\n /** The path with the prefix removed, always starting with `/`. */\n rest: string;\n}\n\n/*\n * One slash between segments, never two, and never a backslash.\n *\n * Not tidiness: everything this module returns is fed to\n * `window.location.assign` or `replace`, and a path that starts with `//` is\n * not a path to a browser but a protocol-relative URL — `//evil.example/x`\n * leaves the site. The site's SPA fallback serves the app at any address, so\n * `/en//evil.example/x` renders like any other page, and before this the\n * «Norsk» button on it handed the rest, `//evil.example/x`, straight to the\n * browser. Backslashes count too, because a browser reads `/\\evil.example`\n * the same way. Collapsing every run rather than only the leading one keeps\n * the rule simple enough to trust: no output of this module can contain `//`.\n */\nfunction normalise(pathname: string): string {\n const collapsed = `/${pathname}`.replace(/[\\\\/]+/g, '/');\n return collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;\n}\n\n/**\n * The address to navigate to, or null when it would leave this origin.\n *\n * A second lock behind `normalise`: whatever the routing above returns, the\n * language switch and the first-visit redirect only ever go somewhere on the\n * site they started on. Resolved by the URL parser itself rather than by a\n * check on the string, so it agrees with the browser about what the address\n * means.\n */\nexport function sameOriginUrl(target: string, origin: string): string | null {\n try {\n const url = new URL(target, origin);\n return url.origin === origin ? url.href : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the language out of a path.\n *\n * Only a prefix that is a language this site actually speaks counts — a site\n * with a page at `/no` and no Norwegian in its list keeps that page.\n */\nexport function languageFromPath(\n pathname: string,\n languages: readonly string[],\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): LanguageRoute {\n const path = normalise(pathname);\n const first = path.split('/')[1] ?? '';\n\n const match = languages.find(\n (tag) => tag !== primary && tag.toLowerCase() === first.toLowerCase(),\n );\n if (!match) return { language: primary, basename: '', rest: path };\n\n const rest = path.slice(first.length + 1);\n return { language: match, basename: `/${match}`, rest: rest === '' ? '/' : rest };\n}\n\n/** The same page, in another language. */\nexport function pathForLanguage(\n pathname: string,\n target: string,\n languages: readonly string[],\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): string {\n const { rest } = languageFromPath(pathname, languages, primary);\n if (target === primary) return rest;\n return rest === '/' ? `/${target}` : `/${target}${rest}`;\n}\n\n/**\n * Every address this page has, for `hreflang`.\n *\n * Without these a search engine sees two unrelated pages that happen to say\n * similar things, and picks one. `x-default` points at the primary, which is\n * what a reader with no stated preference should land on.\n */\nexport function alternateLinks(\n origin: string,\n pathname: string,\n languages: readonly string[],\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): Array<{ hreflang: string; href: string }> {\n if (languages.length < 2) return [];\n const links = languages.map((tag) => ({\n hreflang: tag,\n href: origin + pathForLanguage(pathname, tag, languages, primary),\n }));\n links.push({\n hreflang: 'x-default',\n href: origin + pathForLanguage(pathname, primary, languages, primary),\n });\n return links;\n}\n\n/**\n * Setto's own routes, which have no language of their own.\n *\n * `/setto` is the editor: the customer's back office, in the customer's\n * language, at a fixed address that the chrome navigates to absolutely. A\n * visitor whose browser prefers English must not be bounced to `/en/setto`,\n * where `isAdminRoute()` would no longer recognise it and the site would\n * render instead of the sign-in.\n */\nfunction isReservedPath(pathname: string): boolean {\n const path = normalise(pathname);\n return path === '/setto' || path.startsWith('/setto/');\n}\n\n/**\n * Where a first-time visitor should be sent, or null to leave them alone.\n *\n * Only ever from the unprefixed root towards a prefix, only when the browser\n * asks for a language this site speaks and the visitor has expressed no\n * preference of their own here before. One direction only: a redirect that can\n * send `/en` back to `/` is a redirect that can loop, and somebody who has\n * clicked «Norsk» on an English page must not be bounced back to English on\n * their next click.\n */\nexport function redirectForVisitor(\n pathname: string,\n languages: readonly string[],\n browserLanguages: readonly string[],\n stored: string | null,\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): string | null {\n if (languages.length < 2) return null;\n if (isReservedPath(pathname)) return null;\n\n const current = languageFromPath(pathname, languages, primary);\n // Already somewhere explicit. Their address wins over their browser.\n if (current.basename !== '') return null;\n // They have chosen here before; that choice is theirs to keep.\n if (stored) {\n return stored !== primary && languages.includes(stored)\n ? pathForLanguage(pathname, stored, languages, primary)\n : null;\n }\n\n for (const wanted of browserLanguages) {\n const base = wanted.toLowerCase().split('-')[0];\n if (!base) continue;\n if (base === primary.toLowerCase().split('-')[0]) return null;\n /*\n * Norwegian is three tags for one language; a browser asking for `nb`\n * against a `no` site is already home and must not be sent anywhere.\n */\n const norwegian = ['no', 'nb', 'nn'];\n if (norwegian.includes(base) && norwegian.includes(primary.toLowerCase())) return null;\n\n const hit = languages.find((tag) => tag.toLowerCase().split('-')[0] === base);\n if (hit && hit !== primary) return pathForLanguage(pathname, hit, languages, primary);\n }\n return null;\n}\n","/** GitHub repo directory for editor-uploaded images. */\nexport const SETTO_IMAGE_REPO_DIR = 'public/images/setto';\n\n/** Public URL prefix served by the host site. */\nexport const SETTO_IMAGE_URL_PREFIX = '/images/setto';\n\nconst MIME_EXT: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/svg+xml': 'svg',\n};\n\nexport function extensionFromMime(mime: string): string {\n return MIME_EXT[mime] ?? 'bin';\n}\n\n/** Builds repo + public paths for a newly uploaded Setto image. */\nexport function generateSettoImagePaths(srcKey: string, file: File): {\n repoPath: string;\n publicPath: string;\n} {\n const ext = extensionFromMime(file.type);\n const slug = srcKey.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '') || 'image';\n const name = `${slug}-${Date.now()}.${ext}`;\n return {\n repoPath: `${SETTO_IMAGE_REPO_DIR}/${name}`,\n publicPath: `${SETTO_IMAGE_URL_PREFIX}/${name}`,\n };\n}\n\n/** Returns true when `path` matches an exact entry or a directory prefix entry. */\nexport function isContentPathAllowed(path: string, allowed: string[]): boolean {\n for (const entry of allowed) {\n if (entry.endsWith('/')) {\n if (path.startsWith(entry)) return true;\n } else if (path === entry) {\n return true;\n }\n }\n return false;\n}\n","import { SETTO_IMAGE_REPO_DIR } from './image-paths';\n\nexport interface AssetDraft {\n /** i18n key for the image src, e.g. `hero.illustrationSrc`. */\n srcKey: string;\n /** GitHub repo path, e.g. `public/images/setto/hero-illustration-123.jpg`. */\n repoPath: string;\n /** Public URL path, e.g. `/images/setto/hero-illustration-123.jpg`. */\n publicPath: string;\n /** Src path before this upload (for revert). */\n originalPublicPath: string;\n /** Raw file bytes — published as binary via multipart, not base64 JSON. */\n file: File;\n /** Object URL for in-session preview. */\n previewUrl: string;\n}\n\nexport interface AssetStoreSnapshot {\n drafts: Map<string, AssetDraft>;\n version: number;\n}\n\nexport const EMPTY_ASSET_STORE_SNAPSHOT: AssetStoreSnapshot = {\n drafts: new Map(),\n version: 0,\n};\n\ntype Listener = (snap: AssetStoreSnapshot) => void;\n\nexport class AssetStore {\n private drafts = new Map<string, AssetDraft>();\n private version = 0;\n private listeners = new Set<Listener>();\n private cachedSnapshot: AssetStoreSnapshot = {\n drafts: this.drafts,\n version: 0,\n };\n\n snapshot(): AssetStoreSnapshot {\n return this.cachedSnapshot;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** Returns a preview URL if a draft exists for this src key. */\n getPreviewUrl(srcKey: string): string | null {\n return this.drafts.get(srcKey)?.previewUrl ?? null;\n }\n\n async set(args: {\n srcKey: string;\n originalPublicPath: string;\n repoPath: string;\n publicPath: string;\n file: File;\n }): Promise<void> {\n const existing = this.drafts.get(args.srcKey);\n if (existing) URL.revokeObjectURL(existing.previewUrl);\n\n const previewUrl = URL.createObjectURL(args.file);\n this.drafts.set(args.srcKey, {\n srcKey: args.srcKey,\n repoPath: args.repoPath,\n publicPath: args.publicPath,\n originalPublicPath: args.originalPublicPath,\n file: args.file,\n previewUrl,\n });\n this.bump();\n }\n\n revert(srcKey: string): string | null {\n const draft = this.drafts.get(srcKey);\n if (!draft) return null;\n URL.revokeObjectURL(draft.previewUrl);\n const original = draft.originalPublicPath;\n this.drafts.delete(srcKey);\n this.bump();\n return original;\n }\n\n revertAll(): void {\n for (const draft of this.drafts.values()) {\n URL.revokeObjectURL(draft.previewUrl);\n }\n this.drafts.clear();\n this.bump();\n }\n\n commit(): void {\n this.revertAll();\n }\n\n size(): number {\n return this.drafts.size;\n }\n\n pendingAssets(): AssetDraft[] {\n return Array.from(this.drafts.values());\n }\n\n static isValidRepoPath(path: string): boolean {\n return path.startsWith(`${SETTO_IMAGE_REPO_DIR}/`);\n }\n\n private bump(): void {\n this.version += 1;\n this.cachedSnapshot = { drafts: this.drafts, version: this.version };\n for (const fn of this.listeners) fn(this.cachedSnapshot);\n }\n}\n","/** Section colour theme — keyed by section id, then colour token. */\nexport type SectionsTheme = Record<string, Record<string, string>>;\n\nexport interface ThemeDraftEntry {\n sectionId: string;\n field: string;\n original: string;\n current: string;\n}\n\nexport interface ThemeStoreSnapshot {\n drafts: Map<string, ThemeDraftEntry>;\n version: number;\n}\n\nexport const EMPTY_THEME_STORE_SNAPSHOT: ThemeStoreSnapshot = {\n drafts: new Map(),\n version: 0,\n};\n\ntype Listener = (snap: ThemeStoreSnapshot) => void;\n\nexport class ThemeStore {\n private data: SectionsTheme;\n private baseline: SectionsTheme;\n private drafts = new Map<string, ThemeDraftEntry>();\n private version = 0;\n private listeners = new Set<Listener>();\n private cachedSnapshot: ThemeStoreSnapshot = {\n drafts: this.drafts,\n version: 0,\n };\n\n constructor(initial: SectionsTheme) {\n this.data = structuredClone(initial);\n this.baseline = structuredClone(initial);\n }\n\n snapshot(): ThemeStoreSnapshot {\n return this.cachedSnapshot;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n getSection(sectionId: string): Record<string, string> {\n return this.data[sectionId] ?? {};\n }\n\n get(sectionId: string, field: string): string {\n return this.data[sectionId]?.[field] ?? '';\n }\n\n set(sectionId: string, field: string, value: string): void {\n const id = `${sectionId}::${field}`;\n const original =\n this.drafts.get(id)?.original ??\n this.baseline[sectionId]?.[field] ??\n '';\n\n if (!this.data[sectionId]) this.data[sectionId] = {};\n this.data[sectionId][field] = value;\n\n if (value === original) {\n this.drafts.delete(id);\n } else {\n this.drafts.set(id, { sectionId, field, original, current: value });\n }\n this.bump();\n }\n\n /** Replace baseline from GitHub without creating drafts. */\n loadBaseline(next: SectionsTheme): void {\n this.data = structuredClone(next);\n this.baseline = structuredClone(next);\n this.drafts.clear();\n this.bump();\n }\n\n /** Resets every draft back to its original value. */\n revertAll(): void {\n for (const draft of this.drafts.values()) {\n if (!this.data[draft.sectionId]) this.data[draft.sectionId] = {};\n this.data[draft.sectionId]![draft.field] = draft.original;\n }\n this.drafts.clear();\n this.bump();\n }\n\n commit(): void {\n this.baseline = structuredClone(this.data);\n this.drafts.clear();\n this.bump();\n }\n\n size(): number {\n return this.drafts.size;\n }\n\n serialise(): SectionsTheme {\n return structuredClone(this.data);\n }\n\n private bump(): void {\n this.version += 1;\n this.cachedSnapshot = { drafts: this.drafts, version: this.version };\n for (const fn of this.listeners) fn(this.cachedSnapshot);\n }\n}\n","/**\n * The shape of a site: which pages it has, which sections each page shows and\n * in what order, and what the menu and footer link to.\n *\n * Data rather than TSX, because the owner has to be able to change it. A page\n * written as `<Hero /><Services /><Contact />` can only be reordered by someone\n * who can edit code, so moving a section up, hiding it for the summer or adding\n * a «Vilkår» page used to mean a developer. Kept in\n * `src/content/pages.json`, which the inline editor publishes like any other\n * content file.\n *\n * Nothing is ever deleted from here. «Remove» hides: a section, a page or a\n * menu link that is hidden keeps its place and its text, and showing it again\n * puts it back exactly as it was. The owner asked for undo, and a hidden entry\n * is undo that survives a publish.\n *\n * Every function below is pure and returns a new manifest, so a draft can be\n * compared with its baseline and a failed operation leaves nothing half-done.\n */\n\nexport const PAGES_MANIFEST_VERSION = 1;\n\n/** Where the manifest lives in a site repository. */\nexport const PAGES_PATH = 'src/content/pages.json';\n\n/**\n * Sections Setto can render on its own, without code from the site.\n *\n * `text` is a heading, an optional intro and a list of paragraphs with\n * optional headings: enough for terms, privacy, an «about» page. It is what\n * lets Pixel add a «Vilkår» page in the chat instead of in a sandbox.\n *\n * `blog` is the blog (R24): the list of posts on its page, and a single post\n * at `<page path>/<slug>` — the one page whose path has room below it. At\n * most one per site, and never on the front page, which would swallow every\n * address. `blog-latest` is a band of the newest posts, for the front page.\n * Both read the posts the site's build bundles (`SettoConfig.blog`).\n */\nexport const BUILTIN_SECTION_TYPES = ['text', 'blog', 'blog-latest'] as const;\nexport type BuiltinSectionType = (typeof BUILTIN_SECTION_TYPES)[number];\n\nexport interface PageSection {\n /** Unique across the whole site: it is also the theme id and the anchor. */\n id: string;\n /** A built-in section. Absent means a component the site registers. */\n type?: BuiltinSectionType;\n hidden?: boolean;\n /** What the editor calls it («Tjenester»). Falls back to the id. */\n label?: string;\n}\n\nexport interface PageEntry {\n id: string;\n /** `/`, `/vilkar`. Never under `/setto`, which is the editor's. */\n path: string;\n /** Locale key for the page's name, used by the menu and the tab title. */\n titleKey: string;\n hidden?: boolean;\n sections: PageSection[];\n}\n\nexport interface MenuItem {\n id: string;\n /** `/vilkar`, `/#tjenester`, or an absolute `https://` link. */\n href: string;\n labelKey: string;\n hidden?: boolean;\n}\n\nexport type MenuList = 'menu' | 'footer';\n\nexport interface PagesManifest {\n version: typeof PAGES_MANIFEST_VERSION;\n pages: PageEntry[];\n menu: MenuItem[];\n footer: MenuItem[];\n}\n\nconst ID = /^[a-z0-9][a-z0-9-]{0,62}$/;\n/*\n * A blog post's slug, the same rule as `isValidBlogSlug` in\n * `../blog/contract.ts` (a test holds them together). Written out rather than\n * imported so this file stays self-contained: setto-agent vendors it whole.\n */\nconst POST_SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst PATH = /^\\/(?:[a-z0-9][a-z0-9-]*(?:\\/[a-z0-9][a-z0-9-]*)*)?$/;\n\nexport interface ManifestIssue {\n at: string;\n message: string;\n}\n\nexport type ManifestParse =\n | { ok: true; manifest: PagesManifest }\n | { ok: false; issues: ManifestIssue[] };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Check a manifest from disk, from the network or from a model.\n *\n * Strict on what would break a page — duplicate ids, a path the router cannot\n * hold, a section type nothing renders — and silent about fields it does not\n * know, so a newer editor's manifest still renders on an older site.\n */\nexport function parseManifest(input: unknown): ManifestParse {\n const issues: ManifestIssue[] = [];\n if (!isRecord(input)) return { ok: false, issues: [{ at: '$', message: 'not an object' }] };\n if (input.version !== PAGES_MANIFEST_VERSION) {\n issues.push({ at: 'version', message: `expected ${PAGES_MANIFEST_VERSION}` });\n }\n\n const pages: PageEntry[] = [];\n const pageIds = new Set<string>();\n const paths = new Set<string>();\n const sectionIds = new Set<string>();\n const rawPages = Array.isArray(input.pages) ? input.pages : null;\n if (!rawPages) issues.push({ at: 'pages', message: 'must be a list' });\n\n (rawPages ?? []).forEach((raw, i) => {\n const at = `pages[${i}]`;\n if (!isRecord(raw)) {\n issues.push({ at, message: 'not an object' });\n return;\n }\n const id = String(raw.id ?? '');\n const path = String(raw.path ?? '');\n const titleKey = String(raw.titleKey ?? '');\n if (!ID.test(id)) issues.push({ at: `${at}.id`, message: `invalid id \"${id}\"` });\n else if (pageIds.has(id)) issues.push({ at: `${at}.id`, message: `duplicate page \"${id}\"` });\n pageIds.add(id);\n if (!PATH.test(path)) issues.push({ at: `${at}.path`, message: `invalid path \"${path}\"` });\n else if (path === '/setto' || path.startsWith('/setto/')) {\n issues.push({ at: `${at}.path`, message: '/setto belongs to the editor' });\n } else if (paths.has(path)) issues.push({ at: `${at}.path`, message: `duplicate path \"${path}\"` });\n paths.add(path);\n if (!titleKey) issues.push({ at: `${at}.titleKey`, message: 'required' });\n\n const sections: PageSection[] = [];\n const rawSections = Array.isArray(raw.sections) ? raw.sections : null;\n if (!rawSections) issues.push({ at: `${at}.sections`, message: 'must be a list' });\n (rawSections ?? []).forEach((s, j) => {\n const sat = `${at}.sections[${j}]`;\n if (!isRecord(s)) {\n issues.push({ at: sat, message: 'not an object' });\n return;\n }\n const sid = String(s.id ?? '');\n if (!ID.test(sid)) issues.push({ at: `${sat}.id`, message: `invalid id \"${sid}\"` });\n else if (sectionIds.has(sid)) issues.push({ at: `${sat}.id`, message: `duplicate section \"${sid}\"` });\n sectionIds.add(sid);\n const type = s.type;\n if (type !== undefined && !BUILTIN_SECTION_TYPES.includes(type as BuiltinSectionType)) {\n issues.push({ at: `${sat}.type`, message: `unknown section type \"${String(type)}\"` });\n }\n sections.push({\n id: sid,\n ...(type !== undefined ? { type: type as BuiltinSectionType } : {}),\n ...(s.hidden === true ? { hidden: true } : {}),\n ...(typeof s.label === 'string' && s.label.trim() ? { label: s.label.trim() } : {}),\n });\n });\n\n pages.push({\n id,\n path,\n titleKey,\n ...(raw.hidden === true ? { hidden: true } : {}),\n sections,\n });\n });\n\n const blogs = pages.flatMap((p, i) =>\n p.sections.flatMap((s, j) => (s.type === 'blog' ? [{ page: p, at: `pages[${i}].sections[${j}]` }] : [])),\n );\n if (blogs.length > 1) {\n issues.push({ at: blogs[1]!.at, message: 'a site has one blog; another blog section is already on a page' });\n }\n for (const blog of blogs) {\n if (blog.page.path === '/') issues.push({ at: blog.at, message: 'the blog cannot be the front page' });\n }\n\n const menu = parseMenu(input.menu, 'menu', issues);\n const footer = parseMenu(input.footer, 'footer', issues);\n\n if (issues.length > 0) return { ok: false, issues };\n return { ok: true, manifest: { version: PAGES_MANIFEST_VERSION, pages, menu, footer } };\n}\n\nfunction parseMenu(raw: unknown, at: MenuList, issues: ManifestIssue[]): MenuItem[] {\n if (raw === undefined) return [];\n if (!Array.isArray(raw)) {\n issues.push({ at, message: 'must be a list' });\n return [];\n }\n const ids = new Set<string>();\n const items: MenuItem[] = [];\n raw.forEach((item, i) => {\n const iat = `${at}[${i}]`;\n if (!isRecord(item)) {\n issues.push({ at: iat, message: 'not an object' });\n return;\n }\n const id = String(item.id ?? '');\n const href = String(item.href ?? '');\n const labelKey = String(item.labelKey ?? '');\n if (!ID.test(id)) issues.push({ at: `${iat}.id`, message: `invalid id \"${id}\"` });\n else if (ids.has(id)) issues.push({ at: `${iat}.id`, message: `duplicate item \"${id}\"` });\n ids.add(id);\n if (!isSafeHref(href)) issues.push({ at: `${iat}.href`, message: `invalid link \"${href}\"` });\n if (!labelKey) issues.push({ at: `${iat}.labelKey`, message: 'required' });\n items.push({ id, href, labelKey, ...(item.hidden === true ? { hidden: true } : {}) });\n });\n return items;\n}\n\n/** A path on this site, an anchor, or an http(s)/mailto/tel link. Never `javascript:`. */\nexport function isSafeHref(href: string): boolean {\n if (!href) return false;\n if (href.startsWith('/') && !href.startsWith('//')) return true;\n if (href.startsWith('#')) return true;\n return /^(https?:\\/\\/|mailto:|tel:)/i.test(href);\n}\n\n// ── Reading ─────────────────────────────────────────────────────────────────\n\n/** `/vilkar/` and `/vilkar` are one page; the empty path is the front page. */\nexport function normalisePath(path: string): string {\n const bare = (path.split(/[?#]/)[0] ?? '').replace(/\\/+$/, '');\n return bare === '' ? '/' : bare.toLowerCase();\n}\n\nexport function pageForPath(manifest: PagesManifest, path: string): PageEntry | null {\n const wanted = normalisePath(path);\n return manifest.pages.find((p) => p.path === wanted) ?? (blogSlugForPath(manifest, path) ? blogPage(manifest)!.page : null);\n}\n\n/** The page holding the site's blog, and the section on it. */\nexport function blogPage(manifest: PagesManifest): { page: PageEntry; section: PageSection } | null {\n for (const page of manifest.pages) {\n const section = page.sections.find((s) => s.type === 'blog');\n if (section) return { page, section };\n }\n return null;\n}\n\n/**\n * The post a path names: `/blogg/ny-kaffemaskin` → `ny-kaffemaskin` when the\n * blog lives at `/blogg`. One segment below the blog page and a valid slug;\n * anything else is not a post.\n */\nexport function blogSlugForPath(manifest: PagesManifest, path: string): string | null {\n const blog = blogPage(manifest);\n if (!blog || blog.page.path === '/') return null;\n const wanted = normalisePath(path);\n const prefix = `${blog.page.path}/`;\n if (!wanted.startsWith(prefix)) return null;\n const slug = wanted.slice(prefix.length);\n return slug.length <= 80 && POST_SLUG.test(slug) ? slug : null;\n}\n\nexport function pageById(manifest: PagesManifest, id: string): PageEntry | null {\n return manifest.pages.find((p) => p.id === id) ?? null;\n}\n\n/** The page a section is on, and where. */\nexport function findSection(\n manifest: PagesManifest,\n sectionId: string,\n): { page: PageEntry; index: number; section: PageSection } | null {\n for (const page of manifest.pages) {\n const index = page.sections.findIndex((s) => s.id === sectionId);\n if (index >= 0) return { page, index, section: page.sections[index]! };\n }\n return null;\n}\n\n/**\n * The links a visitor should see.\n *\n * Hidden items go, and so do items that would lead nowhere: a link to a\n * hidden page, or an anchor to a hidden section. Hiding «Tjenester» for the\n * winter should not leave a menu entry that scrolls to nothing.\n */\nexport function visibleMenu(manifest: PagesManifest, list: MenuList): MenuItem[] {\n return manifest[list].filter((item) => !item.hidden && !leadsNowhere(manifest, item.href));\n}\n\n/**\n * The links the site's owner sees, signed in on their own site.\n *\n * What a visitor sees, and one more: the blog's link while the blog is on but\n * has no posts yet. Visitors are spared a menu entry that leads to an empty\n * page; the owner gets it `dimmed`, as the way in — the empty blog is where\n * Pixel offers to write the first article. A blog link the owner hid\n * themselves once posts exist stays hidden.\n */\nexport function ownerMenu(\n manifest: PagesManifest,\n list: MenuList,\n blogEmpty: boolean,\n): Array<MenuItem & { dimmed?: true }> {\n const blog = blogPage(manifest);\n const waiting = blogEmpty && blog && !blog.page.hidden && !blog.section.hidden ? normalisePath(blog.page.path) : null;\n return manifest[list].flatMap((item) => {\n if (!item.hidden && !leadsNowhere(manifest, item.href)) return [item];\n if (waiting && item.hidden && normalisePath(item.href) === waiting) return [{ ...item, dimmed: true as const }];\n return [];\n });\n}\n\nfunction leadsNowhere(manifest: PagesManifest, href: string): boolean {\n if (!href.startsWith('/') && !href.startsWith('#')) return false;\n const [pathPart, fragment] = href.split('#') as [string, string | undefined];\n const page = pageForPath(manifest, pathPart || '/');\n if (pathPart && !page) return false; // a route the site handles in code\n if (page?.hidden) return true;\n if (!fragment) return false;\n const target = findSection(manifest, fragment);\n return target ? Boolean(target.section.hidden || target.page.hidden) : false;\n}\n\n// ── Changing ────────────────────────────────────────────────────────────────\n\nexport class ManifestError extends Error {\n constructor(\n public readonly code:\n | 'page_not_found'\n | 'section_not_found'\n | 'item_not_found'\n | 'duplicate_id'\n | 'duplicate_path'\n | 'invalid',\n message: string,\n ) {\n super(message);\n this.name = 'ManifestError';\n }\n}\n\nfunction clone(manifest: PagesManifest): PagesManifest {\n return JSON.parse(JSON.stringify(manifest)) as PagesManifest;\n}\n\nfunction mustPage(manifest: PagesManifest, pageId: string): PageEntry {\n const page = pageById(manifest, pageId);\n if (!page) throw new ManifestError('page_not_found', `no page \"${pageId}\"`);\n return page;\n}\n\n/**\n * Move a section up (negative) or down (positive) on its page.\n *\n * Skips over hidden neighbours: moving «Om oss» up past a hidden section\n * would otherwise do nothing the owner can see, and look broken. Returns the\n * manifest unchanged at either end rather than throwing — the button is\n * simply at the edge.\n */\nexport function moveSection(manifest: PagesManifest, sectionId: string, delta: -1 | 1): PagesManifest {\n const next = clone(manifest);\n const found = findSection(next, sectionId);\n if (!found) throw new ManifestError('section_not_found', `no section \"${sectionId}\"`);\n const { page, index } = found;\n let target = index + delta;\n while (target >= 0 && target < page.sections.length && page.sections[target]!.hidden) target += delta;\n if (target < 0 || target >= page.sections.length) return manifest;\n const [moved] = page.sections.splice(index, 1);\n page.sections.splice(target, 0, moved!);\n return next;\n}\n\n/** Put a section at an exact position among its page's sections. */\nexport function placeSection(manifest: PagesManifest, sectionId: string, index: number): PagesManifest {\n const next = clone(manifest);\n const found = findSection(next, sectionId);\n if (!found) throw new ManifestError('section_not_found', `no section \"${sectionId}\"`);\n const [moved] = found.page.sections.splice(found.index, 1);\n const at = Math.max(0, Math.min(index, found.page.sections.length));\n found.page.sections.splice(at, 0, moved!);\n return next;\n}\n\nexport function setSectionHidden(manifest: PagesManifest, sectionId: string, hidden: boolean): PagesManifest {\n const next = clone(manifest);\n const found = findSection(next, sectionId);\n if (!found) throw new ManifestError('section_not_found', `no section \"${sectionId}\"`);\n if (hidden) found.section.hidden = true;\n else delete found.section.hidden;\n return next;\n}\n\nexport function addSection(\n manifest: PagesManifest,\n pageId: string,\n section: PageSection,\n index?: number,\n): PagesManifest {\n if (!ID.test(section.id)) throw new ManifestError('invalid', `invalid section id \"${section.id}\"`);\n if (findSection(manifest, section.id)) {\n throw new ManifestError('duplicate_id', `section \"${section.id}\" already exists`);\n }\n const next = clone(manifest);\n const page = mustPage(next, pageId);\n const at = index === undefined ? page.sections.length : Math.max(0, Math.min(index, page.sections.length));\n page.sections.splice(at, 0, { ...section });\n return next;\n}\n\nexport function addPage(manifest: PagesManifest, page: PageEntry): PagesManifest {\n const path = normalisePath(page.path);\n if (!ID.test(page.id) || !PATH.test(path) || path === '/setto' || path.startsWith('/setto/')) {\n throw new ManifestError('invalid', `invalid page \"${page.id}\" at \"${page.path}\"`);\n }\n if (pageById(manifest, page.id)) throw new ManifestError('duplicate_id', `page \"${page.id}\" already exists`);\n if (pageForPath(manifest, path)) throw new ManifestError('duplicate_path', `a page already lives at ${path}`);\n let next = clone(manifest);\n next.pages.push({ id: page.id, path, titleKey: page.titleKey, sections: [] });\n for (const section of page.sections) next = addSection(next, page.id, section);\n return next;\n}\n\nexport function setPageHidden(manifest: PagesManifest, pageId: string, hidden: boolean): PagesManifest {\n const next = clone(manifest);\n const page = mustPage(next, pageId);\n if (page.path === '/' && hidden) throw new ManifestError('invalid', 'the front page cannot be hidden');\n if (hidden) page.hidden = true;\n else delete page.hidden;\n return next;\n}\n\n/** Add a link, or change the one with the same id. */\nexport function upsertMenuItem(\n manifest: PagesManifest,\n list: MenuList,\n item: MenuItem,\n index?: number,\n): PagesManifest {\n if (!ID.test(item.id) || !isSafeHref(item.href) || !item.labelKey) {\n throw new ManifestError('invalid', `invalid link \"${item.id}\"`);\n }\n const next = clone(manifest);\n const items = next[list];\n const existing = items.findIndex((i) => i.id === item.id);\n const clean: MenuItem = { id: item.id, href: item.href, labelKey: item.labelKey };\n if (item.hidden) clean.hidden = true;\n if (existing >= 0) items[existing] = clean;\n else items.splice(index === undefined ? items.length : Math.max(0, Math.min(index, items.length)), 0, clean);\n return next;\n}\n\nexport function moveMenuItem(manifest: PagesManifest, list: MenuList, itemId: string, delta: -1 | 1): PagesManifest {\n const next = clone(manifest);\n const items = next[list];\n const index = items.findIndex((i) => i.id === itemId);\n if (index < 0) throw new ManifestError('item_not_found', `no link \"${itemId}\" in ${list}`);\n const target = index + delta;\n if (target < 0 || target >= items.length) return manifest;\n const [moved] = items.splice(index, 1);\n items.splice(target, 0, moved!);\n return next;\n}\n\nexport function setMenuItemHidden(\n manifest: PagesManifest,\n list: MenuList,\n itemId: string,\n hidden: boolean,\n): PagesManifest {\n const next = clone(manifest);\n const item = next[list].find((i) => i.id === itemId);\n if (!item) throw new ManifestError('item_not_found', `no link \"${itemId}\" in ${list}`);\n if (hidden) item.hidden = true;\n else delete item.hidden;\n return next;\n}\n\n/**\n * One change, as data.\n *\n * What Pixel's structure tools return and what the editor applies, so a\n * suggestion from the chat and a click in the toolbar go through the same\n * functions — and a change the model gets wrong fails here, in a way the\n * owner never sees half of.\n */\nexport type ManifestOp =\n | { op: 'move_section'; sectionId: string; delta: -1 | 1 }\n | { op: 'place_section'; sectionId: string; index: number }\n | { op: 'hide_section'; sectionId: string }\n | { op: 'show_section'; sectionId: string }\n | { op: 'add_section'; pageId: string; section: PageSection; index?: number }\n | { op: 'add_page'; page: PageEntry }\n | { op: 'hide_page'; pageId: string }\n | { op: 'show_page'; pageId: string }\n | { op: 'upsert_link'; list: MenuList; item: MenuItem; index?: number }\n | { op: 'move_link'; list: MenuList; itemId: string; delta: -1 | 1 }\n | { op: 'hide_link'; list: MenuList; itemId: string }\n | { op: 'show_link'; list: MenuList; itemId: string };\n\nexport function applyOp(manifest: PagesManifest, op: ManifestOp): PagesManifest {\n switch (op.op) {\n case 'move_section':\n return moveSection(manifest, op.sectionId, op.delta);\n case 'place_section':\n return placeSection(manifest, op.sectionId, op.index);\n case 'hide_section':\n return setSectionHidden(manifest, op.sectionId, true);\n case 'show_section':\n return setSectionHidden(manifest, op.sectionId, false);\n case 'add_section':\n return addSection(manifest, op.pageId, op.section, op.index);\n case 'add_page':\n return addPage(manifest, op.page);\n case 'hide_page':\n return setPageHidden(manifest, op.pageId, true);\n case 'show_page':\n return setPageHidden(manifest, op.pageId, false);\n case 'upsert_link':\n return upsertMenuItem(manifest, op.list, op.item, op.index);\n case 'move_link':\n return moveMenuItem(manifest, op.list, op.itemId, op.delta);\n case 'hide_link':\n return setMenuItemHidden(manifest, op.list, op.itemId, true);\n case 'show_link':\n return setMenuItemHidden(manifest, op.list, op.itemId, false);\n }\n}\n\n/** Every op or none: a list that fails halfway returns the error and no manifest. */\nexport function applyOps(\n manifest: PagesManifest,\n ops: readonly ManifestOp[],\n): { ok: true; manifest: PagesManifest } | { ok: false; error: string; at: number } {\n let next = manifest;\n for (let i = 0; i < ops.length; i++) {\n try {\n next = applyOp(next, ops[i]!);\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err), at: i };\n }\n }\n return { ok: true, manifest: next };\n}\n\n// ── Built-in sections' content ──────────────────────────────────────────────\n\n/** Where a built-in section keeps its words in the locale files. */\nexport function builtinKeys(sectionId: string) {\n const base = `sections.${sectionId}`;\n return {\n heading: `${base}.heading`,\n intro: `${base}.intro`,\n items: `${base}.items`,\n itemHeading: (itemKey: string) => `${base}.items.${itemKey}.heading`,\n itemText: (itemKey: string) => `${base}.items.${itemKey}.text`,\n };\n}\n\n/** The default locale key for a page's name. */\nexport function pageTitleKey(pageId: string): string {\n return `pages.${pageId}.title`;\n}\n\n/** Stable JSON for the file, so an unchanged manifest is an unchanged file. */\nexport function serialiseManifest(manifest: PagesManifest): string {\n return JSON.stringify(manifest, null, 2) + '\\n';\n}\n","import {\n applyOps,\n parseManifest,\n serialiseManifest,\n type ManifestOp,\n type PagesManifest,\n} from '../pages/manifest';\n\nexport interface PageStoreSnapshot {\n manifest: PagesManifest | null;\n /** How many pages, sections and links differ from what is published. */\n changes: number;\n version: number;\n}\n\nexport const EMPTY_PAGE_STORE_SNAPSHOT: PageStoreSnapshot = {\n manifest: null,\n changes: 0,\n version: 0,\n};\n\ntype Listener = (snap: PageStoreSnapshot) => void;\n\n/**\n * The page manifest as the owner is editing it.\n *\n * The same shape as `ThemeStore` — current against baseline, a snapshot for\n * `useSyncExternalStore`, revert and commit — so the toolbar counts, discards\n * and publishes it the way it does colours. Unlike the other stores it holds\n * one document rather than a map of drafts: an ordering change is not a set of\n * independent keys, and comparing the whole thing is what makes moving a\n * section down and back up again a draft of nothing.\n *\n * `null` throughout for a site without a manifest — every site built before\n * pages were data. `SettoPage` then renders the sections in the order the site\n * listed them, and the structure tools stay out of the editor.\n */\nexport class PageStore {\n private data: PagesManifest | null;\n private baseline: PagesManifest | null;\n private version = 0;\n private listeners = new Set<Listener>();\n private cached: PageStoreSnapshot;\n\n constructor(initial: PagesManifest | null) {\n this.data = initial ? structuredClone(initial) : null;\n this.baseline = initial ? structuredClone(initial) : null;\n this.cached = { manifest: this.data, changes: 0, version: 0 };\n }\n\n snapshot(): PageStoreSnapshot {\n return this.cached;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** The manifest as published, to tell which sections the owner changed. */\n get baselineManifest(): PagesManifest | null {\n return this.baseline;\n }\n\n get manifest(): PagesManifest | null {\n return this.data;\n }\n\n /** True once the site has a manifest to edit. */\n has(): boolean {\n return this.data !== null;\n }\n\n /**\n * Apply changes as drafts. All of them or none: a list that fails halfway\n * leaves the page exactly as it was and says which one failed.\n */\n apply(ops: readonly ManifestOp[]): { ok: true } | { ok: false; error: string; at: number } {\n if (!this.data) return { ok: false, error: 'this site has no page manifest', at: 0 };\n const result = applyOps(this.data, ops);\n if (!result.ok) return result;\n this.data = result.manifest;\n this.bump();\n return { ok: true };\n }\n\n /**\n * Put the draft back to an earlier manifest, keeping the baseline.\n *\n * What «Angre» on one of Pixel's changes does: the panel remembers the\n * manifest from before the change and hands it back here. Checked like\n * anything else, because it has been through a round trip it did not have\n * to survive.\n */\n restore(manifest: PagesManifest): { ok: true } | { ok: false; error: string } {\n const parsed = parseManifest(manifest);\n if (!parsed.ok) return { ok: false, error: parsed.issues[0]?.message ?? 'invalid manifest' };\n this.data = parsed.manifest;\n this.bump();\n return { ok: true };\n }\n\n /**\n * Replace the baseline with what the repository holds, dropping drafts.\n *\n * Checked first: the file in the repository can be newer than this bundle,\n * or hand-edited, and a baseline this store cannot render must not replace\n * the one it can. Returns whether it was taken.\n */\n loadBaseline(next: unknown): boolean {\n const parsed = parseManifest(next);\n if (!parsed.ok) {\n console.warn('[setto] pages.json from the repository is not valid and was ignored', parsed.issues);\n return false;\n }\n this.data = parsed.manifest;\n this.baseline = structuredClone(parsed.manifest);\n this.bump();\n return true;\n }\n\n revertAll(): void {\n this.data = this.baseline ? structuredClone(this.baseline) : null;\n this.bump();\n }\n\n commit(): void {\n this.baseline = this.data ? structuredClone(this.data) : null;\n this.bump();\n }\n\n /** Number of changes, for the toolbar's count. Zero means nothing to publish. */\n size(): number {\n return this.cached.changes;\n }\n\n serialise(): string | null {\n return this.data ? serialiseManifest(this.data) : null;\n }\n\n private bump(): void {\n this.version += 1;\n this.cached = {\n manifest: this.data,\n changes: countChanges(this.baseline, this.data),\n version: this.version,\n };\n for (const fn of this.listeners) fn(this.cached);\n }\n}\n\n/**\n * Roughly how many things the owner changed: each page whose sections or\n * settings differ, each link that differs, each one added.\n *\n * Only has to be right about zero — that decides whether «Publiser» lights —\n * and plausible otherwise, because it is shown as a count.\n */\nexport function countChanges(before: PagesManifest | null, after: PagesManifest | null): number {\n if (!before || !after) return before === after ? 0 : 1;\n let changes = 0;\n const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n\n const beforePages = new Map(before.pages.map((p) => [p.id, p]));\n for (const page of after.pages) {\n const was = beforePages.get(page.id);\n if (!was) {\n changes += 1;\n continue;\n }\n if (was.path !== page.path || was.titleKey !== page.titleKey || Boolean(was.hidden) !== Boolean(page.hidden)) {\n changes += 1;\n }\n const wasSections = new Map(was.sections.map((s, i) => [s.id, { s, i }]));\n page.sections.forEach((s, i) => {\n const prior = wasSections.get(s.id);\n if (!prior || prior.i !== i || !same(prior.s, s)) changes += 1;\n });\n if (was.sections.length > page.sections.length) changes += was.sections.length - page.sections.length;\n }\n if (before.pages.length > after.pages.length) changes += before.pages.length - after.pages.length;\n\n for (const list of ['menu', 'footer'] as const) {\n const wasItems = new Map(before[list].map((item, i) => [item.id, { item, i }]));\n after[list].forEach((item, i) => {\n const prior = wasItems.get(item.id);\n if (!prior || prior.i !== i || !same(prior.item, item)) changes += 1;\n });\n if (before[list].length > after[list].length) changes += before[list].length - after[list].length;\n }\n return changes;\n}\n","import { parseManifest, type PagesManifest } from './manifest';\n\nconst cache = new WeakMap<object, PagesManifest | null>();\n\n/**\n * The manifest the site was built with, checked once.\n *\n * Read on the very first render, before the draft store exists, so the page\n * never flashes its sections in code order — or a hidden one — before the\n * store takes over. A file that fails the check is reported and ignored: the\n * page then renders the way it would without one, which is a working site.\n */\nexport function bundledManifest(raw: unknown): PagesManifest | null {\n if (!raw || typeof raw !== 'object') return null;\n const hit = cache.get(raw);\n if (hit !== undefined) return hit;\n const parsed = parseManifest(raw);\n if (!parsed.ok) {\n console.warn('[setto] pages.json is not valid and was ignored', parsed.issues);\n }\n const manifest = parsed.ok ? parsed.manifest : null;\n cache.set(raw, manifest);\n return manifest;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { Session, SupabaseClient } from '@supabase/supabase-js';\nimport type { SiteRow } from '../types';\n\nexport interface SiteAccessState {\n /** All sites the current user can access. `null` until loaded. */\n sites: SiteRow[] | null;\n /** The site matching `siteId`, or `null` if the user has no access. */\n currentSite: SiteRow | null;\n loading: boolean;\n error: string | null;\n}\n\nconst EMPTY: SiteAccessState = {\n sites: null,\n currentSite: null,\n loading: true,\n error: null,\n};\n\n/**\n * Loads the sites table for the current Supabase session and resolves whether\n * the user has access to `siteId`. Returns a stable shape across loading,\n * success, and failure so callers can read `currentSite` directly.\n */\nexport function useSiteAccess(\n /** Null until supabase-js has loaded, which it has whenever there is a session. */\n supabase: SupabaseClient | null,\n session: Session | null,\n siteId: string,\n): SiteAccessState {\n const [state, setState] = useState<SiteAccessState>(EMPTY);\n const cachedUserIdRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!session || !supabase) {\n cachedUserIdRef.current = null;\n setState({ sites: null, currentSite: null, loading: false, error: null });\n return;\n }\n\n const userId = session.user.id;\n const sameUser = cachedUserIdRef.current === userId;\n let cancelled = false;\n\n setState((prev) => {\n // Supabase emits a new session object on token refresh (e.g. window focus).\n // Keep edit mode stable instead of briefly clearing access.\n if (sameUser && prev.sites !== null && !prev.loading) {\n return prev;\n }\n return {\n ...prev,\n loading: true,\n error: null,\n sites: sameUser ? prev.sites : null,\n currentSite: sameUser ? prev.currentSite : null,\n };\n });\n\n supabase\n .from('sites')\n .select('*')\n .then(({ data, error }) => {\n if (cancelled) return;\n if (error) {\n cachedUserIdRef.current = userId;\n setState({ sites: [], currentSite: null, loading: false, error: error.message });\n return;\n }\n const rows = (data ?? []) as SiteRow[];\n const current = rows.find((s) => s.id === siteId) ?? null;\n cachedUserIdRef.current = userId;\n setState({ sites: rows, currentSite: current, loading: false, error: null });\n });\n\n return () => {\n cancelled = true;\n };\n }, [supabase, session, siteId]);\n\n return state;\n}\n","/**\n * Whether the page is being looked at by a visitor only, so a site may rewrite\n * its own text in the DOM: GSAP's SplitText, a typewriter, anything that moves\n * or replaces the nodes React put there.\n *\n * Text inside `<T>` belongs to React. Rewritten under it, React later removes\n * a node that is no longer where it left it, and the whole page goes blank:\n * that is what turning on editing did to a site whose headline SplitText had\n * split and reverted (2026-10-26). An owner can switch editing on at any\n * moment, so for them the answer is no for the whole visit.\n *\n * `null` while it is not known yet: the session is being read, or the site's\n * membership fetched. A site waits for `true` before it rewrites anything,\n * which for a visitor is a moment after the first paint.\n */\nexport function visitorView(state: {\n authLoading: boolean;\n hasSession: boolean;\n /** Null while the signed-in person's sites are being fetched. */\n sitesLoaded: boolean;\n canEdit: boolean;\n guestEdit: boolean;\n}): boolean | null {\n if (state.authLoading) return null;\n if (!state.hasSession) return !state.guestEdit;\n if (!state.sitesLoaded) return null;\n return !state.canEdit && !state.guestEdit;\n}\n","import { useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { SettoContext, useSetto } from './provider';\n\n/**\n * Setto's own interface, loaded at runtime instead of built into the site.\n *\n * The library mixes two things that have no business sharing a release. Some\n * of it renders the customer's site — `<T>`, sections, the theme — and must be\n * built in, versioned with their content, and never change under them. The\n * rest is Setto's chrome sitting on top: the preview bar, and in time the\n * editor toolbar and the dashboard. None of that is their site.\n *\n * Bundling the chrome meant every change to a button label was a rebuild and\n * redeploy of every site Setto has ever made. Four of those in one day is what\n * this exists to end.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * THIS FILE IS THE FROZEN PART.\n *\n * Everything else about the chrome can change with a single server deploy;\n * this cannot, because it ships inside the customer's bundle. So it does as\n * little as possible: publish a handshake, load a script, and get out of the\n * way. Resist adding anything here that could live on the other side of the\n * boundary — a change to this file costs a re-pin of the entire fleet, which\n * is the exact cost it was written to avoid.\n * ────────────────────────────────────────────────────────────────────────────\n *\n * It fails soft, always. A chrome bundle that will not load, or throws while\n * mounting, must leave the customer's site exactly as it found it: no bar, no\n * error, nothing. That is not politeness — the chrome renders inside somebody\n * else's page, and the worst bug this codebase has produced was a hook after\n * an early return, which white-screens the whole site rather than the bar.\n * Behind a script tag that mistake removes the bar and nothing else.\n */\n\n/** Bumped only for a breaking change to the handshake below. */\nconst CHROME_CONTRACT = 1;\n\n/** What the chrome is handed. Additive changes only; nothing may be removed. */\nexport interface SettoChromeHandshake {\n contract: number;\n /** The host's React, so the chrome bundle ships no framework of its own. */\n react: typeof React;\n reactDom: typeof ReactDOM;\n /**\n * Hand back a component and the host renders it.\n *\n * Inverted deliberately. The first cut had the chrome create its own React\n * root, which cannot work: `createRoot` lives in `react-dom/client`, not\n * `react-dom`, and React 19 removed `render` altogether — so the bundle\n * loaded, found neither, and mounted nothing at all.\n *\n * Rendering it from here is better than passing `createRoot` across would\n * have been. The chrome ends up inside the host's own tree, so its hooks are\n * the host's hooks with no second root to keep in step, and the error\n * boundary that keeps a mistake off the customer's page lives on this side\n * where it cannot be forgotten.\n */\n mount: (Component: React.ComponentType) => void;\n /**\n * The same, for the page at `/setto`.\n *\n * @deprecated Use `mountSlot('admin', …)`. Kept because a chrome bundle\n * older than this file may still call it, and the whole point of this file\n * is that it never has to change again.\n */\n mountAdmin: (Component: React.ComponentType) => void;\n /**\n * Offer a component for a named place in the host: `admin` for the page at\n * `/setto`, `toolbar` for the editor's floating menu.\n *\n * Named rather than one method per surface, because every new method here\n * costs a re-pin of the whole fleet — the exact price this file exists to\n * avoid paying. A new surface is now a string the host already understands,\n * or one it will simply ignore.\n *\n * Registering nothing leaves the host's own version in place. That is what\n * keeps a chrome bundle that fails to load, or throws while rendering, from\n * taking the editor down with it.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n mountSlot: (name: string, Component: React.ComponentType<any>) => void;\n /**\n * The host's own `useSetto`, callable from the chrome.\n *\n * This is what makes the whole arrangement cheap. The chrome renders inside\n * the provider's tree, so it can simply use the context — supabase, api,\n * session, sites, the i18n store — rather than having each field copied\n * across a handshake that could never be extended without a re-pin.\n *\n * It is a hook: obey the rules of hooks, and only call it from a component\n * this file rendered.\n */\n useSetto: () => unknown;\n config: { siteId: string; apiUrl: string; displayName?: string };\n /** Read the current state. Live: call it, never cache what it returned. */\n getState: () => {\n hasSession: boolean;\n accessToken: string | null;\n currentSite: { id: string; display_name?: string; status?: string } | null;\n sitesLoaded: boolean;\n editMode: boolean;\n /** May edit, whether or not editing now (0.44). The chrome loads the editor for it. */\n canEdit?: boolean;\n /** A signed-out visitor trying the editor on setto.no. */\n guestEdit: boolean;\n authLoading: boolean;\n };\n /** Told whenever that state changes. Returns an unsubscribe. */\n subscribe: (listener: () => void) => () => void;\n}\n\ndeclare global {\n interface Window {\n __setto__?: SettoChromeHandshake;\n __settoChromeLoaded__?: boolean;\n }\n}\n\n/** Where the chrome lives. The API host serves it, so one deploy moves it. */\nfunction chromeUrl(apiUrl: string): string {\n return `${apiUrl.replace(/\\/$/, '')}/chrome/v${CHROME_CONTRACT}.js`;\n}\n\n/**\n * Whatever the chrome asked us to draw, kept off the customer's page when it\n * misbehaves. A throw here removes the chrome and nothing else.\n */\nclass ChromeBoundary extends React.Component<\n { children: React.ReactNode; onError?: () => void },\n { dead: boolean }\n> {\n state = { dead: false };\n static getDerivedStateFromError() {\n return { dead: true };\n }\n componentDidCatch(error: unknown) {\n console.warn('[setto] chrome failed, continuing without it', error);\n try {\n this.props.onError?.();\n } catch {\n // Nothing here may throw into the host application.\n }\n }\n render() {\n return this.state.dead ? null : this.props.children;\n }\n}\n\n/**\n * Whatever the chrome has offered, by name.\n *\n * Module scope rather than context: these mount points are scattered through\n * the host — one in its router, one in a portal on the body — with no common\n * ancestor worth threading a provider through.\n */\n/*\n * Heterogeneous on purpose: the admin slot takes nothing, the form-field tools\n * take a field and three callbacks, and the registry cannot be generic over\n * all of them at once. The type is recovered at the reading end, where the\n * caller says what shape it expects.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst slots = new Map<string, React.ComponentType<any>>();\nconst slotListeners = new Set<() => void>();\n\nfunction notifySlots(): void {\n for (const listener of slotListeners) {\n try {\n listener();\n } catch {\n // A listener that throws is the chrome's problem, not the site's.\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction publishSlot(name: string, Component: React.ComponentType<any>): void {\n slots.set(name, Component);\n notifySlots();\n}\n\n/**\n * Drop a slot the chrome offered but could not render.\n *\n * The alternative is a boundary that renders nothing, which is right for an\n * overlay and wrong for a place the host had something of its own to put:\n * `/setto` would go blank rather than fall back to the sign-in it ships with.\n * Retiring the slot puts the host's version back.\n */\nfunction retireSlot(name: string): void {\n if (slots.delete(name)) notifySlots();\n}\n\n/**\n * What the host should render in a named place, or null while the chrome has\n * offered nothing — including after it offered something that threw. Callers\n * render their own version when this is null; every one of them must have one.\n *\n * Also null while supabase-js is still loading (0.47). Everything the chrome\n * offers is an editor's — the dashboard, the menu, the section and image tools\n * — and was written against a `useSetto().supabase` that always existed. The\n * library is fetched only when it is needed now, so an offered component waits\n * here, with the host's own version in its place, until the client is there;\n * asking for the component is what fetches it. For an owner it has long since\n * loaded, since there is no session without it; a guest editor pays here.\n */\nexport function useSettoChromeSlot<P extends object = Record<string, never>>(\n name: string,\n): React.ComponentType<P> | null {\n const [, force] = useState(0);\n useEffect(() => {\n const listener = () => force((n) => n + 1);\n slotListeners.add(listener);\n return () => {\n slotListeners.delete(listener);\n };\n }, []);\n const ctx = useContext(SettoContext);\n const offered = slots.get(name) as React.ComponentType<P> | undefined;\n const waiting = !!offered && !!ctx && !ctx.supabase;\n const loadSupabase = ctx?.loadSupabase;\n useEffect(() => {\n if (!waiting || !loadSupabase) return;\n loadSupabase().catch(() => {\n // Without the client the host's own version stays; nothing to report.\n });\n }, [waiting, loadSupabase]);\n const Offered = waiting ? undefined : offered;\n return useMemo(() => {\n if (!Offered) return null;\n /*\n * `createElement` rather than JSX: spreading a generic `P` into a tag\n * makes TypeScript demand it be assignable to `JSX.IntrinsicAttributes`,\n * which no caller's props are. Same element, no cast.\n */\n return function SettoChromeSlot(props: P) {\n return (\n <ChromeBoundary onError={() => retireSlot(name)}>\n {React.createElement(Offered, props)}\n </ChromeBoundary>\n );\n };\n }, [Offered, name]);\n}\n\n/** @deprecated Use `useSettoChromeSlot('admin')`. */\nexport function useSettoAdminChrome(): React.ComponentType<Record<string, never>> | null {\n return useSettoChromeSlot('admin');\n}\n\nexport function SettoChrome() {\n const setto = useSetto();\n const [Chrome, setChrome] = useState<React.ComponentType | null>(null);\n const listeners = useRef(new Set<() => void>());\n const stateRef = useRef<SettoChromeHandshake['getState']>(() => ({\n hasSession: false,\n accessToken: null,\n currentSite: null,\n sitesLoaded: false,\n editMode: false,\n canEdit: false,\n guestEdit: false,\n authLoading: true,\n }));\n\n /*\n * The newest state, every render, without re-publishing the handshake.\n *\n * The chrome holds a reference to `getState`, so what it reads has to be\n * current. Handing it a snapshot would freeze the bar at whatever was true\n * when the script happened to load.\n */\n stateRef.current = () => ({\n hasSession: !!setto.session,\n accessToken: setto.session?.access_token ?? null,\n currentSite: setto.currentSite\n ? {\n id: setto.currentSite.id,\n display_name: setto.currentSite.display_name,\n status: setto.currentSite.status,\n }\n : null,\n sitesLoaded: setto.sites !== null,\n editMode: setto.editMode,\n canEdit: setto.canEdit,\n guestEdit: setto.guestEdit,\n authLoading: setto.authLoading,\n });\n\n // Anything the chrome is watching hears about it.\n useEffect(() => {\n for (const listener of listeners.current) {\n try {\n listener();\n } catch {\n // A listener that throws is the chrome's problem, not the site's.\n }\n }\n });\n\n useEffect(() => {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n if (window.__settoChromeLoaded__) return;\n\n try {\n window.__setto__ = {\n contract: CHROME_CONTRACT,\n react: React,\n reactDom: ReactDOM,\n config: {\n siteId: setto.config.siteId,\n apiUrl: setto.config.apiUrl,\n displayName: setto.config.displayName,\n },\n getState: () => stateRef.current(),\n subscribe: (listener) => {\n listeners.current.add(listener);\n return () => listeners.current.delete(listener);\n },\n // `setChrome(() => C)`: a component is a function, and the updater form\n // is the only way to put one into state without React calling it.\n mount: (Component) => setChrome(() => Component),\n mountAdmin: (Component) => publishSlot('admin', Component),\n mountSlot: (name, Component) => publishSlot(name, Component),\n useSetto: useSetto as () => unknown,\n };\n\n const script = document.createElement('script');\n /*\n * The site is named in the URL so the server can answer differently for\n * one of them — a canary before a change reaches everybody. Deciding that\n * here would have meant a re-pin every time the channel changed; deciding\n * it there costs a deploy. This parameter exists for no other reason, and\n * it is the reason it had to be added before the contract froze.\n */\n script.src = `${chromeUrl(setto.config.apiUrl)}?site=${encodeURIComponent(setto.config.siteId)}`;\n script.async = true;\n /*\n * A failure is silence. The site is already rendered and correct; the\n * only thing missing is Setto's own furniture, and telling the\n * customer's visitors about that would be worse than the absence.\n */\n script.onerror = () => undefined;\n document.head.appendChild(script);\n window.__settoChromeLoaded__ = true;\n } catch {\n // Nothing here may throw into the host application.\n }\n // Deliberately once per page: the chrome manages its own lifetime.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (!Chrome) return null;\n return (\n <ChromeBoundary>\n <Chrome />\n </ChromeBoundary>\n );\n}\n","/**\n * Base path where the Setto login + dashboard SPA is mounted on the host site.\n * Editors reach the dashboard by visiting `sitenavn.no/setto`. The host app\n * must mount `<SettoAdminApp>` at this path (e.g. `<Route path=\"/setto/*\" …>`).\n */\nexport const SETTO_BASE = '/setto';\n\n/**\n * Site home URL used after sign-in. Edit mode itself is now driven by the\n * Supabase session + site access — no URL flag required — so this just sends\n * the editor to the public site root.\n */\nexport function siteHomeUrl(pathname = '/'): string {\n const u = new URL(window.location.href);\n u.pathname = pathname;\n u.search = '';\n return u.toString();\n}\n\nexport function isAdminRoute(): boolean {\n return window.location.pathname.startsWith(SETTO_BASE);\n}\n\n/** Setto deployment progress panel (`/setto?deployment=…`). */\nexport function isAdminDeploymentView(): boolean {\n return isAdminRoute() && new URLSearchParams(window.location.search).has('deployment');\n}\n\n/**\n * A named dashboard view (`/setto?view=forms`). Views come from the module\n * registry in `src/modules`; the dashboard shows them as tabs. Opening one\n * directly is how the editor's toolbar deep-links into the \"backend\".\n */\nexport function adminViewUrl(view: string): string {\n return `${SETTO_BASE}?view=${encodeURIComponent(view)}`;\n}\n\nexport function currentAdminView(): string | null {\n return new URLSearchParams(window.location.search).get('view');\n}\n\n/**\n * True when the visitor came to `/setto` for a specific panel — a view or a\n * deployment — rather than to sign in. Sign-in normally bounces straight to\n * the site with edit mode on; a panel request stays on the dashboard.\n */\nexport function isAdminPanelView(): boolean {\n return isAdminDeploymentView() || (isAdminRoute() && currentAdminView() !== null);\n}\n\nexport function adminRedirectUrl(): string {\n return `${window.location.origin}${SETTO_BASE}`;\n}\n\n/**\n * The intent a visitor arrived with, carried across the sign-in.\n *\n * «Neste» on the preview bar means \"take me to the checkout\", but a visitor\n * who is not signed in cannot start one — the route wants a session and proof\n * the site is theirs. Sending them to /setto loses the intent, and they come\n * back to the same bar and have to press it again.\n *\n * So the wish rides along in the query string and is honoured on the way back.\n */\nexport const CHECKOUT_INTENT = 'neste';\n\nexport function checkoutIntentUrl(): string {\n return `${SETTO_BASE}?${CHECKOUT_INTENT}=1`;\n}\n\nexport function wantsCheckout(): boolean {\n return new URLSearchParams(window.location.search).get(CHECKOUT_INTENT) === '1';\n}\n\n/** The same address without the marker, so a reload does not start it twice. */\nexport function withoutCheckoutIntent(): string {\n const u = new URL(window.location.href);\n u.searchParams.delete(CHECKOUT_INTENT);\n return u.pathname + (u.search || '') + u.hash;\n}\n","/** Diameter of the collapsed FAB and height of the expanded pill (px). */\nexport const FAB_SIZE = 52;\n\n/** Distance from the viewport edges to the FAB (px). */\nexport const FAB_INSET = 16;\n","import { useEffect } from 'react';\nimport { FAB_INSET, FAB_SIZE } from './constants';\n\nconst STYLE_ID = 'setto-edit-layout';\nconst HTML_CLASS = 'setto-edit-mode';\n\n/**\n * Applies the document-level CSS for inline edit mode. The fixed top toolbar\n * has been replaced with a floating FAB anchored bottom-right, so the host\n * page no longer needs vertical padding — only edit-affordance hover styles\n * and the portal layers above the page.\n */\nexport function useSettoDocumentLayout(active: boolean): void {\n useEffect(() => {\n if (!active) return;\n\n const html = document.documentElement;\n html.classList.add(HTML_CLASS);\n html.style.setProperty('--setto-fab-size', `${FAB_SIZE}px`);\n html.style.setProperty('--setto-fab-inset', `${FAB_INSET}px`);\n\n let styleEl = document.getElementById(STYLE_ID) as HTMLStyleElement | null;\n if (!styleEl) {\n styleEl = document.createElement('style');\n styleEl.id = STYLE_ID;\n styleEl.textContent = `\n html.setto-edit-mode {\n width: 100%;\n overflow-x: clip;\n }\n\n /*\n * Anchored by its right edge, which is also what makes the menu open\n * leftwards: the pill grows and this corner does not move, so the\n * button somebody just tapped stays under their thumb.\n */\n html.setto-edit-mode #setto-toolbar-root {\n position: fixed;\n right: var(--setto-fab-inset);\n bottom: var(--setto-fab-inset);\n z-index: 2147483647;\n }\n\n html.setto-edit-mode #setto-hint-root {\n position: fixed;\n inset: 0;\n pointer-events: none;\n z-index: 2147483645;\n }\n\n html.setto-edit-mode #setto-hint-root [data-setto-ui] {\n pointer-events: auto;\n }\n\n html.setto-edit-mode #setto-section-toolbar-root {\n position: fixed;\n inset: 0;\n pointer-events: none;\n z-index: 2147483646;\n }\n\n html.setto-edit-mode #setto-section-toolbar-root [data-setto-ui] {\n pointer-events: auto;\n }\n\n html.setto-edit-mode [data-setto-key]:hover {\n outline: 1px dashed rgba(196, 80, 42, 0.55);\n outline-offset: 2px;\n border-radius: 2px;\n }\n\n html.setto-edit-mode [data-setto-section]:hover {\n box-shadow: inset 0 0 0 1px rgba(196, 80, 42, 0.3);\n }\n `;\n document.head.appendChild(styleEl);\n }\n\n notifyLayoutChange();\n\n return () => {\n html.classList.remove(HTML_CLASS);\n html.style.removeProperty('--setto-fab-size');\n html.style.removeProperty('--setto-fab-inset');\n styleEl?.remove();\n notifyLayoutChange();\n };\n }, [active]);\n}\n\nfunction notifyLayoutChange(): void {\n requestAnimationFrame(() => {\n window.dispatchEvent(new Event('resize'));\n });\n}\n","import type { CSSProperties } from 'react';\n\ninterface SettoMarkProps {\n size?: number;\n /** Color of the \"S\" letter. Defaults to the Setto crema tone. */\n letterColor?: string;\n /** Color of the accent dot. Defaults to the Setto terracotta. */\n dotColor?: string;\n style?: CSSProperties;\n}\n\n/**\n * Setto brand mark — the foreground of the setto-site favicon (italic \"S\" with\n * a terracotta dot) on a transparent background. The FAB renders the dark\n * Blekk background itself so the mark only carries the glyphs.\n */\nexport function SettoMark({\n size = 24,\n letterColor = '#F2EBDF',\n dotColor = '#C4502A',\n style,\n}: SettoMarkProps) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 64 64\"\n width={size}\n height={size}\n aria-hidden\n style={{ display: 'block', ...style }}\n >\n <text\n x=\"32\"\n y=\"46\"\n textAnchor=\"middle\"\n fontFamily=\"Georgia, serif\"\n fontStyle=\"italic\"\n fontSize=\"42\"\n fill={letterColor}\n >\n S\n </text>\n <circle cx=\"49\" cy=\"17\" r=\"5\" fill={dotColor} />\n </svg>\n );\n}\n","import { useEffect, useState } from 'react';\nimport { FAB_SIZE } from './constants';\nimport { SettoMark } from './setto-mark';\n\n/**\n * What sits where the editor's menu goes when Setto has not sent one.\n *\n * The menu itself is served from setto-server and arrives a moment after edit\n * mode turns on, so silence is the normal state for the first few hundred\n * milliseconds and must not be reported as a fault. After that a fault is\n * exactly what it is, and the owner is standing on a page in edit mode with no\n * way to publish — so say so, and say the one thing that fixes it.\n *\n * It cannot do the menu's work: publishing goes through the same host that\n * failed to send this, so a fallback that offered a Publiser button would be\n * offering a button that cannot work.\n */\nconst GRACE_MS = 4000;\n\nexport function ToolbarUnavailable() {\n const [late, setLate] = useState(false);\n useEffect(() => {\n const timer = setTimeout(() => setLate(true), GRACE_MS);\n return () => clearTimeout(timer);\n }, []);\n if (!late) return null;\n\n return (\n <div role=\"status\" style={pillStyle}>\n <SettoMark size={22} />\n <span>Setto er ikke tilgjengelig. Last siden på nytt.</span>\n </div>\n );\n}\n\nconst pillStyle: React.CSSProperties = {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 8,\n height: FAB_SIZE,\n padding: '0 16px',\n borderRadius: FAB_SIZE / 2,\n background: '#211711',\n color: '#F2EBDF',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n fontSize: 13,\n whiteSpace: 'nowrap',\n boxShadow: '0 8px 24px rgba(33, 23, 17, 0.35), 0 2px 6px rgba(33, 23, 17, 0.2)',\n};\n","import { useEffect, useState, type ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { ThemeStore } from '../lib/theme-store';\nimport { useSettoDocumentLayout } from './document-layout';\nimport { ToolbarUnavailable } from './toolbar-fallback';\nimport { useSettoChromeSlot } from '../chrome';\n\ninterface EditModeShellProps {\n children: ReactNode;\n themeStore: ThemeStore | null;\n /** Editing: the document layout, the section tools and the link hint. */\n active: boolean;\n /**\n * The Setto menu, which an owner has whether or not they are editing: out of\n * edit mode it is only the pencil. Defaults to `active`.\n */\n menu?: boolean;\n}\n\n/**\n * Edit mode: full-width page with a floating Setto FAB anchored bottom-left.\n * Text is edited inline via contentEditable on `<T>` — no sidebar.\n *\n * Always mounted around the host app so toggling edit mode does not remount\n * page content (which would replay GSAP / scroll-driven animations).\n */\nexport function EditModeShell({ children, themeStore, active, menu = active }: EditModeShellProps) {\n useSettoDocumentLayout(active);\n\n /*\n * The editor's menu is Setto's, and Setto sends it.\n *\n * It used to be built in here, which made a change to a button label a\n * publish of this package and a rebuild of every site that pins it. Now the\n * chrome offers one and this renders it in the same portal as before —\n * inside the provider's tree, so its hooks and context are the host's.\n */\n const Toolbar = useSettoChromeSlot('toolbar');\n /*\n * The two smaller pieces of editing chrome, also Setto's and also served.\n *\n * They arrive in the same bundle as the menu, so in practice all three land\n * together. Neither has a fallback: unlike the menu, whose absence looks\n * like a broken editor, these are additive — and when they are missing the\n * menu is missing too and already says so.\n */\n const SectionTools = useSettoChromeSlot('section-toolbar');\n const LinkHint = useSettoChromeSlot('link-hint');\n const [toolbarRoot, setToolbarRoot] = useState<HTMLDivElement | null>(null);\n const [hintRoot, setHintRoot] = useState<HTMLDivElement | null>(null);\n const [sectionToolbarRoot, setSectionToolbarRoot] = useState<HTMLDivElement | null>(null);\n\n /*\n * The menu's root, placed by itself rather than by the edit-mode stylesheet:\n * out of edit mode that stylesheet is gone and the pencil still has to sit\n * in the corner.\n */\n useEffect(() => {\n if (!menu) {\n setToolbarRoot(null);\n return;\n }\n const toolbar = document.createElement('div');\n toolbar.id = 'setto-toolbar-root';\n Object.assign(toolbar.style, {\n position: 'fixed',\n right: 'var(--setto-fab-inset, 16px)',\n bottom: 'var(--setto-fab-inset, 16px)',\n zIndex: '2147483647',\n });\n document.body.appendChild(toolbar);\n setToolbarRoot(toolbar);\n return () => {\n toolbar.remove();\n };\n }, [menu]);\n\n useEffect(() => {\n if (!active) {\n setHintRoot(null);\n setSectionToolbarRoot(null);\n return;\n }\n\n const hint = document.createElement('div');\n hint.id = 'setto-hint-root';\n hint.style.pointerEvents = 'none';\n document.body.appendChild(hint);\n\n const sectionBar = document.createElement('div');\n sectionBar.id = 'setto-section-toolbar-root';\n sectionBar.style.pointerEvents = 'none';\n document.body.appendChild(sectionBar);\n\n setHintRoot(hint);\n setSectionToolbarRoot(sectionBar);\n\n return () => {\n hint.remove();\n sectionBar.remove();\n };\n }, [active]);\n\n return (\n <>\n {children}\n {menu && toolbarRoot\n ? createPortal(Toolbar ? <Toolbar /> : <ToolbarUnavailable />, toolbarRoot)\n : null}\n {active && hintRoot && LinkHint ? createPortal(<LinkHint />, hintRoot) : null}\n {active && sectionToolbarRoot && themeStore && SectionTools\n ? createPortal(<SectionTools />, sectionToolbarRoot)\n : null}\n </>\n );\n}\n\n/** @deprecated Use EditModeShell */\nexport const EditModeMount = EditModeShell;\n","/**\n * The chat's public settings: whether the site has chat at all, and how it\n * introduces itself.\n *\n * Its own file, apart from the widget, because this is the one question every\n * visitor's page asks; the widget and its Markdown renderer are fetched only\n * when the answer is yes (see `index.ts`).\n */\nexport type PublicSettings = {\n enabled: boolean;\n displayName: string | null;\n greeting: string;\n /** The owner's opening line per language; an older server omits it. */\n welcome?: { no?: string | null; en?: string | null } | null;\n /** The assistant's persona on this site; an older server omits both. */\n agentName?: string | null;\n agentAvatarUrl?: string | null;\n};\n\n/** Never on Setto's own page, where the owner's chat is the dashboard's. */\nexport function chatShownHere(pathname: string): boolean {\n return !pathname.startsWith('/setto');\n}\n\n/** The settings when chat is on, otherwise null — including when the call fails. */\nexport async function fetchEnabledChatSettings(\n apiUrl: string,\n siteId: string,\n signal?: AbortSignal,\n): Promise<PublicSettings | null> {\n try {\n const response = await fetch(\n `${apiUrl.replace(/\\/+$/, '')}/sites/${encodeURIComponent(siteId)}/chat/settings/public`,\n { headers: { Accept: 'application/json' }, signal },\n );\n if (!response.ok) return null;\n const settings = (await response.json()) as PublicSettings | null;\n return settings?.enabled ? settings : null;\n } catch {\n return null;\n }\n}\n","import { Component, createElement, lazy, Suspense, useEffect, useState, type ReactNode } from 'react';\nimport type { SettoModule } from '../module';\nimport { useSetto } from '../../provider';\nimport { chatShownHere, fetchEnabledChatSettings, type PublicSettings } from './settings';\n\nexport const chatModule: SettoModule = {\n id: 'chat',\n label: 'Chat',\n};\n\n/*\n * The widget, with its Markdown stack (react-markdown, remark-gfm, micromark),\n * is a chunk of its own: about 230 kB that every visitor of every site used to\n * download, where most sites have no chat switched on.\n */\nconst SettoChatWidget = lazy(() =>\n import('./SettoChat').then((module) => ({ default: module.SettoChatWidget })),\n);\n\n/**\n * A widget that will not load (a chunk gone after a deploy, a dropped\n * connection) or throws leaves the site as it was: no chat, no white page.\n */\nclass ChatBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {\n state = { failed: false };\n static getDerivedStateFromError() {\n return { failed: true };\n }\n componentDidCatch(error: unknown) {\n console.warn('[setto] chat failed, continuing without it', error);\n }\n render() {\n return this.state.failed ? null : this.props.children;\n }\n}\n\n/**\n * The visitor chat, when the site has it switched on.\n *\n * Asks setto-server for the public settings and fetches the widget only when\n * they say chat is on (0.47). Renders nothing until then, nothing on `/setto`,\n * and nothing at all for a site without chat. The provider mounts it already;\n * a site does not need to.\n */\nexport function SettoChat() {\n const { config } = useSetto();\n const [settings, setSettings] = useState<PublicSettings | null>(null);\n\n useEffect(() => {\n if (!chatShownHere(window.location.pathname)) return;\n let cancelled = false;\n void fetchEnabledChatSettings(config.apiUrl, config.siteId).then((next) => {\n if (!cancelled && next) setSettings(next);\n });\n return () => {\n cancelled = true;\n };\n }, [config.apiUrl, config.siteId]);\n\n if (!settings) return null;\n return createElement(\n ChatBoundary,\n null,\n createElement(Suspense, { fallback: null }, createElement(SettoChatWidget, { settings })),\n );\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { SupabaseClient, Session } from '@supabase/supabase-js';\nimport { useTranslation } from 'react-i18next';\nimport {\n browserStorage,\n needsSupabaseAtStart,\n supabaseLoader,\n supabaseStorageKey,\n} from './lib/supabase';\nimport { createApi, type SettoApi } from './lib/api';\nimport { I18nStore } from './lib/i18n-store';\nimport { AutoLanguageSwitcher, InlineLanguagesContext } from './LanguageSwitcher';\nimport { readStoredLanguage, siteLanguages } from './lib/languages';\nimport {\n alternateLinks,\n languageFromPath,\n redirectForVisitor,\n sameOriginUrl,\n} from './lib/language-routing';\nimport { AssetStore } from './lib/asset-store';\nimport { ThemeStore } from './lib/theme-store';\nimport { PageStore } from './lib/page-store';\nimport { bundledManifest } from './pages/bundled';\nimport { useSiteAccess } from './lib/use-site-access';\nimport { visitorView } from './lib/visitor-view';\nimport { SettoChrome } from './chrome';\nimport { isAdminRoute } from './lib/urls';\nimport type { SettoConfig, SiteRow } from './types';\nimport { EditModeShell } from './edit-mode/mount';\nimport { SettoChat } from './modules/chat';\n\nexport interface SettoContextValue {\n config: SettoConfig;\n /**\n * The Supabase client, or null until supabase-js has loaded (0.47).\n *\n * The library is fetched only when someone can be signed in: a session is\n * stored for this project, the page is `/setto`, a sign-in arrives in the\n * URL, the chrome offers an editor component, or `loadSupabase` is called.\n * For a visitor it stays null for the whole visit. It is never null while\n * `session` is set, and never null inside a component the chrome offered\n * through a slot. Elsewhere, check it or call `loadSupabase`.\n */\n supabase: SupabaseClient | null;\n /**\n * The Supabase client, loading supabase-js first if nothing has yet (0.47).\n * Memoised: always the same client as `supabase`. Absent on older clients.\n */\n loadSupabase: () => Promise<SupabaseClient>;\n api: SettoApi;\n session: Session | null;\n /**\n * True while the initial auth state is being read from local storage. False\n * from the first render for a visitor with no stored session (0.47).\n */\n authLoading: boolean;\n /**\n * True while the owner is editing: `canEdit`, and they chose to edit. What\n * makes text editable, shows hidden sections and draws the section tools.\n */\n editMode: boolean;\n /**\n * True when this person may edit this site: signed in, a member, the site is\n * paid for (or this is the site's support account), and this is not `/setto`. The Setto menu is drawn whenever this\n * is; outside `editMode` it shows the site as a visitor sees it.\n * Absent on a client older than 0.33, where `editMode` meant this.\n */\n canEdit: boolean;\n /** Switch editing on or off. Remembered for this site in this browser. */\n setEditing: (on: boolean) => void;\n /** Site row matching `config.siteId`, or `null` if the user has no access. */\n currentSite: SiteRow | null;\n /** All sites the user can access (loaded after sign-in). */\n sites: SiteRow[] | null;\n /**\n * Lazily created when i18next is initialised. Components that need it\n * should `if (!store) return null;` until then.\n */\n store: I18nStore | null;\n themeStore: ThemeStore | null;\n assetStore: AssetStore | null;\n /**\n * The page manifest being edited: section order, hidden sections, pages and\n * menu links. Holds `null` inside for a site that has no `pages.json`.\n * Absent on a client older than 0.29, which the chrome has to allow for.\n */\n pageStore: PageStore | null;\n /** The section the editor has selected, or null. */\n selectedSectionId: string | null;\n selectSection: (id: string | null) => void;\n /**\n * True while a signed-out visitor is trying the editor (setto.no).\n *\n * Here beside `editMode` rather than in `GuestEditProvider`'s own context\n * for the same reason the selected section is: the chrome that draws the\n * section toolbar sits above that provider and can call only `useSetto`.\n */\n guestEdit: boolean;\n setGuestEdit: (on: boolean) => void;\n}\n\n/**\n * Exported for one caller: the chrome bundle.\n *\n * The dashboard is compiled into that bundle, so its `useSetto` reads *this*\n * module's context — a different instance from the one the host provider\n * fills, which would otherwise throw \"must be used within SettoProvider\" the\n * moment it rendered. Handing it the host's value through this provider is\n * what lets the same components run on either side of the boundary.\n *\n * Not part of the public API in any other sense. Use `useSetto`.\n */\nexport const SettoContext = createContext<SettoContextValue | null>(null);\n\nexport interface SettoProviderProps {\n config: SettoConfig;\n children: ReactNode;\n}\n\n/**\n * Wraps the host app. Initialises Supabase, the API client, and listens for\n * auth changes. Mounts the edit toolbar and enables inline editing when active.\n *\n * The owner may edit (`canEdit`) when ALL of:\n * 1. There is an authenticated Supabase session.\n * 2. The user has access to `config.siteId` in the Setto sites table.\n * 3. The current path is not the `/setto` admin SPA.\n *\n * Once an editor signs in via `/setto` they stay signed in until they sign out\n * there. Whether they are editing is their own switch (`setEditing`): the\n * Setto menu's pencil turns it on, and publishing turns it off.\n */\nexport function SettoProvider({ config, children }: SettoProviderProps) {\n const { url: supabaseUrl, anonKey: supabaseAnonKey } = config.supabase;\n const loader = useMemo(\n () => supabaseLoader({ url: supabaseUrl, anonKey: supabaseAnonKey }),\n [supabaseUrl, supabaseAnonKey],\n );\n const [supabase, setSupabase] = useState<SupabaseClient | null>(() => loader.client);\n if (supabase && supabase !== loader.client) setSupabase(loader.client);\n\n const loadSupabase = useCallback(\n () =>\n loader.load().then((client) => {\n setSupabase(client);\n return client;\n }),\n [loader],\n );\n\n /*\n * The token for an API call. Only a page that has loaded supabase-js, or is\n * loading it, can have a session; anything else answers `not_authenticated`\n * without fetching the library just to find that out.\n */\n const api = useMemo(\n () =>\n createApi({\n apiUrl: config.apiUrl,\n supabase: () =>\n loader.client || loader.loading ? loader.load() : Promise.resolve(null),\n }),\n [config.apiUrl, loader],\n );\n\n /*\n * Whether someone can be signed in on this page load, which is the only time\n * the answer to \"is there a session?\" needs supabase-js (lib/supabase.ts).\n * For everybody else it is \"no\", known at once: `authLoading` is false from\n * the first render and the library is never fetched.\n */\n const [authWanted, setAuthWanted] = useState(() =>\n typeof window === 'undefined'\n ? false\n : needsSupabaseAtStart(config.supabase, {\n pathname: window.location.pathname,\n hash: window.location.hash,\n search: window.location.search,\n storage: browserStorage(),\n }),\n );\n const [authLoadFailed, setAuthLoadFailed] = useState(false);\n const [sessionRead, setSessionRead] = useState(false);\n const [session, setSession] = useState<Session | null>(null);\n const authLoading = authWanted && !authLoadFailed && (!supabase || !sessionRead);\n const [onAdminRoute, setOnAdminRoute] = useState(() =>\n typeof window === 'undefined' ? false : isAdminRoute(),\n );\n\n useEffect(() => {\n if (!authWanted || supabase) return;\n let cancelled = false;\n loadSupabase().catch((error: unknown) => {\n if (cancelled) return;\n console.warn('[setto] could not load sign-in, continuing signed out', error);\n setAuthLoadFailed(true);\n });\n return () => {\n cancelled = true;\n };\n }, [authWanted, supabase, loadSupabase]);\n\n /*\n * Signed in in another tab while this one was open: supabase-js would have\n * heard it through its own storage listener, had it been loaded.\n */\n useEffect(() => {\n if (authWanted) return;\n const prefix = supabaseStorageKey(supabaseUrl);\n const onStorage = (event: StorageEvent) => {\n if (event.key?.startsWith(prefix) && event.newValue) setAuthWanted(true);\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n }, [authWanted, supabaseUrl]);\n\n useEffect(() => {\n if (!supabase) return;\n let cancelled = false;\n supabase.auth.getSession().then(\n ({ data }) => {\n if (cancelled) return;\n setSession(data.session ?? null);\n setSessionRead(true);\n },\n () => {\n if (!cancelled) setSessionRead(true);\n },\n );\n const { data: sub } = supabase.auth.onAuthStateChange((_event, session) => {\n setSession(session);\n });\n return () => {\n cancelled = true;\n sub.subscription.unsubscribe();\n };\n }, [supabase]);\n\n // Track whether we are inside the /setto admin SPA so the inline editor stays\n // off while the dashboard is rendered. Listens to popstate; admin nav uses\n // `window.location.replace` for top-level transitions.\n useEffect(() => {\n const compute = () => setOnAdminRoute(isAdminRoute());\n compute();\n window.addEventListener('popstate', compute);\n return () => window.removeEventListener('popstate', compute);\n }, []);\n\n const access = useSiteAccess(supabase, session, config.siteId);\n\n // The i18n store hangs off the live i18next instance from react-i18next.\n const { i18n } = useTranslation();\n\n /*\n * Every language this site speaks, primary first.\n *\n * Computed rather than read straight off the config so a list that forgets\n * to name the primary language cannot make the site's own copy unreachable.\n */\n const languages = useMemo(\n () => siteLanguages(config.languages, config.languages?.[0]),\n [config.languages],\n );\n\n /*\n * The URL says which language this is.\n *\n * Not `localStorage`, which is where it lived for one release and which no\n * search engine and no shared link can see. `/priser` is Norwegian and\n * `/en/priser` is English, and both are addresses somebody can send to\n * somebody else.\n *\n * A first-time visitor whose browser asks for a language the site speaks is\n * moved to that address once — never away from one they are already at, so\n * a click on «Norsk» is not undone on the next page.\n */\n useEffect(() => {\n if (!i18n || languages.length < 2) return;\n\n const redirect = redirectForVisitor(\n window.location.pathname,\n languages,\n navigator.languages ?? [navigator.language],\n readStoredLanguage(),\n );\n if (redirect && redirect !== window.location.pathname) {\n // Only ever to somewhere on this site; see `sameOriginUrl`.\n const url = sameOriginUrl(\n redirect + window.location.search + window.location.hash,\n window.location.origin,\n );\n if (url) {\n window.location.replace(url);\n return;\n }\n }\n\n const { language } = languageFromPath(window.location.pathname, languages);\n if (language !== i18n.language) void i18n.changeLanguage(language);\n document.documentElement.lang = language;\n }, [i18n, languages]);\n\n /*\n * `hreflang`, so the two addresses are understood as one page in two\n * languages rather than two pages that happen to say similar things.\n *\n * Written from here rather than into `index.html` because only this knows\n * which path the visitor is on, and a static head cannot name the\n * alternates for a route it has never heard of.\n *\n * Unless the page already names them (0.49.0). A page the build wrote a\n * head for — a blog post, or a page a site drew ahead of time — knows\n * better than a guess from the path: an untranslated post has no English\n * address of its own (its `/en` copy points its canonical at the\n * Norwegian one), and links added here would have named it anyway.\n */\n useEffect(() => {\n if (languages.length < 2) return;\n if (document.head.querySelector('link[rel=\"alternate\"][hreflang]:not([data-setto-alternate])')) return;\n const links = alternateLinks(window.location.origin, window.location.pathname, languages);\n const added = links.map(({ hreflang, href }) => {\n const el = document.createElement('link');\n el.rel = 'alternate';\n el.hreflang = hreflang;\n el.href = href;\n el.dataset.settoAlternate = '';\n document.head.appendChild(el);\n return el;\n });\n return () => added.forEach((el) => el.remove());\n }, [languages]);\n const storeRef = useRef<I18nStore | null>(null);\n const themeStoreRef = useRef<ThemeStore | null>(null);\n const assetStoreRef = useRef<AssetStore | null>(null);\n const pageStoreRef = useRef<PageStore | null>(null);\n const [storeReady, setStoreReady] = useState(false);\n\n useEffect(() => {\n if (!i18n) return;\n storeRef.current = new I18nStore(i18n);\n themeStoreRef.current = new ThemeStore(config.theme ?? {});\n assetStoreRef.current = new AssetStore();\n pageStoreRef.current = new PageStore(bundledManifest(config.pages));\n setStoreReady(true);\n }, [i18n, config.theme, config.pages]);\n\n /*\n * A member of the site, paid for or not (Simon, 2026-10-26): a preview's\n * owner edits it before choosing a plan, and setto-server decides what that\n * costs (Pixel's larger changes are limited until there is a plan). Until\n * 0.46 only a `live` site could be edited here.\n *\n * The site's support account, which a Setto admin signs in as with\n * «Rediger» in the admin, is a member of the one site its `app_metadata`\n * names, so it passes the same way.\n */\n const canEdit =\n !!session &&\n !!access.currentSite &&\n !onAdminRoute &&\n !authLoading &&\n !access.loading;\n\n /*\n * Editing is a switch the owner holds, not the same thing as being signed in\n * (Simon, 2026-09-25). Signed in, they see their site as a visitor does with\n * only a pencil at the bottom; the pencil turns editing on, and publishing\n * turns it off again. Remembered per site in this browser so a reload while\n * editing stays editing. Off to begin with.\n */\n const [editing, setEditingState] = useState(() => readEditing(config.siteId));\n const setEditing = useCallback(\n (on: boolean) => {\n writeEditing(config.siteId, on);\n setEditingState(on);\n },\n [config.siteId],\n );\n const editMode = canEdit && editing;\n\n /*\n * Which section is selected, held here rather than in a context of its own.\n *\n * It used to have one, which was tidier until the section toolbar moved to\n * the chrome: that bundle can call exactly one hook of the host's,\n * `useSetto`, so a second context was a second thing to hand across the\n * boundary — and the way to hand it across would have been another method on\n * the loader, the one file that cannot change without a re-pin of the fleet.\n * `useSectionEdit()` still exists and still reads the same two fields.\n */\n const [selectedSectionId, setSelectedSectionId] = useState<string | null>(null);\n const selectSection = useCallback((id: string | null) => setSelectedSectionId(id), []);\n\n const [guestEdit, setGuestEdit] = useState(false);\n // Real edit mode always wins; a signed-in owner is never also a guest.\n useEffect(() => {\n if (editMode && guestEdit) setGuestEdit(false);\n }, [editMode, guestEdit]);\n useEffect(() => {\n document.documentElement.classList.toggle('setto-guest-editing', guestEdit);\n return () => document.documentElement.classList.remove('setto-guest-editing');\n }, [guestEdit]);\n\n const value: SettoContextValue = {\n config,\n supabase,\n loadSupabase,\n api,\n session,\n authLoading,\n editMode,\n canEdit,\n setEditing,\n currentSite: access.currentSite,\n sites: access.sites,\n store: storeReady ? storeRef.current : null,\n themeStore: storeReady ? themeStoreRef.current : null,\n assetStore: storeReady ? assetStoreRef.current : null,\n pageStore: storeReady ? pageStoreRef.current : null,\n selectedSectionId,\n selectSection,\n guestEdit,\n setGuestEdit,\n };\n\n // Filled in while the site's tree is drawn; read by the floating switcher drawn after it.\n const inlineLanguages = useRef({ drawn: false }).current;\n\n const editShellActive = editMode && !!value.store;\n const menuShown = canEdit && !!value.store;\n\n return (\n <SettoContext.Provider value={value}>\n <InlineLanguagesContext.Provider value={inlineLanguages}>\n <EditModeShell active={editShellActive} menu={menuShown} themeStore={value.themeStore}>\n {children}\n </EditModeShell>\n {/*\n * Setto's own furniture, fetched at runtime rather than built in.\n *\n * The bar used to live in this bundle, which meant every change to it\n * — a label, a colour, where a button led — was a rebuild and redeploy\n * of every site Setto has made. See `chrome.tsx`: what ships here now\n * is a loader that must never change, and everything interesting is a\n * server deploy away.\n */}\n {/*\n * Everywhere, including /setto.\n *\n * This guard was right when the thing behind it was the preview bar,\n * which has no business over the editor. It is wrong for the loader:\n * the chrome is now responsible for the dashboard too, so skipping it\n * on the admin route meant no handshake, no bundle, and a silent\n * fall back to the bundled copy — which is exactly what the fleet\n * showed. What may be drawn where is the chrome's decision now, and\n * the chrome is the part that can be changed without a re-pin.\n */}\n <SettoChrome />\n <SettoChat />\n {/*\n * The visitor's own language control.\n *\n * Renders nothing at all for a single-language site, which is all of\n * them today, and stands down when the site places its own\n * `<SettoLanguages inline>` somewhere in its design.\n */}\n <AutoLanguageSwitcher languages={languages} />\n </InlineLanguagesContext.Provider>\n </SettoContext.Provider>\n );\n}\n\nconst editingKey = (siteId: string) => `setto-editing:${siteId}`;\n\nfunction readEditing(siteId: string): boolean {\n try {\n return window.localStorage.getItem(editingKey(siteId)) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeEditing(siteId: string, on: boolean): void {\n try {\n if (on) window.localStorage.setItem(editingKey(siteId), '1');\n else window.localStorage.removeItem(editingKey(siteId));\n } catch {\n // Private mode: the switch lasts for this page.\n }\n}\n\nexport function useSetto(): SettoContextValue {\n const ctx = useContext(SettoContext);\n if (!ctx) {\n throw new Error('useSetto() must be used inside <SettoProvider>');\n }\n return ctx;\n}\n\n/**\n * True once it is known that nobody on this page can edit it, false for an\n * owner, null until it is known. Wait for `true` before rewriting text in the\n * DOM (SplitText and the like): see `lib/visitor-view.ts`.\n */\nexport function useVisitorView(): boolean | null {\n const { authLoading, session, sites, canEdit, guestEdit } = useSetto();\n return visitorView({ authLoading, hasSession: !!session, sitesLoaded: sites !== null, canEdit, guestEdit });\n}\n","import { createContext, useContext, useEffect, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { languageName, siteLanguages, storeLanguage } from './lib/languages';\nimport { SettoContext } from './provider';\nimport { pathForLanguage, sameOriginUrl } from './lib/language-routing';\n\n/**\n * The control a visitor uses to read the site in their own language.\n *\n * Mounted by `SettoProvider` rather than placed by the agent, and only when\n * the site actually speaks more than one language — so it costs a Norwegian\n * plumber's site nothing, and a site that gains a second language grows the\n * control without anybody editing a header.\n *\n * That decision is worth stating because it is a trade. Auto-mounting means\n * the switcher cannot sit inside a design it knows nothing about, so it sits\n * in a corner instead: quiet, small, and out of the way of whatever the agent\n * built. A site that wants it in its own header can render `<SettoLanguages>`\n * anywhere and pass `inline`, and the floating one stands down.\n *\n * Styling is inline for the same reason the editing chrome's is: this renders\n * inside a page whose stylesheet Setto did not write, and most of these sites\n * ship Tailwind's Preflight, which would otherwise strip a bare `<button>`\n * back to nothing.\n */\n\nexport interface SettoLanguagesProps {\n /**\n * Every language the site speaks, primary first. Read from the provider's\n * config when left out, which is what a site should do: the list lives in\n * `setto.config.json` and grows when a customer adds a language in Språk,\n * so a header that hard-codes it goes stale the first time they do.\n */\n languages?: readonly string[];\n /**\n * Rendered in the flow of the page rather than fixed in a corner.\n *\n * Also tells the auto-mounted copy to stand down, so a site that places its\n * own switcher does not end up with two.\n */\n inline?: boolean;\n}\n\n/** Set on `document.documentElement` while an inline switcher is on the page. */\nconst INLINE_MARKER = 'data-setto-languages-inline';\n\n/**\n * Whether an inline switcher has been drawn in this render, ahead of the\n * floating copy (the provider draws that after the site's tree). Set while\n * drawing rather than from an effect, so a page drawn on a server — and the\n * browser's first render of it — leaves the floating copy out from the start\n * (0.49.0). It was in the prerendered HTML of setto.no and vanished once the\n * page's script ran: a «Norsk» pill blinking in the corner of every page.\n */\nexport const InlineLanguagesContext = createContext<{ drawn: boolean } | null>(null);\n\nexport function SettoLanguages({ languages: given, inline = false }: SettoLanguagesProps) {\n const { i18n } = useTranslation();\n const setto = useContext(SettoContext);\n const configured = setto?.config.languages;\n const languages = given ?? siteLanguages(configured, configured?.[0]);\n const [open, setOpen] = useState(false);\n const [hover, setHover] = useState(false);\n const [surface, setSurface] = useState<{ background: string; color: string } | null>(null);\n const ref = useRef<HTMLDivElement>(null);\n const drawnInline = useContext(InlineLanguagesContext);\n if (inline && drawnInline) drawnInline.drawn = true;\n\n /*\n * Announce an inline switcher so the floating one can hide. A ref on the\n * document rather than context, because the two can be mounted by different\n * trees — the provider's own and the site's.\n */\n useEffect(() => {\n if (!inline) return;\n const root = document.documentElement;\n const count = Number(root.getAttribute(INLINE_MARKER) ?? '0') + 1;\n root.setAttribute(INLINE_MARKER, String(count));\n return () => {\n const left = Number(root.getAttribute(INLINE_MARKER) ?? '1') - 1;\n if (left > 0) root.setAttribute(INLINE_MARKER, String(left));\n else root.removeAttribute(INLINE_MARKER);\n };\n }, [inline]);\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: MouseEvent) => {\n if (!ref.current?.contains(e.target as Node)) setOpen(false);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') setOpen(false);\n };\n document.addEventListener('mousedown', onDown);\n document.addEventListener('keydown', onKey);\n return () => {\n document.removeEventListener('mousedown', onDown);\n document.removeEventListener('keydown', onKey);\n };\n }, [open]);\n\n if (languages.length < 2) return null;\n\n const current = i18n.language;\n\n /*\n * The inline list opens over somebody's header, light or dark, and cannot\n * know which from a stylesheet it did not write. So it borrows: the first\n * opaque background above it and the text colour the trigger inherited.\n */\n const toggle = () => {\n if (!open && inline && ref.current) setSurface(surroundings(ref.current));\n setOpen((o) => !o);\n };\n\n const choose = (tag: string) => {\n setOpen(false);\n if (tag === current) return;\n /*\n * Remembered so the redirect for a first-time visitor does not argue with\n * a choice they have just made — it is not what decides the language any\n * more, the address is.\n */\n storeLanguage(tag);\n\n /*\n * A real navigation rather than `changeLanguage` and a `pushState`.\n *\n * The language is in the URL now, so switching it *is* going somewhere\n * else. A full load is also the only way to be sure the page comes back\n * with the right `lang` attribute, the right alternates, and the right\n * router basename — and this client cannot reach the site's router to do\n * it any other way: `react-router` is the site's dependency, not ours.\n * Switching language is a rare, deliberate act; a page load is an honest\n * price for it.\n */\n const target = pathForLanguage(window.location.pathname, tag, languages);\n // Never off the site, whatever the address bar held. See `normalise`.\n const url = sameOriginUrl(target + window.location.search + window.location.hash, window.location.origin);\n if (url) window.location.assign(url);\n };\n\n return (\n <div ref={ref} style={inline ? inlineWrapStyle : floatingWrapStyle}>\n <button\n type=\"button\"\n onClick={toggle}\n onMouseEnter={() => setHover(true)}\n onMouseLeave={() => setHover(false)}\n aria-expanded={open}\n aria-haspopup=\"listbox\"\n aria-label={`Språk: ${languageName(current)}`}\n title={inline ? languageName(current) : undefined}\n style={inline ? { ...inlineTriggerStyle, opacity: hover || open ? 1 : inlineTriggerStyle.opacity } : floatingTriggerStyle}\n >\n <GlobeIcon />\n {inline ? shortCode(current) : languageName(current)}\n </button>\n\n {open ? (\n <ul\n role=\"listbox\"\n style={\n inline\n ? { ...inlineListStyle, ...(surface ? { background: surface.background, color: surface.color } : {}) }\n : floatingListStyle\n }\n >\n {languages.map((tag) => (\n <li key={tag}>\n <button\n type=\"button\"\n role=\"option\"\n aria-selected={tag === current}\n onClick={() => choose(tag)}\n style={{\n ...optionStyle,\n ...(inline ? { color: 'inherit' } : {}),\n fontWeight: tag === current ? 600 : 400,\n }}\n >\n {languageName(tag)}\n </button>\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n}\n\n/**\n * The floating copy, mounted by the provider.\n *\n * Renders nothing when the site places its own, and nothing when there is only\n * one language to be in.\n */\nexport function AutoLanguageSwitcher({ languages }: { languages: readonly string[] }) {\n const drawnInline = useContext(InlineLanguagesContext);\n const [inlineElsewhere, setInlineElsewhere] = useState(() => drawnInline?.drawn ?? false);\n\n useEffect(() => {\n const check = () => setInlineElsewhere(document.documentElement.hasAttribute(INLINE_MARKER));\n check();\n // The site's own switcher may mount after this one; watch rather than\n // read once, or a page ends up with both for its first frame and forever.\n const observer = new MutationObserver(check);\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [INLINE_MARKER],\n });\n return () => observer.disconnect();\n }, []);\n\n if (inlineElsewhere || languages.length < 2) return null;\n return <SettoLanguages languages={languages} />;\n}\n\n/** «NO», «EN», «PT-BR» — as short as a theme icon, the full name is in the label and the list. */\nfunction shortCode(tag: string): string {\n return tag.toUpperCase();\n}\n\n/** The first opaque background above `el`, and the text colour it has. */\nfunction surroundings(el: HTMLElement): { background: string; color: string } {\n const color = getComputedStyle(el).color;\n for (let node: HTMLElement | null = el; node; node = node.parentElement) {\n const background = getComputedStyle(node).backgroundColor;\n if (background && !/^(transparent|rgba\\(.*,\\s*0\\))$/.test(background)) return { background, color };\n }\n return { background: '#ffffff', color: '#1a1a1a' };\n}\n\n/**\n * A globe.\n *\n * «A文» was tried here and reverted: it is the mark browsers use, but it is\n * not one people recognise on a plumber's website, and an icon that has to be\n * explained has already failed. The globe is imprecise — it says «the\n * internet» as readily as it says «language» — and it is what everybody\n * already reads as a language control, which on a small business's site\n * matters more than being right.\n */\nfunction GlobeIcon() {\n return (\n <svg\n width=\"15\"\n height=\"15\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.8\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M3 12h18M12 3c2.4 2.6 3.6 5.6 3.6 9s-1.2 6.4-3.6 9c-2.4-2.6-3.6-5.6-3.6-9S9.6 5.6 12 3z\" />\n </svg>\n );\n}\n\n/*\n * Bottom-left, because the editor's own button is bottom-right and a customer\n * signing in should not find two round things fighting over one corner.\n */\nconst floatingWrapStyle: React.CSSProperties = {\n position: 'fixed',\n left: 'max(16px, env(safe-area-inset-left))',\n bottom: 'max(16px, env(safe-area-inset-bottom))',\n zIndex: 2147482000,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nconst inlineWrapStyle: React.CSSProperties = {\n position: 'relative',\n display: 'inline-block',\n fontFamily: 'inherit',\n};\n\nconst triggerBase: React.CSSProperties = {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 7,\n minHeight: 40,\n fontSize: 13.5,\n fontWeight: 500,\n lineHeight: 1,\n cursor: 'pointer',\n};\n\n/*\n * The floating copy has to be seen against a page it knows nothing about, so\n * it brings its own pill: a translucent ground, a hairline and a little lift.\n */\nconst floatingTriggerStyle: React.CSSProperties = {\n ...triggerBase,\n padding: '8px 14px',\n borderRadius: 999,\n border: '1px solid rgba(127, 127, 127, 0.32)',\n background: 'rgba(255, 255, 255, 0.82)',\n backdropFilter: 'blur(8px)',\n WebkitBackdropFilter: 'blur(8px)',\n color: '#1a1a1a',\n boxShadow: '0 4px 14px rgba(0, 0, 0, 0.12)',\n};\n\n/*\n * Placed in somebody's own header, it brings nothing.\n *\n * No ground, no border, no shadow, and `currentColor` — a control that draws\n * its own pill inside a header that has already decided what a control looks\n * like is two designs arguing. Language is a setting, not an action, so it\n * should read quieter than the buttons beside it, not louder.\n */\nconst inlineTriggerStyle: React.CSSProperties = {\n ...triggerBase,\n gap: 5,\n minHeight: 36,\n padding: '6px 6px',\n border: 0,\n borderRadius: 8,\n background: 'transparent',\n color: 'inherit',\n fontSize: 12,\n fontWeight: 500,\n letterSpacing: '0.06em',\n opacity: 0.7,\n transition: 'opacity 160ms ease',\n};\n\nconst listBase: React.CSSProperties = {\n position: 'absolute',\n margin: 0,\n padding: 4,\n listStyle: 'none',\n minWidth: 150,\n borderRadius: 12,\n border: '1px solid rgba(127, 127, 127, 0.24)',\n background: '#ffffff',\n boxShadow: '0 12px 32px rgba(0, 0, 0, 0.18)',\n zIndex: 1,\n};\n\nconst floatingListStyle: React.CSSProperties = { ...listBase, left: 0, bottom: 'calc(100% + 8px)' };\n/* Right-aligned: an inline switcher sits at the end of a header, beside the theme button. */\nconst inlineListStyle: React.CSSProperties = { ...listBase, right: 0, top: 'calc(100% + 8px)' };\n\nconst optionStyle: React.CSSProperties = {\n display: 'block',\n width: '100%',\n minHeight: 40,\n padding: '9px 12px',\n border: 0,\n borderRadius: 8,\n background: 'transparent',\n color: '#1a1a1a',\n fontSize: 13.5,\n textAlign: 'left',\n cursor: 'pointer',\n};\n","import { createPortal } from 'react-dom';\nimport type { ReactNode } from 'react';\nimport { useSettoChromeSlot } from './chrome';\nimport { useSetto } from './provider';\n\n/**\n * Lets visitors inline-edit a marketing site (e.g. setto.no) without auth —\n * text, section/block colours, icons and list items. Changes are session-only\n * and never published. Real Setto edit mode always takes precedence.\n *\n * A provider in name only since 2026-09-09: the state moved into the main\n * context so the chrome could see it, and what is left here is the one thing\n * guest mode adds — the section toolbar, over a page nobody is signed in to.\n * The component comes from Setto like the rest of the editing chrome, so there\n * is nothing to draw until it arrives, and nothing to draw at all if it does\n * not. That is the right failure for a demo.\n */\nexport function GuestEditProvider({ children }: { children: ReactNode }) {\n const { guestEdit, themeStore } = useSetto();\n const SectionTools = useSettoChromeSlot('section-toolbar');\n\n return (\n <>\n {children}\n {guestEdit && themeStore && SectionTools\n ? createPortal(<SectionTools />, document.body)\n : null}\n </>\n );\n}\n\nexport interface GuestEditContextValue {\n active: boolean;\n start: () => void;\n stop: () => void;\n}\n\nexport function useGuestEdit(): GuestEditContextValue {\n const { guestEdit, setGuestEdit, selectSection } = useSetto();\n return {\n active: guestEdit,\n start: () => setGuestEdit(true),\n stop: () => {\n setGuestEdit(false);\n selectSection(null);\n },\n };\n}\n","/** Editable text inside a navigation target (link or button), excluding language toggles. */\nexport function isLinkContext(el: HTMLElement): boolean {\n const key = el.getAttribute('data-setto-key');\n if (key?.startsWith('lang.')) return false;\n if (el.closest('[data-setto-no-hint]')) return false;\n return !!(el.closest('a[href]') || el.closest('button'));\n}\n\n/** Same as Ctrl/Cmd+click — follow the parent link or trigger the parent button. */\nexport function activateLinkContext(el: HTMLElement): void {\n const anchor = el.closest('a[href]');\n if (anchor instanceof HTMLAnchorElement) {\n anchor.click();\n return;\n }\n const button = el.closest('button');\n if (button instanceof HTMLButtonElement) {\n button.click();\n }\n}\n","import { useLayoutEffect, useRef, useState, type RefObject } from 'react';\nimport { createPortal } from 'react-dom';\nimport { activateLinkContext } from '../lib/link-context';\n\nconst MARGIN = 10;\nconst OFFSET = 8;\nconst MIN_TOUCH = 44;\n\ninterface LinkActionChipProps {\n anchorRef: RefObject<HTMLElement | null>;\n visible: boolean;\n}\n\nfunction placeChip(anchor: DOMRect, width: number, height: number): { left: number; top: number } {\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n\n let left = anchor.left + anchor.width / 2 - width / 2;\n let top = anchor.bottom + OFFSET;\n\n if (left + width > vw - MARGIN) left = vw - width - MARGIN;\n if (left < MARGIN) left = MARGIN;\n\n if (top + height > vh - MARGIN) {\n top = anchor.top - height - OFFSET;\n }\n if (top < MARGIN) top = MARGIN;\n\n return { left, top };\n}\n\n/**\n * Touch-only chip shown when editable link/button text is focused.\n * Replaces Ctrl/Cmd+click on coarse-pointer devices.\n */\nexport function LinkActionChip({ anchorRef, visible }: LinkActionChipProps) {\n const chipRef = useRef<HTMLButtonElement>(null);\n const [position, setPosition] = useState<{ left: number; top: number } | null>(null);\n\n useLayoutEffect(() => {\n if (!visible || !anchorRef.current) {\n setPosition(null);\n return;\n }\n\n const update = () => {\n const el = anchorRef.current;\n const chip = chipRef.current;\n if (!el) return;\n const rect = el.getBoundingClientRect();\n const width = chip?.offsetWidth ?? 120;\n const height = chip?.offsetHeight ?? MIN_TOUCH;\n setPosition(placeChip(rect, width, height));\n };\n\n update();\n window.addEventListener('scroll', update, true);\n window.addEventListener('resize', update);\n return () => {\n window.removeEventListener('scroll', update, true);\n window.removeEventListener('resize', update);\n };\n }, [visible, anchorRef]);\n\n if (!visible || !anchorRef.current) return null;\n\n const host = document.getElementById('setto-hint-root') ?? document.body;\n\n const style: React.CSSProperties = {\n position: 'fixed',\n left: position?.left ?? 0,\n top: position?.top ?? 0,\n visibility: position ? 'visible' : 'hidden',\n minHeight: MIN_TOUCH,\n minWidth: MIN_TOUCH,\n padding: '10px 14px',\n background: '#1a1a1a',\n color: '#fff',\n fontSize: 13,\n fontWeight: 500,\n border: 'none',\n borderRadius: 8,\n boxShadow: '0 4px 16px rgba(0,0,0,0.2)',\n fontFamily: 'system-ui, sans-serif',\n whiteSpace: 'nowrap',\n touchAction: 'manipulation',\n zIndex: 2147483647,\n };\n\n return createPortal(\n <button\n ref={chipRef}\n type=\"button\"\n data-setto-ui\n style={style}\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n const el = anchorRef.current;\n if (el) activateLinkContext(el);\n el?.blur();\n }}\n >\n Naviger ↗\n </button>,\n host,\n );\n}\n","/** Place the text caret at viewport coordinates inside a contentEditable element. */\nexport function placeCaretAtPoint(x: number, y: number, el: HTMLElement): void {\n el.focus();\n\n const doc = el.ownerDocument;\n const selection = doc.getSelection();\n if (!selection) return;\n\n const range = rangeFromPoint(doc, x, y);\n if (!range) return;\n\n if (!el.contains(range.startContainer)) {\n range.selectNodeContents(el);\n range.collapse(false);\n }\n\n selection.removeAllRanges();\n selection.addRange(range);\n}\n\nfunction rangeFromPoint(doc: Document, x: number, y: number): Range | null {\n if (doc.caretRangeFromPoint) {\n return doc.caretRangeFromPoint(x, y);\n }\n\n const legacy = doc as Document & {\n caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;\n };\n const pos = legacy.caretPositionFromPoint?.(x, y);\n if (!pos) return null;\n\n const range = doc.createRange();\n range.setStart(pos.offsetNode, pos.offset);\n range.collapse(true);\n return range;\n}\n","import { useSyncExternalStore } from 'react';\n\nconst QUERY = '(hover: none) and (pointer: coarse)';\n\nfunction subscribe(onChange: () => void): () => void {\n const mq = window.matchMedia(QUERY);\n mq.addEventListener('change', onChange);\n return () => mq.removeEventListener('change', onChange);\n}\n\nfunction getSnapshot(): boolean {\n return window.matchMedia(QUERY).matches;\n}\n\n/** True on touch-first devices (phones, tablets without hover). */\nexport function useCoarsePointer(): boolean {\n return useSyncExternalStore(subscribe, getSnapshot, () => false);\n}\n","import { useTranslation } from 'react-i18next';\nimport {\n useEffect,\n useRef,\n useState,\n type ClipboardEvent,\n type FocusEvent,\n type FormEvent,\n type KeyboardEvent,\n type MouseEvent,\n} from 'react';\nimport { LinkActionChip } from './edit-mode/link-action-chip';\nimport { isLinkContext } from './lib/link-context';\nimport { placeCaretAtPoint } from './lib/place-caret-at-point';\nimport { useCoarsePointer } from './lib/use-coarse-pointer';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\n\nexport interface TProps {\n /** The dotted translation key, e.g. 'hero.headline'. */\n k: string;\n}\n\n/**\n * Renders a translation key. In edit mode the text is contentEditable inline;\n * changes flow into the draft store for the active language.\n */\nexport function T({ k }: TProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guestEdit = useGuestEdit();\n const editable = editMode || guestEdit.active;\n const ref = useRef<HTMLSpanElement>(null);\n const [focused, setFocused] = useState(false);\n const [linkContext, setLinkContext] = useState(false);\n const coarsePointer = useCoarsePointer();\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const value = store ? store.get(k, i18n.language) : t(k);\n\n useEffect(() => {\n const el = ref.current;\n if (!el || focused || !editable) return;\n if (el.textContent !== value) el.textContent = value;\n }, [value, focused, editable]);\n\n if (!editable) return <>{value}</>;\n\n const handleMouseDown = (e: MouseEvent<HTMLSpanElement>) => {\n e.stopPropagation();\n const el = e.currentTarget;\n if (!isLinkContext(el)) return;\n if (e.ctrlKey || e.metaKey) return;\n e.preventDefault();\n };\n\n const handleMouseUp = (e: MouseEvent<HTMLSpanElement>) => {\n if (e.button !== 0) return;\n e.stopPropagation();\n const el = e.currentTarget;\n if (isLinkContext(el) && (e.ctrlKey || e.metaKey)) return;\n if (isLinkContext(el)) {\n placeCaretAtPoint(e.clientX, e.clientY, el);\n }\n };\n\n const handleClick = (e: MouseEvent<HTMLSpanElement>) => {\n e.stopPropagation();\n const el = e.currentTarget;\n if (isLinkContext(el) && (e.ctrlKey || e.metaKey)) return;\n if (isLinkContext(el)) {\n e.preventDefault();\n }\n };\n\n /** Block parent <button>/<a> activation (Space/Enter) while typing. */\n const handleKeyDown = (e: KeyboardEvent<HTMLSpanElement>) => {\n if (!isLinkContext(e.currentTarget)) return;\n e.stopPropagation();\n };\n\n const handleKeyUp = (e: KeyboardEvent<HTMLSpanElement>) => {\n if (!isLinkContext(e.currentTarget)) return;\n if (e.key === ' ' || e.key === 'Enter') {\n e.preventDefault();\n e.stopPropagation();\n }\n };\n\n const commit = (el: HTMLSpanElement) => {\n const text = el.textContent ?? '';\n store?.set(k, i18n.language, text);\n };\n\n const handleBlur = (e: FocusEvent<HTMLSpanElement>) => {\n setFocused(false);\n setLinkContext(false);\n commit(e.currentTarget);\n };\n\n const handleInput = (e: FormEvent<HTMLSpanElement>) => {\n store?.set(k, i18n.language, e.currentTarget.textContent ?? '');\n };\n\n const handlePaste = (e: ClipboardEvent<HTMLSpanElement>) => {\n e.preventDefault();\n const text = e.clipboardData.getData('text/plain');\n if (!text) return;\n const el = e.currentTarget;\n el.focus();\n document.execCommand('insertText', false, text);\n store?.set(k, i18n.language, el.textContent ?? '');\n };\n\n const lang = toBcp47(i18n.language);\n\n const showLinkChip = coarsePointer && focused && linkContext;\n\n return (\n <>\n <span\n ref={ref}\n data-setto-key={k}\n contentEditable\n suppressContentEditableWarning\n lang={lang}\n spellCheck={false}\n role=\"textbox\"\n tabIndex={0}\n onFocus={(e) => {\n setFocused(true);\n setLinkContext(isLinkContext(e.currentTarget));\n }}\n onBlur={handleBlur}\n onInput={handleInput}\n onPaste={handlePaste}\n onMouseDown={handleMouseDown}\n onMouseUp={handleMouseUp}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n onKeyUp={handleKeyUp}\n style={{\n cursor: 'text',\n color: 'inherit',\n outline: focused\n ? editMode\n ? '2px solid #640AFF'\n : '2px solid #C4502A'\n : undefined,\n outlineOffset: 2,\n borderRadius: 2,\n transition: 'outline-color 120ms',\n }}\n />\n {showLinkChip ? <LinkActionChip anchorRef={ref} visible={focused} /> : null}\n </>\n );\n}\n\n/** Map i18next language codes to BCP 47 for browser spellcheck. */\nfunction toBcp47(code: string): string {\n const base = (code.split('-')[0] ?? code).toLowerCase();\n if (base === 'no' || base === 'nb' || base === 'nn') return 'nb-NO';\n if (base === 'en') return 'en';\n return code;\n}\n","import { useSetto } from './provider';\n\n/**\n * Which section the editor has selected.\n *\n * A context of its own until 2026-09-09, when the section toolbar moved out to\n * the chrome served by setto-server. That bundle can call exactly one hook of\n * the host's — `useSetto` — so the state moved into the main context and this\n * became an adapter. Kept because `SettoSection` and `SettoBlock` read it on\n * every render of every page, and renaming that in thirteen pinned sites buys\n * nothing.\n */\nexport interface SectionEditContextValue {\n selectedId: string | null;\n selectSection: (id: string | null) => void;\n}\n\nexport function useSectionEdit(): SectionEditContextValue {\n const { selectedSectionId, selectSection } = useSetto();\n return { selectedId: selectedSectionId, selectSection };\n}\n","import type { CSSProperties, MouseEvent } from 'react';\n\n/** Returns true when the click target is editable text or Setto UI chrome. */\nexport function isTextEditClick(target: HTMLElement): boolean {\n if (target.closest('[data-setto-key]')) return true;\n if (target.closest('[data-setto-ui]')) return true;\n if (target.closest('[data-setto-icon]')) return true;\n if (target.closest('[data-setto-image]')) return true;\n if (target.closest('[data-setto-repeater]')) return true;\n let node: HTMLElement | null = target;\n while (node) {\n if (\n node.matches('h1,h2,h3,h4,h5,h6,p,li,figcaption') &&\n node.querySelector('[data-setto-key]')\n ) {\n return true;\n }\n node = node.parentElement;\n }\n return false;\n}\n\n/** True when the click landed on a nested theme target inside `container`. */\nexport function isNestedThemeTarget(\n target: HTMLElement,\n container: HTMLElement,\n): boolean {\n const hit = target.closest('[data-setto-section]');\n return !!(hit && hit !== container);\n}\n\nexport function handleThemeTargetClick(\n e: MouseEvent<HTMLElement>,\n editable: boolean,\n themeId: string,\n selected: boolean,\n selectSection: (id: string | null) => void,\n onClick?: (e: MouseEvent<HTMLElement>) => void,\n): void {\n onClick?.(e);\n if (!editable || e.defaultPrevented) return;\n\n const target = e.target as HTMLElement;\n if (isTextEditClick(target)) return;\n if (target.closest('a[href], button, input, textarea, select')) return;\n\n e.preventDefault();\n e.stopPropagation();\n selectSection(selected ? null : themeId);\n}\n\nexport function themeTargetEditStyle(\n editable: boolean,\n selected: boolean,\n accent = '#640AFF',\n): CSSProperties {\n if (!editable) return {};\n return {\n cursor: 'pointer',\n outline: selected ? `2px solid ${accent}` : undefined,\n outlineOffset: selected ? -2 : undefined,\n };\n}\n","import { useSyncExternalStore } from 'react';\nimport { useSetto } from './provider';\nimport { EMPTY_THEME_STORE_SNAPSHOT } from './lib/theme-store';\n\n/** Returns the current colour tokens for a section (live in edit mode). */\nexport function useSectionTheme(sectionId: string): Record<string, string> {\n const { themeStore, config } = useSetto();\n\n const version = useSyncExternalStore(\n (cb) => themeStore?.subscribe(() => cb()) ?? (() => {}),\n () => themeStore?.snapshot().version ?? EMPTY_THEME_STORE_SNAPSHOT.version,\n () => EMPTY_THEME_STORE_SNAPSHOT.version,\n );\n\n void version;\n\n if (themeStore) return themeStore.getSection(sectionId);\n return config.theme?.[sectionId] ?? {};\n}\n","import {\n forwardRef,\n useCallback,\n type ComponentPropsWithoutRef,\n type MouseEvent,\n} from 'react';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\nimport { useSectionEdit } from './section-context';\nimport {\n handleThemeTargetClick,\n isNestedThemeTarget,\n themeTargetEditStyle,\n} from './theme-target-utils';\nimport { useSectionTheme } from './use-section-theme';\n\nexport interface SettoSectionProps extends ComponentPropsWithoutRef<'section'> {\n /** Theme key, e.g. 'values'. */\n sectionId: string;\n}\n\n/**\n * Wraps a page section with theme-driven background colour and edit-mode\n * selection. Click the section chrome (not editable text or nested blocks)\n * to open the colour toolbar.\n *\n * The section also carries `id={sectionId}`, which is what makes a header's\n * `href=\"#produkter\"` land anywhere. Every generated site so far wrote that nav\n * and shipped it dead: the only handle on the element was\n * `data-setto-section`, an attribute no fragment identifier can address, and a\n * menu that silently does nothing looks exactly like a menu that works until\n * somebody taps it. An explicit `id` prop still wins — it is spread after this\n * one — so a page that needs a different anchor can say so.\n */\nexport const SettoSection = forwardRef<HTMLElement, SettoSectionProps>(\n function SettoSection({ sectionId, className, style, children, onClick, ...rest }, ref) {\n const { editMode } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const accent = editMode ? '#640AFF' : '#C4502A';\n const { selectedId, selectSection } = useSectionEdit();\n const colors = useSectionTheme(sectionId);\n const selected = selectedId === sectionId;\n\n const handleClick = useCallback(\n (e: MouseEvent<HTMLElement>) => {\n if (editable) {\n const target = e.target as HTMLElement;\n if (isNestedThemeTarget(target, e.currentTarget)) return;\n }\n handleThemeTargetClick(e, editable, sectionId, selected, selectSection, onClick);\n },\n [editable, onClick, selectSection, selected, sectionId],\n );\n\n const mergedStyle = {\n ...style,\n ...(colors.background ? { backgroundColor: colors.background } : {}),\n ...themeTargetEditStyle(editable, selected, accent),\n };\n\n return (\n <section\n ref={ref}\n id={sectionId}\n data-setto-section={sectionId}\n className={className}\n style={mergedStyle}\n onClick={handleClick}\n {...rest}\n >\n {children}\n </section>\n );\n },\n);\n","import {\n forwardRef,\n useCallback,\n type ComponentPropsWithoutRef,\n type MouseEvent,\n} from 'react';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\nimport { useSectionEdit } from './section-context';\nimport { handleThemeTargetClick, themeTargetEditStyle } from './theme-target-utils';\nimport { useSectionTheme } from './use-section-theme';\n\nexport interface SettoBlockProps extends ComponentPropsWithoutRef<'div'> {\n /** Theme key in sections.json, e.g. 'innovationCard'. */\n blockId: string;\n}\n\n/**\n * Themeable block (card, panel) inside a section. Click the block chrome to\n * edit its colours; click text to edit copy.\n */\nexport const SettoBlock = forwardRef<HTMLDivElement, SettoBlockProps>(\n function SettoBlock({ blockId, className, style, children, onClick, ...rest }, ref) {\n const { editMode } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const accent = editMode ? '#640AFF' : '#C4502A';\n const { selectedId, selectSection } = useSectionEdit();\n const colors = useSectionTheme(blockId);\n const selected = selectedId === blockId;\n\n const handleClick = useCallback(\n (e: MouseEvent<HTMLDivElement>) => {\n handleThemeTargetClick(\n e as MouseEvent<HTMLElement>,\n editable,\n blockId,\n selected,\n selectSection,\n onClick as ((e: MouseEvent<HTMLElement>) => void) | undefined,\n );\n },\n [editable, blockId, selected, selectSection, onClick],\n );\n\n const mergedStyle = {\n ...style,\n ...(colors.background ? { backgroundColor: colors.background } : {}),\n ...themeTargetEditStyle(editable, selected, accent),\n };\n\n return (\n <div\n ref={ref}\n data-setto-section={blockId}\n className={className}\n style={mergedStyle}\n onClick={handleClick}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n","import {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nexport interface PopoverPosition {\n top: number;\n left: number;\n}\n\ninterface FloatingPopoverProps {\n open: boolean;\n anchorRef: React.RefObject<HTMLElement | null>;\n onClose: () => void;\n ariaLabel: string;\n children: ReactNode;\n style?: CSSProperties;\n minWidth?: number;\n}\n\n/** Anchored popover portal used by icon picker and similar edit UI. */\nexport function FloatingPopover({\n open,\n anchorRef,\n onClose,\n ariaLabel,\n children,\n style,\n minWidth = 280,\n}: FloatingPopoverProps) {\n const popoverRef = useRef<HTMLDivElement>(null);\n const [pos, setPos] = useState<PopoverPosition | null>(null);\n\n useLayoutEffect(() => {\n if (!open || !anchorRef.current) {\n setPos(null);\n return;\n }\n\n const update = () => {\n const anchor = anchorRef.current;\n const pop = popoverRef.current;\n if (!anchor) return;\n\n const rect = anchor.getBoundingClientRect();\n const popoverH = pop?.offsetHeight ?? 200;\n const popoverW = pop?.offsetWidth ?? minWidth;\n\n let top = rect.bottom + 6;\n let left = rect.left;\n\n if (left + popoverW > window.innerWidth - 8) {\n left = window.innerWidth - popoverW - 8;\n }\n if (left < 8) left = 8;\n if (top + popoverH > window.innerHeight - 8) {\n top = rect.top - popoverH - 6;\n }\n if (top < 8) top = rect.bottom + 6;\n\n setPos({ top, left });\n };\n\n update();\n requestAnimationFrame(update);\n window.addEventListener('scroll', update, true);\n window.addEventListener('resize', update);\n return () => {\n window.removeEventListener('scroll', update, true);\n window.removeEventListener('resize', update);\n };\n }, [open, anchorRef, minWidth]);\n\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose();\n };\n window.addEventListener('keydown', onKey);\n return () => window.removeEventListener('keydown', onKey);\n }, [open, onClose]);\n\n useEffect(() => {\n if (!open) return;\n const close = (e: MouseEvent) => {\n const target = e.target as Node;\n if (anchorRef.current?.contains(target)) return;\n if (popoverRef.current?.contains(target)) return;\n onClose();\n };\n document.addEventListener('mousedown', close);\n return () => document.removeEventListener('mousedown', close);\n }, [open, onClose, anchorRef]);\n\n if (!open) return null;\n\n return createPortal(\n <div\n ref={popoverRef}\n role=\"dialog\"\n aria-label={ariaLabel}\n data-setto-ui\n style={{\n position: 'fixed',\n top: pos?.top ?? -9999,\n left: pos?.left ?? 0,\n visibility: pos ? 'visible' : 'hidden',\n zIndex: 2147483647,\n background: '#fff',\n border: '1px solid #e0e0e0',\n borderRadius: 8,\n boxShadow: '0 8px 24px rgba(0,0,0,0.15)',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n ...style,\n }}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={(e) => e.stopPropagation()}\n >\n {children}\n </div>,\n document.body,\n );\n}\n","import {\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type CSSProperties,\n type MouseEvent,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { FloatingPopover } from './edit-mode/floating-popover';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\n\nexport interface SettoIconProps {\n /** i18n key storing the Lucide icon name, e.g. `problem.cards.complicated.icon`. */\n k: string;\n /** Map of icon name → Lucide component (provided by the host site). */\n icons: Record<string, ComponentType<SettoIconRenderProps>>;\n size?: number;\n className?: string;\n style?: CSSProperties;\n}\n\nexport interface SettoIconRenderProps {\n size?: number;\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * Renders an icon whose identity is stored in i18n. In edit mode, click to open\n * an icon browser and pick a replacement.\n */\nexport function SettoIcon({ k, icons, size = 24, className, style }: SettoIconProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const accent = editMode ? '#640AFF' : '#C4502A';\n const anchorRef = useRef<HTMLSpanElement>(null);\n const [open, setOpen] = useState(false);\n const [search, setSearch] = useState('');\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const iconName = store ? store.get(k, i18n.language) : t(k);\n const Icon = icons[iconName] ?? icons[Object.keys(icons)[0] ?? ''] ?? null;\n\n if (!Icon) return null;\n\n if (!editable) {\n return <Icon size={size} className={className} style={style} />;\n }\n\n const handleClick = (e: MouseEvent<HTMLSpanElement>) => {\n e.stopPropagation();\n e.preventDefault();\n setOpen((v) => !v);\n };\n\n const filtered = Object.entries(icons).filter(([name]) =>\n name.toLowerCase().includes(search.toLowerCase()),\n );\n\n return (\n <>\n <span\n ref={anchorRef}\n data-setto-icon\n data-setto-key={k}\n role=\"button\"\n tabIndex={0}\n aria-label=\"Velg ikon\"\n onClick={handleClick}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n setOpen((v) => !v);\n }\n }}\n style={{\n display: 'inline-flex',\n cursor: 'pointer',\n outline: open ? `2px solid ${accent}` : undefined,\n outlineOffset: 2,\n borderRadius: 4,\n }}\n >\n <Icon size={size} className={className} style={style} />\n </span>\n\n <FloatingPopover\n open={open}\n anchorRef={anchorRef}\n onClose={() => {\n setOpen(false);\n setSearch('');\n }}\n ariaLabel=\"Ikonvelger\"\n minWidth={320}\n style={{ padding: 12, maxWidth: 360 }}\n >\n <input\n type=\"search\"\n value={search}\n onChange={(e) => setSearch(e.target.value)}\n placeholder=\"Søk ikon…\"\n data-setto-ui\n style={{\n width: '100%',\n boxSizing: 'border-box',\n padding: '8px 10px',\n marginBottom: 10,\n border: '1px solid #e0e0e0',\n borderRadius: 6,\n fontSize: 13,\n }}\n />\n <div\n style={{\n display: 'grid',\n gridTemplateColumns: 'repeat(6, 1fr)',\n gap: 4,\n maxHeight: 240,\n overflowY: 'auto',\n }}\n >\n {filtered.map(([name, Item]) => {\n const selected = name === iconName;\n return (\n <button\n key={name}\n type=\"button\"\n title={name}\n data-setto-ui\n onClick={() => {\n store?.set(k, i18n.language, name);\n setOpen(false);\n setSearch('');\n }}\n style={{\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: 8,\n background: selected ? '#f5f3ff' : 'transparent',\n border: selected ? '1px solid #640AFF' : '1px solid transparent',\n borderRadius: 6,\n cursor: 'pointer',\n color: style?.color ?? 'currentColor',\n }}\n >\n <Item size={20} />\n </button>\n );\n })}\n </div>\n </FloatingPopover>\n </>\n );\n}\n","/**\n * Setto's public media store: the `setto-media` Vercel Blob store, where blog\n * photographs live instead of in each site's repo (R24). setto-server writes\n * to it (`blog/<siteId>/<hash>/<name>.<ext>`), a post refers to the URL, and\n * the site's Vercel Image Optimization resizes it through the\n * `remotePatterns` entry in `settoVercelImagesConfig`.\n *\n * One store for every site, so its host is a constant. It changes only if the\n * store is replaced — then here, in the server's token, and in each site's\n * `vercel.json`, together.\n */\nexport const SETTO_MEDIA_HOST = '3adyw42hy72dtzjo.public.blob.vercel-storage.com';\n\n/** Where blog photographs sit in the store. */\nexport const SETTO_MEDIA_BLOG_PREFIX = '/blog/';\n\n/** A blog photograph in Setto's media store: https, that host, under `/blog/`. */\nexport function isSettoMediaUrl(src: string | null | undefined): src is string {\n if (!src) return false;\n try {\n const url = new URL(src);\n return (\n url.protocol === 'https:' &&\n url.hostname === SETTO_MEDIA_HOST &&\n !url.username &&\n !url.password &&\n url.port === '' &&\n url.pathname.startsWith(SETTO_MEDIA_BLOG_PREFIX)\n );\n } catch {\n return false;\n }\n}\n","/**\n * Images through Vercel's Image Optimization, for sites that turned it on.\n *\n * A site keeps one original per image in its repository; the CDN makes each\n * width on first request, in AVIF or WebP as the browser accepts, and caches\n * it by the file's content. A site turns it on with two things that must\n * agree: `\"images\": { \"optimize\": true }` in `setto.config.json`, and an\n * `images` block in `vercel.json` whose `sizes` and `qualities` are exactly\n * the constants below — Vercel refuses a `w` or `q` it was not given. The\n * block, for copying: `settoVercelImagesConfig`.\n *\n * Blog photographs are the one exception to \"a file of this site's own\": they\n * live in Setto's media store (`./media.ts`) and reach the optimizer through\n * the block's `remotePatterns` entry. A site whose `vercel.json` predates that\n * entry gets a refusal from the optimizer, and `SettoImage` falls back to the\n * original, as it does for any failed variant.\n */\n\nimport { SETTO_MEDIA_BLOG_PREFIX, SETTO_MEDIA_HOST, isSettoMediaUrl } from './media';\n\nconst escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/** Phone, phone at 2–3×, tablet, laptop, wide and retina desktop. */\nexport const SETTO_IMAGE_WIDTHS = [384, 640, 828, 1080, 1440, 1920, 2560] as const;\n\n/** One quality for every image, so each width is one cached variant rather than several. */\nexport const SETTO_IMAGE_QUALITY = 75;\n\n/** The `images` block of `vercel.json` that matches `SettoImage`. */\nexport const settoVercelImagesConfig = {\n sizes: [...SETTO_IMAGE_WIDTHS],\n qualities: [SETTO_IMAGE_QUALITY],\n formats: ['image/avif', 'image/webp'],\n localPatterns: [{ pathname: '^/images/.*$', search: '' }],\n // Vercel reads hostname and pathname as regular expressions; anchored so a\n // look-alike host cannot borrow the optimizer. Checked on a deployment\n // (R24): this form resizes, an unlisted host or path is refused with 400.\n remotePatterns: [\n {\n protocol: 'https',\n hostname: `^${escapeRegExp(SETTO_MEDIA_HOST)}$`,\n pathname: `^${escapeRegExp(SETTO_MEDIA_BLOG_PREFIX)}.*$`,\n },\n ],\n minimumCacheTTL: 2678400,\n} as const;\n\n/** The formats Vercel transforms; anything else (SVG, GIF) is served as it is. */\nconst OPTIMIZABLE = /\\.(jpe?g|png|webp|avif)$/i;\n\n/**\n * Whether an image can go through the optimizer: a file of this site's own,\n * under `/images/`, or a blog photograph in Setto's media store, in a format\n * it transforms. A draft's `blob:` preview, any other external address, an\n * SVG logo and a moving GIF cannot.\n */\nexport function isOptimizable(src: string | null | undefined): src is string {\n if (!src) return false;\n if (src.startsWith('/images/')) return OPTIMIZABLE.test(src.split(/[?#]/)[0]!);\n return isSettoMediaUrl(src) && OPTIMIZABLE.test(new URL(src).pathname);\n}\n\n/**\n * Where there is no optimizer to ask: the Vite dev server and a local\n * preview. A deployment elsewhere without one (a build sandbox) is caught by\n * the image's own error instead.\n */\nexport function hasNoOptimizer(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname.endsWith('.localhost');\n}\n\nexport function optimizedUrl(src: string, width: number): string {\n return `/_vercel/image?url=${encodeURIComponent(src)}&w=${width}&q=${SETTO_IMAGE_QUALITY}`;\n}\n\nexport function optimizedSrcSet(src: string): string {\n return SETTO_IMAGE_WIDTHS.map((w) => `${optimizedUrl(src, w)} ${w}w`).join(', ');\n}\n","import {\n useEffect,\n useRef,\n useState,\n type ChangeEvent,\n type ImgHTMLAttributes,\n type MouseEvent,\n type SyntheticEvent,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { generateSettoImagePaths } from './lib/image-paths';\nimport { hasNoOptimizer, isOptimizable, optimizedSrcSet, optimizedUrl } from './lib/optimized-image';\nimport type { I18nStore } from './lib/i18n-store';\nimport { useSetto } from './provider';\nimport { useSettoChromeSlot } from './chrome';\n\nexport interface SettoImageProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {\n /** i18n key for the public URL path, e.g. `hero.illustrationSrc`. */\n srcKey: string;\n}\n\n/**\n * What the served chrome is handed to draw over an image in edit mode: the\n * picker with stock photographs, the camera, an upload and «prøv lykken».\n *\n * The chrome only ever gives the image a file. Where it came from — a\n * phone's camera or Unsplash — is the chrome's business; how it becomes a\n * draft and a published path is this component's, so every source ends up\n * under `public/images/setto/` the same way.\n */\nexport interface ImageToolsProps {\n srcKey: string;\n alt?: string;\n /** The pointer is over the image. */\n hovered: boolean;\n /** An unpublished replacement is showing. */\n hasDraft: boolean;\n busy: boolean;\n /** The rendered image, for its size and its place on the page. */\n imageEl: HTMLImageElement | null;\n applyFile: (file: File) => Promise<void>;\n revert: () => void;\n}\n\nconst ACCEPT = 'image/png,image/jpeg,image/webp,image/svg+xml';\n\nfunction setSrcAllLanguages(\n store: I18nStore,\n i18n: ReturnType<typeof useTranslation>['i18n'],\n srcKey: string,\n value: string,\n): void {\n const langs = i18n.languages?.length ? i18n.languages : [i18n.language];\n for (const lng of langs) {\n store.set(srcKey, lng, value);\n }\n}\n\n/**\n * The image as a visitor gets it.\n *\n * On a site with optimization on, a `srcSet` of widths from Vercel's\n * optimizer, so a phone fetches a phone-sized WebP or AVIF instead of the\n * 2000-pixel original. `sizes` is the site's to give where the image is\n * narrower than the screen; without it the browser assumes the full width,\n * which is never too small, only sometimes larger than needed. If the\n * optimizer does not answer — a build sandbox has none, a plan can run out —\n * the image falls back to its original, so an image is never lost to it.\n * Edit mode never gets here: it shows drafts, which the optimizer cannot see.\n */\nfunction PublishedImage({\n src,\n optimize,\n sizes,\n srcSet,\n onError,\n ...rest\n}: ImgHTMLAttributes<HTMLImageElement> & { src: string; optimize: boolean }) {\n const [direct, setDirect] = useState(false);\n const optimized =\n optimize &&\n !direct &&\n !srcSet &&\n isOptimizable(src) &&\n !(typeof window !== 'undefined' && hasNoOptimizer(window.location.hostname));\n\n if (!optimized) return <img src={src} srcSet={srcSet} sizes={sizes} onError={onError} {...rest} />;\n return (\n <img\n src={optimizedUrl(src, 1080)}\n srcSet={optimizedSrcSet(src)}\n sizes={sizes ?? '100vw'}\n onError={(e: SyntheticEvent<HTMLImageElement, Event>) => {\n setDirect(true);\n onError?.(e);\n }}\n {...rest}\n />\n );\n}\n\n/**\n * Renders an image whose src is stored in i18n. In edit mode, hover to upload\n * a replacement — saved under `public/images/setto/` on publish.\n */\nexport function SettoImage({ srcKey, alt, className, style, ...rest }: SettoImageProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store, assetStore, config } = useSetto();\n const fileRef = useRef<HTMLInputElement>(null);\n const [hovered, setHovered] = useState(false);\n const [uploading, setUploading] = useState(false);\n const imgRef = useRef<HTMLImageElement>(null);\n const Tools = useSettoChromeSlot<ImageToolsProps>('image-tools');\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const [, forceAssets] = useState(0);\n useEffect(() => {\n if (!assetStore) return;\n return assetStore.subscribe(() => forceAssets((x) => x + 1));\n }, [assetStore]);\n\n const srcPath = store ? store.get(srcKey, i18n.language) : t(srcKey);\n const previewUrl = assetStore?.getPreviewUrl(srcKey);\n const src = previewUrl ?? srcPath;\n\n if (!editMode) {\n return (\n <PublishedImage\n src={srcPath}\n optimize={config.images?.optimize === true}\n alt={alt}\n className={className}\n style={style}\n {...rest}\n />\n );\n }\n\n const isFullWidth = className?.includes('w-full');\n const isFullHeight = className?.includes('h-full');\n\n const openFilePicker = (e: MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n if (!uploading) fileRef.current?.click();\n };\n\n const applyFile = async (file: File) => {\n if (!assetStore || !store) return;\n setUploading(true);\n try {\n const originalPublicPath = store.original(srcKey, i18n.language);\n const { repoPath, publicPath } = generateSettoImagePaths(srcKey, file);\n await assetStore.set({\n srcKey,\n originalPublicPath,\n repoPath,\n publicPath,\n file,\n });\n setSrcAllLanguages(store, i18n, srcKey, publicPath);\n } finally {\n setUploading(false);\n }\n };\n\n const handleFile = async (e: ChangeEvent<HTMLInputElement>) => {\n const file = e.target.files?.[0];\n e.target.value = '';\n if (file) await applyFile(file);\n };\n\n const revert = () => {\n if (!assetStore || !store) return;\n const original = assetStore.revert(srcKey);\n if (original !== null) {\n setSrcAllLanguages(store, i18n, srcKey, original);\n }\n };\n\n const handleRevert = (e: MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n if (!assetStore || !store) return;\n const original = assetStore.revert(srcKey);\n if (original !== null) {\n setSrcAllLanguages(store, i18n, srcKey, original);\n }\n };\n\n return (\n <>\n <span\n data-setto-image\n data-setto-src-key={srcKey}\n data-setto-ui\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n style={{\n display: isFullWidth || isFullHeight ? 'block' : 'inline-block',\n width: isFullWidth ? '100%' : undefined,\n height: isFullHeight ? '100%' : undefined,\n position: 'relative',\n outline: hovered ? '2px solid #640AFF' : undefined,\n outlineOffset: 2,\n borderRadius: 4,\n }}\n >\n <img ref={imgRef} src={src} alt={alt} className={className} style={style} {...rest} />\n\n {Tools ? (\n <Tools\n srcKey={srcKey}\n alt={alt}\n hovered={hovered}\n hasDraft={Boolean(previewUrl)}\n busy={uploading}\n imageEl={imgRef.current}\n applyFile={applyFile}\n revert={revert}\n />\n ) : null}\n\n {previewUrl && !hovered && !Tools ? (\n <span\n aria-hidden\n data-setto-ui\n style={{\n position: 'absolute',\n top: 4,\n right: 4,\n background: '#640AFF',\n color: '#fff',\n fontSize: 10,\n padding: '2px 6px',\n borderRadius: 4,\n fontFamily: 'system-ui, sans-serif',\n pointerEvents: 'none',\n }}\n >\n Nytt bilde\n </span>\n ) : null}\n\n {hovered && !Tools ? (\n <span\n data-setto-ui\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 8,\n background: 'rgba(0, 0, 0, 0.45)',\n borderRadius: 4,\n }}\n >\n <button\n type=\"button\"\n data-setto-ui\n disabled={uploading}\n onClick={openFilePicker}\n onMouseDown={(e) => e.stopPropagation()}\n style={{\n padding: '10px 18px',\n background: '#fff',\n color: '#222',\n border: 'none',\n borderRadius: 6,\n fontSize: 13,\n fontWeight: 500,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: uploading ? 'wait' : 'pointer',\n boxShadow: '0 2px 8px rgba(0,0,0,0.2)',\n }}\n >\n {uploading ? 'Laster opp…' : 'Velg fil…'}\n </button>\n {previewUrl ? (\n <button\n type=\"button\"\n data-setto-ui\n disabled={uploading}\n onClick={handleRevert}\n onMouseDown={(e) => e.stopPropagation()}\n style={{\n padding: '6px 12px',\n background: 'transparent',\n color: '#fff',\n border: '1px solid rgba(255,255,255,0.6)',\n borderRadius: 6,\n fontSize: 12,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: uploading ? 'wait' : 'pointer',\n }}\n >\n Angre\n </button>\n ) : null}\n </span>\n ) : null}\n </span>\n\n <input\n ref={fileRef}\n type=\"file\"\n accept={ACCEPT}\n hidden\n onChange={handleFile}\n />\n </>\n );\n}\n","import { Fragment, useEffect, useState, type CSSProperties, type ReactNode } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\n\nexport interface SettoRepeaterProps {\n /** List prefix in i18n, e.g. `faq.items`. */\n itemsKey: string;\n /** Default field values for a newly added item. */\n defaultItem: Record<string, string>;\n /** Label shown on add/remove controls. */\n itemLabel?: string;\n children: (itemKey: string, index: number) => ReactNode;\n className?: string;\n}\n\nconst STYLE_ID = 'setto-repeater-styles';\n\n/** Hover-reveal styles for the remove button — injected once per document. */\nfunction useRepeaterStyles() {\n useEffect(() => {\n if (document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = `\n .setto-repeater-remove {\n opacity: 0;\n transition: opacity 120ms ease;\n }\n .setto-repeater-item:hover .setto-repeater-remove,\n .setto-repeater-remove:focus-visible {\n opacity: 1;\n }\n @media (hover: none) {\n .setto-repeater-remove { opacity: 1; }\n }\n `;\n document.head.appendChild(el);\n }, []);\n}\n\n/**\n * Renders a dynamic list from i18n. In edit mode, editors can add items (button\n * at the end of the list) and remove items (round × revealed on hover).\n *\n * The published site gets no per-item wrapper — only the editor does.\n *\n * The wrapper exists to give the remove button something to be absolutely\n * positioned against, which is edit chrome and has no business in the output.\n * Leaving it in cost real layout: an item styled `border-b py-7 first:pt-0` is\n * the *only* child of its own wrapper, so `:first-child` matched every item and\n * `pt-0` won on all of them — every row in a repeated list sat flush on the\n * rule above it instead of clearing it by 28px. The same trap catches `last:`,\n * `odd:`, `even:` and `:not(:last-child)`; `last:border-b-0` would have erased\n * every divider on the page.\n *\n * Worse, it was invisible while authoring: in edit mode the remove button is\n * rendered before the children, so the item is not `:first-child` there and the\n * padding appears. The editor showed the correct layout and the published site\n * shipped the broken one. Dropping the wrapper from the published output is\n * what brings the two back into agreement.\n */\nexport function SettoRepeater({\n itemsKey,\n defaultItem,\n itemLabel = 'element',\n children,\n className,\n}: SettoRepeaterProps) {\n const { i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const lng = i18n.language;\n\n useRepeaterStyles();\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const keys = store ? store.getListKeys(itemsKey, lng) : [];\n\n const handleAdd = () => {\n store?.addListItem(itemsKey, lng, defaultItem);\n };\n\n const handleRemove = (itemKey: string) => {\n if (keys.length <= 1) return;\n store?.removeListItem(itemsKey, itemKey, lng);\n };\n\n const canRemove = keys.length > 1;\n\n return (\n <div className={className} data-setto-repeater>\n {keys.map((itemKey, index) =>\n editable ? (\n <div key={itemKey} className=\"setto-repeater-item\" style={{ position: 'relative' }}>\n {canRemove ? (\n <button\n type=\"button\"\n data-setto-ui\n className=\"setto-repeater-remove\"\n aria-label={`Fjern ${itemLabel}`}\n title={`Fjern ${itemLabel}`}\n onClick={(e) => {\n e.stopPropagation();\n handleRemove(itemKey);\n }}\n style={removeBtnStyle}\n >\n ×\n </button>\n ) : null}\n {children(itemKey, index)}\n </div>\n ) : (\n <Fragment key={itemKey}>{children(itemKey, index)}</Fragment>\n ),\n )}\n\n {editable ? (\n <div\n data-setto-ui\n style={{\n display: 'flex',\n justifyContent: 'flex-end',\n marginTop: 8,\n }}\n >\n <button\n type=\"button\"\n data-setto-ui\n onClick={(e) => {\n e.stopPropagation();\n handleAdd();\n }}\n style={addBtnStyle}\n >\n + Legg til {itemLabel}\n </button>\n </div>\n ) : null}\n </div>\n );\n}\n\nconst addBtnStyle: CSSProperties = {\n padding: '6px 10px',\n background: '#f7f7f7',\n border: '1px solid #e0e0e0',\n borderRadius: 6,\n fontSize: 12,\n color: '#444',\n cursor: 'pointer',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nconst removeBtnStyle: CSSProperties = {\n position: 'absolute',\n top: 4,\n right: 4,\n zIndex: 2,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n width: 24,\n height: 24,\n padding: 0,\n background: '#ffffff',\n border: '1px solid #e0e0e0',\n borderRadius: '50%',\n fontSize: 16,\n lineHeight: 1,\n color: '#444',\n cursor: 'pointer',\n boxShadow: '0 1px 4px rgba(0,0,0,0.18)',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n","import {\n Fragment,\n useEffect,\n useRef,\n useSyncExternalStore,\n type ComponentType,\n type CSSProperties,\n type ReactNode,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useSetto } from '../provider';\nimport { useSettoChromeSlot } from '../chrome';\nimport { SettoSection } from '../SettoSection';\nimport { SettoRepeater } from '../SettoRepeater';\nimport { T } from '../T';\nimport { EMPTY_PAGE_STORE_SNAPSHOT } from '../lib/page-store';\nimport { bundledManifest } from './bundled';\nimport {\n builtinKeys,\n pageById,\n pageForPath,\n ownerMenu,\n visibleMenu,\n type BuiltinSectionType,\n type MenuItem,\n type MenuList,\n type PageEntry,\n type PageSection,\n type PagesManifest,\n} from './manifest';\nimport { SettoBlogLatest, SettoBlogSection } from '../blog/SettoBlog';\n\n/**\n * The manifest as it stands now, drafts included, re-rendering on change.\n * `null` on a site that has none.\n */\nexport function usePageManifest(): PagesManifest | null {\n const { pageStore, config } = useSetto();\n const snap = useSyncExternalStore(\n (cb) => pageStore?.subscribe(() => cb()) ?? (() => {}),\n () => pageStore?.snapshot() ?? EMPTY_PAGE_STORE_SNAPSHOT,\n () => pageStore?.snapshot() ?? EMPTY_PAGE_STORE_SNAPSHOT,\n );\n // Before the store exists — the first render — the bundled file is the truth.\n return pageStore ? snap.manifest : bundledManifest(config.pages);\n}\n\n/**\n * The links a menu or footer should show, or `null` when the site has no\n * manifest and its own hard-coded list is still the truth.\n *\n * Already filtered: hidden links, links to hidden pages and anchors to hidden\n * sections are gone. Render each label with `<T k={item.labelKey} />`.\n *\n * The signed-in owner also gets the blog's link while the blog has no posts\n * (`ownerMenu`), marked `dimmed` and drawn faded by a stylesheet this hook\n * adds, so no site's navbar has to know about it.\n */\nexport function useSettoMenu(list: MenuList = 'menu'): Array<MenuItem & { dimmed?: true }> | null {\n const manifest = usePageManifest();\n const { canEdit, config } = useSetto();\n const blogEmpty = (config.blog?.posts.length ?? 0) === 0;\n const items: Array<MenuItem & { dimmed?: true }> | null = manifest\n ? canEdit\n ? ownerMenu(manifest, list, blogEmpty)\n : visibleMenu(manifest, list)\n : null;\n const dimmed = items?.filter((item) => item.dimmed).map((item) => item.href) ?? [];\n useDimmedLinks(dimmed, config.languages ?? []);\n return items;\n}\n\nconst DIM_STYLE_ID = 'setto-dimmed-links';\n\n/*\n * One stylesheet for every menu on the page. A site draws `useSettoMenu` in\n * several places — the menu, the footer, a phone's drawer — and each says\n * what it dims; the sheet is the union, so a footer with nothing to dim does\n * not undo the menu's.\n */\nconst dimmedBy = new Map<object, string[]>();\n\nfunction drawDimmedLinks() {\n if (typeof document === 'undefined') return;\n const selectors = [...new Set([...dimmedBy.values()].flat())];\n let style = document.getElementById(DIM_STYLE_ID);\n if (!selectors.length) {\n style?.remove();\n return;\n }\n if (!style) {\n style = document.createElement('style');\n style.id = DIM_STYLE_ID;\n document.head.appendChild(style);\n }\n style.textContent = `${selectors.join(',')}{opacity:.45;transition:opacity .15s}${selectors.map((s) => `${s}:hover`).join(',')}{opacity:.8}`;\n}\n\n/** Fades the owner-only links wherever the site draws them, in every language's prefix. */\nfunction useDimmedLinks(hrefs: string[], languages: string[]) {\n const key = hrefs.join('|');\n const langs = languages.join(',');\n useEffect(() => {\n if (!key) return;\n const mine = {};\n dimmedBy.set(\n mine,\n key.split('|').flatMap((href) => [\n `a[href=\"${href}\"]`,\n ...langs\n .split(',')\n .slice(1)\n .filter(Boolean)\n .map((language) => `a[href=\"/${language}${href}\"]`),\n ]),\n );\n drawDimmedLinks();\n return () => {\n dimmedBy.delete(mine);\n drawDimmedLinks();\n };\n }, [key, langs]);\n}\n\n/** What a built-in section's renderer is given. */\nexport interface BuiltinSectionProps {\n sectionId: string;\n /** The first visible section on a page gets the page's `h1`. */\n first: boolean;\n}\n\nexport interface SettoPageProps {\n /** The page to render. Wins over `path`. */\n pageId?: string;\n /** Or the one living at this path — the router's pathname, for a catch-all route. */\n path?: string;\n /**\n * The site's own sections, by section id.\n *\n * The manifest decides their order and which are hidden. A component listed\n * here that the manifest does not mention is rendered after the rest, so a\n * section added in code never silently disappears.\n */\n sections?: Record<string, ComponentType>;\n /** A site's own look for a built-in section type. */\n builtins?: Partial<Record<BuiltinSectionType, ComponentType<BuiltinSectionProps>>>;\n /** Shown when no page lives at `path`, or a visitor reaches a hidden one. */\n fallback?: ReactNode;\n}\n\n/**\n * A page, drawn from the manifest.\n *\n * Two ways in. A page the site wrote in code names itself:\n *\n * <SettoPage pageId=\"home\" sections={{ hero: Hero, services: Services }} />\n *\n * and a catch-all route renders whatever the owner added since:\n *\n * <Route path=\"*\" element={<SettoPage path={pathname} fallback={<NotFound />} />} />\n *\n * Without a manifest it renders `sections` in the order given, which is what\n * the page did before it had one.\n */\nexport function SettoPage({ pageId, path, sections = {}, builtins, fallback = null }: SettoPageProps) {\n const manifest = usePageManifest();\n const { editMode } = useSetto();\n\n if (!manifest) {\n if (!pageId && path !== undefined && path !== '/' && path !== '') return <>{fallback}</>;\n return (\n <>\n {Object.entries(sections).map(([id, Component]) => (\n <Component key={id} />\n ))}\n </>\n );\n }\n\n const page = pageId ? pageById(manifest, pageId) : pageForPath(manifest, path ?? '/');\n if (!page) {\n // A page written in code, not yet in the manifest: render it as it was.\n if (pageId) {\n return (\n <>\n {Object.entries(sections).map(([id, Component]) => (\n <Component key={id} />\n ))}\n </>\n );\n }\n return <>{fallback}</>;\n }\n if (page.hidden && !editMode) return <>{fallback}</>;\n\n return (\n <PageBody page={page} sections={sections} builtins={builtins} editMode={editMode} manifest={manifest} />\n );\n}\n\nfunction PageBody({\n page,\n sections,\n builtins,\n editMode,\n manifest,\n}: {\n page: PageEntry;\n sections: Record<string, ComponentType>;\n builtins?: SettoPageProps['builtins'];\n editMode: boolean;\n manifest: PagesManifest;\n}) {\n usePageTitle(page);\n const HiddenPageNote = useSettoChromeSlot<{ pageId: string }>('hidden-page');\n\n const listed = new Set(manifest.pages.flatMap((p) => p.sections.map((s) => s.id)));\n const unlisted = Object.keys(sections).filter((id) => !listed.has(id));\n const firstVisible = page.sections.find((s) => !s.hidden && (s.type || sections[s.id]))?.id;\n\n return (\n <>\n {page.hidden && editMode ? (\n HiddenPageNote ? <HiddenPageNote pageId={page.id} /> : <HiddenNote text=\"Denne siden er skjult for besøkende.\" />\n ) : null}\n {page.sections.map((section) => (\n <Fragment key={section.id}>\n {renderSection(section, sections, builtins, editMode, section.id === firstVisible)}\n </Fragment>\n ))}\n {unlisted.map((id) => {\n const Component = sections[id]!;\n return <Component key={id} />;\n })}\n </>\n );\n}\n\nfunction renderSection(\n section: PageSection,\n sections: Record<string, ComponentType>,\n builtins: SettoPageProps['builtins'],\n editMode: boolean,\n first: boolean,\n): ReactNode {\n if (section.hidden) {\n return editMode ? <HiddenSection section={section} /> : null;\n }\n if (section.type) {\n const Builtin = builtins?.[section.type] ?? BUILTIN_RENDERERS[section.type];\n return <Builtin sectionId={section.id} first={first} />;\n }\n const Component = sections[section.id];\n if (!Component) {\n warnOnce(section.id);\n return null;\n }\n return <Component />;\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(id: string) {\n if (warned.has(id)) return;\n warned.add(id);\n console.warn(`[setto] section \"${id}\" is in pages.json but the page does not provide it`);\n}\n\n/**\n * A hidden section, as the owner sees it: a line saying it is there and a\n * way to bring it back. The chrome draws the real one; this is what shows\n * when it has not arrived.\n */\nfunction HiddenSection({ section }: { section: PageSection }) {\n const { pageStore } = useSetto();\n const Offered = useSettoChromeSlot<{ sectionId: string; label: string }>('hidden-section');\n const label = section.label ?? section.id;\n if (Offered) return <Offered sectionId={section.id} label={label} />;\n return (\n <div data-setto-ui style={hiddenBarStyle}>\n <span>Skjult: {label}</span>\n {pageStore ? (\n <button\n type=\"button\"\n data-setto-ui\n style={hiddenBtnStyle}\n onClick={() => pageStore.apply([{ op: 'show_section', sectionId: section.id }])}\n >\n Vis\n </button>\n ) : null}\n </div>\n );\n}\n\nfunction HiddenNote({ text }: { text: string }) {\n return (\n <div data-setto-ui style={hiddenBarStyle}>\n <span>{text}</span>\n </div>\n );\n}\n\n/** The tab says which page this is, for every page but the front. */\nfunction usePageTitle(page: PageEntry) {\n const { t } = useTranslation();\n const original = useRef<string | null>(null);\n const title = page.path === '/' ? null : t(page.titleKey);\n useEffect(() => {\n if (!title || typeof document === 'undefined') return;\n original.current ??= document.title;\n const base = original.current;\n document.title = base ? `${title} · ${base}` : title;\n return () => {\n document.title = base;\n };\n }, [title]);\n}\n\n// ── Built-in sections ───────────────────────────────────────────────────────\n\n/**\n * Headings and paragraphs, for terms, privacy and the like.\n *\n * Styled inline and from the page it sits in — its font, its colours — because\n * the library cannot know the site's Tailwind classes, and a Tailwind class\n * written here would be purged from the site's CSS anyway. A site that wants\n * its own look passes `builtins={{ text: MyText }}`.\n */\nexport function SettoTextSection({ sectionId, first }: BuiltinSectionProps) {\n const keys = builtinKeys(sectionId);\n const { i18n } = useTranslation();\n const { store, editMode } = useSetto();\n const intro = store ? store.get(keys.intro, i18n.language) : i18n.t(keys.intro, { defaultValue: '' });\n const Heading = first ? 'h1' : 'h2';\n\n return (\n <SettoSection sectionId={sectionId} style={textSectionStyle}>\n <div style={textInnerStyle}>\n <Heading style={first ? textH1Style : textH2Style}>\n <T k={keys.heading} />\n </Heading>\n {intro || editMode ? (\n <p style={textIntroStyle}>\n <T k={keys.intro} />\n </p>\n ) : null}\n <SettoRepeater\n itemsKey={keys.items}\n defaultItem={{ heading: 'Overskrift', text: 'Tekst' }}\n itemLabel=\"avsnitt\"\n >\n {(itemKey) => <TextItem sectionId={sectionId} itemKey={itemKey} />}\n </SettoRepeater>\n </div>\n </SettoSection>\n );\n}\n\nfunction TextItem({ sectionId, itemKey }: { sectionId: string; itemKey: string }) {\n const keys = builtinKeys(sectionId);\n const { i18n } = useTranslation();\n const { store, editMode } = useSetto();\n const heading = store\n ? store.get(keys.itemHeading(itemKey), i18n.language)\n : i18n.t(keys.itemHeading(itemKey), { defaultValue: '' });\n return (\n <div style={textItemStyle}>\n {heading || editMode ? (\n <h3 style={textH3Style}>\n <T k={keys.itemHeading(itemKey)} />\n </h3>\n ) : null}\n <p style={textParagraphStyle}>\n <T k={keys.itemText(itemKey)} />\n </p>\n </div>\n );\n}\n\nconst BUILTIN_RENDERERS: Record<BuiltinSectionType, ComponentType<BuiltinSectionProps>> = {\n text: SettoTextSection,\n blog: SettoBlogSection,\n 'blog-latest': SettoBlogLatest,\n};\n\n// ── Styles ──────────────────────────────────────────────────────────────────\n\nconst textSectionStyle: CSSProperties = { padding: 'clamp(48px, 8vw, 96px) 16px' };\nconst textInnerStyle: CSSProperties = { maxWidth: '68ch', margin: '0 auto' };\nconst textH1Style: CSSProperties = {\n fontFamily: 'var(--setto-display-font, inherit)',\n fontSize: 'clamp(2rem, 4vw, 2.75rem)',\n lineHeight: 1.15,\n fontWeight: 600,\n margin: '0 0 0.75em',\n};\nconst textH2Style: CSSProperties = { ...textH1Style, fontSize: 'clamp(1.5rem, 3vw, 2rem)' };\nconst textH3Style: CSSProperties = {\n fontFamily: 'var(--setto-display-font, inherit)',\n fontSize: '1.125rem',\n lineHeight: 1.3,\n fontWeight: 600,\n margin: '0 0 0.4em',\n};\nconst textIntroStyle: CSSProperties = { fontSize: '1.125rem', lineHeight: 1.6, opacity: 0.85, margin: '0 0 2em' };\nconst textItemStyle: CSSProperties = { margin: '0 0 1.75em' };\nconst textParagraphStyle: CSSProperties = { lineHeight: 1.7, margin: 0, whiteSpace: 'pre-line' };\n\nconst hiddenBarStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 12,\n padding: '10px 16px',\n margin: '4px 0',\n border: '1px dashed rgba(100, 10, 255, 0.45)',\n borderRadius: 8,\n background: 'rgba(100, 10, 255, 0.05)',\n color: '#3b2a66',\n font: '500 13px system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\nconst hiddenBtnStyle: CSSProperties = {\n border: 'none',\n borderRadius: 999,\n padding: '4px 12px',\n background: '#640AFF',\n color: '#fff',\n font: '600 12px system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: 'pointer',\n};\n","/**\n * The blog post contract, version 1.\n *\n * A post is an MDX file in the site's repo, at\n * `src/content/blog/<slug>.<locale>.mdx`. The file is the record, so its shape\n * is a contract between everything that touches it: Pixel, which writes it;\n * setto-server, which validates and commits it; the click-to-edit path, which\n * patches one paragraph or one image in it; and this library, which renders\n * it. A redesign of the blog may change how a component looks, never its name,\n * its props or where posts live — old posts must keep rendering.\n *\n * MDX compiles to JavaScript, and these files are written by a model and\n * patched by owners. So the contract is closed: frontmatter with known keys,\n * CommonMark (plus GFM tables and strikethrough), and the four components\n * below with quoted string props. No `import`, no `export`, no `{…}`. A post\n * is data that happens to use JSX syntax, and is rendered from its syntax\n * tree — it is never compiled and never run.\n *\n * Changing anything here is a contract change: bump `BLOG_CONTRACT_VERSION`\n * and migrate the posts that exist, in the same release.\n */\n\nexport const BLOG_CONTRACT_VERSION = 1;\n\n/** Where published posts live, relative to the site repo root. */\nexport const BLOG_DIR = 'src/content/blog';\n\n/** The public route the blog is served under. */\nexport const BLOG_ROUTE = '/blogg';\n\n/** Lowercase words joined by single hyphens: `ny-kaffemaskin-i-butikken`. */\nexport const BLOG_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nexport const BLOG_SLUG_MAX = 80;\n\n/** A site language code, as the locale files use them: `no`, `en`, `sv`. */\nexport const BLOG_LOCALE_PATTERN = /^[a-z]{2,3}$/;\n\n/** Hard ceiling on a post file, so a runaway generation cannot be committed. */\nexport const BLOG_MAX_SOURCE_LENGTH = 200_000;\n\nexport interface BlogFrontmatter {\n /** The post's only top-level heading; the body starts at `##`. */\n title: string;\n /** The lead under the title, the meta description and the share text. */\n description: string;\n /** Publication date, `YYYY-MM-DD`. */\n date: string;\n /** Must match the file name. */\n slug: string;\n /** Must match the file name. */\n locale: string;\n /** Cover image (https), also the share image. Optional: the site's own is the fallback. */\n cover?: string;\n tags?: string[];\n}\n\nexport const BLOG_FRONTMATTER_KEYS = [\n 'title',\n 'description',\n 'date',\n 'slug',\n 'locale',\n 'cover',\n 'tags',\n] as const satisfies readonly (keyof BlogFrontmatter)[];\n\nexport const BLOG_TITLE_MAX = 120;\nexport const BLOG_DESCRIPTION_MAX = 300;\nexport const BLOG_TAGS_MAX = 8;\nexport const BLOG_TAG_MAX = 40;\n\nexport type BlogPropKind = 'text' | 'image-url' | 'youtube-id' | 'enum';\n\nexport interface BlogPropSpec {\n kind: BlogPropKind;\n required: boolean;\n /** For `text`: the longest value accepted. */\n max?: number;\n /** For `enum`: the accepted values. */\n values?: readonly string[];\n}\n\n/**\n * What a component may contain:\n * - `none`: self-closing, no children;\n * - `images`: only `<Image>` elements (a gallery);\n * - `markdown`: paragraphs and lists with inline formatting, no headings and\n * no components.\n */\nexport type BlogChildren = 'none' | 'images' | 'markdown';\n\nexport interface BlogComponentSpec {\n props: Readonly<Record<string, BlogPropSpec>>;\n children: BlogChildren;\n}\n\nexport const BLOG_GALLERY_MIN = 2;\nexport const BLOG_GALLERY_MAX = 24;\n\nexport const BLOG_COMPONENTS = {\n Image: {\n props: {\n src: { kind: 'image-url', required: true },\n alt: { kind: 'text', required: true, max: 300 },\n caption: { kind: 'text', required: false, max: 300 },\n },\n children: 'none',\n },\n Gallery: {\n props: {\n caption: { kind: 'text', required: false, max: 300 },\n },\n children: 'images',\n },\n YouTube: {\n props: {\n /** The 11-character video id, never a URL: no other embed can be smuggled in. */\n id: { kind: 'youtube-id', required: true },\n title: { kind: 'text', required: false, max: 200 },\n },\n children: 'none',\n },\n Callout: {\n props: {\n tone: { kind: 'enum', required: false, values: ['info', 'tip', 'warning'] },\n },\n children: 'markdown',\n },\n} as const satisfies Record<string, BlogComponentSpec>;\n\nexport type BlogComponentName = keyof typeof BLOG_COMPONENTS;\n\nexport const BLOG_COMPONENT_NAMES = Object.keys(BLOG_COMPONENTS) as BlogComponentName[];\n\nexport function isBlogComponentName(name: string): name is BlogComponentName {\n return Object.prototype.hasOwnProperty.call(BLOG_COMPONENTS, name);\n}\n\nexport const YOUTUBE_ID_PATTERN = /^[A-Za-z0-9_-]{11}$/;\n\n/** Link targets a post may use. Anything else, `javascript:` included, is refused. */\nexport const BLOG_LINK_SCHEMES = ['https:', 'http:', 'mailto:', 'tel:'] as const;\n\nexport function isValidBlogSlug(slug: string): boolean {\n return slug.length <= BLOG_SLUG_MAX && BLOG_SLUG_PATTERN.test(slug);\n}\n\nexport function isValidBlogLocale(locale: string): boolean {\n return BLOG_LOCALE_PATTERN.test(locale);\n}\n\n/** `src/content/blog/<slug>.<locale>.mdx`. Throws on a slug or locale the contract refuses. */\nexport function blogPostPath(slug: string, locale: string): string {\n if (!isValidBlogSlug(slug)) throw new Error(`Invalid blog slug \"${slug}\"`);\n if (!isValidBlogLocale(locale)) throw new Error(`Invalid blog locale \"${locale}\"`);\n return `${BLOG_DIR}/${slug}.${locale}.mdx`;\n}\n\n/** The slug and locale a post path names, or null if it is not a post path. */\nexport function parseBlogPostPath(path: string): { slug: string; locale: string } | null {\n const prefix = `${BLOG_DIR}/`;\n if (!path.startsWith(prefix)) return null;\n const match = /^([^/]+)\\.([^./]+)\\.mdx$/.exec(path.slice(prefix.length));\n if (!match) return null;\n const [, slug = '', locale = ''] = match;\n return isValidBlogSlug(slug) && isValidBlogLocale(locale) ? { slug, locale } : null;\n}\n\n/** The public URL path of a post. */\nexport function blogPostRoute(slug: string): string {\n return `${BLOG_ROUTE}/${slug}`;\n}\n","/**\n * The posts a site's build hands to the library, and how a page chooses among\n * them. No parser and no React: the build (`@setto/client/vite`) has already\n * validated every file against the contract and turned its body into a syntax\n * tree, so the browser only walks data.\n */\nimport type { Root } from 'mdast';\nimport type { BlogFrontmatter } from './contract';\n\n/** A post as the list knows it: its frontmatter, and nothing to download. */\nexport type BlogPostSummary = BlogFrontmatter;\n\n/** A post as its page knows it: frontmatter and the body's syntax tree. */\nexport interface BlogPostData {\n frontmatter: BlogFrontmatter;\n body: Root;\n}\n\n/**\n * What `virtual:setto-blog` exports and `SettoConfig.blog` carries. Bodies are\n * loaded one at a time, so a site with a hundred posts does not ship a\n * hundred articles to read one.\n */\nexport interface SettoBlogData {\n posts: readonly BlogPostSummary[];\n load(slug: string, locale: string): Promise<BlogPostData | null>;\n}\n\n/** Newest first; a tie breaks on slug so the order never flickers. */\nexport function byDateDesc(a: BlogPostSummary, b: BlogPostSummary): number {\n return a.date === b.date ? a.slug.localeCompare(b.slug) : a.date < b.date ? 1 : -1;\n}\n\n/**\n * One entry per post, in the reader's language where it exists and in the\n * site's own otherwise. A post written only in Norwegian still shows to an\n * English reader — untranslated is better than missing.\n */\nexport function postsForLanguage(\n posts: readonly BlogPostSummary[],\n language: string,\n fallbackLanguage: string,\n): BlogPostSummary[] {\n const bySlug = new Map<string, BlogPostSummary>();\n for (const post of posts) {\n const current = bySlug.get(post.slug);\n if (!current || rank(post, language, fallbackLanguage) < rank(current, language, fallbackLanguage)) {\n bySlug.set(post.slug, post);\n }\n }\n return [...bySlug.values()].sort(byDateDesc);\n}\n\n/** The version of one post to show this reader, or null if there is none. */\nexport function postForSlug(\n posts: readonly BlogPostSummary[],\n slug: string,\n language: string,\n fallbackLanguage: string,\n): BlogPostSummary | null {\n return postsForLanguage(posts.filter((p) => p.slug === slug), language, fallbackLanguage)[0] ?? null;\n}\n\nfunction rank(post: BlogPostSummary, language: string, fallbackLanguage: string): number {\n if (post.locale === language) return 0;\n if (post.locale === fallbackLanguage) return 1;\n return 2;\n}\n\n/** `2026-10-01` as «1. oktober 2026» or «1 October 2026». */\nexport function formatPostDate(date: string, language: string): string {\n const parsed = new Date(`${date}T12:00:00Z`);\n if (Number.isNaN(parsed.getTime())) return date;\n const locale = language === 'no' || language === 'nb' || language === 'nn' ? 'nb-NO' : language;\n try {\n return new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' }).format(parsed);\n } catch {\n return date;\n }\n}\n","/**\n * The few words the blog says itself — around the posts, never in them. In\n * Norwegian and English; any other language reads English, which is what a\n * visitor who chose it can most likely read.\n */\nconst NO = {\n blog: 'Blogg',\n latest: 'Fra bloggen',\n allPosts: 'Alle innlegg',\n readMore: 'Les mer',\n back: 'Alle innlegg',\n empty: 'Ingen innlegg ennå.',\n notFound: 'Fant ikke innlegget.',\n loading: 'Henter innlegget …',\n share: 'Del',\n moreShare: 'Flere valg …',\n copyLink: 'Kopier lenke',\n copied: 'Lenken er kopiert',\n email: 'E-post',\n video: 'Video',\n play: 'Spill av',\n};\n\nexport type BlogStrings = typeof NO;\n\nconst EN: BlogStrings = {\n blog: 'Blog',\n latest: 'From the blog',\n allPosts: 'All posts',\n readMore: 'Read more',\n back: 'All posts',\n empty: 'No posts yet.',\n notFound: 'That post could not be found.',\n loading: 'Loading the post …',\n share: 'Share',\n moreShare: 'More …',\n copyLink: 'Copy link',\n copied: 'Link copied',\n email: 'Email',\n video: 'Video',\n play: 'Play',\n};\n\nexport function blogStrings(language: string): BlogStrings {\n return language === 'no' || language === 'nb' || language === 'nn' ? NO : EN;\n}\n","/**\n * A post's body, drawn from its syntax tree.\n *\n * Every node the contract admits has a case here and nothing else does: no\n * `dangerouslySetInnerHTML`, no evaluation, no component looked up by a name\n * the file chose. A node the contract would have refused — which the build\n * already refused — renders as nothing. Links are checked again on the way\n * out, because a renderer should not trust that the gate ran.\n */\nimport { useState, type ReactNode } from 'react';\nimport type { Nodes, PhrasingContent, RootContent, Table } from 'mdast';\nimport type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';\nimport { useSetto } from '../provider';\nimport { hasNoOptimizer, isOptimizable, optimizedSrcSet, optimizedUrl } from '../lib/optimized-image';\nimport { isSafeHref } from '../pages/manifest';\nimport { YOUTUBE_ID_PATTERN } from './contract';\nimport { blogStrings } from './strings';\n\nexport function BlogBody({ nodes, language }: { nodes: readonly RootContent[]; language: string }) {\n return <>{nodes.map((node, i) => renderFlow(node, i, language))}</>;\n}\n\n/**\n * Where a draft's node sits in its file, for the owner's click-to-fix.\n *\n * A draft comes from setto-server with `at: [start, end)` on each node in\n * place of mdast's `position`; a published post never has it. The chrome\n * finds the clickable blocks by this attribute, so the renderer stays the one\n * that draws posts and drafts alike.\n */\nfunction at(node: unknown): { 'data-setto-at'?: string } {\n const range = (node as { at?: unknown }).at;\n return Array.isArray(range) && range.length === 2 && range.every((n) => Number.isInteger(n))\n ? { 'data-setto-at': `${range[0]}:${range[1]}` }\n : {};\n}\n\n/** A draft's photo: its place, and what the owner's photo editor starts from. */\nfunction atImage(node: unknown, alt: string): Record<string, string> {\n const where = at(node);\n return where['data-setto-at'] ? { ...where, 'data-setto-kind': 'image', 'data-setto-alt': alt } : {};\n}\n\nfunction renderFlow(node: Nodes, key: number, language: string): ReactNode {\n switch (node.type) {\n case 'paragraph':\n return (\n <p key={key} {...at(node)}>\n {renderPhrasing(node.children)}\n </p>\n );\n case 'heading': {\n const Tag = node.depth === 2 ? 'h2' : node.depth === 3 ? 'h3' : 'h4';\n return (\n <Tag key={key} {...at(node)}>\n {renderPhrasing(node.children)}\n </Tag>\n );\n }\n case 'list': {\n const items = node.children.map((item, i) => (\n <li key={i}>{item.children.map((child, j) => renderListChild(child, j, item.spread === true, language))}</li>\n ));\n return node.ordered ? (\n <ol key={key} start={node.start ?? undefined}>\n {items}\n </ol>\n ) : (\n <ul key={key}>{items}</ul>\n );\n }\n case 'blockquote':\n return <blockquote key={key}>{node.children.map((child, i) => renderFlow(child, i, language))}</blockquote>;\n case 'thematicBreak':\n return <hr key={key} />;\n case 'code':\n return (\n <pre key={key}>\n <code>{node.value}</code>\n </pre>\n );\n case 'table':\n return <BlogTable key={key} table={node} />;\n case 'mdxJsxFlowElement':\n return <BlogComponent key={key} element={node} language={language} />;\n default:\n return null;\n }\n}\n\n/** A tight list's paragraphs are just its text, as Markdown means them. */\nfunction renderListChild(child: Nodes, key: number, spread: boolean, language: string): ReactNode {\n if (child.type === 'paragraph' && !spread)\n return (\n <span key={key} {...at(child)}>\n {renderPhrasing(child.children)}\n </span>\n );\n return renderFlow(child, key, language);\n}\n\nfunction renderPhrasing(children: readonly PhrasingContent[]): ReactNode {\n return children.map((child, i) => {\n switch (child.type) {\n case 'text':\n return child.value;\n case 'emphasis':\n return <em key={i}>{renderPhrasing(child.children)}</em>;\n case 'strong':\n return <strong key={i}>{renderPhrasing(child.children)}</strong>;\n case 'delete':\n return <del key={i}>{renderPhrasing(child.children)}</del>;\n case 'inlineCode':\n return <code key={i}>{child.value}</code>;\n case 'break':\n return <br key={i} />;\n case 'link': {\n const safe = isSafeHref(child.url);\n if (!safe) return <span key={i}>{renderPhrasing(child.children)}</span>;\n const external = /^https?:\\/\\//i.test(child.url);\n return (\n <a key={i} href={child.url} {...(external ? { rel: 'noopener noreferrer' } : {})}>\n {renderPhrasing(child.children)}\n </a>\n );\n }\n default:\n return null;\n }\n });\n}\n\nfunction BlogTable({ table }: { table: Table }) {\n const [head, ...rows] = table.children;\n const align = (i: number) => table.align?.[i] ?? undefined;\n return (\n <div className=\"setto-blog__table\">\n <table>\n {head ? (\n <thead>\n <tr>\n {head.children.map((cell, i) => (\n <th key={i} style={{ textAlign: align(i) }}>\n {renderPhrasing(cell.children)}\n </th>\n ))}\n </tr>\n </thead>\n ) : null}\n <tbody>\n {rows.map((row, r) => (\n <tr key={r}>\n {row.children.map((cell, i) => (\n <td key={i} style={{ textAlign: align(i) }}>\n {renderPhrasing(cell.children)}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\n// ── The four components ──────────────────────────────────────────────────────\n\nfunction attrs(element: MdxJsxFlowElement): Record<string, string> {\n const out: Record<string, string> = {};\n for (const attribute of element.attributes) {\n const a = attribute as MdxJsxAttribute;\n if (a.type === 'mdxJsxAttribute' && typeof a.value === 'string') out[a.name] = a.value;\n }\n return out;\n}\n\nfunction BlogComponent({ element, language }: { element: MdxJsxFlowElement; language: string }) {\n const props = attrs(element);\n switch (element.name) {\n case 'Image':\n return props.src && props.alt !== undefined ? (\n <figure className=\"setto-blog__figure\" {...atImage(element, props.alt)}>\n <BlogImg src={props.src} alt={props.alt} sizes=\"(min-width: 760px) 720px, 100vw\" />\n {props.caption ? <figcaption>{props.caption}</figcaption> : null}\n </figure>\n ) : null;\n case 'Gallery': {\n const images = element.children.filter(\n (child): child is MdxJsxFlowElement => child.type === 'mdxJsxFlowElement' && child.name === 'Image',\n );\n return (\n <figure className=\"setto-blog__gallery\">\n <div className=\"setto-blog__gallery-grid\">\n {images.map((image, i) => {\n const a = attrs(image);\n return a.src ? (\n <figure key={i} className=\"setto-blog__gallery-item\" {...atImage(image, a.alt ?? '')}>\n <BlogImg src={a.src} alt={a.alt ?? ''} sizes=\"(min-width: 760px) 360px, 50vw\" />\n {a.caption ? <figcaption>{a.caption}</figcaption> : null}\n </figure>\n ) : null;\n })}\n </div>\n {props.caption ? <figcaption>{props.caption}</figcaption> : null}\n </figure>\n );\n }\n case 'YouTube':\n return props.id && YOUTUBE_ID_PATTERN.test(props.id) ? (\n <YouTubeEmbed id={props.id} title={props.title} language={language} />\n ) : null;\n case 'Callout':\n return (\n <aside className=\"setto-blog__callout\" data-tone={props.tone ?? 'info'}>\n {element.children.map((child, i) => renderFlow(child as Nodes, i, language))}\n </aside>\n );\n default:\n return null;\n }\n}\n\n/**\n * An image, resized by the site's optimizer when it has one and the image is\n * one it may read (`isOptimizable`: this site's own, or a blog photograph in\n * Setto's media store). If a variant fails, the original is shown instead.\n */\nexport function BlogImg({ src, alt, sizes, className }: { src: string; alt: string; sizes: string; className?: string }) {\n const { config } = useSetto();\n const [failed, setFailed] = useState(false);\n const optimize =\n config.images?.optimize === true &&\n !failed &&\n isOptimizable(src) &&\n !(typeof window !== 'undefined' && hasNoOptimizer(window.location.hostname));\n if (!optimize) return <img src={src} alt={alt} loading=\"lazy\" decoding=\"async\" className={className} />;\n return (\n <img\n src={optimizedUrl(src, 1080)}\n srcSet={optimizedSrcSet(src)}\n sizes={sizes}\n alt={alt}\n loading=\"lazy\"\n decoding=\"async\"\n className={className}\n onError={() => setFailed(true)}\n />\n );\n}\n\n/**\n * A YouTube video that costs the reader nothing until they ask for it: a\n * still and a play button, and only on a click the player itself, from\n * YouTube's no-cookie domain.\n */\nfunction YouTubeEmbed({ id, title, language }: { id: string; title?: string; language: string }) {\n const [playing, setPlaying] = useState(false);\n const strings = blogStrings(language);\n const label = title ?? strings.video;\n return (\n <figure className=\"setto-blog__video\">\n <div className=\"setto-blog__video-frame\">\n {playing ? (\n <iframe\n src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0`}\n title={label}\n allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n allowFullScreen\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n ) : (\n <button type=\"button\" className=\"setto-blog__video-play\" onClick={() => setPlaying(true)} aria-label={`${strings.play}: ${label}`}>\n <img src={`https://i.ytimg.com/vi/${id}/hqdefault.jpg`} alt=\"\" loading=\"lazy\" decoding=\"async\" />\n <span aria-hidden=\"true\" className=\"setto-blog__video-icon\">\n <svg viewBox=\"0 0 68 48\" width=\"68\" height=\"48\">\n <path d=\"M66.5 7.7A8.5 8.5 0 0 0 60.5 1.7C55.2.3 34 .3 34 .3s-21.2 0-26.5 1.4A8.5 8.5 0 0 0 1.5 7.7C.1 13 .1 24 .1 24s0 11 1.4 16.3a8.5 8.5 0 0 0 6 6c5.3 1.4 26.5 1.4 26.5 1.4s21.2 0 26.5-1.4a8.5 8.5 0 0 0 6-6C67.9 35 67.9 24 67.9 24s0-11-1.4-16.3z\" fill=\"#f00\" />\n <path d=\"M45 24 27 14v20\" fill=\"#fff\" />\n </svg>\n </span>\n </button>\n )}\n </div>\n {title ? <figcaption>{title}</figcaption> : null}\n </figure>\n );\n}\n","/**\n * The blog's two built-in sections (R24).\n *\n * `blog` lives on the blog page and draws either the list of posts or, at\n * `<page path>/<slug>`, one post. `blog-latest` is a band of the newest posts\n * for the front page. Both read the posts the site's build bundles\n * (`SettoConfig.blog`, from `virtual:setto-blog`). The band draws nothing\n * without them; the blog page says there are none yet.\n *\n * The owner, signed in on their own site, also gets the `blog-owner` chrome\n * slot at the top of the blog page: Pixel's welcome on an empty blog, the\n * article Pixel is writing, and a draft waiting for approval — drawn here, in\n * the site's own blog design, by `BlogDraft`, so what the owner approves is\n * what readers will see.\n *\n * The look is the site's: type and colour are inherited, and the stylesheet\n * below only gives shape — scoped under `.setto-blog` so Tailwind's reset\n * cannot strip it, and at zero specificity for colour so the site always\n * wins. However a redesign restyles these classes, the posts keep rendering:\n * the file contract is what may not change.\n */\nimport {\n useEffect,\n useInsertionEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport type { RootContent } from 'mdast';\nimport { useTranslation } from 'react-i18next';\nimport { useSetto } from '../provider';\nimport { useSettoChromeSlot } from '../chrome';\nimport { languageFromPath } from '../lib/language-routing';\nimport { SettoSection } from '../SettoSection';\nimport { blogPage, blogSlugForPath, findSection, normalisePath, type PagesManifest } from '../pages/manifest';\nimport { usePageManifest, type BuiltinSectionProps } from '../pages/SettoPage';\nimport { BLOG_ROUTE, isValidBlogSlug, type BlogFrontmatter } from './contract';\nimport { formatPostDate, postForSlug, postsForLanguage, type BlogPostData, type BlogPostSummary } from './data';\nimport { BlogBody, BlogImg } from './render';\nimport { blogStrings, type BlogStrings } from './strings';\n\nconst LATEST_COUNT = 3;\n\nfunction useBlogContext(path?: string) {\n const { config } = useSetto();\n const { i18n, t } = useTranslation();\n const manifest = usePageManifest();\n const language = i18n.language || config.languages?.[0] || 'no';\n const fallbackLanguage = config.languages?.[0] ?? 'no';\n const languages = config.languages ?? [fallbackLanguage];\n /*\n * A site in two languages serves the second under a prefix (`/en/blogg/…`)\n * and gives the router that prefix as its basename. The blog reads the\n * address without it, and writes its links with it, so an English reader\n * stays in English.\n *\n * The address is the `path` a site hands over (its router's location, the\n * prefix already taken off) when it has one: on a server, or in the first\n * render of a page the build drew, there is no `window.location` to read\n * that would agree with it. Without one, the browser's address, as before.\n * The prefix comes from the browser's address where there is one, and from\n * the language being drawn where there is not.\n */\n const route =\n typeof window === 'undefined'\n ? { basename: language === fallbackLanguage || !languages.includes(language) ? '' : `/${language}`, rest: '/' }\n : languageFromPath(window.location.pathname, languages);\n const href = (to: string) => `${route.basename}${to}`;\n return { config, t, manifest, language, fallbackLanguage, strings: blogStrings(language), path: path ?? route.rest, href };\n}\n\nfunction blogPathOf(manifest: PagesManifest | null): string {\n return (manifest && blogPage(manifest)?.page.path) || BLOG_ROUTE;\n}\n\n// ── `blog` ───────────────────────────────────────────────────────────────────\n\nexport function SettoBlogSection({ sectionId, first }: BuiltinSectionProps) {\n useBlogStyles();\n const ctx = useBlogContext();\n const slug = ctx.manifest ? blogSlugForPath(ctx.manifest, ctx.path) : null;\n const page = ctx.manifest ? findSection(ctx.manifest, sectionId)?.page : undefined;\n const title = page ? ctx.t(page.titleKey, { defaultValue: ctx.strings.blog }) : ctx.strings.blog;\n const blogPath = blogPathOf(ctx.manifest);\n const inner = useRef<HTMLDivElement>(null);\n const clear = useClearFixedHeader(inner, first);\n\n return (\n <SettoSection sectionId={sectionId} className=\"setto-blog\">\n <div className=\"setto-blog__inner\" ref={inner} style={clear ? { paddingTop: clear } : undefined}>\n {slug ? (\n <BlogPostView slug={slug} blogPath={blogPath} ctx={ctx} />\n ) : (\n <BlogIndexView title={title} first={first} blogPath={blogPath} ctx={ctx} />\n )}\n </div>\n </SettoSection>\n );\n}\n\n/**\n * The blog for a site that routes by hand instead of through `pages.json`\n * (setto.no): mount it on `<basePath>` and `<basePath>/*`, and pass the same\n * path to `settoBlog({ blogPath })`.\n *\n * <Route path=\"/blogg/*\" element={<SettoBlog basePath=\"/blogg\" />} />\n *\n * Both of the rest are optional, and are what a page drawn ahead of time\n * needs to come out the same on the server and in the browser's first render\n * (0.49.0), so `hydrateRoot` can take it over:\n *\n * <SettoBlog basePath=\"/blogg\" path={useLocation().pathname} initialPost={post} />\n *\n * - `path`: the address within the router (`useLocation().pathname`, the\n * language prefix already taken off). Without it the blog reads\n * `window.location`, which a server does not have.\n * - `initialPost`: the post being shown, already loaded (`blog.load(slug,\n * locale)`). Used when it is the one this address shows, in place of\n * fetching it in an effect; without it the post's first render is «Henter\n * innlegget …», as before.\n */\nexport function SettoBlog({\n basePath = BLOG_ROUTE,\n title,\n path,\n initialPost,\n}: {\n basePath?: string;\n title?: string;\n path?: string;\n initialPost?: BlogPostData | null;\n}) {\n useBlogStyles();\n const ctx = useBlogContext(path);\n const base = normalisePath(basePath);\n const here = normalisePath(ctx.path);\n const rest = here.startsWith(`${base}/`) ? here.slice(base.length + 1) : '';\n const slug = rest && isValidBlogSlug(rest) ? rest : null;\n const inner = useRef<HTMLDivElement>(null);\n const clear = useClearFixedHeader(inner, true);\n return (\n <section className=\"setto-blog\">\n <div className=\"setto-blog__inner\" ref={inner} style={clear ? { paddingTop: clear } : undefined}>\n {slug ? (\n <BlogPostView slug={slug} blogPath={base} ctx={ctx} initialPost={initialPost} />\n ) : (\n <BlogIndexView title={title ?? ctx.strings.blog} first blogPath={base} ctx={ctx} />\n )}\n </div>\n </section>\n );\n}\n\n/**\n * Room for a fixed header. The blog page starts at the top of the page, and\n * sites differ: some pad their pages below a fixed header, some do not, and\n * on a phone the header can be taller than the section's own padding. So the\n * first section measures: whatever fixed element covers the top of the\n * viewport, and how far its bottom reaches past where the content starts —\n * that much, plus a little air, and nothing when the site already made room.\n */\nfunction useClearFixedHeader(ref: RefObject<HTMLElement | null>, enabled: boolean): number {\n const [clear, setClear] = useState(0);\n useLayoutEffect(() => {\n if (!enabled || typeof window === 'undefined') return;\n const measure = () => {\n const el = ref.current;\n if (!el) return;\n const covering = document\n .elementsFromPoint(window.innerWidth / 2, 1)\n .map((node) => fixedAncestor(node))\n .find((node): node is HTMLElement => node !== null && !node.contains(el));\n // A fixed header's bottom is a distance from the top of the window; the\n // content's start is a distance from the top of the page. At the top of\n // the page the two are comparable, and padding added inside `el` does\n // not move `el` itself, so this does not feed back on its own answer.\n const headerBottom = covering ? covering.getBoundingClientRect().bottom : 0;\n const start = el.getBoundingClientRect().top + window.scrollY;\n const overlap = Math.ceil(headerBottom + 16 - start);\n setClear(overlap > 0 ? overlap : 0);\n };\n measure();\n window.addEventListener('resize', measure);\n return () => window.removeEventListener('resize', measure);\n }, [ref, enabled]);\n return clear;\n}\n\nfunction fixedAncestor(node: Element): HTMLElement | null {\n for (let at: Element | null = node; at && at !== document.body; at = at.parentElement) {\n if (getComputedStyle(at).position === 'fixed') return at as HTMLElement;\n }\n return null;\n}\n\ntype Ctx = ReturnType<typeof useBlogContext>;\n\n/** A post not yet published, as setto-server sends it: the frontmatter and the body's tree, each node with `at`. */\nexport interface BlogDraftData {\n frontmatter: BlogFrontmatter;\n body: { children: RootContent[] };\n}\n\n/** What the chrome's `blog-owner` slot is given. */\nexport interface BlogOwnerSlotProps {\n blogPath: string;\n language: string;\n /** Published posts in this language, as of the site's last build. */\n posts: number;\n /** Draws a draft in the site's own blog design; title, lead and cover carry `data-setto-field`. */\n Draft: ComponentType<{ draft: BlogDraftData }>;\n}\n\nfunction BlogIndexView({ title, first, blogPath, ctx }: { title: string; first: boolean; blogPath: string; ctx: Ctx }) {\n const posts = ctx.config.blog ? postsForLanguage(ctx.config.blog.posts, ctx.language, ctx.fallbackLanguage) : [];\n const Heading = first ? 'h1' : 'h2';\n const { canEdit } = useSetto();\n const Owner = useSettoChromeSlot<BlogOwnerSlotProps>('blog-owner');\n return (\n <>\n <Heading className=\"setto-blog__title\">{title}</Heading>\n {canEdit && Owner ? (\n <div className=\"setto-blog__owner\" data-setto-ui=\"\">\n <Owner blogPath={blogPath} language={ctx.language} posts={posts.length} Draft={BlogDraft} />\n </div>\n ) : null}\n {posts.length === 0 ? (\n <p className=\"setto-blog__empty\">{ctx.strings.empty}</p>\n ) : (\n <div className=\"setto-blog__list\">\n {posts.map((post) => (\n <PostCard key={post.slug} post={post} blogPath={blogPath} ctx={ctx} headingLevel={first ? 'h2' : 'h3'} />\n ))}\n </div>\n )}\n </>\n );\n}\n\nfunction PostCard({\n post,\n blogPath,\n ctx,\n headingLevel,\n}: {\n post: BlogPostSummary;\n blogPath: string;\n ctx: Ctx;\n headingLevel: 'h2' | 'h3';\n}) {\n const Heading = headingLevel;\n const href = ctx.href(`${blogPath}/${post.slug}`);\n return (\n <article className=\"setto-blog__card\">\n {post.cover ? (\n <a href={href} className=\"setto-blog__card-cover\" tabIndex={-1} aria-hidden=\"true\">\n <BlogImg src={post.cover} alt=\"\" sizes=\"(min-width: 960px) 360px, (min-width: 640px) 50vw, 100vw\" />\n </a>\n ) : null}\n <div className=\"setto-blog__card-body\">\n <time className=\"setto-blog__date\" dateTime={post.date}>\n {formatPostDate(post.date, ctx.language)}\n </time>\n <Heading className=\"setto-blog__card-title\">\n <a href={href}>{post.title}</a>\n </Heading>\n <p className=\"setto-blog__card-lead\">{post.description}</p>\n <a href={href} className=\"setto-blog__more\" aria-label={`${ctx.strings.readMore}: ${post.title}`}>\n {ctx.strings.readMore} <span aria-hidden=\"true\">→</span>\n </a>\n </div>\n </article>\n );\n}\n\n/** Whether a loaded post is the version `summary` names. */\nfunction isPostFor(post: BlogPostData | null | undefined, summary: BlogPostSummary | null): post is BlogPostData {\n return !!post && !!summary && post.frontmatter.slug === summary.slug && post.frontmatter.locale === summary.locale;\n}\n\nfunction BlogPostView({\n slug,\n blogPath,\n ctx,\n initialPost,\n}: {\n slug: string;\n blogPath: string;\n ctx: Ctx;\n initialPost?: BlogPostData | null;\n}) {\n const blog = ctx.config.blog;\n const summary = blog ? postForSlug(blog.posts, slug, ctx.language, ctx.fallbackLanguage) : null;\n // A post handed over already loaded is drawn at once, and the same on the\n // server as in the browser's first render; anything else is fetched.\n const [post, setPost] = useState<BlogPostData | null>(() => (isPostFor(initialPost, summary) ? initialPost : null));\n const [state, setState] = useState<'loading' | 'ready' | 'missing'>(() =>\n !summary ? 'missing' : isPostFor(initialPost, summary) ? 'ready' : 'loading',\n );\n\n useEffect(() => {\n if (!blog || !summary) {\n setState('missing');\n return;\n }\n if (isPostFor(initialPost, summary)) {\n setPost(initialPost);\n setState('ready');\n return;\n }\n let live = true;\n setState('loading');\n blog\n .load(summary.slug, summary.locale)\n .then((loaded) => {\n if (!live) return;\n setPost(loaded);\n setState(loaded ? 'ready' : 'missing');\n })\n .catch(() => live && setState('missing'));\n return () => {\n live = false;\n };\n // `initialPost` only counts while it is this post; the slug and locale say when that changes.\n }, [blog, summary?.slug, summary?.locale]);\n\n usePostTitle(summary?.title ?? null, ctx.config.displayName);\n\n const back = (\n <a href={ctx.href(blogPath)} className=\"setto-blog__back\">\n <span aria-hidden=\"true\">←</span> {ctx.strings.back}\n </a>\n );\n\n if (!summary || state === 'missing') {\n return (\n <div className=\"setto-blog__post\">\n {back}\n <p className=\"setto-blog__empty\">{ctx.strings.notFound}</p>\n </div>\n );\n }\n\n const fm = post?.frontmatter ?? summary;\n return (\n <PostArticle frontmatter={fm} ctx={ctx} before={back} after={<ShareBar title={fm.title} strings={ctx.strings} />}>\n {state === 'ready' && isPostFor(post, summary) ? (\n <BlogBody nodes={post.body.children} language={ctx.language} />\n ) : (\n <p className=\"setto-blog__loading\" aria-live=\"polite\">\n {ctx.strings.loading}\n </p>\n )}\n </PostArticle>\n );\n}\n\n/** One post's page: the header, the cover and the text. Published posts and drafts alike. */\nfunction PostArticle({\n frontmatter: fm,\n ctx,\n before,\n after,\n draft = false,\n children,\n}: {\n frontmatter: Pick<BlogFrontmatter, 'title' | 'description' | 'date' | 'locale' | 'cover'>;\n ctx: Ctx;\n before?: ReactNode;\n after?: ReactNode;\n draft?: boolean;\n children: ReactNode;\n}) {\n const field = (name: string) => (draft ? { 'data-setto-field': name } : {});\n const Title = draft ? 'h2' : 'h1';\n return (\n <article className=\"setto-blog__post\" lang={fm.locale}>\n {before}\n <header className=\"setto-blog__post-header\">\n <time className=\"setto-blog__date\" dateTime={fm.date}>\n {formatPostDate(fm.date, ctx.language)}\n </time>\n <Title className=\"setto-blog__post-title\" {...field('title')}>\n {fm.title}\n </Title>\n <p className=\"setto-blog__lead\" {...field('description')}>\n {fm.description}\n </p>\n </header>\n {fm.cover ? (\n <figure className=\"setto-blog__cover\" {...field('cover')}>\n <BlogImg src={fm.cover} alt=\"\" sizes=\"(min-width: 1040px) 960px, 100vw\" />\n </figure>\n ) : null}\n <div className=\"setto-blog__prose\">{children}</div>\n {after}\n </article>\n );\n}\n\n/** A draft, as it will read once published. Given to the chrome's `blog-owner` slot. */\nexport function BlogDraft({ draft }: { draft: BlogDraftData }) {\n useBlogStyles();\n const ctx = useBlogContext();\n return (\n <PostArticle frontmatter={draft.frontmatter} ctx={ctx} draft>\n <BlogBody nodes={draft.body.children} language={ctx.language} />\n </PostArticle>\n );\n}\n\n/**\n * The tab says which post this is. Set after the page's own title effect —\n * a child's effect runs before its parent's, so this waits a tick.\n */\nfunction usePostTitle(title: string | null, siteName: string | undefined) {\n useEffect(() => {\n if (!title || typeof document === 'undefined') return;\n const previous = document.title;\n const timer = window.setTimeout(() => {\n document.title = siteName ? `${title} · ${siteName}` : title;\n }, 0);\n return () => {\n window.clearTimeout(timer);\n document.title = previous;\n };\n }, [title, siteName]);\n}\n\n/**\n * Plain links to each service's own share page, and the phone's share sheet\n * where there is one. No SDK, no script from Facebook, nothing loaded until\n * a reader taps.\n */\nfunction ShareBar({ title, strings }: { title: string; strings: BlogStrings }) {\n const [copied, setCopied] = useState(false);\n const [native, setNative] = useState(false);\n /*\n * The address is read once the bar is on the page, not while drawing it:\n * a server has none, and a link drawn with one in the browser but not on\n * the server is one `hydrateRoot` keeps the server's version of, so the\n * share links would have pointed nowhere.\n */\n const [url, setUrl] = useState('');\n useEffect(() => {\n setNative(typeof navigator !== 'undefined' && typeof navigator.share === 'function');\n setUrl(`${window.location.origin}${window.location.pathname}`);\n }, []);\n const u = encodeURIComponent(url);\n const t = encodeURIComponent(title);\n\n return (\n <div className=\"setto-blog__share\" aria-label={strings.share}>\n <span className=\"setto-blog__share-label\">{strings.share}</span>\n {native ? (\n <button type=\"button\" onClick={() => void navigator.share({ title, url }).catch(() => undefined)}>\n {strings.moreShare}\n </button>\n ) : null}\n <a href={`https://www.facebook.com/sharer/sharer.php?u=${u}`} target=\"_blank\" rel=\"noopener noreferrer\">\n Facebook\n </a>\n <a href={`https://www.linkedin.com/sharing/share-offsite/?url=${u}`} target=\"_blank\" rel=\"noopener noreferrer\">\n LinkedIn\n </a>\n <a href={`mailto:?subject=${t}&body=${u}`}>{strings.email}</a>\n <button\n type=\"button\"\n onClick={() => {\n void navigator.clipboard?.writeText(url).then(() => {\n setCopied(true);\n window.setTimeout(() => setCopied(false), 2000);\n });\n }}\n >\n {copied ? strings.copied : strings.copyLink}\n </button>\n </div>\n );\n}\n\n// ── `blog-latest` ────────────────────────────────────────────────────────────\n\nexport function SettoBlogLatest({ sectionId, first }: BuiltinSectionProps) {\n useBlogStyles();\n const ctx = useBlogContext();\n if (!ctx.config.blog) return null;\n const posts = postsForLanguage(ctx.config.blog.posts, ctx.language, ctx.fallbackLanguage).slice(0, LATEST_COUNT);\n if (posts.length === 0) return null;\n const blogPath = blogPathOf(ctx.manifest);\n const Heading = first ? 'h1' : 'h2';\n return (\n <SettoSection sectionId={sectionId} className=\"setto-blog setto-blog--latest\">\n <div className=\"setto-blog__inner setto-blog__inner--wide\">\n <div className=\"setto-blog__latest-head\">\n <Heading className=\"setto-blog__title\">{ctx.strings.latest}</Heading>\n <a href={ctx.href(blogPath)} className=\"setto-blog__more\">\n {ctx.strings.allPosts} <span aria-hidden=\"true\">→</span>\n </a>\n </div>\n <div className=\"setto-blog__list\">\n {posts.map((post) => (\n <PostCard key={post.slug} post={post} blogPath={blogPath} ctx={ctx} headingLevel=\"h3\" />\n ))}\n </div>\n </div>\n </SettoSection>\n );\n}\n\n// ── Styles ───────────────────────────────────────────────────────────────────\n\nconst STYLE_ID = 'setto-blog-styles';\n\n/**\n * Shape is scoped `.setto-blog :where(…)` (one class: beats Preflight's\n * element resets); colour stays at zero specificity so the site's own wins.\n * Same split, same reason, as the form's sheet.\n */\nexport const BLOG_CSS = `\n.setto-blog{padding:clamp(48px,8vw,96px) 16px}\n.setto-blog :where(.setto-blog__inner){max-width:68ch;margin:0 auto}\n.setto-blog :where(.setto-blog__inner--wide){max-width:1120px}\n.setto-blog :where(.setto-blog__title){font-family:var(--setto-display-font,inherit);font-size:clamp(2rem,4vw,2.75rem);line-height:1.15;font-weight:600;margin:0 0 .75em}\n.setto-blog :where(.setto-blog__list){display:grid;gap:clamp(1.5rem,3vw,2.5rem);grid-template-columns:repeat(auto-fill,minmax(min(100%,300px),1fr))}\n.setto-blog :where(.setto-blog__card){display:grid;gap:.9rem;align-content:start}\n.setto-blog :where(.setto-blog__card-cover){display:block;overflow:hidden;border-radius:.9rem;aspect-ratio:16/10}\n.setto-blog :where(.setto-blog__card-cover img,.setto-blog__cover img,.setto-blog__figure img,.setto-blog__gallery-item img){display:block;width:100%;height:100%;object-fit:cover}\n.setto-blog :where(.setto-blog__card-body){display:grid;gap:.45rem}\n.setto-blog :where(.setto-blog__card-title){font-family:var(--setto-display-font,inherit);font-size:1.3rem;line-height:1.25;font-weight:600;margin:0}\n.setto-blog :where(.setto-blog__card-lead){margin:0;line-height:1.55}\n.setto-blog :where(.setto-blog__date){font-size:.875rem;letter-spacing:.01em}\n.setto-blog :where(.setto-blog__more,.setto-blog__back){display:inline-flex;gap:.35em;align-items:center;font-weight:500;width:fit-content}\n.setto-blog :where(.setto-blog__back){margin-bottom:2rem}\n.setto-blog :where(.setto-blog__latest-head){display:flex;flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:.5rem 1.5rem;margin-bottom:1.75rem}\n.setto-blog :where(.setto-blog__latest-head .setto-blog__title){margin:0}\n.setto-blog :where(.setto-blog__post-header){display:grid;gap:.6rem;margin-bottom:2rem}\n.setto-blog :where(.setto-blog__post-title){font-family:var(--setto-display-font,inherit);font-size:clamp(2rem,5vw,3rem);line-height:1.1;font-weight:600;margin:0}\n.setto-blog :where(.setto-blog__lead){font-size:1.2rem;line-height:1.5;margin:0}\n.setto-blog :where(.setto-blog__cover){margin:0 0 2.5rem;overflow:hidden;border-radius:1rem;aspect-ratio:16/9}\n.setto-blog :where(.setto-blog__prose){font-size:1.075rem;line-height:1.7}\n.setto-blog :where(.setto-blog__prose > * + *){margin-top:1.15em}\n.setto-blog :where(.setto-blog__prose h2,.setto-blog__prose h3,.setto-blog__prose h4){font-family:var(--setto-display-font,inherit);line-height:1.25;font-weight:600;margin:1.8em 0 0}\n.setto-blog :where(.setto-blog__prose h2){font-size:1.6rem}\n.setto-blog :where(.setto-blog__prose h3){font-size:1.3rem}\n.setto-blog :where(.setto-blog__prose h4){font-size:1.1rem}\n.setto-blog :where(.setto-blog__prose ul,.setto-blog__prose ol){padding-left:1.4em}\n.setto-blog :where(.setto-blog__prose ul){list-style:disc}\n.setto-blog :where(.setto-blog__prose ol){list-style:decimal}\n.setto-blog :where(.setto-blog__prose li + li){margin-top:.35em}\n.setto-blog :where(.setto-blog__prose blockquote){margin-left:0;padding-left:1.1em;border-left-width:3px;border-left-style:solid;font-style:italic}\n.setto-blog :where(.setto-blog__prose pre){overflow-x:auto;padding:1em;border-radius:.6rem;font-size:.9em}\n.setto-blog :where(.setto-blog__prose code){font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.92em}\n.setto-blog :where(.setto-blog__prose hr){border:0;border-top-width:1px;border-top-style:solid;margin:2.5em 0}\n.setto-blog :where(.setto-blog__prose a){text-decoration:underline;text-underline-offset:.18em}\n.setto-blog :where(.setto-blog__table){overflow-x:auto}\n.setto-blog :where(.setto-blog__table table){border-collapse:collapse;width:100%;font-size:.95em}\n.setto-blog :where(.setto-blog__table th,.setto-blog__table td){padding:.55em .8em;border-bottom-width:1px;border-bottom-style:solid;text-align:left}\n.setto-blog :where(.setto-blog__figure,.setto-blog__gallery,.setto-blog__video){margin:2em 0}\n.setto-blog :where(.setto-blog__figure img){border-radius:.8rem;height:auto}\n.setto-blog :where(figcaption){font-size:.9rem;margin-top:.6em;opacity:.75}\n.setto-blog :where(.setto-blog__gallery-grid){display:grid;gap:.6rem;grid-template-columns:repeat(auto-fit,minmax(min(100%,150px),1fr))}\n.setto-blog :where(.setto-blog__gallery-item){margin:0}\n.setto-blog :where(.setto-blog__gallery-item img){border-radius:.6rem;aspect-ratio:4/3}\n.setto-blog :where(.setto-blog__video-frame){position:relative;aspect-ratio:16/9;border-radius:.8rem;overflow:hidden}\n.setto-blog :where(.setto-blog__video-frame iframe){position:absolute;inset:0;width:100%;height:100%;border:0}\n.setto-blog :where(.setto-blog__video-play){position:absolute;inset:0;width:100%;height:100%;padding:0;border:0;cursor:pointer;display:grid;place-items:center}\n.setto-blog :where(.setto-blog__video-play img){position:absolute;inset:0;width:100%;height:100%;object-fit:cover}\n.setto-blog :where(.setto-blog__video-icon){position:relative;display:block;line-height:0}\n.setto-blog :where(.setto-blog__callout){padding:1.1em 1.3em;border-radius:.8rem;border-left-width:4px;border-left-style:solid}\n.setto-blog :where(.setto-blog__callout > * + *){margin-top:.7em}\n.setto-blog :where(.setto-blog__callout ul,.setto-blog__callout ol){padding-left:1.3em;list-style:disc}\n.setto-blog :where(.setto-blog__share){display:flex;flex-wrap:wrap;gap:.5rem .9rem;align-items:center;margin-top:3rem;padding-top:1.5rem;border-top-width:1px;border-top-style:solid}\n.setto-blog :where(.setto-blog__share-label){font-weight:600}\n.setto-blog :where(.setto-blog__share a,.setto-blog__share button){font:inherit;padding:.35rem .85rem;border-radius:999px;border-width:1px;border-style:solid;cursor:pointer;text-decoration:none;line-height:1.4}\n.setto-blog :where(.setto-blog__empty,.setto-blog__loading){opacity:.75}\n:where(.setto-blog){color:inherit}\n:where(.setto-blog__date){opacity:.7}\n:where(.setto-blog a){color:inherit}\n:where(.setto-blog__prose blockquote,.setto-blog__prose hr,.setto-blog__table th,.setto-blog__table td,.setto-blog__share){border-color:color-mix(in srgb,currentColor 18%,transparent)}\n:where(.setto-blog__prose pre,.setto-blog__card-cover){background:color-mix(in srgb,currentColor 6%,transparent)}\n:where(.setto-blog__share a,.setto-blog__share button){border-color:color-mix(in srgb,currentColor 30%,transparent);background:transparent;color:inherit}\n:where(.setto-blog__callout){background:color-mix(in srgb,currentColor 5%,transparent);border-left-color:color-mix(in srgb,currentColor 40%,transparent)}\n:where(.setto-blog__callout[data-tone=\"tip\"]){border-left-color:#0f7b4f}\n:where(.setto-blog__callout[data-tone=\"warning\"]){border-left-color:#b54708}\n:where(.setto-blog__video-frame){background:#000}\n`;\n\nfunction useBlogStyles() {\n useInsertionEffect(() => {\n if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = BLOG_CSS;\n document.head.appendChild(el);\n }, []);\n}\n\n","import type { i18n as I18nType, TFunction } from 'i18next';\nimport { collectKeysUnder, getNested } from '../../lib/nested-resource';\n\n/**\n * What a form is made of, and where that lives.\n *\n * A form's fields are content, not code. They sit in the locale bundle under\n * `form.<formId>.fields.<n>` as an ordinary Setto list — the same shape a\n * repeater uses — so the editor can add, remove, reorder and relabel them\n * with the draft store it already has, and publishing writes them to\n * `no.json` through the path that already exists. Nothing new has to be\n * stored, fetched or deployed for a form to change.\n *\n * \"form\": {\n * \"kontakt\": {\n * \"submit\": \"Send\", \"success\": \"Takk! …\", \"error\": \"Noe gikk galt.\",\n * \"fields\": {\n * \"1\": { \"name\": \"navn\", \"type\": \"text\", \"label\": \"Navn\", \"required\": \"true\" },\n * \"2\": { \"name\": \"epost\", \"type\": \"email\", \"label\": \"E-post\", \"required\": \"true\" },\n * \"3\": { \"name\": \"tjeneste\", \"type\": \"select\", \"label\": \"Hva gjelder det?\",\n * \"options\": \"Tak\\nVindu\\nAnnet\" },\n * \"4\": { \"name\": \"melding\", \"type\": \"textarea\", \"label\": \"Melding\" }\n * }\n * }\n * }\n *\n * Every value is a string because every locale value is: `required` is\n * `\"true\"`, `options` is one per line. `label`, `placeholder` and `options`\n * are per language; `name`, `type` and `required` are the same in all of them.\n */\n\nexport const FORM_FIELD_TYPES = [\n 'text',\n 'email',\n 'tel',\n 'number',\n 'url',\n 'date',\n 'textarea',\n 'select',\n 'radio',\n 'checkbox',\n 'checkboxes',\n] as const;\n\nexport type FormFieldType = (typeof FORM_FIELD_TYPES)[number];\n\n/** What the editor calls each type. */\nexport const FORM_FIELD_TYPE_LABELS: Record<FormFieldType, string> = {\n text: 'Kort tekst',\n email: 'E-post',\n tel: 'Telefon',\n number: 'Tall',\n url: 'Nettadresse',\n date: 'Dato',\n textarea: 'Lang tekst',\n select: 'Nedtrekksliste',\n radio: 'Ett valg',\n checkbox: 'Avkrysning',\n checkboxes: 'Flere valg',\n};\n\n/** Field props that are the same in every language. */\nexport const STRUCTURAL_FIELD_PROPS = ['name', 'type', 'required'] as const;\n\nexport function isFormFieldType(value: unknown): value is FormFieldType {\n return typeof value === 'string' && (FORM_FIELD_TYPES as readonly string[]).includes(value);\n}\n\nexport function fieldTypeHasOptions(type: FormFieldType): boolean {\n return type === 'select' || type === 'radio' || type === 'checkboxes';\n}\n\nexport function fieldTypeHasPlaceholder(type: FormFieldType): boolean {\n return !fieldTypeHasOptions(type) && type !== 'checkbox' && type !== 'date';\n}\n\n/** A field as the form renders it, whichever source it came from. */\nexport interface ResolvedFormField {\n /** Item key under `form.<id>.fields` — absent when the field came from props. */\n itemKey?: string;\n name: string;\n type: FormFieldType;\n /** i18n key the label is rendered (and inline-edited) through. */\n labelKey: string;\n label: string;\n placeholder: string;\n required: boolean;\n options: string[];\n}\n\nexport function formFieldsPrefix(formId: string): string {\n return `form.${formId}.fields`;\n}\n\nexport function parseOptions(value: string | undefined): string[] {\n if (!value) return [];\n return value\n .split('\\n')\n .map((o) => o.trim())\n .filter((o) => o !== '');\n}\n\nfunction readString(item: Record<string, unknown>, prop: string): string {\n const value = item[prop];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Fields as the locale bundle defines them, or null when no loaded language\n * has a `fields` list for this form and it should fall back to whatever the\n * host passed. The current language is read first, then i18next's fallback\n * chain, so a second language that has not translated the form still gets\n * its structure. Items without a name are skipped: they are the empty husks a\n * half-finished edit can leave behind, not fields.\n */\nexport function readLocaleFields(\n i18n: I18nType,\n lng: string,\n formId: string,\n ns = 'translation',\n): ResolvedFormField[] | null {\n const prefix = formFieldsPrefix(formId);\n const candidates = [lng, ...(i18n.languages ?? [])].filter((l, i, all) => all.indexOf(l) === i);\n let bundle: Record<string, unknown> | undefined;\n let list: unknown;\n for (const candidate of candidates) {\n const b = i18n.getResourceBundle(candidate, ns) as Record<string, unknown> | undefined;\n const l = getNested(b, prefix);\n if (l && typeof l === 'object' && !Array.isArray(l)) {\n bundle = b;\n list = l;\n break;\n }\n }\n if (!list) return null;\n\n const fields: ResolvedFormField[] = [];\n for (const itemKey of collectKeysUnder(bundle, prefix)) {\n const item = (list as Record<string, unknown>)[itemKey];\n if (!item || typeof item !== 'object') continue;\n const record = item as Record<string, unknown>;\n const name = readString(record, 'name').trim();\n if (!name) continue;\n const type = isFormFieldType(record.type) ? record.type : 'text';\n fields.push({\n itemKey,\n name,\n type,\n labelKey: `${prefix}.${itemKey}.label`,\n label: readString(record, 'label'),\n placeholder: readString(record, 'placeholder'),\n required: readString(record, 'required') === 'true',\n options: parseOptions(readString(record, 'options')),\n });\n }\n return fields;\n}\n\n/** The host-supplied shape a form can still be given as a prop. */\nexport interface FormFieldProp {\n /** Submitted form field name. */\n name: string;\n type: FormFieldType;\n required?: boolean;\n /** i18n key for the field label. */\n labelKey: string;\n /** i18n key for the placeholder text. */\n placeholderKey?: string;\n /** i18n key for the options of a select/radio/checkboxes field, one per line. */\n optionsKey?: string;\n}\n\nexport function resolvePropFields(fields: FormFieldProp[], t: TFunction): ResolvedFormField[] {\n return fields.map((field) => ({\n name: field.name,\n type: isFormFieldType(field.type) ? field.type : 'text',\n labelKey: field.labelKey,\n label: t(field.labelKey, { defaultValue: '' }),\n placeholder: field.placeholderKey ? t(field.placeholderKey, { defaultValue: '' }) : '',\n required: field.required === true,\n options: field.optionsKey ? parseOptions(t(field.optionsKey, { defaultValue: '' })) : [],\n }));\n}\n\n/** `Hva gjelder det?` → `hva-gjelder-det`; falls back to `felt`. */\nexport function slugifyFieldName(label: string): string {\n const slug = label\n .toLowerCase()\n .replace(/æ/g, 'ae')\n .replace(/ø/g, 'o')\n .replace(/å/g, 'a')\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^a-z0-9_]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n return slug || 'felt';\n}\n\n/** A name no existing field uses. */\nexport function uniqueFieldName(base: string, taken: Iterable<string>): string {\n const used = new Set(taken);\n if (!used.has(base)) return base;\n let n = 2;\n while (used.has(`${base}-${n}`)) n += 1;\n return `${base}-${n}`;\n}\n\nexport type FormValue = string | boolean | string[];\nexport type FormValues = Record<string, FormValue>;\n\nexport function emptyValue(type: FormFieldType): FormValue {\n if (type === 'checkbox') return false;\n if (type === 'checkboxes') return [];\n return '';\n}\n\nexport function emptyValues(fields: ResolvedFormField[]): FormValues {\n return Object.fromEntries(fields.map((f) => [f.name, emptyValue(f.type)]));\n}\n\nfunction isBlank(value: FormValue | undefined): boolean {\n if (value === undefined) return true;\n if (typeof value === 'string') return value.trim() === '';\n if (typeof value === 'boolean') return !value;\n return value.length === 0;\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\nconst URL_RE = /^(https?:\\/\\/)?[^\\s/$.?#].[^\\s]*$/i;\n\nexport type FieldErrorCode = 'required' | 'email' | 'url' | 'number';\n\n/** Norwegian fallbacks; a site overrides them via `form.validation.<code>`. */\nexport const FIELD_ERROR_DEFAULTS: Record<FieldErrorCode, string> = {\n required: 'Må fylles ut',\n email: 'Skriv inn en gyldig e-postadresse',\n url: 'Skriv inn en gyldig nettadresse',\n number: 'Skriv inn et tall',\n};\n\nexport function validateValues(\n fields: ResolvedFormField[],\n values: FormValues,\n): Record<string, FieldErrorCode> {\n const errors: Record<string, FieldErrorCode> = {};\n for (const field of fields) {\n const value = values[field.name];\n if (field.required && isBlank(value)) {\n errors[field.name] = 'required';\n continue;\n }\n if (typeof value !== 'string' || value.trim() === '') continue;\n if (field.type === 'email' && !EMAIL_RE.test(value.trim())) errors[field.name] = 'email';\n if (field.type === 'url' && !URL_RE.test(value.trim())) errors[field.name] = 'url';\n if (field.type === 'number' && Number.isNaN(Number(value.trim()))) errors[field.name] = 'number';\n }\n return errors;\n}\n\n/**\n * The body `SettoForm` posts to setto-server. See `form-submission.ts` there.\n *\n * `hp` and `elapsed` are the bot signals: the honeypot's value (a person\n * cannot see the field, so anything in it came from a script) and the\n * milliseconds between the visitor's first touch of the form and submit\n * (a script fills a form in tens of milliseconds; a person cannot).\n */\nexport interface SubmissionEnvelope {\n data: FormValues;\n labels: Record<string, string>;\n order: string[];\n title?: string;\n page?: string;\n hp: string;\n elapsed: number;\n}\n\nexport function buildEnvelope(\n fields: ResolvedFormField[],\n values: FormValues,\n extra: { title?: string; page?: string; hp: string; elapsed: number },\n): SubmissionEnvelope {\n const data: FormValues = {};\n const labels: Record<string, string> = {};\n for (const field of fields) {\n const value = values[field.name] ?? emptyValue(field.type);\n data[field.name] = typeof value === 'string' ? value.trim() : value;\n if (field.label.trim()) labels[field.name] = field.label.trim();\n }\n return {\n data,\n labels,\n order: fields.map((f) => f.name),\n ...(extra.title ? { title: extra.title } : {}),\n ...(extra.page ? { page: extra.page } : {}),\n hp: extra.hp,\n elapsed: Math.max(0, Math.round(extra.elapsed)),\n };\n}\n\n/** Where a site's forms go unless the host says otherwise. */\nexport function settoSubmissionUrl(apiUrl: string, siteId: string, formId: string): string {\n return `${apiUrl.replace(/\\/+$/, '')}/sites/${encodeURIComponent(siteId)}/forms/${encodeURIComponent(formId)}/submissions`;\n}\n","import {\n useEffect,\n useId,\n useInsertionEffect,\n useRef,\n useState,\n type ChangeEvent,\n type CSSProperties,\n type FormEvent,\n type ReactNode,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { T } from '../../T';\nimport { useGuestEdit } from '../../guest-edit';\nimport { useSetto } from '../../provider';\nimport { useSettoChromeSlot } from '../../chrome';\nimport type { FieldPatch, FormFieldToolsProps } from './field-tools';\nimport {\n buildEnvelope,\n emptyValue,\n FIELD_ERROR_DEFAULTS,\n formFieldsPrefix,\n readLocaleFields,\n resolvePropFields,\n settoSubmissionUrl,\n slugifyFieldName,\n uniqueFieldName,\n validateValues,\n type FieldErrorCode,\n type FormFieldProp,\n type FormValue,\n type FormValues,\n type ResolvedFormField,\n} from './fields';\n\n/**\n * A form the site owner can change and a visitor can trust.\n *\n * Fields come from the locale (`form.<id>.fields`, see `fields.ts`) and fall\n * back to the `fields` prop until the editor first touches them, at which\n * point the prop fields are copied into the locale and the locale wins. From\n * then on adding, removing, reordering and relabelling are ordinary drafts.\n *\n * Submissions go to setto-server, which stores them and emails the site's\n * recipients. A site with its own backend passes `endpoint` and gets the bare\n * values instead. Either way the visitor sees the form replaced by the\n * success message — with focus moved to it, so it is announced as well as\n * seen.\n *\n * Bots: a honeypot input a person never sees, the time from first touch to\n * submit, and controlled inputs (a script that pokes `.value` never changes\n * React state, so it submits an empty form). The server adds an Origin check,\n * a per-site and per-address rate limit, and a link-count heuristic. None of\n * it asks the visitor to prove anything.\n */\n\nexport interface SettoFormClassNames {\n form?: string;\n field?: string;\n label?: string;\n input?: string;\n textarea?: string;\n select?: string;\n /** Wrapper around a radio / checkbox group's options. */\n options?: string;\n /** One radio / checkbox option (the label element). */\n option?: string;\n /** A single checkbox field (the label element). */\n checkbox?: string;\n actions?: string;\n button?: string;\n success?: string;\n error?: string;\n fieldError?: string;\n}\n\nexport interface SettoFormProps {\n /** Scopes the form's i18n keys and identifies it in the inbox. */\n formId: string;\n /** Seed fields, used until the locale has a `form.<id>.fields` list. */\n fields?: FormFieldProp[];\n /**\n * POST target for a site with its own backend; receives the bare values as\n * JSON. Leave unset to submit to Setto.\n */\n endpoint?: string;\n /** @deprecated Ignored — forms post to Setto unless `endpoint` is set. */\n endpointKey?: string;\n /** Class on the `<form>` (and the success panel that replaces it). */\n className?: string;\n /** Classes per part; the `setto-form__*` classes stay for CSS hooks. */\n classNames?: SettoFormClassNames;\n}\n\ntype Status = 'idle' | 'submitting' | 'success' | 'error';\n\nconst HONEYPOT_NAME = 'website';\n\nconst warnedEndpointKeys = new Set<string>();\n\nfunction cx(...parts: Array<string | undefined | false | null>): string {\n return parts.filter(Boolean).join(' ');\n}\n\nexport function SettoForm({\n formId,\n fields: propFields,\n endpoint,\n endpointKey,\n className,\n classNames = {},\n}: SettoFormProps) {\n const { t, i18n } = useTranslation();\n const { config, editMode, store } = useSetto();\n /*\n * The editing tools for a field come from Setto, not from this bundle.\n *\n * The form itself is the customer's — it renders their fields and takes\n * their visitors' submissions, and has to keep working with Setto\n * unreachable. What sits on top of it in edit mode is Setto's furniture, so\n * it is served like the rest of it and simply absent when it has not\n * arrived.\n */\n const FieldTools = useSettoChromeSlot<FormFieldToolsProps>('form-field-tools');\n const guestEdit = useGuestEdit();\n const editable = editMode || guestEdit.active;\n const lng = i18n.language;\n const uid = useId();\n useFormStyles();\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n useEffect(() => {\n if (endpointKey && !warnedEndpointKeys.has(formId)) {\n warnedEndpointKeys.add(formId);\n console.warn(\n `[setto] <SettoForm formId=\"${formId}\"> passes endpointKey, which is no longer used. ` +\n 'Forms submit to Setto; pass `endpoint` for a custom backend.',\n );\n }\n }, [endpointKey, formId]);\n\n const localeFields = readLocaleFields(i18n, lng, formId);\n const fields = localeFields ?? resolvePropFields(propFields ?? [], t);\n const fromLocale = localeFields !== null;\n const prefix = formFieldsPrefix(formId);\n\n const [values, setValues] = useState<FormValues>({});\n const [errors, setErrors] = useState<Record<string, FieldErrorCode>>({});\n const [status, setStatus] = useState<Status>('idle');\n const [justAdded, setJustAdded] = useState<string | null>(null);\n const formRef = useRef<HTMLFormElement>(null);\n const successRef = useRef<HTMLDivElement>(null);\n const honeypotRef = useRef<HTMLInputElement>(null);\n const startedAt = useRef<number | null>(null);\n\n useEffect(() => {\n if (status === 'success') successRef.current?.focus({ preventScroll: false });\n }, [status]);\n\n const valueOf = (field: ResolvedFormField): FormValue =>\n values[field.name] ?? emptyValue(field.type);\n\n const setValue = (name: string, value: FormValue) => {\n setValues((prev) => ({ ...prev, [name]: value }));\n setErrors((prev) => {\n if (!(name in prev)) return prev;\n const next = { ...prev };\n delete next[name];\n return next;\n });\n };\n\n const markStarted = () => {\n if (startedAt.current === null) startedAt.current = performance.now();\n };\n\n const submitKey = `form.${formId}.submit`;\n const successKey = `form.${formId}.success`;\n const errorKey = `form.${formId}.error`;\n const title = t(`form.${formId}.title`, { defaultValue: '' }) || undefined;\n\n const onSubmit = async (e: FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n if (status === 'submitting') return;\n\n const nextErrors = validateValues(fields, values);\n setErrors(nextErrors);\n const firstInvalid = fields.find((f) => nextErrors[f.name]);\n if (firstInvalid) {\n const el = formRef.current?.querySelector<HTMLElement>(\n `[data-setto-field=\"${cssEscape(firstInvalid.name)}\"] [name]`,\n );\n el?.focus();\n return;\n }\n\n setStatus('submitting');\n const elapsed = startedAt.current === null ? 0 : performance.now() - startedAt.current;\n const envelope = buildEnvelope(fields, values, {\n title,\n page: typeof window !== 'undefined' ? window.location.href : undefined,\n hp: honeypotRef.current?.value ?? '',\n elapsed,\n });\n\n try {\n const url = endpoint || settoSubmissionUrl(config.apiUrl, config.siteId, formId);\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(endpoint ? envelope.data : envelope),\n });\n if (!res.ok) throw new Error(`Form submission failed: ${res.status}`);\n setStatus('success');\n setValues({});\n startedAt.current = null;\n } catch (err) {\n console.error('[setto] form submission failed', err);\n setStatus('error');\n }\n };\n\n /* ── Editing the field set ── */\n\n /**\n * Copies prop fields into the locale the first time the editor changes the\n * structure. Returns each field's item key so the change that triggered the\n * copy can find its target.\n */\n const ensureLocaleFields = (): Map<string, string> => {\n const keys = new Map<string, string>();\n if (!store) return keys;\n if (fromLocale) {\n for (const f of fields) if (f.itemKey) keys.set(f.name, f.itemKey);\n return keys;\n }\n const langs = i18n.languages?.length ? i18n.languages : [lng];\n for (const prop of propFields ?? []) {\n const itemKey = store.addListItem(prefix, lng, {\n name: prop.name,\n type: prop.type,\n ...(prop.required ? { required: 'true' } : {}),\n });\n for (const lang of langs) {\n const ft = i18n.getFixedT(lang);\n const label = ft(prop.labelKey, { defaultValue: '' });\n if (label) store.set(`${prefix}.${itemKey}.label`, lang, label);\n const placeholder = prop.placeholderKey ? ft(prop.placeholderKey, { defaultValue: '' }) : '';\n if (placeholder) store.set(`${prefix}.${itemKey}.placeholder`, lang, placeholder);\n const options = prop.optionsKey ? ft(prop.optionsKey, { defaultValue: '' }) : '';\n if (options) store.set(`${prefix}.${itemKey}.options`, lang, options);\n }\n keys.set(prop.name, itemKey);\n }\n return keys;\n };\n\n const itemKeyFor = (field: ResolvedFormField): string | undefined =>\n field.itemKey ?? ensureLocaleFields().get(field.name);\n\n const allLanguages = (): string[] => (i18n.languages?.length ? [...i18n.languages] : [lng]);\n\n const setEverywhere = (key: string, value: string | undefined) => {\n for (const lang of allLanguages()) {\n if (value === undefined || value === '') store!.delete(key, lang);\n else store!.set(key, lang, value);\n }\n };\n\n const addField = () => {\n if (!store) return;\n store.batch(() => {\n ensureLocaleFields();\n const taken = fields.map((f) => f.name);\n const itemKey = store.addListItem(prefix, lng, {\n name: uniqueFieldName('felt', taken),\n type: 'text',\n });\n for (const lang of allLanguages()) store.set(`${prefix}.${itemKey}.label`, lang, 'Nytt felt');\n setJustAdded(itemKey);\n });\n };\n\n const moveField = (field: ResolvedFormField, direction: -1 | 1) => {\n if (!store) return;\n store.batch(() => {\n const itemKey = itemKeyFor(field);\n if (itemKey) store.moveListItem(prefix, itemKey, direction, lng);\n });\n };\n\n const removeField = (field: ResolvedFormField) => {\n if (!store || fields.length <= 1) return;\n store.batch(() => {\n const itemKey = itemKeyFor(field);\n if (itemKey) store.removeListItem(prefix, itemKey, lng);\n });\n };\n\n const updateField = (field: ResolvedFormField, patch: FieldPatch) => {\n if (!store) return;\n store.batch(() => {\n const itemKey = itemKeyFor(field);\n if (!itemKey) return;\n const item = `${prefix}.${itemKey}`;\n const others = fields.filter((f) => f !== field).map((f) => f.name);\n\n if (patch.type !== undefined) setEverywhere(`${item}.type`, patch.type);\n if (patch.required !== undefined) {\n setEverywhere(`${item}.required`, patch.required ? 'true' : undefined);\n }\n if (patch.name !== undefined) {\n setEverywhere(`${item}.name`, uniqueFieldName(slugifyFieldName(patch.name), others));\n }\n if (patch.label !== undefined) {\n store.set(`${item}.label`, lng, patch.label);\n // A field still carrying its generated name takes one from the label.\n if (patch.name === undefined && /^felt(-\\d+)?$/.test(field.name) && patch.label.trim()) {\n setEverywhere(`${item}.name`, uniqueFieldName(slugifyFieldName(patch.label), others));\n }\n }\n if (patch.placeholder !== undefined) {\n if (patch.placeholder) store.set(`${item}.placeholder`, lng, patch.placeholder);\n else store.delete(`${item}.placeholder`, lng);\n }\n if (patch.options !== undefined) {\n if (patch.options.trim()) store.set(`${item}.options`, lng, patch.options);\n else store.delete(`${item}.options`, lng);\n }\n });\n };\n\n /* ── Render ── */\n\n if (status === 'success') {\n return (\n <div\n ref={successRef}\n tabIndex={-1}\n role=\"status\"\n aria-live=\"polite\"\n data-setto-form={formId}\n data-setto-form-status=\"success\"\n className={cx('setto-form__success', className, classNames.success)}\n >\n <CheckIcon />\n <p className=\"setto-form__success-text\">\n <T k={successKey} />\n </p>\n <button\n type=\"button\"\n className=\"setto-form__again\"\n onClick={() => {\n setStatus('idle');\n setErrors({});\n }}\n >\n {t('form.again', { defaultValue: 'Send en ny melding' })}\n </button>\n </div>\n );\n }\n\n const submitting = status === 'submitting';\n\n return (\n <form\n ref={formRef}\n data-setto-form={formId}\n className={cx('setto-form', className, classNames.form)}\n onSubmit={onSubmit}\n onFocusCapture={markStarted}\n onPointerDownCapture={markStarted}\n onKeyDownCapture={markStarted}\n noValidate\n >\n {fields.map((field, index) => {\n const id = `${uid}-${field.name}`;\n const error = errors[field.name];\n const errorId = error ? `${id}-error` : undefined;\n return (\n <div\n key={field.itemKey ?? field.name}\n data-setto-field={field.name}\n className={cx('setto-form__field', `setto-form__field--${field.type}`, classNames.field)}\n >\n <FieldControl\n field={field}\n id={id}\n value={valueOf(field)}\n editable={editable}\n invalid={error !== undefined}\n describedBy={errorId}\n classNames={classNames}\n placeholderFallback={t('form.choose', { defaultValue: 'Velg …' })}\n onChange={(value) => setValue(field.name, value)}\n />\n {error ? (\n <p id={errorId} className={cx('setto-form__field-error', classNames.fieldError)}>\n {t(`form.validation.${error}`, { defaultValue: FIELD_ERROR_DEFAULTS[error] })}\n </p>\n ) : null}\n {editable && store && FieldTools ? (\n <FieldTools\n field={field}\n index={index}\n count={fields.length}\n autoOpen={justAdded !== null && justAdded === field.itemKey}\n onMove={(direction) => moveField(field, direction)}\n onRemove={() => removeField(field)}\n onChange={(patch) => updateField(field, patch)}\n />\n ) : null}\n </div>\n );\n })}\n\n {editable && store ? (\n <button\n type=\"button\"\n data-setto-ui\n className=\"setto-form__add-field\"\n style={addFieldStyle}\n onClick={addField}\n >\n + Legg til felt\n </button>\n ) : null}\n\n <div className=\"setto-form__hp\" aria-hidden=\"true\">\n <label htmlFor={`${uid}-${HONEYPOT_NAME}`}>Nettside</label>\n <input\n ref={honeypotRef}\n id={`${uid}-${HONEYPOT_NAME}`}\n type=\"text\"\n name={HONEYPOT_NAME}\n tabIndex={-1}\n autoComplete=\"off\"\n defaultValue=\"\"\n />\n </div>\n\n <div className={cx('setto-form__actions', classNames.actions)}>\n <button\n type=\"submit\"\n className={cx('setto-form__button', classNames.button)}\n disabled={submitting}\n aria-busy={submitting || undefined}\n >\n {submitting ? t('form.sending', { defaultValue: 'Sender …' }) : <T k={submitKey} />}\n </button>\n {status === 'error' ? (\n <p role=\"alert\" data-setto-form-status=\"error\" className={cx('setto-form__error', classNames.error)}>\n <T k={errorKey} />\n </p>\n ) : null}\n </div>\n\n {editable ? (\n <div className=\"setto-form__edit-previews\" style={previewStyle}>\n <div>\n <span style={previewHintStyle}>Etter innsending vises:</span> <T k={successKey} />\n </div>\n {status !== 'error' ? (\n <div>\n <span style={previewHintStyle}>Ved feil vises:</span> <T k={errorKey} />\n </div>\n ) : null}\n </div>\n ) : null}\n </form>\n );\n}\n\n/* ─────────── Field rendering ─────────── */\n\ninterface FieldControlProps {\n field: ResolvedFormField;\n id: string;\n value: FormValue;\n editable: boolean;\n invalid: boolean;\n describedBy?: string;\n classNames: SettoFormClassNames;\n placeholderFallback: string;\n onChange: (value: FormValue) => void;\n}\n\nfunction FieldControl({\n field,\n id,\n value,\n editable,\n invalid,\n describedBy,\n classNames,\n placeholderFallback,\n onChange,\n}: FieldControlProps) {\n const labelId = `${id}-label`;\n // Native `required` for the semantics (the form is noValidate, so the\n // browser announces it but never blocks); our own messages do the rest.\n const aria = {\n 'aria-invalid': invalid || undefined,\n 'aria-describedby': describedBy,\n required: field.required || undefined,\n };\n\n const labelText = (\n <>\n <T k={field.labelKey} />\n {field.required ? (\n <span aria-hidden=\"true\" className=\"setto-form__required\">\n *\n </span>\n ) : null}\n </>\n );\n\n if (field.type === 'checkbox') {\n const checked = value === true;\n return (\n <FieldLabel\n editable={editable}\n htmlFor={id}\n id={labelId}\n className={cx('setto-form__check', classNames.checkbox)}\n >\n <input\n id={id}\n type=\"checkbox\"\n name={field.name}\n checked={checked}\n onChange={(e) => onChange(e.target.checked)}\n {...(editable ? { 'aria-labelledby': labelId } : {})}\n {...aria}\n />\n <span>{labelText}</span>\n </FieldLabel>\n );\n }\n\n if (field.type === 'radio' || field.type === 'checkboxes') {\n const multiple = field.type === 'checkboxes';\n const selected = multiple ? (Array.isArray(value) ? value : []) : value;\n const toggle = (option: string, on: boolean) => {\n if (!multiple) {\n onChange(option);\n return;\n }\n const set = new Set(Array.isArray(selected) ? selected : []);\n if (on) set.add(option);\n else set.delete(option);\n onChange(field.options.filter((o) => set.has(o)));\n };\n return (\n <fieldset\n className=\"setto-form__fieldset\"\n role={multiple ? undefined : 'radiogroup'}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy}\n aria-required={!multiple && field.required ? true : undefined}\n >\n <legend className={cx('setto-form__legend', classNames.label)}>{labelText}</legend>\n <div className={cx('setto-form__options', classNames.options)}>\n {field.options.map((option, i) => {\n const optionId = `${id}-${i}`;\n const on = multiple ? (selected as string[]).includes(option) : selected === option;\n return (\n <label key={option} htmlFor={optionId} className={cx('setto-form__option', classNames.option)}>\n <input\n id={optionId}\n type={multiple ? 'checkbox' : 'radio'}\n name={field.name}\n value={option}\n checked={on}\n required={!multiple && field.required ? true : undefined}\n onChange={(e) => toggle(option, e.target.checked)}\n />\n <span>{option}</span>\n </label>\n );\n })}\n </div>\n </fieldset>\n );\n }\n\n const text = typeof value === 'string' ? value : '';\n const labelled = editable ? { 'aria-labelledby': labelId } : {};\n\n let control: ReactNode;\n if (field.type === 'textarea') {\n control = (\n <textarea\n id={id}\n name={field.name}\n value={text}\n rows={5}\n placeholder={field.placeholder || undefined}\n onChange={(e: ChangeEvent<HTMLTextAreaElement>) => onChange(e.target.value)}\n className={cx('setto-form__textarea', classNames.textarea)}\n {...labelled}\n {...aria}\n />\n );\n } else if (field.type === 'select') {\n control = (\n <select\n id={id}\n name={field.name}\n value={text}\n onChange={(e: ChangeEvent<HTMLSelectElement>) => onChange(e.target.value)}\n className={cx('setto-form__select', classNames.select)}\n {...labelled}\n {...aria}\n >\n <option value=\"\" disabled={field.required}>\n {field.placeholder || placeholderFallback}\n </option>\n {field.options.map((option) => (\n <option key={option} value={option}>\n {option}\n </option>\n ))}\n </select>\n );\n } else {\n control = (\n <input\n id={id}\n type={inputType(field)}\n name={field.name}\n value={text}\n placeholder={field.placeholder || undefined}\n inputMode={inputMode(field)}\n autoComplete={autoCompleteFor(field)}\n onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.target.value)}\n className={cx('setto-form__input', classNames.input)}\n {...labelled}\n {...aria}\n />\n );\n }\n\n return (\n <>\n <FieldLabel\n editable={editable}\n htmlFor={id}\n id={labelId}\n className={cx('setto-form__label', classNames.label)}\n >\n {labelText}\n </FieldLabel>\n {control}\n </>\n );\n}\n\n/**\n * A `<label for>` in the published site; a `<span id>` (and `aria-labelledby`\n * on the control) while editing, because clicking a label focuses its control\n * and would take the caret away from the text the editor is trying to change.\n */\nfunction FieldLabel({\n editable,\n htmlFor,\n id,\n className,\n children,\n}: {\n editable: boolean;\n htmlFor: string;\n id: string;\n className: string;\n children: ReactNode;\n}) {\n if (editable) {\n return (\n <span id={id} className={className}>\n {children}\n </span>\n );\n }\n return (\n <label htmlFor={htmlFor} className={className}>\n {children}\n </label>\n );\n}\n\nfunction inputType(field: ResolvedFormField): string {\n switch (field.type) {\n case 'email':\n case 'tel':\n case 'url':\n case 'date':\n return field.type;\n case 'number':\n // A text input with a numeric keyboard: no spinner, and values such as\n // \"+47 …\" or \"12,5\" are validated by us rather than refused by the browser.\n return 'text';\n default:\n return 'text';\n }\n}\n\nfunction inputMode(field: ResolvedFormField): 'email' | 'tel' | 'url' | 'decimal' | undefined {\n switch (field.type) {\n case 'email':\n return 'email';\n case 'tel':\n return 'tel';\n case 'url':\n return 'url';\n case 'number':\n return 'decimal';\n default:\n return undefined;\n }\n}\n\nfunction autoCompleteFor(field: ResolvedFormField): string | undefined {\n if (field.type === 'email') return 'email';\n if (field.type === 'tel') return 'tel';\n if (field.type === 'url') return 'url';\n if (/^(navn|name|fullt?[-_]?navn|full[-_]?name)$/i.test(field.name)) return 'name';\n if (/^(firma|bedrift|company|organisasjon|organization)$/i.test(field.name)) return 'organization';\n return undefined;\n}\n\nfunction cssEscape(value: string): string {\n return typeof CSS !== 'undefined' && typeof CSS.escape === 'function'\n ? CSS.escape(value)\n : value.replace(/[\"\\\\]/g, '\\\\$&');\n}\n\nfunction CheckIcon() {\n return (\n <svg\n className=\"setto-form__success-icon\"\n viewBox=\"0 0 40 40\"\n fill=\"none\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <circle cx=\"20\" cy=\"20\" r=\"19\" stroke=\"currentColor\" strokeWidth=\"2\" />\n <path\n d=\"M12 20.5l5.5 5.5L28 15\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\n/* ─────────── Baseline styles ─────────── */\n\nconst STYLE_ID = 'setto-form-styles';\n\n/**\n * Enough that an unstyled form looks intentional, while still losing to\n * anything the site says on purpose. Colours lean on `currentColor`, so the\n * form follows whatever section it sits in, light or dark.\n *\n * Every rule is scoped under `.setto-form`, which is not decoration: written\n * at the zero specificity of a bare `:where()`, these rules lost to Tailwind's\n * Preflight — `button, input, optgroup, select, textarea { padding: 0 }` is an\n * element selector, and an element selector outranks nothing at all. Every\n * generated site ships Preflight, so every form went out with no padding on\n * its fields or its button. Simon, on a real site: \"the form in the bottom\n * seems unstyled.\"\n *\n * So the sheet is in two halves, and which half a property lands in is decided\n * by who it has to beat.\n *\n * SHAPE — padding, width, radius, the things Preflight strips — is scoped\n * `.setto-form :where(…)`. That scores one class, which beats an element\n * selector, and puts back exactly what the reset took away.\n *\n * COLOUR — background, border colour, text colour — stays at zero specificity,\n * because here the site really must win. The generator emits `bg-card` and\n * `text-foreground` on these very elements, and scoping those under a class\n * would tie on weight and then beat them on order, quietly discarding the\n * palette the build chose. Shape is ours; colour is theirs.\n */\nexport const BASE_CSS = `\n.setto-form{display:grid;gap:1.1rem;position:relative}\n.setto-form :where(.setto-form__field){display:grid;gap:.4rem;position:relative}\n.setto-form :where(.setto-form__label,.setto-form__legend){font-weight:500;line-height:1.3;padding:0}\n.setto-form :where(.setto-form__required){opacity:.6;margin-left:.15em}\n.setto-form :where(.setto-form__input,.setto-form__textarea,.setto-form__select){width:100%;box-sizing:border-box;padding:.7rem .85rem;border-width:1px;border-style:solid;border-radius:.6rem;font:inherit;line-height:1.4}\n.setto-form :where(.setto-form__textarea){min-height:7.5rem;resize:vertical}\n.setto-form :where(.setto-form__fieldset){border:0;padding:0;margin:0;min-width:0;display:grid;gap:.5rem}\n.setto-form :where(.setto-form__options){display:grid;gap:.5rem}\n.setto-form :where(.setto-form__option,.setto-form__check){display:flex;gap:.6rem;align-items:flex-start;line-height:1.4;cursor:pointer;font-weight:400}\n.setto-form :where(.setto-form__option input,.setto-form__check input){margin:.25em 0 0;flex:none;accent-color:currentColor}\n.setto-form :where(.setto-form__actions){display:flex;flex-wrap:wrap;gap:.75rem 1rem;align-items:center}\n.setto-form :where(.setto-form__button){cursor:pointer;font:inherit;font-weight:500;padding:.75rem 1.4rem;border-radius:999px;border-width:1px;border-style:solid}\n.setto-form :where(.setto-form__success){display:grid;gap:.75rem;justify-items:start;outline:none}\n.setto-form :where(.setto-form__success-icon){width:2.5rem;height:2.5rem}\n.setto-form :where(.setto-form__success-text){margin:0;font-size:1.05em}\n.setto-form :where(.setto-form__hp){position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none}\n:where(.setto-form__input,.setto-form__textarea,.setto-form__select){border-color:color-mix(in srgb,currentColor 28%,transparent);background:color-mix(in srgb,currentColor 4%,transparent);color:inherit}\n:where(.setto-form__input,.setto-form__textarea,.setto-form__select)::placeholder{color:inherit;opacity:.5}\n:where(.setto-form__input,.setto-form__textarea,.setto-form__select):focus-visible{outline:2px solid currentColor;outline-offset:1px}\n:where(.setto-form__button){border-color:currentColor;background:transparent;color:inherit}\n:where(.setto-form__button:disabled){opacity:.6;cursor:progress}\n:where(.setto-form__field-error,.setto-form__error){font-size:.875rem;color:#b42318;margin:0}\n:where(.setto-form__success-icon){color:#0f7b4f}\n:where(.setto-form__again){background:none;border:0;padding:0;color:inherit;text-decoration:underline;cursor:pointer;font:inherit;opacity:.8;width:fit-content;max-width:100%;text-align:inherit}\n:where(.setto-form [aria-invalid=\"true\"]){border-color:#b42318}\n`;\n\nfunction useFormStyles() {\n useInsertionEffect(() => {\n if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = BASE_CSS;\n document.head.appendChild(el);\n }, []);\n}\n\nconst addFieldStyle: CSSProperties = {\n justifySelf: 'start',\n padding: '6px 12px',\n border: '1px dashed #999',\n borderRadius: 999,\n background: 'rgba(255,255,255,0.85)',\n color: '#333',\n fontSize: 13,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: 'pointer',\n};\n\nconst previewStyle: CSSProperties = {\n display: 'grid',\n gap: 6,\n padding: '10px 12px',\n border: '1px dashed rgba(100,10,255,0.35)',\n borderRadius: 8,\n fontSize: '0.9em',\n lineHeight: 1.4,\n};\n\nconst previewHintStyle: CSSProperties = {\n color: '#640AFF',\n fontSize: 11,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n textTransform: 'uppercase',\n letterSpacing: '0.04em',\n marginRight: 4,\n};\n","import type { SettoModule } from '../module';\n\n/**\n * The forms module: a form primitive the site renders, and the api segment\n * behind it. Server side lives in setto-server `src/modules/forms`, and so\n * does the inbox the customer reads submissions in.\n */\nexport const formsModule: SettoModule = {\n id: 'forms',\n label: 'Skjemaer',\n};\n\nexport { SettoForm } from './SettoForm';\nexport type { SettoFormProps, SettoFormClassNames } from './SettoForm';\nexport type { FormSettings, FormSubmissionRow, FormsApi } from './api';\nexport {\n FORM_FIELD_TYPES,\n FORM_FIELD_TYPE_LABELS,\n fieldTypeHasOptions,\n fieldTypeHasPlaceholder,\n formFieldsPrefix,\n isFormFieldType,\n readLocaleFields,\n settoSubmissionUrl,\n} from './fields';\nexport type {\n FormFieldProp,\n FormFieldType,\n FormValue,\n FormValues,\n ResolvedFormField,\n SubmissionEnvelope,\n} from './fields';\n","import type { SettoModule } from '../module';\n\n/**\n * The customer's own domain.\n *\n * A dashboard tab rather than a step in the conversation: a domain is a\n * setting somebody returns to — when they finally buy the name, when they move\n * registrar, when a record gets deleted by accident — and the conversation\n * that built the site is not somewhere anybody goes back to.\n *\n * Only the tab is here. The panel behind it is served from setto-server, which\n * is also where the DNS instructions are worked out.\n */\nexport const domainModule: SettoModule = {\n id: 'domain',\n label: 'Domene',\n};\n","import { chatModule } from './chat';\nimport { domainModule } from './domain';\nimport { formsModule } from './forms';\nimport type { SettoModule } from './module';\n\nexport type { SettoModule } from './module';\n\n/** Every module the dashboard shows, in tab order. Setto draws the tabs. */\nexport const SETTO_MODULES: readonly SettoModule[] = [formsModule, chatModule, domainModule];\n\nexport function findModule(id: string | null): SettoModule | undefined {\n return id ? SETTO_MODULES.find((m) => m.id === id) : undefined;\n}\n","import { useTranslation } from 'react-i18next';\nimport { useSetto } from './provider';\n\nexport interface SettoVideoProps {\n /** i18n key holding the video URL (YouTube, Vimeo, or direct MP4). */\n srcKey: string;\n /** Optional i18n key holding a poster image URL (HTML5 video only). */\n posterKey?: string;\n title?: string;\n className?: string;\n}\n\n/**\n * Renders a video from a URL stored in i18n. YouTube and Vimeo URLs become\n * iframe embeds; everything else renders as an HTML5 `<video>` element.\n *\n * Editors can change the URL via the i18n draft store (a dedicated picker\n * UI may follow; until then it's swap-via-publish like other content).\n */\nexport function SettoVideo({ srcKey, posterKey, title, className }: SettoVideoProps) {\n const { t, i18n } = useTranslation();\n const { store } = useSetto();\n\n const src = store ? store.get(srcKey, i18n.language) : t(srcKey, { defaultValue: '' });\n const poster = posterKey\n ? store\n ? store.get(posterKey, i18n.language)\n : t(posterKey, { defaultValue: '' })\n : undefined;\n\n if (!src) {\n return (\n <div\n className={className}\n data-setto-video={srcKey}\n data-setto-video-empty=\"1\"\n />\n );\n }\n\n const embed = toEmbedUrl(src);\n if (embed) {\n return (\n <iframe\n className={className}\n src={embed}\n title={title ?? 'Video'}\n loading=\"lazy\"\n allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n allowFullScreen\n data-setto-video={srcKey}\n />\n );\n }\n\n return (\n <video\n className={className}\n src={src}\n poster={poster}\n controls\n preload=\"metadata\"\n data-setto-video={srcKey}\n />\n );\n}\n\nfunction toEmbedUrl(url: string): string | null {\n try {\n const u = new URL(url);\n if (u.hostname === 'youtu.be') {\n return `https://www.youtube.com/embed/${u.pathname.slice(1)}`;\n }\n if (u.hostname.endsWith('youtube.com')) {\n const v = u.searchParams.get('v');\n if (v) return `https://www.youtube.com/embed/${v}`;\n if (u.pathname.startsWith('/embed/')) return url;\n }\n if (u.hostname.endsWith('vimeo.com')) {\n const id = u.pathname.split('/').filter(Boolean).pop();\n if (id && /^\\d+$/.test(id)) return `https://player.vimeo.com/video/${id}`;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import type { MapLocation } from '../map-tools';\nimport type { I18nStore } from './i18n-store';\n\n/**\n * Where a `SettoMap` points, and how that becomes an OpenStreetMap embed.\n *\n * The location is content, stored under the map's key in every locale file:\n * `{ lat, lng, zoom, title }`, all strings, because every other value in those\n * files is. Pure on purpose — the component, the editor's tools and the tests\n * all agree on one reading of what the build agent wrote.\n */\n\n/** What a locale file holds under a map's key. Every field may be missing. */\nexport interface RawMapContent {\n lat?: unknown;\n lng?: unknown;\n zoom?: unknown;\n}\n\nexport const MAP_MIN_ZOOM = 1;\nexport const MAP_MAX_ZOOM = 19;\nexport const MAP_DEFAULT_ZOOM = 15;\nexport const MAP_DEFAULT_TITLE = 'Kart';\n\n/** Web mercator stops here; a map centred further north cannot be drawn. */\nexport const MERCATOR_MAX_LAT = 85.0511287798066;\n\n/**\n * The frame the zoom is chosen for.\n *\n * The embed is told a bounding box, not a zoom, and fits that box into\n * whatever size the iframe has. A box sized for a small frame keeps the zoom\n * the owner chose on anything larger — a phone-width map or a wide `h-72` band\n * both open at it — where a box sized for a desktop would zoom a phone out.\n */\nexport const MAP_ASSUMED_WIDTH = 320;\nexport const MAP_ASSUMED_HEIGHT = 240;\n\nconst TILE_SIZE = 256;\n\n/**\n * A coordinate as the locale spells it.\n *\n * Strict about shape, because `Number('')` is 0 and a map of the Gulf of\n * Guinea is the wrong way to say a value is missing. A decimal comma is\n * accepted: the owner is Norwegian and so is their keyboard.\n */\nexport function parseCoordinate(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value !== 'string') return null;\n const text = value.trim().replace(',', '.');\n if (!/^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$/.test(text)) return null;\n const n = Number(text);\n return Number.isFinite(n) ? n : null;\n}\n\n/**\n * The zoom, forgiving where the coordinates are not.\n *\n * A missing or unreadable zoom still gives a usable map, so it falls back to\n * the default; a readable one out of range is clamped and rounded rather than\n * thrown away.\n */\nexport function parseZoom(value: unknown): number {\n const n = parseCoordinate(value);\n if (n === null) return MAP_DEFAULT_ZOOM;\n return Math.min(MAP_MAX_ZOOM, Math.max(MAP_MIN_ZOOM, Math.round(n)));\n}\n\n/** A location, or null when the coordinates are missing, unreadable or off the map. */\nexport function parseMapLocation(raw: RawMapContent | null | undefined): MapLocation | null {\n if (!raw) return null;\n const lat = parseCoordinate(raw.lat);\n const lng = parseCoordinate(raw.lng);\n if (lat === null || lng === null) return null;\n if (Math.abs(lat) > MERCATOR_MAX_LAT || Math.abs(lng) > 180) return null;\n return { lat, lng, zoom: parseZoom(raw.zoom) };\n}\n\n/** Six decimals is about ten centimetres; more is noise in a content file. */\nexport function formatCoordinate(n: number): string {\n const fixed = n.toFixed(6);\n const trimmed = fixed.includes('.') ? fixed.replace(/0+$/, '').replace(/\\.$/, '') : fixed;\n return trimmed === '-0' ? '0' : trimmed;\n}\n\n/** The strings a location is stored as. */\nexport function serialiseMapLocation(location: MapLocation): {\n lat: string;\n lng: string;\n zoom: string;\n} {\n return {\n lat: formatCoordinate(location.lat),\n lng: formatCoordinate(location.lng),\n zoom: String(parseZoom(location.zoom)),\n };\n}\n\nfunction worldSize(zoom: number): number {\n return TILE_SIZE * 2 ** zoom;\n}\n\nfunction latToWorldY(lat: number, zoom: number): number {\n const clamped = Math.max(-MERCATOR_MAX_LAT, Math.min(MERCATOR_MAX_LAT, lat));\n const sin = Math.sin((clamped * Math.PI) / 180);\n return (0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * worldSize(zoom);\n}\n\nfunction worldYToLat(y: number, zoom: number): number {\n const n = Math.PI - (2 * Math.PI * y) / worldSize(zoom);\n return (180 / Math.PI) * Math.atan(Math.sinh(n));\n}\n\nexport interface MapBbox {\n minLng: number;\n minLat: number;\n maxLng: number;\n maxLat: number;\n}\n\n/**\n * The box a frame of `width` × `height` pixels would show, centred on the\n * location at its zoom. Longitude is linear in web mercator; latitude is not,\n * so it goes through world pixels and back.\n */\nexport function mapBbox(\n location: MapLocation,\n width: number = MAP_ASSUMED_WIDTH,\n height: number = MAP_ASSUMED_HEIGHT,\n): MapBbox {\n const degreesPerPixel = 360 / worldSize(location.zoom);\n const halfLng = (width / 2) * degreesPerPixel;\n const y = latToWorldY(location.lat, location.zoom);\n const max = worldSize(location.zoom);\n return {\n minLng: Math.max(-180, location.lng - halfLng),\n maxLng: Math.min(180, location.lng + halfLng),\n minLat: worldYToLat(Math.min(max, y + height / 2), location.zoom),\n maxLat: worldYToLat(Math.max(0, y - height / 2), location.zoom),\n };\n}\n\n/** The OpenStreetMap embed for a location, marker on the point itself. */\nexport function mapEmbedUrl(location: MapLocation): string {\n const box = mapBbox(location);\n const bbox = [box.minLng, box.minLat, box.maxLng, box.maxLat].map(formatCoordinate).join(',');\n const marker = `${formatCoordinate(location.lat)},${formatCoordinate(location.lng)}`;\n return `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${marker}`;\n}\n\n/**\n * Write a location to every language at once.\n *\n * A place is not translated, so the same numbers go into each locale, the way\n * `SettoImage` writes an image path. The title is left alone: that one is\n * words, and belongs to each language.\n */\nexport function writeMapLocation(\n store: Pick<I18nStore, 'set' | 'batch'>,\n languages: readonly string[],\n key: string,\n location: MapLocation,\n): void {\n const values = serialiseMapLocation(location);\n store.batch(() => {\n for (const lng of languages) {\n store.set(`${key}.lat`, lng, values.lat);\n store.set(`${key}.lng`, lng, values.lng);\n store.set(`${key}.zoom`, lng, values.zoom);\n }\n });\n}\n","import { useEffect, useState, type CSSProperties } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useSettoChromeSlot } from './chrome';\nimport { useGuestEdit } from './guest-edit';\nimport {\n MAP_DEFAULT_TITLE,\n mapEmbedUrl,\n parseMapLocation,\n writeMapLocation,\n} from './lib/map-location';\nimport type { MapToolsProps } from './map-tools';\nimport { useSetto } from './provider';\n\nexport interface SettoMapProps {\n /**\n * i18n key prefix holding `lat`, `lng`, optional `zoom` (1–19, default 15)\n * and optional `title`. A static string literal, like every other key.\n */\n k: string;\n className?: string;\n style?: CSSProperties;\n /** The iframe's loading strategy. Default `lazy`. */\n loading?: 'lazy' | 'eager';\n}\n\n/**\n * A map whose location is content.\n *\n * Rendered as an OpenStreetMap embed with a marker on the point, because a\n * hand-written embed with a guessed pin in the middle of a fjord is what the\n * build agent produced without it, and nobody could move that pin. Here the\n * point lives in the locale, so it publishes like text, and in edit mode the\n * tools Setto serves (`map-tools`) sit over the map to move it.\n *\n * The wrapper carries the site's classes in both modes and the iframe fills\n * it, so a map sized with `h-72 w-full` is the same box whether or not anybody\n * is editing. Without a usable location the wrapper renders empty — no iframe\n * pointing at 0,0 — and still takes the tools, so the owner can set one.\n */\nexport function SettoMap({ k, className, style, loading = 'lazy' }: SettoMapProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guestEdit = useGuestEdit();\n const editable = editMode || guestEdit.active;\n /*\n * The tools come from Setto, not from this bundle: the map is the\n * customer's and has to render with Setto unreachable, and when the chrome\n * has not arrived there is simply nothing drawn on top of it.\n */\n const MapTools = useSettoChromeSlot<MapToolsProps>('map-tools');\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const lng = i18n.language;\n const read = (field: string): string => {\n const key = `${k}.${field}`;\n // The draft layer first; then i18next, which falls back across languages.\n return (store?.get(key, lng) || t(key, { defaultValue: '' })) as string;\n };\n\n const location = parseMapLocation({ lat: read('lat'), lng: read('lng'), zoom: read('zoom') });\n const title = read('title') || MAP_DEFAULT_TITLE;\n const tools =\n editable && store && MapTools ? (\n <MapTools\n location={location}\n onChange={(next) => writeMapLocation(store, store.languages(lng), k, next)}\n />\n ) : null;\n\n if (!location) {\n return (\n <div className={className} style={style} data-setto-map={k} data-setto-map-empty=\"1\">\n {tools ? <div style={fillStyle}>{tools}</div> : null}\n </div>\n );\n }\n\n return (\n <div className={className} style={style} data-setto-map={k}>\n <div style={fillStyle}>\n <iframe\n src={mapEmbedUrl(location)}\n title={title}\n loading={loading}\n referrerPolicy=\"strict-origin-when-cross-origin\"\n style={iframeStyle}\n />\n {tools}\n </div>\n </div>\n );\n}\n\n/*\n * Positioned inside the wrapper rather than on it: the site's classes may\n * already position the wrapper (`absolute inset-0`), and an inline `relative`\n * would silently override them. The radius is inherited so `rounded-xl` on\n * the wrapper clips the map the way it would clip an image.\n */\nconst fillStyle: CSSProperties = {\n position: 'relative',\n width: '100%',\n height: '100%',\n borderRadius: 'inherit',\n overflow: 'hidden',\n};\n\nconst iframeStyle: CSSProperties = {\n display: 'block',\n width: '100%',\n height: '100%',\n border: 0,\n};\n","import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport type { AnimationPreset } from './block-tree/schema';\n\nexport interface SettoAnimationProps {\n preset: AnimationPreset;\n /** Delay before play, in milliseconds. */\n delay?: number;\n /** Duration in milliseconds. Defaults per preset. */\n duration?: number;\n className?: string;\n children: ReactNode;\n}\n\nconst DEFAULT_DURATION: Record<AnimationPreset, number> = {\n fadeIn: 600,\n slideUp: 700,\n stagger: 700,\n scrollReveal: 700,\n};\n\n/**\n * Lightweight, CSS-driven reveal wrapper. Triggers once when scrolled into\n * view (or immediately, for non-scroll presets). Honors\n * `prefers-reduced-motion`, falls back to plain children with no animation.\n *\n * Hosts that use GSAP (carryon.no, setto-site) should keep their own\n * `data-reveal` system; this primitive exists so generated layout trees\n * have a portable animation primitive without dragging GSAP into the\n * setto-client bundle.\n */\nexport function SettoAnimation({\n preset,\n delay = 0,\n duration,\n className,\n children,\n}: SettoAnimationProps) {\n const ref = useRef<HTMLDivElement>(null);\n const [visible, setVisible] = useState(preset === 'fadeIn' || preset === 'slideUp');\n\n useEffect(() => {\n if (preset === 'fadeIn' || preset === 'slideUp') {\n const t = window.setTimeout(() => setVisible(true), delay);\n return () => window.clearTimeout(t);\n }\n const el = ref.current;\n if (!el || typeof IntersectionObserver === 'undefined') {\n setVisible(true);\n return;\n }\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n setVisible(true);\n io.disconnect();\n }\n }\n },\n { threshold: 0.15 },\n );\n io.observe(el);\n return () => io.disconnect();\n }, [preset, delay]);\n\n const reduced =\n typeof window !== 'undefined' &&\n window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n\n const ms = duration ?? DEFAULT_DURATION[preset];\n const transition = reduced\n ? undefined\n : `opacity ${ms}ms ease-out ${delay}ms, transform ${ms}ms ease-out ${delay}ms`;\n\n const hiddenTransform = preset === 'slideUp' || preset === 'scrollReveal' ? 'translateY(24px)' : 'none';\n const style = reduced\n ? undefined\n : {\n opacity: visible ? 1 : 0,\n transform: visible ? 'none' : hiddenTransform,\n transition,\n willChange: 'opacity, transform',\n };\n\n if (preset === 'stagger') {\n return (\n <div\n ref={ref}\n className={className}\n data-setto-animation={preset}\n data-setto-animation-visible={visible ? '1' : '0'}\n >\n {wrapChildrenForStagger(children, visible, ms, delay, reduced)}\n </div>\n );\n }\n\n return (\n <div\n ref={ref}\n className={className}\n style={style}\n data-setto-animation={preset}\n data-setto-animation-visible={visible ? '1' : '0'}\n >\n {children}\n </div>\n );\n}\n\nfunction wrapChildrenForStagger(\n children: ReactNode,\n visible: boolean,\n ms: number,\n baseDelay: number,\n reduced: boolean,\n): ReactNode {\n if (reduced) return children;\n const arr = Array.isArray(children) ? children : [children];\n const step = 80;\n return arr.map((child, i) => (\n <div\n key={i}\n style={{\n opacity: visible ? 1 : 0,\n transform: visible ? 'none' : 'translateY(16px)',\n transition: `opacity ${ms}ms ease-out ${baseDelay + i * step}ms, transform ${ms}ms ease-out ${baseDelay + i * step}ms`,\n }}\n >\n {child}\n </div>\n ));\n}\n","import { useEffect, useState, type ReactNode } from 'react';\nimport { siteHomeUrl } from '../lib/urls';\nimport { useSetto } from '../provider';\n\ntype Mode = 'signin' | 'forgot' | 'set_password';\n\nexport interface AuthGateProps {\n /** Rendered after a session is established. */\n children: ReactNode;\n}\n\nfunction authCallbackType(): 'invite' | 'recovery' | null {\n const hash = window.location.hash.replace(/^#/, '');\n if (!hash) return null;\n const type = new URLSearchParams(hash).get('type');\n if (type === 'invite' || type === 'recovery') return type;\n return null;\n}\n\nfunction clearAuthHashFromUrl() {\n const { pathname, search } = window.location;\n window.history.replaceState(null, '', pathname + search);\n}\n\nfunction consumeInviteErrorFromUrl(): string | null {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('setto_invite_error');\n if (!code) return null;\n params.delete('setto_invite_error');\n const qs = params.toString();\n window.history.replaceState(null, '', `${window.location.pathname}${qs ? `?${qs}` : ''}`);\n return code === 'invalid'\n ? 'Lenken er ugyldig eller utløpt. Be om en ny nullstilling eller invitasjon.'\n : 'Kunne ikke aktivere lenken.';\n}\n\n/**\n * Wraps `children` with Supabase email/password login. Sign-up is disabled;\n * editors are invited by platform admins. Supports password reset and invite\n * links from Supabase email.\n */\nexport function AuthGate({ children }: AuthGateProps) {\n const { supabase: loaded, loadSupabase, api, config, session, authLoading } = useSetto();\n // Loaded by the time the form is shown, unless the host's router brought us here.\n const client = async () => loaded ?? (await loadSupabase());\n const [mode, setMode] = useState<Mode>('signin');\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n const [confirmPassword, setConfirmPassword] = useState('');\n const [error, setError] = useState<string | null>(null);\n const [info, setInfo] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n\n useEffect(() => {\n const inviteError = consumeInviteErrorFromUrl();\n if (inviteError) {\n setError(inviteError);\n setMode('signin');\n return;\n }\n const callback = authCallbackType();\n if (callback) setMode('set_password');\n }, []);\n\n if (authLoading) {\n return <div style={loadingStyle}>Laster …</div>;\n }\n\n if (session && mode !== 'set_password') return <>{children}</>;\n\n if (mode === 'set_password' && !session) {\n return (\n <div style={loadingStyle}>\n {authCallbackType()\n ? 'Aktiverer invitasjon …'\n : 'Åpne lenken fra e-posten for å sette passord.'}\n </div>\n );\n }\n\n const submitSignIn = async (e: React.FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n setInfo(null);\n try {\n const supabase = await client();\n const result = await supabase.auth.signInWithPassword({ email, password });\n if (result.error) throw result.error;\n if (result.data.session) {\n await supabase.auth.setSession({\n access_token: result.data.session.access_token,\n refresh_token: result.data.session.refresh_token,\n });\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Ukjent feil');\n } finally {\n setBusy(false);\n }\n };\n\n const submitForgot = async (e: React.FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n setInfo(null);\n try {\n await api.requestPasswordReset(config.siteId, email);\n setInfo('Vi har sendt en lenke for å nullstille passordet. Sjekk innboksen.');\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Ukjent feil');\n } finally {\n setBusy(false);\n }\n };\n\n const submitSetPassword = async (e: React.FormEvent) => {\n e.preventDefault();\n if (password !== confirmPassword) {\n setError('Passordene er ikke like.');\n return;\n }\n if (password.length < 8) {\n setError('Passordet må være minst 8 tegn.');\n return;\n }\n setBusy(true);\n setError(null);\n setInfo(null);\n try {\n const supabase = await client();\n const { error: updateError } = await supabase.auth.updateUser({ password });\n if (updateError) throw updateError;\n clearAuthHashFromUrl();\n const { data: sessionData } = await supabase.auth.getSession();\n if (sessionData.session) {\n window.location.replace(siteHomeUrl());\n return;\n }\n setMode('signin');\n setPassword('');\n setConfirmPassword('');\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Ukjent feil');\n } finally {\n setBusy(false);\n }\n };\n\n if (mode === 'set_password') {\n const callback = authCallbackType();\n return (\n <div style={shellStyle}>\n <form onSubmit={submitSetPassword} style={formStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <p style={{ margin: 0, color: '#888', fontSize: 13 }}>\n {callback === 'invite'\n ? 'Velg et passord for å fullføre invitasjonen.'\n : 'Velg et nytt passord.'}\n </p>\n <input\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n placeholder=\"Nytt passord\"\n autoComplete=\"new-password\"\n required\n minLength={8}\n style={inputStyle}\n />\n <input\n type=\"password\"\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n placeholder=\"Gjenta passord\"\n autoComplete=\"new-password\"\n required\n minLength={8}\n style={inputStyle}\n />\n {error ? <div style={{ color: '#ff7a7a', fontSize: 12 }}>{error}</div> : null}\n {info ? <div style={{ color: '#9fd89f', fontSize: 12 }}>{info}</div> : null}\n <button type=\"submit\" disabled={busy} style={btnStyle}>\n {busy ? '...' : 'Lagre passord'}\n </button>\n </form>\n </div>\n );\n }\n\n if (mode === 'forgot') {\n return (\n <div style={shellStyle}>\n <form onSubmit={submitForgot} style={formStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <p style={{ margin: 0, color: '#888', fontSize: 13 }}>\n Skriv inn e-posten din, så sender vi en lenke for å nullstille passordet.\n </p>\n <input\n type=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n placeholder=\"E-post\"\n autoComplete=\"email\"\n required\n style={inputStyle}\n />\n {error ? <div style={{ color: '#ff7a7a', fontSize: 12 }}>{error}</div> : null}\n {info ? <div style={{ color: '#9fd89f', fontSize: 12 }}>{info}</div> : null}\n <button type=\"submit\" disabled={busy} style={btnStyle}>\n {busy ? '...' : 'Send lenke'}\n </button>\n <button\n type=\"button\"\n onClick={() => {\n setMode('signin');\n setError(null);\n setInfo(null);\n }}\n style={linkStyle}\n >\n Tilbake til innlogging\n </button>\n </form>\n </div>\n );\n }\n\n return (\n <div style={shellStyle}>\n <form onSubmit={submitSignIn} style={formStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <p style={{ margin: 0, color: '#888', fontSize: 13 }}>\n Logg inn for å redigere innholdet. Har du fått invitasjon, bruk lenken i e-posten\n første gang.\n </p>\n <input\n type=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n placeholder=\"E-post\"\n autoComplete=\"email\"\n required\n style={inputStyle}\n />\n <input\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n placeholder=\"Passord\"\n autoComplete=\"current-password\"\n required\n style={inputStyle}\n />\n {error ? <div style={{ color: '#ff7a7a', fontSize: 12 }}>{error}</div> : null}\n {info ? <div style={{ color: '#9fd89f', fontSize: 12 }}>{info}</div> : null}\n <button type=\"submit\" disabled={busy} style={btnStyle}>\n {busy ? '...' : 'Logg inn'}\n </button>\n <button\n type=\"button\"\n onClick={() => {\n setMode('forgot');\n setError(null);\n setInfo(null);\n }}\n style={linkStyle}\n >\n Glemt passord?\n </button>\n </form>\n </div>\n );\n}\n\nconst shellStyle: React.CSSProperties = {\n minHeight: '100dvh',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#0a0a0d',\n color: '#fff',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nconst formStyle: React.CSSProperties = {\n display: 'flex',\n flexDirection: 'column',\n gap: 12,\n width: 320,\n background: '#15151a',\n padding: 24,\n borderRadius: 12,\n boxShadow: '0 12px 40px rgba(0,0,0,0.4)',\n};\n\nconst inputStyle: React.CSSProperties = {\n background: '#1f1f25',\n color: '#fff',\n border: '1px solid #2a2a32',\n borderRadius: 6,\n padding: '10px 12px',\n fontSize: 14,\n};\n\nconst btnStyle: React.CSSProperties = {\n background: '#640AFF',\n color: '#fff',\n border: 'none',\n borderRadius: 6,\n padding: '10px 12px',\n fontSize: 14,\n fontWeight: 500,\n cursor: 'pointer',\n};\n\nconst linkStyle: React.CSSProperties = {\n background: 'transparent',\n color: '#bda6ff',\n border: 'none',\n fontSize: 12,\n cursor: 'pointer',\n};\n\nconst loadingStyle: React.CSSProperties = {\n ...shellStyle,\n fontSize: 14,\n color: '#888',\n};\n","import type { CSSProperties } from 'react';\n\n/**\n * The dashboard's look, shared by the shell and every module view so a new\n * module's panel reads as part of the same place.\n */\n\nexport const shellStyle: CSSProperties = {\n minHeight: '100dvh',\n background: '#0a0a0d',\n color: '#fff',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nexport const headerStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n padding: '16px 24px',\n borderBottom: '1px solid #1c1c22',\n};\n\nexport const mainStyle: CSSProperties = {\n maxWidth: 720,\n margin: '0 auto',\n padding: 24,\n display: 'flex',\n flexDirection: 'column',\n gap: 16,\n};\n\nexport const cardStyle: CSSProperties = {\n background: '#15151a',\n borderRadius: 12,\n padding: 20,\n display: 'flex',\n flexDirection: 'column',\n gap: 12,\n};\n\nexport const panelStyle: CSSProperties = {\n background: '#1a1a20',\n borderRadius: 8,\n padding: 14,\n display: 'flex',\n flexDirection: 'column',\n gap: 10,\n};\n\nexport const rowStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n background: '#1a1a20',\n padding: '6px 10px',\n borderRadius: 6,\n};\n\nexport const mutedStyle: CSSProperties = {\n color: '#888',\n fontSize: 13,\n margin: 0,\n};\n\nexport const errStyle: CSSProperties = {\n color: '#ff7a7a',\n fontSize: 13,\n margin: 0,\n};\n\nexport const subheadingStyle: CSSProperties = {\n margin: 0,\n fontSize: 14,\n color: '#aaa',\n};\n\nexport const primaryBtnStyle: CSSProperties = {\n display: 'inline-block',\n background: '#640AFF',\n color: '#fff',\n border: 'none',\n borderRadius: 6,\n padding: '10px 14px',\n fontSize: 14,\n fontWeight: 500,\n textDecoration: 'none',\n cursor: 'pointer',\n};\n\nexport const secondaryBtnStyle: CSSProperties = {\n background: 'transparent',\n color: '#bda6ff',\n border: '1px solid #2a2a32',\n borderRadius: 6,\n padding: '6px 10px',\n fontSize: 12,\n cursor: 'pointer',\n};\n\nexport const dangerBtnStyle: CSSProperties = {\n alignSelf: 'flex-start',\n background: 'transparent',\n color: '#ff7a7a',\n border: '1px solid #4a3030',\n borderRadius: 6,\n padding: '8px 14px',\n fontSize: 13,\n cursor: 'pointer',\n};\n\nexport const inputStyle: CSSProperties = {\n width: '100%',\n boxSizing: 'border-box',\n background: '#0f0f13',\n color: '#fff',\n border: '1px solid #2a2a32',\n borderRadius: 6,\n padding: '8px 10px',\n fontSize: 13,\n fontFamily: 'inherit',\n};\n\nexport const tabBarStyle: CSSProperties = {\n display: 'flex',\n gap: 4,\n borderBottom: '1px solid #1c1c22',\n paddingBottom: 0,\n};\n\nexport function tabStyle(active: boolean): CSSProperties {\n return {\n background: 'transparent',\n border: 'none',\n borderBottom: active ? '2px solid #640AFF' : '2px solid transparent',\n color: active ? '#fff' : '#888',\n padding: '8px 12px',\n fontSize: 13,\n fontWeight: 500,\n cursor: 'pointer',\n marginBottom: -1,\n };\n}\n","import { useEffect, useRef } from 'react';\nimport { AuthGate } from '../edit-mode/auth-gate';\nimport { CHECKOUT_INTENT, isAdminPanelView, siteHomeUrl, wantsCheckout } from '../lib/urls';\nimport { useSettoAdminChrome } from '../chrome';\nimport { useSetto } from '../provider';\nimport {\n cardStyle,\n headerStyle,\n mainStyle,\n mutedStyle,\n primaryBtnStyle,\n secondaryBtnStyle,\n shellStyle,\n} from './styles';\n\n/**\n * The page at `/setto`. Mount it under a route like `<Route path=\"/setto/*\" …>`.\n *\n * What draws it lives in setto-server now, not here. The chrome bundle offers a\n * dashboard at runtime — publish history, the forms inbox, the domain panel —\n * and that is what fills this route, so changing any of it is one deploy of\n * Setto rather than a rebuild of every site it has ever made.\n *\n * What stays behind is the door: sign in, and get back to the site to edit.\n * That much has to work from the site's own bundle, because it is the only way\n * in and because the bug that takes the chrome down could be mine. Everything\n * past the door is Setto's, needs Setto to be reachable to do anything at all,\n * and is better absent than drawn from a copy that has been quietly rotting in\n * a pinned version since the day the site was built.\n */\nexport function SettoAdminApp() {\n const Chrome = useSettoAdminChrome();\n const { supabase, loadSupabase } = useSetto();\n /*\n * The sign-in needs supabase-js, which a page load on `/setto` fetches from\n * the start; this is for arriving here by the host's own router instead.\n */\n useEffect(() => {\n if (supabase) return;\n loadSupabase().catch(() => {\n // The gate's own submit tries again and says what went wrong.\n });\n }, [supabase, loadSupabase]);\n if (Chrome) return <Chrome />;\n\n return (\n <AuthGate>\n <SiteDoor />\n </AuthGate>\n );\n}\n\nfunction SiteDoor() {\n const { supabase, session, sites, currentSite, config } = useSetto();\n const redirectAfterSignIn = useRef(false);\n\n useEffect(() => {\n if (!supabase) return;\n const { data: sub } = supabase.auth.onAuthStateChange((event) => {\n if (event === 'SIGNED_IN' && !isAdminPanelView()) {\n redirectAfterSignIn.current = true;\n }\n });\n return () => sub.subscription.unsubscribe();\n }, [supabase]);\n\n useEffect(() => {\n if (!redirectAfterSignIn.current || !session || sites === null || isAdminPanelView()) {\n return;\n }\n if (currentSite) {\n redirectAfterSignIn.current = false;\n /*\n * Back to the site, carrying whatever they came to do.\n *\n * Somebody who pressed «Neste» on the preview bar wanted the checkout,\n * not the front page; without the marker they land where they started\n * and have to press the same button again, now that they are signed in.\n */\n window.location.replace(\n wantsCheckout() ? `${siteHomeUrl()}?${CHECKOUT_INTENT}=1` : siteHomeUrl(),\n );\n return;\n }\n redirectAfterSignIn.current = false;\n }, [session, sites, currentSite]);\n\n if (redirectAfterSignIn.current && session && (sites === null || currentSite)) {\n return <div style={loadingRedirectStyle}>Åpner redigering …</div>;\n }\n\n return (\n <div style={shellStyle}>\n <header style={headerStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <SignOutButton />\n </header>\n\n <main style={mainStyle}>\n {sites === null ? <p style={mutedStyle}>Laster sider…</p> : null}\n\n {currentSite ? (\n <section style={cardStyle}>\n <h2 style={{ margin: 0, fontSize: 18 }}>{currentSite.display_name}</h2>\n <div style={{ display: 'flex', gap: 8 }}>\n <a href={siteHomeUrl()} style={primaryBtnStyle}>\n Begynn å redigere\n </a>\n </div>\n {/*\n Only ever seen when the chrome did not load, so it says what is\n missing rather than pretending the page is complete. Naming the\n panels matters: somebody who came for the skjema-innboksen needs\n to know it exists and is coming back, not wonder where it went.\n */}\n <p style={mutedStyle}>\n Publiseringer, skjemaer og domene er ikke tilgjengelig akkurat nå. Last siden på\n nytt om litt — redigering virker som vanlig i mellomtiden.\n </p>\n </section>\n ) : sites && sites.length === 0 ? (\n <p style={mutedStyle}>\n Du er ikke medlem av noen sider ennå. Be administratoren legge deg til.\n </p>\n ) : null}\n\n {sites && !currentSite && sites.length > 0 ? (\n <section style={cardStyle}>\n <p style={mutedStyle}>\n Du er logget inn på denne siden ({config.siteId}), men er ikke medlem her. Spør\n administrator om tilgang.\n </p>\n </section>\n ) : null}\n </main>\n </div>\n );\n}\n\nfunction SignOutButton() {\n const { supabase } = useSetto();\n return (\n <button onClick={() => void supabase?.auth.signOut()} style={secondaryBtnStyle}>\n Logg ut\n </button>\n );\n}\n\nconst loadingRedirectStyle: React.CSSProperties = {\n minHeight: '100dvh',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#0a0a0d',\n color: '#888',\n fontSize: 14,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n","/**\n * Per-type metadata for block-tree nodes.\n *\n * The renderer dispatches on node `type`; the validator and key extractor\n * consult this registry for allowed children, required content keys, and\n * whether a type carries a theme id.\n */\n\nimport type { BlockNode, BlockNodeType } from './schema';\n\nexport interface BlockTypeMeta {\n /**\n * Allowed child types. `null` means the node is a leaf; `'any'` means any\n * other type may appear as a child.\n */\n allowedChildren: BlockNodeType[] | 'any' | null;\n /** True when the node has a theme id (used in `sections.json`). */\n themed: boolean;\n /** True when this node participates as a `SectionToolbar` target. */\n selectable: boolean;\n}\n\nexport const BLOCK_REGISTRY: Record<BlockNodeType, BlockTypeMeta> = {\n section: { allowedChildren: 'any', themed: true, selectable: true },\n block: { allowedChildren: 'any', themed: true, selectable: true },\n container: { allowedChildren: 'any', themed: false, selectable: false },\n animation: { allowedChildren: 'any', themed: false, selectable: false },\n repeater: { allowedChildren: 'any', themed: false, selectable: false },\n text: { allowedChildren: null, themed: false, selectable: false },\n image: { allowedChildren: null, themed: false, selectable: false },\n icon: { allowedChildren: null, themed: false, selectable: false },\n form: { allowedChildren: null, themed: false, selectable: false },\n video: { allowedChildren: null, themed: false, selectable: false },\n};\n\n/** All known block types, kept in sync with `BLOCK_REGISTRY`. */\nexport const BLOCK_TYPES: readonly BlockNodeType[] = Object.keys(\n BLOCK_REGISTRY,\n) as BlockNodeType[];\n\n/** Returns the children of a node, or an empty array for leaves. */\nexport function nodeChildren(node: BlockNode): BlockNode[] {\n switch (node.type) {\n case 'section':\n case 'block':\n case 'container':\n case 'animation':\n return node.children;\n case 'repeater':\n return node.itemTemplate;\n default:\n return [];\n }\n}\n","/**\n * Runtime validator for block trees.\n *\n * Used by both `setto-client` (when loading a `home.layout.json` at boot)\n * and `setto-agent` (after generation, before sandbox build). No external\n * dependencies so we can ship to host sites without bundle bloat.\n */\n\nimport { BLOCK_REGISTRY, nodeChildren } from './registry';\nimport { FORM_FIELD_TYPES, isFormFieldType } from '../modules/forms/fields';\nimport type { BlockNode, BlockNodeType, BlockTree, FormField } from './schema';\n\nexport interface ValidationIssue {\n /** Dotted path to the offending node, e.g. `root[2].children[0]`. */\n path: string;\n message: string;\n}\n\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; issues: ValidationIssue[] };\n\nconst ANIMATION_PRESETS = ['fadeIn', 'slideUp', 'stagger', 'scrollReveal'] as const;\n\n/**\n * Validates a parsed block tree. Returns the first batch of issues found —\n * the goal is enough detail for a fixer model to act on, not exhaustive\n * reporting.\n */\nexport function validateBlockTree(input: unknown): ValidationResult {\n const issues: ValidationIssue[] = [];\n\n if (!isRecord(input)) {\n return fail('$', 'Block tree must be an object');\n }\n if (input.version !== '1') {\n issues.push({ path: '$.version', message: 'Expected version \"1\"' });\n }\n if (!Array.isArray(input.root)) {\n return fail('$.root', 'root must be an array of block nodes');\n }\n\n const seenIds = new Set<string>();\n for (let i = 0; i < input.root.length; i++) {\n validateNode(input.root[i], `root[${i}]`, seenIds, issues);\n }\n\n return issues.length ? { ok: false, issues } : { ok: true };\n}\n\nfunction validateNode(\n raw: unknown,\n path: string,\n seenIds: Set<string>,\n issues: ValidationIssue[],\n): void {\n if (!isRecord(raw)) {\n issues.push({ path, message: 'Node must be an object' });\n return;\n }\n const type = raw.type;\n if (typeof type !== 'string' || !(type in BLOCK_REGISTRY)) {\n issues.push({ path, message: `Unknown block type \"${String(type)}\"` });\n return;\n }\n if (typeof raw.id !== 'string' || raw.id.length === 0) {\n issues.push({ path, message: 'Node is missing a non-empty string id' });\n } else if (seenIds.has(raw.id)) {\n issues.push({ path, message: `Duplicate node id \"${raw.id}\"` });\n } else {\n seenIds.add(raw.id);\n }\n if (raw.className !== undefined && typeof raw.className !== 'string') {\n issues.push({ path: `${path}.className`, message: 'className must be a string' });\n }\n\n validateTypeSpecific(raw, type as BlockNodeType, path, issues);\n\n // Leaf types must not carry a `children` array on the raw object.\n const meta = BLOCK_REGISTRY[type as BlockNodeType];\n if (\n meta.allowedChildren === null &&\n Array.isArray(raw.children) &&\n (raw.children as unknown[]).length > 0\n ) {\n issues.push({ path, message: `Type \"${type}\" cannot have children` });\n return;\n }\n\n const children = nodeChildren(raw as unknown as BlockNode);\n if (meta.allowedChildren === null && children.length > 0) {\n issues.push({ path, message: `Type \"${type}\" cannot have children` });\n return;\n }\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n const childPath =\n type === 'repeater' ? `${path}.itemTemplate[${i}]` : `${path}.children[${i}]`;\n validateNode(child, childPath, seenIds, issues);\n if (\n meta.allowedChildren !== 'any' &&\n meta.allowedChildren !== null &&\n isRecord(child) &&\n typeof child.type === 'string' &&\n !meta.allowedChildren.includes(child.type as BlockNodeType)\n ) {\n issues.push({\n path: childPath,\n message: `Type \"${child.type}\" not allowed inside \"${type}\"`,\n });\n }\n }\n}\n\nfunction validateTypeSpecific(\n raw: Record<string, unknown>,\n type: BlockNodeType,\n path: string,\n issues: ValidationIssue[],\n): void {\n switch (type) {\n case 'section':\n requireString(raw, 'sectionId', path, issues);\n requireArray(raw, 'children', path, issues);\n break;\n case 'block':\n requireString(raw, 'blockId', path, issues);\n requireArray(raw, 'children', path, issues);\n break;\n case 'container':\n requireArray(raw, 'children', path, issues);\n break;\n case 'text':\n requireString(raw, 'k', path, issues);\n break;\n case 'image':\n requireString(raw, 'srcKey', path, issues);\n break;\n case 'icon':\n requireString(raw, 'k', path, issues);\n break;\n case 'repeater':\n requireString(raw, 'itemsKey', path, issues);\n requireArray(raw, 'itemTemplate', path, issues);\n if (!isRecord(raw.defaultItem)) {\n issues.push({\n path: `${path}.defaultItem`,\n message: 'defaultItem must be an object mapping field names to default strings',\n });\n } else {\n for (const [field, value] of Object.entries(raw.defaultItem)) {\n if (typeof value !== 'string') {\n issues.push({\n path: `${path}.defaultItem.${field}`,\n message: 'defaultItem values must be strings',\n });\n }\n }\n }\n break;\n case 'form':\n requireString(raw, 'formId', path, issues);\n // Fields may live in the locale instead (`form.<id>.fields`), so a\n // missing prop is fine; a present one has to be well-formed.\n if (raw.fields !== undefined) {\n if (!Array.isArray(raw.fields)) {\n issues.push({ path: `${path}.fields`, message: 'form.fields must be an array' });\n break;\n }\n for (let i = 0; i < raw.fields.length; i++) {\n validateFormField(raw.fields[i], `${path}.fields[${i}]`, issues);\n }\n }\n if (raw.endpoint !== undefined && typeof raw.endpoint !== 'string') {\n issues.push({ path: `${path}.endpoint`, message: 'form.endpoint must be a string' });\n }\n break;\n case 'video':\n requireString(raw, 'srcKey', path, issues);\n break;\n case 'animation':\n requireArray(raw, 'children', path, issues);\n if (typeof raw.preset !== 'string' || !ANIMATION_PRESETS.includes(raw.preset as never)) {\n issues.push({\n path: `${path}.preset`,\n message: `preset must be one of ${ANIMATION_PRESETS.join(', ')}`,\n });\n }\n break;\n }\n}\n\nfunction validateFormField(\n raw: unknown,\n path: string,\n issues: ValidationIssue[],\n): void {\n if (!isRecord(raw)) {\n issues.push({ path, message: 'field must be an object' });\n return;\n }\n if (typeof raw.name !== 'string' || raw.name.length === 0) {\n issues.push({ path: `${path}.name`, message: 'field.name must be a non-empty string' });\n }\n if (!isFormFieldType(raw.type)) {\n issues.push({\n path: `${path}.type`,\n message: `field.type must be one of ${FORM_FIELD_TYPES.join(', ')}`,\n });\n }\n requireString(raw as Record<string, unknown>, 'labelKey', path, issues);\n}\n\nfunction requireString(\n raw: Record<string, unknown>,\n field: string,\n path: string,\n issues: ValidationIssue[],\n): void {\n const value = raw[field];\n if (typeof value !== 'string' || value.length === 0) {\n issues.push({ path: `${path}.${field}`, message: `${field} must be a non-empty string` });\n }\n}\n\nfunction requireArray(\n raw: Record<string, unknown>,\n field: string,\n path: string,\n issues: ValidationIssue[],\n): void {\n if (!Array.isArray(raw[field])) {\n issues.push({ path: `${path}.${field}`, message: `${field} must be an array` });\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction fail(path: string, message: string): ValidationResult {\n return { ok: false, issues: [{ path, message }] };\n}\n\n/** Narrowing helper: validates and returns a typed tree, or throws. */\nexport function parseBlockTree(input: unknown): BlockTree {\n const result = validateBlockTree(input);\n if (!result.ok) {\n const first = result.issues[0];\n const detail = first ? `${first.path}: ${first.message}` : 'unknown';\n throw new Error(`Invalid block tree at ${detail}`);\n }\n return input as BlockTree;\n}\n\nexport type { FormField };\n","import {\n createContext,\n useContext,\n type ComponentType,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport { T } from '../T';\nimport { SettoSection } from '../SettoSection';\nimport { SettoBlock } from '../SettoBlock';\nimport { SettoRepeater } from '../SettoRepeater';\nimport { SettoImage } from '../SettoImage';\nimport { SettoIcon, type SettoIconRenderProps } from '../SettoIcon';\nimport { SettoForm } from '../modules/forms/SettoForm';\nimport { SettoVideo } from '../SettoVideo';\nimport { SettoAnimation } from '../SettoAnimation';\nimport { validateBlockTree } from './validate';\nimport type {\n BlockNode,\n BlockTree,\n ContainerTag,\n TextAs,\n} from './schema';\n\nexport interface SettoBlockTreeProps {\n /** Validated block tree, typically parsed from `home.layout.json`. */\n tree: BlockTree;\n /**\n * Icon registry consumed by `SettoIcon` nodes — the same map a host would\n * pass directly to `<SettoIcon icons={…}>`.\n */\n icons: Record<string, ComponentType<SettoIconRenderProps>>;\n /**\n * When true (default), validates the tree and throws on schema errors.\n * Disable in production after a one-time boot check.\n */\n validate?: boolean;\n}\n\ninterface IconRegistry {\n icons: Record<string, ComponentType<SettoIconRenderProps>>;\n}\n\nconst IconRegistryContext = createContext<IconRegistry | null>(null);\n\ninterface RepeaterScope {\n /** i18n prefix, e.g. 'faq.items'. */\n itemsKey: string;\n /** Current item key — '1', '2', ... */\n itemKey: string;\n}\n\nconst RepeaterScopeContext = createContext<RepeaterScope | null>(null);\n\n/**\n * Renders a block tree by dispatching each node to the matching Setto\n * primitive. Inside a `repeater`, leaf nodes use keys relative to the item;\n * the renderer composes them with the active scope so the agent can author\n * trees without knowing per-item suffixes.\n */\nexport function SettoBlockTree({ tree, icons, validate = true }: SettoBlockTreeProps) {\n if (validate) {\n const result = validateBlockTree(tree);\n if (!result.ok) {\n const first = result.issues[0];\n const detail = first ? `${first.path}: ${first.message}` : 'unknown';\n throw new Error(`Invalid block tree at ${detail}`);\n }\n }\n\n return (\n <IconRegistryContext.Provider value={{ icons }}>\n {tree.root.map((node) => (\n <RenderNode key={node.id} node={node} />\n ))}\n </IconRegistryContext.Provider>\n );\n}\n\nfunction RenderNode({ node }: { node: BlockNode }): ReactElement | null {\n switch (node.type) {\n case 'section':\n return (\n <SettoSection sectionId={node.sectionId} className={node.className}>\n {renderChildren(node.children)}\n </SettoSection>\n );\n\n case 'block':\n return (\n <SettoBlock blockId={node.blockId} className={node.className}>\n {renderChildren(node.children)}\n </SettoBlock>\n );\n\n case 'container':\n return renderContainer(node.tag ?? 'div', node.className, renderChildren(node.children));\n\n case 'animation':\n return (\n <SettoAnimation\n preset={node.preset}\n delay={node.delay}\n duration={node.duration}\n className={node.className}\n >\n {renderChildren(node.children)}\n </SettoAnimation>\n );\n\n case 'repeater':\n return (\n <SettoRepeater\n itemsKey={node.itemsKey}\n defaultItem={node.defaultItem}\n itemLabel={node.itemLabel}\n className={node.className}\n >\n {(itemKey) => (\n <RepeaterScopeContext.Provider\n value={{ itemsKey: node.itemsKey, itemKey }}\n >\n {renderChildren(node.itemTemplate)}\n </RepeaterScopeContext.Provider>\n )}\n </SettoRepeater>\n );\n\n case 'text':\n return <TextLeaf node={node} />;\n\n case 'image':\n return <ImageLeaf node={node} />;\n\n case 'icon':\n return <IconLeaf node={node} />;\n\n case 'form':\n return (\n <SettoForm\n formId={node.formId}\n fields={node.fields}\n endpoint={node.endpoint}\n className={node.className}\n />\n );\n\n case 'video':\n return <VideoLeaf node={node} />;\n }\n}\n\nfunction renderChildren(children: BlockNode[]): ReactNode {\n return children.map((child) => <RenderNode key={child.id} node={child} />);\n}\n\nfunction TextLeaf({ node }: { node: Extract<BlockNode, { type: 'text' }> }) {\n const k = useScopedKey(node.k);\n const inner = <T k={k} />;\n if (!node.as) {\n return node.className ? <span className={node.className}>{inner}</span> : inner;\n }\n return renderTag(node.as, node.className, inner);\n}\n\nfunction ImageLeaf({ node }: { node: Extract<BlockNode, { type: 'image' }> }) {\n const srcKey = useScopedKey(node.srcKey);\n return <SettoImage srcKey={srcKey} alt={node.alt} className={node.className} />;\n}\n\nfunction VideoLeaf({ node }: { node: Extract<BlockNode, { type: 'video' }> }) {\n const srcKey = useScopedKey(node.srcKey);\n const posterKey = useScopedKey(node.posterKey ?? '');\n return (\n <SettoVideo\n srcKey={srcKey}\n posterKey={node.posterKey ? posterKey : undefined}\n title={node.title}\n className={node.className}\n />\n );\n}\n\nfunction IconLeaf({ node }: { node: Extract<BlockNode, { type: 'icon' }> }) {\n const registry = useContext(IconRegistryContext);\n const k = useScopedKey(node.k);\n if (!registry) {\n throw new Error('SettoBlockTree must be mounted with an `icons` prop for icon nodes');\n }\n return (\n <SettoIcon\n k={k}\n icons={registry.icons}\n size={node.size}\n className={node.className}\n />\n );\n}\n\nfunction useScopedKey(key: string): string {\n const scope = useContext(RepeaterScopeContext);\n if (!scope) return key;\n return `${scope.itemsKey}.${scope.itemKey}.${key}`;\n}\n\nfunction renderTag(\n tag: TextAs,\n className: string | undefined,\n children: ReactNode,\n): ReactElement {\n switch (tag) {\n case 'h1': return <h1 className={className}>{children}</h1>;\n case 'h2': return <h2 className={className}>{children}</h2>;\n case 'h3': return <h3 className={className}>{children}</h3>;\n case 'h4': return <h4 className={className}>{children}</h4>;\n case 'h5': return <h5 className={className}>{children}</h5>;\n case 'h6': return <h6 className={className}>{children}</h6>;\n case 'p': return <p className={className}>{children}</p>;\n case 'span': return <span className={className}>{children}</span>;\n case 'div': return <div className={className}>{children}</div>;\n case 'label': return <label className={className}>{children}</label>;\n case 'em': return <em className={className}>{children}</em>;\n case 'strong': return <strong className={className}>{children}</strong>;\n }\n}\n\nfunction renderContainer(\n tag: ContainerTag,\n className: string | undefined,\n children: ReactNode,\n): ReactElement {\n switch (tag) {\n case 'div': return <div className={className}>{children}</div>;\n case 'section': return <section className={className}>{children}</section>;\n case 'header': return <header className={className}>{children}</header>;\n case 'footer': return <footer className={className}>{children}</footer>;\n case 'main': return <main className={className}>{children}</main>;\n case 'aside': return <aside className={className}>{children}</aside>;\n case 'nav': return <nav className={className}>{children}</nav>;\n case 'article': return <article className={className}>{children}</article>;\n case 'ul': return <ul className={className}>{children}</ul>;\n case 'ol': return <ol className={className}>{children}</ol>;\n case 'li': return <li className={className}>{children}</li>;\n case 'p': return <p className={className}>{children}</p>;\n case 'span': return <span className={className}>{children}</span>;\n }\n}\n","/**\n * Walks a block tree and reports the i18n keys, theme ids, and required\n * sample-locale entries it expects. The agent uses this output to validate\n * that the generated `no.json` covers everything the tree references.\n */\n\nimport type { BlockNode, BlockTree, RepeaterNode } from './schema';\n\nexport interface ContentKeyRequirements {\n /** Plain i18n keys that must exist with a string value. */\n keys: Set<string>;\n /**\n * Section / block theme ids referenced by the tree. The deterministic\n * sections.json overlay and section-schemas.ts must include each id.\n */\n themeIds: Set<string>;\n /**\n * Repeater requirements — at least one item entry must exist in the\n * locale under `itemsKey`, with every field from `defaultItem`.\n */\n repeaters: Array<{\n itemsKey: string;\n fields: string[];\n /**\n * Item-relative keys produced by walking the item template. The\n * validator checks every existing locale item has these keys.\n */\n itemKeys: string[];\n }>;\n}\n\n/** Returns content requirements for an already-validated tree. */\nexport function extractContentKeys(tree: BlockTree): ContentKeyRequirements {\n const out: ContentKeyRequirements = {\n keys: new Set(),\n themeIds: new Set(),\n repeaters: [],\n };\n for (const node of tree.root) {\n walk(node, out, null);\n }\n return out;\n}\n\nfunction walk(\n node: BlockNode,\n out: ContentKeyRequirements,\n repeaterCtx: { itemsKey: string } | null,\n): void {\n switch (node.type) {\n case 'section':\n out.themeIds.add(node.sectionId);\n for (const child of node.children) walk(child, out, repeaterCtx);\n return;\n case 'block':\n out.themeIds.add(node.blockId);\n for (const child of node.children) walk(child, out, repeaterCtx);\n return;\n case 'container':\n case 'animation':\n for (const child of node.children) walk(child, out, repeaterCtx);\n return;\n case 'text':\n out.keys.add(scopedKey(node.k, repeaterCtx));\n return;\n case 'image':\n out.keys.add(scopedKey(node.srcKey, repeaterCtx));\n return;\n case 'icon':\n out.keys.add(scopedKey(node.k, repeaterCtx));\n return;\n case 'video':\n out.keys.add(scopedKey(node.srcKey, repeaterCtx));\n if (node.posterKey) out.keys.add(scopedKey(node.posterKey, repeaterCtx));\n return;\n case 'form':\n out.keys.add(`form.${node.formId}.submit`);\n out.keys.add(`form.${node.formId}.success`);\n out.keys.add(`form.${node.formId}.error`);\n for (const field of node.fields ?? []) {\n out.keys.add(field.labelKey);\n if (field.placeholderKey) out.keys.add(field.placeholderKey);\n if (field.optionsKey) out.keys.add(field.optionsKey);\n }\n return;\n case 'repeater':\n recordRepeater(node, out);\n // Repeater inner nodes resolve relative to the item key, so we\n // don't add their content paths into `keys` — coverage is checked\n // per existing locale item via `itemKeys`.\n for (const child of node.itemTemplate) {\n walk(child, out, { itemsKey: node.itemsKey });\n }\n return;\n }\n}\n\nfunction scopedKey(\n key: string,\n repeaterCtx: { itemsKey: string } | null,\n): string {\n if (!repeaterCtx) return key;\n // Inside a repeater, leaf nodes use keys relative to the item.\n // For validation we collect them under the item template instead.\n return `${repeaterCtx.itemsKey}.*.${key}`;\n}\n\nfunction recordRepeater(node: RepeaterNode, out: ContentKeyRequirements): void {\n const fields = Object.keys(node.defaultItem);\n const itemKeys: string[] = [];\n collectRelativeKeys(node.itemTemplate, '', itemKeys);\n out.repeaters.push({\n itemsKey: node.itemsKey,\n fields,\n itemKeys,\n });\n}\n\nfunction collectRelativeKeys(\n nodes: BlockNode[],\n prefix: string,\n out: string[],\n): void {\n for (const node of nodes) {\n switch (node.type) {\n case 'text':\n case 'icon':\n out.push(prefix ? `${prefix}.${node.k}` : node.k);\n break;\n case 'image':\n out.push(prefix ? `${prefix}.${node.srcKey}` : node.srcKey);\n break;\n case 'video':\n out.push(prefix ? `${prefix}.${node.srcKey}` : node.srcKey);\n if (node.posterKey) {\n out.push(prefix ? `${prefix}.${node.posterKey}` : node.posterKey);\n }\n break;\n case 'section':\n case 'block':\n case 'container':\n case 'animation':\n collectRelativeKeys(node.children, prefix, out);\n break;\n case 'repeater':\n // Nested repeaters are valid but their inner keys are scoped under\n // a different prefix at runtime — not part of the outer template.\n break;\n case 'form':\n // Forms inside repeaters are uncommon and use the form's own scope.\n break;\n }\n }\n}\n"],"names":["res","walk","isRecord","at","Component","STYLE_ID","session","SettoSection","SettoBlock","Fragment","shellStyle"],"mappings":";;;;;;AAiBA,MAAM,cAAc;AAGb,MAAM,mBAAmB;AAMhC,MAAM,WAAmC;AAAA,EACvC,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI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AA,MACrD;AACA;AAAA,IACF,KAAK;AACH,qBAAe,MAAM,GAAG;AAIxB,iBAAW,SAAS,KAAK,cAAc;AACrC,aAAK,OAAO,KAAK,EAAE,UAAU,KAAK,UAAU;AAAA,MAC9C;AACA;AAAA,EAAA;AAEN;AAEA,SAAS,UACP,KACA,aACQ;AACR,MAAI,CAAC,YAAa,QAAO;AAGzB,SAAO,GAAG,YAAY,QAAQ,MAAM,GAAG;AACzC;AAEA,SAAS,eAAe,MAAoB,KAAmC;AAC7E,QAAM,SAAS,OAAO,KAAK,KAAK,WAAW;AAC3C,QAAM,WAAqB,CAAA;AAC3B,sBAAoB,KAAK,cAAc,IAAI,QAAQ;AACnD,MAAI,UAAU,KAAK;AAAA,IACjB,UAAU,KAAK;AAAA,IACf;AAAA,IACA;AAAA,EAAA,CACD;AACH;AAEA,SAAS,oBACP,OACA,QACA,KACM;AACN,aAAW,QAAQ,OAAO;AACxB,YAAQ,KAAK,MAAA;AAAA,MACX,KAAK;AAAA,MACL,KAAK;AACH,YAAI,KAAsC,KAAK,CAAC;AAChD;AAAA,MACF,KAAK;AACH,YAAI,KAA2C,KAAK,MAAM;AAC1D;AAAA,MACF,KAAK;AACH,YAAI,KAA2C,KAAK,MAAM;AAC1D,YAAI,KAAK,WAAW;AAClB,cAAI,KAA8C,KAAK,SAAS;AAAA,QAClE;AACA;AAAA,MACF,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AACH,4BAAoB,KAAK,UAAU,QAAQ,GAAG;AAC9C;AAAA,IAOA;AAAA,EAEN;AACF;"}
|
|
1
|
+
{"version":3,"file":"setto-client.js","sources":["../src/lib/languages.ts","../src/lib/supabase.ts","../src/modules/forms/api.ts","../src/lib/api.ts","../src/lib/nested-resource.ts","../src/lib/i18n-store.ts","../src/lib/language-routing.ts","../src/lib/image-paths.ts","../src/lib/asset-store.ts","../src/lib/theme-store.ts","../src/pages/manifest.ts","../src/lib/page-store.ts","../src/pages/bundled.ts","../src/lib/use-site-access.ts","../src/lib/visitor-view.ts","../src/chrome.tsx","../src/lib/urls.ts","../src/edit-mode/constants.ts","../src/edit-mode/document-layout.ts","../src/edit-mode/setto-mark.tsx","../src/edit-mode/toolbar-fallback.tsx","../src/edit-mode/mount.tsx","../src/modules/chat/settings.ts","../src/modules/chat/index.ts","../src/provider.tsx","../src/LanguageSwitcher.tsx","../src/guest-edit.tsx","../src/lib/link-context.ts","../src/edit-mode/link-action-chip.tsx","../src/lib/place-caret-at-point.ts","../src/lib/use-coarse-pointer.ts","../src/T.tsx","../src/section-context.tsx","../src/theme-target-utils.ts","../src/use-section-theme.ts","../src/SettoSection.tsx","../src/SettoBlock.tsx","../src/edit-mode/floating-popover.tsx","../src/SettoIcon.tsx","../src/lib/media.ts","../src/lib/optimized-image.ts","../src/SettoImage.tsx","../src/SettoRepeater.tsx","../src/pages/head.ts","../src/pages/SettoPage.tsx","../src/blog/contract.ts","../src/blog/data.ts","../src/blog/strings.ts","../src/blog/render.tsx","../src/blog/SettoBlog.tsx","../src/modules/forms/fields.ts","../src/modules/forms/SettoForm.tsx","../src/modules/forms/index.ts","../src/modules/domain/index.ts","../src/modules/index.ts","../src/SettoVideo.tsx","../src/lib/map-location.ts","../src/SettoMap.tsx","../src/SettoAnimation.tsx","../src/edit-mode/auth-gate.tsx","../src/admin/styles.ts","../src/admin/App.tsx","../src/block-tree/registry.ts","../src/block-tree/validate.ts","../src/block-tree/SettoBlockTree.tsx","../src/block-tree/extract-keys.ts"],"sourcesContent":["/**\n * Which languages a site speaks, and which one a visitor is reading.\n *\n * Every Setto site has been Norwegian-only, not because the machinery could\n * not hold more — `I18nStore` has taken a language argument since the\n * beginning and the publish path already serialises one bundle per language —\n * but because nothing ever told a site it had a second one, and nothing gave a\n * visitor a way to ask for it.\n *\n * The choice is deliberately per browser and not per URL. A path prefix\n * (`/en/…`) is the better answer for search engines and the wrong answer for\n * this pipeline today: every site is a single-page app whose routes the agent\n * writes, and quietly doubling every route is not a thing to do to thirteen\n * live sites in one release. Recorded here rather than hidden: when these\n * sites want to be found in two languages, this is the decision to revisit.\n */\n\nconst STORAGE_KEY = 'setto.lang';\n\n/** Norwegian is the floor: every site has it, and it is what the agent writes. */\nexport const DEFAULT_LANGUAGE = 'no';\n\n/**\n * Language names in their own language, because a switcher that says\n * \"Norwegian\" to a Norwegian is written for the wrong person.\n */\nconst ENDONYMS: Record<string, string> = {\n no: 'Norsk',\n nb: 'Norsk',\n nn: 'Nynorsk',\n en: 'English',\n sv: 'Svenska',\n da: 'Dansk',\n de: 'Deutsch',\n fr: 'Français',\n es: 'Español',\n it: 'Italiano',\n nl: 'Nederlands',\n pl: 'Polski',\n pt: 'Português',\n fi: 'Suomi',\n is: 'Íslenska',\n lt: 'Lietuvių',\n uk: 'Українська',\n ru: 'Русский',\n ar: 'العربية',\n tr: 'Türkçe',\n so: 'Soomaali',\n ti: 'ትግርኛ',\n th: 'ไทย',\n vi: 'Tiếng Việt',\n zh: '中文',\n ja: '日本語',\n};\n\n/** «Norsk», or the tag itself when we have no name for it. */\nexport function languageName(tag: string): string {\n const base = tag.toLowerCase().split('-')[0] ?? tag;\n return ENDONYMS[base] ?? tag.toUpperCase();\n}\n\n/**\n * The languages this site actually speaks, primary first, no duplicates.\n *\n * A configured list that forgets to include the primary language is a site\n * whose own copy is unreachable, so the primary is inserted rather than\n * trusted.\n */\nexport function siteLanguages(\n configured: readonly string[] | undefined,\n primary: string = DEFAULT_LANGUAGE,\n): string[] {\n const out = [primary];\n for (const tag of configured ?? []) {\n if (tag && !out.includes(tag)) out.push(tag);\n }\n return out;\n}\n\n/** What this browser last chose here, if anything. */\nexport function readStoredLanguage(): string | null {\n try {\n return window.localStorage.getItem(STORAGE_KEY);\n } catch {\n // A browser with site data blocked still gets a language, just not a memory.\n return null;\n }\n}\n\nexport function storeLanguage(tag: string): void {\n try {\n window.localStorage.setItem(STORAGE_KEY, tag);\n } catch {\n // Same.\n }\n}\n\n/**\n * The language to open in.\n *\n * Their own previous choice first — it is the only signal that is definitely\n * about this site. Then what the browser asks for, matched on the base tag so\n * `en-GB` finds `en`. Then the site's primary, which is always present.\n *\n * Note what is *not* here: no geolocation, and no guessing from a domain. A\n * Norwegian abroad is still Norwegian, and a site that decides it knows better\n * than `Accept-Language` is a site people fight with.\n */\nexport function pickInitialLanguage(\n available: readonly string[],\n browserLanguages: readonly string[] = typeof navigator === 'undefined'\n ? []\n : (navigator.languages ?? [navigator.language]),\n stored: string | null = null,\n): string {\n const fallback = available[0] ?? DEFAULT_LANGUAGE;\n if (stored && available.includes(stored)) return stored;\n\n for (const wanted of browserLanguages) {\n const base = wanted.toLowerCase().split('-')[0];\n if (!base) continue;\n const hit = available.find((tag) => tag.toLowerCase().split('-')[0] === base);\n if (hit) return hit;\n /*\n * Norwegian is three tags for one language. A browser asking for `nb`\n * should be given `no`, which is what every Setto bundle is named, or the\n * site opens in English for a Norwegian.\n */\n if ((base === 'nb' || base === 'nn' || base === 'no') && available.includes('no')) {\n return 'no';\n }\n }\n return fallback;\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\n\nexport interface SupabaseConnection {\n url: string;\n anonKey: string;\n}\n\n/**\n * Where supabase-js keeps the session for this project, in `localStorage`.\n * Per project URL so a host site with a Supabase of its own never collides,\n * and so local `supabase start` sessions stay apart from production ones.\n */\nexport function supabaseStorageKey(url: string): string {\n return `setto-auth-${url}`;\n}\n\n/**\n * One client per Supabase project, fetched only when somebody needs it.\n *\n * supabase-js is about 200 kB of the bundle every visitor of every site\n * downloaded, and a visitor is never signed in: the client was created, read\n * an empty `localStorage` and did nothing else for the whole visit. So the\n * library is a separate chunk now, loaded the first time something asks —\n * a stored session, the `/setto` page, a sign-in arriving in the URL, an\n * editor's chrome, or the visitor chat joining its Realtime channel.\n */\nexport interface SupabaseLoader {\n /** The client once it has loaded, otherwise null. */\n readonly client: SupabaseClient | null;\n /** True while the library is being fetched. */\n readonly loading: boolean;\n /**\n * The client, loading it on first call. Memoised: every caller gets the\n * same client. A failed fetch (a stale chunk after a deploy, a dropped\n * connection) rejects, and the next call tries again.\n */\n load(): Promise<SupabaseClient>;\n}\n\nconst loaders = new Map<string, SupabaseLoader>();\n\nexport function supabaseLoader(config: SupabaseConnection): SupabaseLoader {\n const key = `${config.url}\\n${config.anonKey}`;\n const existing = loaders.get(key);\n if (existing) return existing;\n\n let client: SupabaseClient | null = null;\n let pending: Promise<SupabaseClient> | null = null;\n\n const loader: SupabaseLoader = {\n get client() {\n return client;\n },\n get loading() {\n return pending !== null && client === null;\n },\n load() {\n if (client) return Promise.resolve(client);\n pending ??= import('@supabase/supabase-js').then(\n ({ createClient }) => {\n client = createClient(config.url, config.anonKey, {\n auth: {\n persistSession: true,\n autoRefreshToken: true,\n storageKey: supabaseStorageKey(config.url),\n },\n });\n return client;\n },\n (error: unknown) => {\n pending = null;\n throw error;\n },\n );\n return pending;\n },\n };\n loaders.set(key, loader);\n return loader;\n}\n\n/** The client for this project, loading supabase-js on first call. */\nexport function loadSupabase(config: SupabaseConnection): Promise<SupabaseClient> {\n return supabaseLoader(config).load();\n}\n\n/** True when `localStorage` holds anything supabase-js wrote for this project. */\nexport function hasStoredSession(url: string, storage: Pick<Storage, 'length' | 'key'> | null): boolean {\n if (!storage) return false;\n const prefix = supabaseStorageKey(url);\n try {\n for (let i = 0; i < storage.length; i += 1) {\n if (storage.key(i)?.startsWith(prefix)) return true;\n }\n } catch {\n // Storage that throws (blocked cookies, private mode) holds no session.\n }\n return false;\n}\n\n/**\n * A sign-in arriving in the address: the implicit-flow fragment GoTrue and\n * setto-server's handoffs append (`#access_token=…&refresh_token=…`, which is\n * also how the support account's «Rediger» lands), an auth error, or an\n * invite/recovery callback. supabase-js reads and clears these itself\n * (`detectSessionInUrl`), so the client must exist on such a page.\n */\nexport function hasAuthInUrl(hash: string, search: string): boolean {\n const fragment = new URLSearchParams(hash.replace(/^#/, ''));\n if (\n fragment.has('access_token') ||\n fragment.has('refresh_token') ||\n fragment.has('error_description') ||\n fragment.has('error_code')\n ) {\n return true;\n }\n const query = new URLSearchParams(search);\n return query.has('error_description') || query.has('error_code');\n}\n\n/**\n * Whether this page load can have a signed-in person on it, and so needs\n * supabase-js from the start: a session stored for this project, the\n * `/setto` page (the sign-in and the dashboard), or a sign-in in the URL.\n * Anything else is a visitor, whose answer — no session — is known without it.\n */\nexport function needsSupabaseAtStart(\n config: SupabaseConnection,\n env: {\n pathname: string;\n hash: string;\n search: string;\n storage: Pick<Storage, 'length' | 'key'> | null;\n },\n): boolean {\n // The same test as `isAdminRoute` in urls.ts, which decides what `/setto` renders.\n if (env.pathname.startsWith('/setto')) return true;\n if (hasAuthInUrl(env.hash, env.search)) return true;\n return hasStoredSession(config.url, env.storage);\n}\n\n/** `localStorage`, or null where reading it throws. */\nexport function browserStorage(): Storage | null {\n try {\n return typeof window === 'undefined' ? null : window.localStorage;\n } catch {\n return null;\n }\n}\n","import type { ApiRequest } from '../../lib/api';\n\n/** The forms row of `site_module_settings` as the server reports it, with the defaults resolved. */\nexport interface FormSettings {\n /** Addresses the owner chose; empty means \"use the defaults\". */\n recipients: string[];\n /** The site owners' addresses — where mail goes when `recipients` is empty. */\n defaultRecipients: string[];\n /** What a submission would be sent to right now. */\n effectiveRecipients: string[];\n updatedAt: string | null;\n}\n\n/** A row of `form_submissions`, read through Supabase RLS in the dashboard. */\nexport interface FormSubmissionRow {\n id: string;\n site_id: string;\n form_id: string;\n data: Record<string, unknown>;\n labels: Record<string, string>;\n field_order: string[];\n meta: {\n page?: string;\n title?: string;\n referer?: string;\n userAgent?: string;\n ip?: string;\n /** Milliseconds from the visitor's first interaction to submit; absent for API clients. */\n elapsed?: number;\n recipientSource?: 'settings' | 'owners' | 'none';\n };\n email_status: 'pending' | 'sent' | 'failed' | 'skipped';\n email_error: string | null;\n recipients: string[];\n created_at: string;\n}\n\nexport function createFormsApi(request: ApiRequest) {\n const base = (siteId: string) => `/sites/${encodeURIComponent(siteId)}/forms`;\n return {\n getSettings(siteId: string): Promise<FormSettings> {\n return request<FormSettings>(`${base(siteId)}/settings`, {}, 'getFormSettings');\n },\n saveSettings(siteId: string, recipients: string[]): Promise<FormSettings> {\n return request<FormSettings>(\n `${base(siteId)}/settings`,\n { method: 'PUT', body: { recipients } },\n 'saveFormSettings',\n );\n },\n deleteSubmission(siteId: string, id: string): Promise<void> {\n return request<void>(\n `${base(siteId)}/submissions/${encodeURIComponent(id)}`,\n { method: 'DELETE' },\n 'deleteSubmission',\n );\n },\n };\n}\n\nexport type FormsApi = ReturnType<typeof createFormsApi>;\n","import type { SupabaseClient } from '@supabase/supabase-js';\nimport { createFormsApi } from '../modules/forms/api';\nimport type { ContentFile, PublishFile, PublishResult } from '../types';\nimport type { AssetDraft } from './asset-store';\n\n/**\n * The client a call should read its token from: the one already loaded, the\n * one being loaded, or null when nobody on this page has needed supabase-js\n * yet — which means nobody is signed in (see `lib/supabase.ts`).\n */\nexport type SupabaseSource = SupabaseClient | (() => Promise<SupabaseClient | null>);\n\n/** Returns a fresh access token from the current Supabase session. */\nasync function bearer(source: SupabaseSource): Promise<string> {\n const sb = typeof source === 'function' ? await source() : source;\n if (!sb) throw new Error('not_authenticated');\n const { data } = await sb.auth.getSession();\n const token = data.session?.access_token;\n if (!token) throw new Error('not_authenticated');\n return token;\n}\n\nasync function parseJson<T>(res: Response): Promise<T> {\n const contentType = res.headers.get('content-type') ?? '';\n if (!contentType.includes('application/json')) {\n const text = await res.text();\n throw new Error(\n `expected JSON from ${res.url}, got ${contentType || 'unknown content-type'}: ${text.slice(0, 120)}`,\n );\n }\n return (await res.json()) as T;\n}\n\nasync function asError(res: Response, fallback: string): Promise<Error> {\n try {\n const body = await parseJson<{ error?: unknown; detail?: unknown }>(res);\n const detail =\n body.error != null\n ? String(body.error)\n : body.detail != null\n ? String(body.detail)\n : fallback;\n return new Error(`${fallback}: ${res.status} ${detail}`);\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('expected JSON')) {\n return new Error(`${fallback}: ${res.status} ${err.message}`);\n }\n return new Error(`${fallback}: ${res.status}`);\n }\n}\n\n/**\n * One authenticated JSON call against setto-server. Modules build their api\n * segment on this (see `modules/forms/api.ts`) rather than on `fetch`, so\n * bearer handling and error shaping stay in one place.\n */\nexport type ApiRequest = <T>(\n path: string,\n init?: { method?: string; body?: unknown },\n label?: string,\n) => Promise<T>;\n\nexport function createApi(args: { apiUrl: string; supabase: SupabaseSource }) {\n // Public chat already normalizes this boundary. Authenticated dashboard calls\n // must do the same: a configured `https://api.setto.no/` otherwise turns\n // `/sites/...` into `//sites/...`, which some proxies reject before Hono.\n const apiUrl = args.apiUrl.replace(/\\/+$/, '');\n const { supabase } = args;\n\n const request: ApiRequest = async <T,>(\n path: string,\n init: { method?: string; body?: unknown } = {},\n label = `${init.method ?? 'GET'} ${path}`,\n ): Promise<T> => {\n const token = await bearer(supabase);\n const res = await fetch(`${apiUrl}${path}`, {\n method: init.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n body: init.body !== undefined ? JSON.stringify(init.body) : undefined,\n });\n if (!res.ok) throw await asError(res, `${label} failed`);\n if (res.status === 204) return undefined as T;\n return parseJson<T>(res);\n };\n\n return {\n request,\n forms: createFormsApi(request),\n\n async getContent(siteId: string): Promise<{ files: ContentFile[] }> {\n const token = await bearer(supabase);\n const res = await fetch(`${apiUrl}/sites/${encodeURIComponent(siteId)}/content`, {\n headers: { Authorization: `Bearer ${token}` },\n });\n if (!res.ok) throw await asError(res, 'getContent failed');\n return parseJson<{ files: ContentFile[] }>(res);\n },\n\n async publish(\n siteId: string,\n files: PublishFile[],\n options?: { message?: string; assets?: AssetDraft[] },\n ): Promise<PublishResult> {\n const token = await bearer(supabase);\n const assets = options?.assets ?? [];\n\n if (assets.length === 0) {\n const res = await fetch(`${apiUrl}/sites/${encodeURIComponent(siteId)}/publish`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({ files, message: options?.message }),\n });\n if (!res.ok) throw await asError(res, 'publish failed');\n return parseJson<PublishResult>(res);\n }\n\n const form = new FormData();\n form.append(\n 'manifest',\n JSON.stringify({\n files,\n assets: assets.map((a) => ({ path: a.repoPath })),\n message: options?.message,\n }),\n );\n assets.forEach((asset, index) => {\n form.append(`asset_${index}`, asset.file, asset.file.name);\n });\n\n const res = await fetch(`${apiUrl}/sites/${encodeURIComponent(siteId)}/publish`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: form,\n });\n if (!res.ok) throw await asError(res, 'publish failed');\n return parseJson<PublishResult>(res);\n },\n\n async expireStaleDeployments(siteId: string): Promise<{ expired: number }> {\n const token = await bearer(supabase);\n const res = await fetch(\n `${apiUrl}/sites/${encodeURIComponent(siteId)}/deployments/expire-stale`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n },\n );\n if (!res.ok) throw await asError(res, 'expireStaleDeployments failed');\n return parseJson<{ expired: number }>(res);\n },\n\n async cancelDeployment(siteId: string, deploymentId: string): Promise<void> {\n const token = await bearer(supabase);\n const res = await fetch(\n `${apiUrl}/sites/${encodeURIComponent(siteId)}/deployments/${encodeURIComponent(deploymentId)}/cancel`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n },\n );\n if (!res.ok) throw await asError(res, 'cancelDeployment failed');\n },\n\n /** Request a password-reset email (link goes via setto-server, then site /setto). */\n async requestPasswordReset(siteId: string, email: string): Promise<void> {\n const res = await fetch(\n `${apiUrl}/sites/${encodeURIComponent(siteId)}/auth/password-reset`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email }),\n },\n );\n if (!res.ok) throw await asError(res, 'requestPasswordReset failed');\n },\n };\n}\n\nexport type SettoApi = ReturnType<typeof createApi>;\n","/*\n * Segments that name the object machinery rather than content.\n *\n * The keys these helpers walk come from locale JSON, and `JSON.parse` keeps\n * `\"__proto__\"` as an ordinary own key, so a locale file can carry one. Walked\n * with a plain `obj[part]`, `__proto__` lands on `Object.prototype` and\n * `constructor` on `Object`: a removal of `__proto__.toString` would delete a\n * method every object on the page shares, in the editor's browser. No Setto\n * key is ever named like this, so they are refused outright, and the walk\n * below follows own properties only for the same reason.\n */\nconst UNSAFE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);\n\n/** True for a single key segment that may be read or written. */\nexport function isSafeSegment(segment: string): boolean {\n return !UNSAFE_SEGMENTS.has(segment);\n}\n\n/** True when every segment of a dotted key may be read or written. */\nexport function isSafeKey(key: string): boolean {\n return key.split('.').every(isSafeSegment);\n}\n\n/** Reads a dotted key path from a nested object. */\nexport function getNested(obj: unknown, key: string): unknown {\n if (!obj || typeof obj !== 'object') return undefined;\n if (!isSafeKey(key)) return undefined;\n const parts = key.split('.');\n let cur: unknown = obj;\n for (const part of parts) {\n if (!cur || typeof cur !== 'object') return undefined;\n if (!Object.prototype.hasOwnProperty.call(cur, part)) return undefined;\n cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\n/** Sets a dotted key path on a nested object (mutates in place). */\nexport function setNested(obj: Record<string, unknown>, key: string, value: unknown): void {\n if (!isSafeKey(key)) return;\n const parts = key.split('.');\n let cur = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n const next = Object.prototype.hasOwnProperty.call(cur, part) ? cur[part] : undefined;\n if (!next || typeof next !== 'object') {\n cur[part] = {};\n }\n cur = cur[part] as Record<string, unknown>;\n }\n cur[parts[parts.length - 1]!] = value;\n}\n\n/**\n * Deletes a dotted key path from a nested object (mutates in place).\n *\n * Parents left empty by the deletion go too. Deleting the last leaf of\n * `form.kontakt.fields.3` used to leave `\"3\": {}` behind, which published as\n * a phantom list item and rendered as an empty field.\n */\nexport function deleteNested(obj: Record<string, unknown>, key: string): void {\n if (!isSafeKey(key)) return;\n const parts = key.split('.');\n const chain: Record<string, unknown>[] = [obj];\n let cur: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (!Object.prototype.hasOwnProperty.call(cur, part)) return;\n const next = cur[part];\n if (!next || typeof next !== 'object') return;\n cur = next as Record<string, unknown>;\n chain.push(cur);\n }\n delete cur[parts[parts.length - 1]!];\n for (let i = chain.length - 1; i > 0; i--) {\n if (Object.keys(chain[i]!).length > 0) break;\n delete chain[i - 1]![parts[i - 1]!];\n }\n}\n\n/** Collects all dotted keys under a prefix from a nested object. */\nexport function collectKeysUnder(obj: unknown, prefix: string): string[] {\n const base = getNested(obj, prefix);\n if (!base || typeof base !== 'object' || Array.isArray(base)) return [];\n return Object.keys(base as Record<string, unknown>).filter(isSafeSegment).sort(compareListKeys);\n}\n\nexport function compareListKeys(a: string, b: string): number {\n const na = Number(a);\n const nb = Number(b);\n if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;\n return a.localeCompare(b);\n}\n","import type { i18n as I18nType } from 'i18next';\nimport {\n collectKeysUnder,\n compareListKeys,\n deleteNested,\n getNested,\n isSafeKey,\n isSafeSegment,\n} from './nested-resource';\n\n/**\n * Tracks an in-memory layer of edits on top of a loaded i18next instance.\n *\n * On disk, a site has one JSON file per language under `content_paths`. At\n * runtime, i18next holds those JSONs as resource bundles in\n * `i18n.store.data[lng].translation`.\n *\n * The draft store mutates the resource bundles directly so the page re-renders\n * with the editor's text immediately. When the user publishes, we serialise\n * the merged resource bundles back to JSON and POST them to setto-server.\n */\nexport interface DraftEntry {\n /** Dotted key path, e.g. 'hero.headline'. */\n key: string;\n /** Language code, e.g. 'no'. */\n lng: string;\n /** Value before any edits in this session — used for diff and revert. */\n original: string;\n /** Current draft value. */\n current: string;\n /**\n * The key did not exist before this session (a list item the editor added).\n * Reverting deletes it instead of writing an empty string back, which would\n * leave a blank item on the page.\n */\n created?: boolean;\n /**\n * The key existed and the editor deleted it (a list item they removed).\n * Without this a removal was invisible to the draft count: an editor who\n * only deleted a FAQ entry had nothing to publish.\n */\n removed?: boolean;\n}\n\nexport interface I18nStoreSnapshot {\n /** All edits made in this session, keyed by `${lng}::${key}`. */\n drafts: Map<string, DraftEntry>;\n /** Bumps every time the store changes; React components subscribe to this. */\n version: number;\n}\n\n/** Stable empty snapshot for useSyncExternalStore when the store is not ready. */\nexport const EMPTY_I18N_STORE_SNAPSHOT: I18nStoreSnapshot = {\n drafts: new Map(),\n version: 0,\n};\n\ntype Listener = (snap: I18nStoreSnapshot) => void;\n\nexport class I18nStore {\n private drafts = new Map<string, DraftEntry>();\n private version = 0;\n private listeners = new Set<Listener>();\n /** Stable namespace used by react-i18next defaults. */\n private ns: string;\n private i18n: I18nType;\n /** >0 while a batch is running; consumers are notified once at the end. */\n private batchDepth = 0;\n /** Cached reference — useSyncExternalStore requires referential stability. */\n private cachedSnapshot: I18nStoreSnapshot = {\n drafts: this.drafts,\n version: 0,\n };\n\n constructor(i18n: I18nType, options?: { namespace?: string }) {\n this.i18n = i18n;\n this.ns = options?.namespace ?? 'translation';\n }\n\n snapshot(): I18nStoreSnapshot {\n return this.cachedSnapshot;\n }\n\n /**\n * Put a locale file into i18next as the published baseline.\n *\n * Same reason as `languages`: the editor chrome cannot reach the live\n * i18next instance from its own bundle, and this store already holds it.\n * Deep and overwriting, which is what seeding a baseline means — the file\n * from the repository is the truth, and any draft on top of it lives here,\n * not in i18next.\n */\n addBaselineBundle(lng: string, resources: Record<string, unknown>): void {\n this.i18n.addResourceBundle(lng, this.ns, resources, true, true);\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Returns the current rendered value for a key in a given language,\n * reading through any draft layer.\n */\n get(key: string, lng: string): string {\n const id = `${lng}::${key}`;\n const draft = this.drafts.get(id);\n if (draft) return draft.current;\n return String(this.i18n.getResource(lng, this.ns, key) ?? '');\n }\n\n /** Returns the original (pre-edit) value for a key. */\n original(key: string, lng: string): string {\n const id = `${lng}::${key}`;\n const draft = this.drafts.get(id);\n if (draft) return draft.original;\n return String(this.i18n.getResource(lng, this.ns, key) ?? '');\n }\n\n /**\n * Records an edit. Mutates the live i18next bundle so consumers re-render.\n * If the value is set back to the original, the draft entry is cleared.\n */\n set(key: string, lng: string, value: string): void {\n // `__proto__` and its kin are machinery, never content; see nested-resource.\n if (!isSafeKey(key)) return;\n const id = `${lng}::${key}`;\n const existing = this.drafts.get(id);\n const resource = this.i18n.getResource(lng, this.ns, key) as unknown;\n const original = existing?.original ?? String(resource ?? '');\n const created = existing ? existing.created === true : resource === undefined;\n\n if (value === original && !created) {\n this.drafts.delete(id);\n } else {\n this.drafts.set(id, { key, lng, original, current: value, ...(created ? { created } : {}) });\n }\n\n this.i18n.addResource(lng, this.ns, key, value);\n this.notify();\n }\n\n /**\n * Deletes a key from the bundle. A key that was created this session simply\n * disappears; one that was on disk is kept as a removal draft so the\n * deletion counts as a change and reverts cleanly.\n */\n delete(key: string, lng: string): void {\n if (!isSafeKey(key)) return;\n const id = `${lng}::${key}`;\n const existing = this.drafts.get(id);\n const resource = this.i18n.getResource(lng, this.ns, key) as unknown;\n if (existing?.created) {\n this.drafts.delete(id);\n } else if (existing || resource !== undefined) {\n const original = existing?.original ?? String(resource ?? '');\n this.drafts.set(id, { key, lng, original, current: '', removed: true });\n }\n this.deleteFromBundle(lng, key);\n this.notify();\n }\n\n /** Resets a single draft back to its original value. */\n revert(key: string, lng: string): void {\n const id = `${lng}::${key}`;\n const draft = this.drafts.get(id);\n if (!draft) return;\n this.restore(draft);\n this.drafts.delete(id);\n this.notify();\n }\n\n /** Resets every draft. */\n revertAll(): void {\n for (const draft of this.drafts.values()) this.restore(draft);\n this.drafts.clear();\n this.notify();\n }\n\n /** Marks the current state as the new baseline (after a successful publish). */\n commit(): void {\n this.drafts.clear();\n this.bump();\n }\n\n /** Number of pending draft entries across all languages. */\n size(): number {\n return this.drafts.size;\n }\n\n /** Returns sorted item keys under a list prefix, e.g. `faq.items` → ['1','2',…]. */\n getListKeys(prefix: string, lng: string): string[] {\n const bundle = this.i18n.getResourceBundle(lng, this.ns) as Record<string, unknown> | undefined;\n return collectKeysUnder(bundle, prefix);\n }\n\n /**\n * Adds a new list item under `prefix` with the given field defaults.\n * Adds the same key across all loaded languages.\n */\n addListItem(prefix: string, _lng: string, template: Record<string, string>): string {\n const langs = this.languages(_lng);\n const allKeys = langs.flatMap((l) => this.getListKeys(prefix, l));\n const numeric = allKeys.map(Number).filter((n) => !Number.isNaN(n));\n const nextKey = numeric.length > 0 ? String(Math.max(...numeric) + 1) : '1';\n\n this.batch(() => {\n for (const lang of langs) {\n for (const [field, value] of Object.entries(template)) {\n this.set(`${prefix}.${nextKey}.${field}`, lang, value);\n }\n }\n });\n return nextKey;\n }\n\n /** Removes a list item and all nested keys under `prefix.itemKey` in every language. */\n removeListItem(prefix: string, itemKey: string, _lng: string): void {\n this.batch(() => {\n for (const lang of this.languages(_lng)) {\n for (const leaf of this.leavesUnder(`${prefix}.${itemKey}`, lang)) {\n this.delete(leaf, lang);\n }\n }\n });\n }\n\n /**\n * Moves a list item one step up or down by swapping its values with its\n * neighbour's, in every language. Items keep their numeric keys and the keys\n * keep their order; only the contents trade places. That is what makes the\n * move a set of ordinary drafts — publish, revert and the change count all\n * work without knowing a move happened.\n */\n moveListItem(prefix: string, itemKey: string, direction: -1 | 1, _lng: string): boolean {\n const keys = this.getListKeys(prefix, _lng).sort(compareListKeys);\n const index = keys.indexOf(itemKey);\n const targetIndex = index + direction;\n if (index < 0 || targetIndex < 0 || targetIndex >= keys.length) return false;\n const other = keys[targetIndex]!;\n\n this.batch(() => {\n for (const lang of this.languages(_lng)) {\n const a = `${prefix}.${itemKey}`;\n const b = `${prefix}.${other}`;\n const fieldsA = this.leavesUnder(a, lang).map((k) => k.slice(a.length + 1));\n const fieldsB = this.leavesUnder(b, lang).map((k) => k.slice(b.length + 1));\n const fields = [...new Set([...fieldsA, ...fieldsB])];\n const valuesA = new Map(fields.map((f) => [f, this.valueOrUndefined(`${a}.${f}`, lang)]));\n const valuesB = new Map(fields.map((f) => [f, this.valueOrUndefined(`${b}.${f}`, lang)]));\n for (const f of fields) {\n this.setOrDelete(`${a}.${f}`, lang, valuesB.get(f));\n this.setOrDelete(`${b}.${f}`, lang, valuesA.get(f));\n }\n }\n });\n return true;\n }\n\n /** Re-sorts list keys after removal (optional compaction — not used by default). */\n sortListKeys(prefix: string, lng: string): string[] {\n return this.getListKeys(prefix, lng).sort(compareListKeys);\n }\n\n /**\n * Serialises the full resource bundle per language as it currently looks in\n * i18next (with drafts applied). Used as the payload for /publish.\n *\n * The caller maps language → file path via `sites.content_paths`.\n */\n serialiseBundles(): Record<string, unknown> {\n const langs = this.i18n.languages?.length ? this.i18n.languages : ['no', 'en'];\n const out: Record<string, unknown> = {};\n for (const lng of langs) {\n const bundle = this.i18n.getResourceBundle(lng, this.ns);\n if (bundle) out[lng] = bundle;\n }\n return out;\n }\n\n /** Runs `fn` and notifies consumers once, however many edits it makes. */\n batch(fn: () => void): void {\n this.batchDepth += 1;\n try {\n fn();\n } finally {\n this.batchDepth -= 1;\n }\n if (this.batchDepth === 0) this.notify();\n }\n\n /**\n * Every language this site has content for, in i18next's own order.\n *\n * Public because the editor chrome needs it and cannot get it the usual way:\n * that code runs in a second bundle whose `react-i18next` is a different\n * module instance from the host's, so its `useTranslation` finds no\n * initialised i18next and reports no languages at all. This store is the\n * host's own object, handed across by reference, and it already holds the\n * live instance.\n *\n * Deduplicated, because i18next appends its fallback chain and every caller\n * was doing that itself.\n */\n languages(fallback: string): string[] {\n return this.i18n.languages?.length ? Array.from(new Set(this.i18n.languages)) : [fallback];\n }\n\n private valueOrUndefined(key: string, lng: string): string | undefined {\n const resource = this.i18n.getResource(lng, this.ns, key) as unknown;\n return resource === undefined ? undefined : String(resource);\n }\n\n private setOrDelete(key: string, lng: string, value: string | undefined): void {\n if (value === undefined) {\n if (this.i18n.getResource(lng, this.ns, key) !== undefined) this.delete(key, lng);\n } else {\n this.set(key, lng, value);\n }\n }\n\n /** Every string key under `prefix`, nested to any depth. */\n private leavesUnder(prefix: string, lng: string): string[] {\n const bundle = (this.i18n.getResourceBundle(lng, this.ns) ?? {}) as Record<string, unknown>;\n const node = getNested(bundle, prefix);\n const out: string[] = [];\n const walk = (value: unknown, path: string) => {\n if (value && typeof value === 'object') {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (isSafeSegment(k)) walk(v, `${path}.${k}`);\n }\n } else if (value !== undefined) {\n out.push(path);\n }\n };\n walk(node, prefix);\n return out;\n }\n\n private deleteFromBundle(lng: string, key: string): void {\n const bundle = (this.i18n.getResourceBundle(lng, this.ns) ?? {}) as Record<string, unknown>;\n deleteNested(bundle, key);\n this.i18n.addResourceBundle(lng, this.ns, bundle, true, true);\n }\n\n private restore(draft: DraftEntry): void {\n if (draft.created) {\n this.deleteFromBundle(draft.lng, draft.key);\n } else {\n this.i18n.addResource(draft.lng, this.ns, draft.key, draft.original);\n }\n }\n\n private notify(): void {\n if (this.batchDepth > 0) return;\n // Trigger consumers of useTranslation to re-render. i18next exposes\n // languageChanged for this but a manual emit is simpler and side-effect-free.\n this.i18n.emit('languageChanged', this.i18n.language);\n this.bump();\n }\n\n private bump(): void {\n this.version += 1;\n this.cachedSnapshot = { drafts: this.drafts, version: this.version };\n for (const fn of this.listeners) fn(this.cachedSnapshot);\n }\n}\n","/**\n * The language lives in the URL.\n *\n * It did not, for one release: the choice was kept per browser in\n * `localStorage`, which is invisible to a search engine and unshareable\n * between people. A Norwegian plumber who wants to be found in English cannot\n * be, if the English version has no address. So the primary language stays at\n * the root — `/`, `/priser` — and every other language takes a prefix:\n * `/en`, `/en/priser`.\n *\n * Primary at the root rather than `/no/…` deliberately: every Setto site alive\n * today has its Norwegian pages at the root, they are linked to and indexed\n * there, and moving them would trade a real thing for a tidy one.\n *\n * The routes themselves never learn about this. `BrowserRouter` takes the\n * prefix as its `basename`, so a site's own `/priser` keeps matching whether\n * the visitor is at `/priser` or `/en/priser` — which matters because those\n * routes are written per site by the build agent, and a scheme that required\n * it to think about languages is a scheme that would be got wrong.\n */\n\nimport { DEFAULT_LANGUAGE } from './languages';\n\nexport interface LanguageRoute {\n /** The language this URL is in. */\n language: string;\n /** `''` for the primary language, `/en` otherwise. Feed to `basename`. */\n basename: string;\n /** The path with the prefix removed, always starting with `/`. */\n rest: string;\n}\n\n/*\n * One slash between segments, never two, and never a backslash.\n *\n * Not tidiness: everything this module returns is fed to\n * `window.location.assign` or `replace`, and a path that starts with `//` is\n * not a path to a browser but a protocol-relative URL — `//evil.example/x`\n * leaves the site. The site's SPA fallback serves the app at any address, so\n * `/en//evil.example/x` renders like any other page, and before this the\n * «Norsk» button on it handed the rest, `//evil.example/x`, straight to the\n * browser. Backslashes count too, because a browser reads `/\\evil.example`\n * the same way. Collapsing every run rather than only the leading one keeps\n * the rule simple enough to trust: no output of this module can contain `//`.\n */\nfunction normalise(pathname: string): string {\n const collapsed = `/${pathname}`.replace(/[\\\\/]+/g, '/');\n return collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;\n}\n\n/**\n * The address to navigate to, or null when it would leave this origin.\n *\n * A second lock behind `normalise`: whatever the routing above returns, the\n * language switch and the first-visit redirect only ever go somewhere on the\n * site they started on. Resolved by the URL parser itself rather than by a\n * check on the string, so it agrees with the browser about what the address\n * means.\n */\nexport function sameOriginUrl(target: string, origin: string): string | null {\n try {\n const url = new URL(target, origin);\n return url.origin === origin ? url.href : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the language out of a path.\n *\n * Only a prefix that is a language this site actually speaks counts — a site\n * with a page at `/no` and no Norwegian in its list keeps that page.\n */\nexport function languageFromPath(\n pathname: string,\n languages: readonly string[],\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): LanguageRoute {\n const path = normalise(pathname);\n const first = path.split('/')[1] ?? '';\n\n const match = languages.find(\n (tag) => tag !== primary && tag.toLowerCase() === first.toLowerCase(),\n );\n if (!match) return { language: primary, basename: '', rest: path };\n\n const rest = path.slice(first.length + 1);\n return { language: match, basename: `/${match}`, rest: rest === '' ? '/' : rest };\n}\n\n/** The same page, in another language. */\nexport function pathForLanguage(\n pathname: string,\n target: string,\n languages: readonly string[],\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): string {\n const { rest } = languageFromPath(pathname, languages, primary);\n if (target === primary) return rest;\n return rest === '/' ? `/${target}` : `/${target}${rest}`;\n}\n\n/**\n * Every address this page has, for `hreflang`.\n *\n * Without these a search engine sees two unrelated pages that happen to say\n * similar things, and picks one. `x-default` points at the primary, which is\n * what a reader with no stated preference should land on.\n */\nexport function alternateLinks(\n origin: string,\n pathname: string,\n languages: readonly string[],\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): Array<{ hreflang: string; href: string }> {\n if (languages.length < 2) return [];\n const links = languages.map((tag) => ({\n hreflang: tag,\n href: origin + pathForLanguage(pathname, tag, languages, primary),\n }));\n links.push({\n hreflang: 'x-default',\n href: origin + pathForLanguage(pathname, primary, languages, primary),\n });\n return links;\n}\n\n/**\n * Setto's own routes, which have no language of their own.\n *\n * `/setto` is the editor: the customer's back office, in the customer's\n * language, at a fixed address that the chrome navigates to absolutely. A\n * visitor whose browser prefers English must not be bounced to `/en/setto`,\n * where `isAdminRoute()` would no longer recognise it and the site would\n * render instead of the sign-in.\n */\nfunction isReservedPath(pathname: string): boolean {\n const path = normalise(pathname);\n return path === '/setto' || path.startsWith('/setto/');\n}\n\n/**\n * Where a first-time visitor should be sent, or null to leave them alone.\n *\n * Only ever from the unprefixed root towards a prefix, only when the browser\n * asks for a language this site speaks and the visitor has expressed no\n * preference of their own here before. One direction only: a redirect that can\n * send `/en` back to `/` is a redirect that can loop, and somebody who has\n * clicked «Norsk» on an English page must not be bounced back to English on\n * their next click.\n */\nexport function redirectForVisitor(\n pathname: string,\n languages: readonly string[],\n browserLanguages: readonly string[],\n stored: string | null,\n primary: string = languages[0] ?? DEFAULT_LANGUAGE,\n): string | null {\n if (languages.length < 2) return null;\n if (isReservedPath(pathname)) return null;\n\n const current = languageFromPath(pathname, languages, primary);\n // Already somewhere explicit. Their address wins over their browser.\n if (current.basename !== '') return null;\n // They have chosen here before; that choice is theirs to keep.\n if (stored) {\n return stored !== primary && languages.includes(stored)\n ? pathForLanguage(pathname, stored, languages, primary)\n : null;\n }\n\n for (const wanted of browserLanguages) {\n const base = wanted.toLowerCase().split('-')[0];\n if (!base) continue;\n if (base === primary.toLowerCase().split('-')[0]) return null;\n /*\n * Norwegian is three tags for one language; a browser asking for `nb`\n * against a `no` site is already home and must not be sent anywhere.\n */\n const norwegian = ['no', 'nb', 'nn'];\n if (norwegian.includes(base) && norwegian.includes(primary.toLowerCase())) return null;\n\n const hit = languages.find((tag) => tag.toLowerCase().split('-')[0] === base);\n if (hit && hit !== primary) return pathForLanguage(pathname, hit, languages, primary);\n }\n return null;\n}\n","/** GitHub repo directory for editor-uploaded images. */\nexport const SETTO_IMAGE_REPO_DIR = 'public/images/setto';\n\n/** Public URL prefix served by the host site. */\nexport const SETTO_IMAGE_URL_PREFIX = '/images/setto';\n\nconst MIME_EXT: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/svg+xml': 'svg',\n};\n\nexport function extensionFromMime(mime: string): string {\n return MIME_EXT[mime] ?? 'bin';\n}\n\n/** Builds repo + public paths for a newly uploaded Setto image. */\nexport function generateSettoImagePaths(srcKey: string, file: File): {\n repoPath: string;\n publicPath: string;\n} {\n const ext = extensionFromMime(file.type);\n const slug = srcKey.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '') || 'image';\n const name = `${slug}-${Date.now()}.${ext}`;\n return {\n repoPath: `${SETTO_IMAGE_REPO_DIR}/${name}`,\n publicPath: `${SETTO_IMAGE_URL_PREFIX}/${name}`,\n };\n}\n\n/** Returns true when `path` matches an exact entry or a directory prefix entry. */\nexport function isContentPathAllowed(path: string, allowed: string[]): boolean {\n for (const entry of allowed) {\n if (entry.endsWith('/')) {\n if (path.startsWith(entry)) return true;\n } else if (path === entry) {\n return true;\n }\n }\n return false;\n}\n","import { SETTO_IMAGE_REPO_DIR } from './image-paths';\n\nexport interface AssetDraft {\n /** i18n key for the image src, e.g. `hero.illustrationSrc`. */\n srcKey: string;\n /** GitHub repo path, e.g. `public/images/setto/hero-illustration-123.jpg`. */\n repoPath: string;\n /** Public URL path, e.g. `/images/setto/hero-illustration-123.jpg`. */\n publicPath: string;\n /** Src path before this upload (for revert). */\n originalPublicPath: string;\n /** Raw file bytes — published as binary via multipart, not base64 JSON. */\n file: File;\n /** Object URL for in-session preview. */\n previewUrl: string;\n}\n\nexport interface AssetStoreSnapshot {\n drafts: Map<string, AssetDraft>;\n version: number;\n}\n\nexport const EMPTY_ASSET_STORE_SNAPSHOT: AssetStoreSnapshot = {\n drafts: new Map(),\n version: 0,\n};\n\ntype Listener = (snap: AssetStoreSnapshot) => void;\n\nexport class AssetStore {\n private drafts = new Map<string, AssetDraft>();\n private version = 0;\n private listeners = new Set<Listener>();\n private cachedSnapshot: AssetStoreSnapshot = {\n drafts: this.drafts,\n version: 0,\n };\n\n snapshot(): AssetStoreSnapshot {\n return this.cachedSnapshot;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** Returns a preview URL if a draft exists for this src key. */\n getPreviewUrl(srcKey: string): string | null {\n return this.drafts.get(srcKey)?.previewUrl ?? null;\n }\n\n async set(args: {\n srcKey: string;\n originalPublicPath: string;\n repoPath: string;\n publicPath: string;\n file: File;\n }): Promise<void> {\n const existing = this.drafts.get(args.srcKey);\n if (existing) URL.revokeObjectURL(existing.previewUrl);\n\n const previewUrl = URL.createObjectURL(args.file);\n this.drafts.set(args.srcKey, {\n srcKey: args.srcKey,\n repoPath: args.repoPath,\n publicPath: args.publicPath,\n originalPublicPath: args.originalPublicPath,\n file: args.file,\n previewUrl,\n });\n this.bump();\n }\n\n revert(srcKey: string): string | null {\n const draft = this.drafts.get(srcKey);\n if (!draft) return null;\n URL.revokeObjectURL(draft.previewUrl);\n const original = draft.originalPublicPath;\n this.drafts.delete(srcKey);\n this.bump();\n return original;\n }\n\n revertAll(): void {\n for (const draft of this.drafts.values()) {\n URL.revokeObjectURL(draft.previewUrl);\n }\n this.drafts.clear();\n this.bump();\n }\n\n commit(): void {\n this.revertAll();\n }\n\n size(): number {\n return this.drafts.size;\n }\n\n pendingAssets(): AssetDraft[] {\n return Array.from(this.drafts.values());\n }\n\n static isValidRepoPath(path: string): boolean {\n return path.startsWith(`${SETTO_IMAGE_REPO_DIR}/`);\n }\n\n private bump(): void {\n this.version += 1;\n this.cachedSnapshot = { drafts: this.drafts, version: this.version };\n for (const fn of this.listeners) fn(this.cachedSnapshot);\n }\n}\n","/** Section colour theme — keyed by section id, then colour token. */\nexport type SectionsTheme = Record<string, Record<string, string>>;\n\nexport interface ThemeDraftEntry {\n sectionId: string;\n field: string;\n original: string;\n current: string;\n}\n\nexport interface ThemeStoreSnapshot {\n drafts: Map<string, ThemeDraftEntry>;\n version: number;\n}\n\nexport const EMPTY_THEME_STORE_SNAPSHOT: ThemeStoreSnapshot = {\n drafts: new Map(),\n version: 0,\n};\n\ntype Listener = (snap: ThemeStoreSnapshot) => void;\n\nexport class ThemeStore {\n private data: SectionsTheme;\n private baseline: SectionsTheme;\n private drafts = new Map<string, ThemeDraftEntry>();\n private version = 0;\n private listeners = new Set<Listener>();\n private cachedSnapshot: ThemeStoreSnapshot = {\n drafts: this.drafts,\n version: 0,\n };\n\n constructor(initial: SectionsTheme) {\n this.data = structuredClone(initial);\n this.baseline = structuredClone(initial);\n }\n\n snapshot(): ThemeStoreSnapshot {\n return this.cachedSnapshot;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n getSection(sectionId: string): Record<string, string> {\n return this.data[sectionId] ?? {};\n }\n\n get(sectionId: string, field: string): string {\n return this.data[sectionId]?.[field] ?? '';\n }\n\n set(sectionId: string, field: string, value: string): void {\n const id = `${sectionId}::${field}`;\n const original =\n this.drafts.get(id)?.original ??\n this.baseline[sectionId]?.[field] ??\n '';\n\n if (!this.data[sectionId]) this.data[sectionId] = {};\n this.data[sectionId][field] = value;\n\n if (value === original) {\n this.drafts.delete(id);\n } else {\n this.drafts.set(id, { sectionId, field, original, current: value });\n }\n this.bump();\n }\n\n /** Replace baseline from GitHub without creating drafts. */\n loadBaseline(next: SectionsTheme): void {\n this.data = structuredClone(next);\n this.baseline = structuredClone(next);\n this.drafts.clear();\n this.bump();\n }\n\n /** Resets every draft back to its original value. */\n revertAll(): void {\n for (const draft of this.drafts.values()) {\n if (!this.data[draft.sectionId]) this.data[draft.sectionId] = {};\n this.data[draft.sectionId]![draft.field] = draft.original;\n }\n this.drafts.clear();\n this.bump();\n }\n\n commit(): void {\n this.baseline = structuredClone(this.data);\n this.drafts.clear();\n this.bump();\n }\n\n size(): number {\n return this.drafts.size;\n }\n\n serialise(): SectionsTheme {\n return structuredClone(this.data);\n }\n\n private bump(): void {\n this.version += 1;\n this.cachedSnapshot = { drafts: this.drafts, version: this.version };\n for (const fn of this.listeners) fn(this.cachedSnapshot);\n }\n}\n","/**\n * The shape of a site: which pages it has, which sections each page shows and\n * in what order, and what the menu and footer link to.\n *\n * Data rather than TSX, because the owner has to be able to change it. A page\n * written as `<Hero /><Services /><Contact />` can only be reordered by someone\n * who can edit code, so moving a section up, hiding it for the summer or adding\n * a «Vilkår» page used to mean a developer. Kept in\n * `src/content/pages.json`, which the inline editor publishes like any other\n * content file.\n *\n * Nothing is ever deleted from here. «Remove» hides: a section, a page or a\n * menu link that is hidden keeps its place and its text, and showing it again\n * puts it back exactly as it was. The owner asked for undo, and a hidden entry\n * is undo that survives a publish.\n *\n * Every function below is pure and returns a new manifest, so a draft can be\n * compared with its baseline and a failed operation leaves nothing half-done.\n */\n\nexport const PAGES_MANIFEST_VERSION = 1;\n\n/** Where the manifest lives in a site repository. */\nexport const PAGES_PATH = 'src/content/pages.json';\n\n/**\n * Sections Setto can render on its own, without code from the site.\n *\n * `text` is a heading, an optional intro and a list of paragraphs with\n * optional headings: enough for terms, privacy, an «about» page. It is what\n * lets Pixel add a «Vilkår» page in the chat instead of in a sandbox.\n *\n * `blog` is the blog (R24): the list of posts on its page, and a single post\n * at `<page path>/<slug>` — the one page whose path has room below it. At\n * most one per site, and never on the front page, which would swallow every\n * address. `blog-latest` is a band of the newest posts, for the front page.\n * Both read the posts the site's build bundles (`SettoConfig.blog`).\n */\nexport const BUILTIN_SECTION_TYPES = ['text', 'blog', 'blog-latest'] as const;\nexport type BuiltinSectionType = (typeof BUILTIN_SECTION_TYPES)[number];\n\nexport interface PageSection {\n /** Unique across the whole site: it is also the theme id and the anchor. */\n id: string;\n /** A built-in section. Absent means a component the site registers. */\n type?: BuiltinSectionType;\n hidden?: boolean;\n /** What the editor calls it («Tjenester»). Falls back to the id. */\n label?: string;\n}\n\nexport interface PageEntry {\n id: string;\n /** `/`, `/vilkar`. Never under `/setto`, which is the editor's. */\n path: string;\n /** Locale key for the page's name, used by the menu and the tab title. */\n titleKey: string;\n hidden?: boolean;\n sections: PageSection[];\n}\n\nexport interface MenuItem {\n id: string;\n /** `/vilkar`, `/#tjenester`, or an absolute `https://` link. */\n href: string;\n labelKey: string;\n hidden?: boolean;\n}\n\nexport type MenuList = 'menu' | 'footer';\n\nexport interface PagesManifest {\n version: typeof PAGES_MANIFEST_VERSION;\n pages: PageEntry[];\n menu: MenuItem[];\n footer: MenuItem[];\n}\n\nconst ID = /^[a-z0-9][a-z0-9-]{0,62}$/;\n/*\n * A blog post's slug, the same rule as `isValidBlogSlug` in\n * `../blog/contract.ts` (a test holds them together). Written out rather than\n * imported so this file stays self-contained: setto-agent vendors it whole.\n */\nconst POST_SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst PATH = /^\\/(?:[a-z0-9][a-z0-9-]*(?:\\/[a-z0-9][a-z0-9-]*)*)?$/;\n\nexport interface ManifestIssue {\n at: string;\n message: string;\n}\n\nexport type ManifestParse =\n | { ok: true; manifest: PagesManifest }\n | { ok: false; issues: ManifestIssue[] };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Check a manifest from disk, from the network or from a model.\n *\n * Strict on what would break a page — duplicate ids, a path the router cannot\n * hold, a section type nothing renders — and silent about fields it does not\n * know, so a newer editor's manifest still renders on an older site.\n */\nexport function parseManifest(input: unknown): ManifestParse {\n const issues: ManifestIssue[] = [];\n if (!isRecord(input)) return { ok: false, issues: [{ at: '$', message: 'not an object' }] };\n if (input.version !== PAGES_MANIFEST_VERSION) {\n issues.push({ at: 'version', message: `expected ${PAGES_MANIFEST_VERSION}` });\n }\n\n const pages: PageEntry[] = [];\n const pageIds = new Set<string>();\n const paths = new Set<string>();\n const sectionIds = new Set<string>();\n const rawPages = Array.isArray(input.pages) ? input.pages : null;\n if (!rawPages) issues.push({ at: 'pages', message: 'must be a list' });\n\n (rawPages ?? []).forEach((raw, i) => {\n const at = `pages[${i}]`;\n if (!isRecord(raw)) {\n issues.push({ at, message: 'not an object' });\n return;\n }\n const id = String(raw.id ?? '');\n const path = String(raw.path ?? '');\n const titleKey = String(raw.titleKey ?? '');\n if (!ID.test(id)) issues.push({ at: `${at}.id`, message: `invalid id \"${id}\"` });\n else if (pageIds.has(id)) issues.push({ at: `${at}.id`, message: `duplicate page \"${id}\"` });\n pageIds.add(id);\n if (!PATH.test(path)) issues.push({ at: `${at}.path`, message: `invalid path \"${path}\"` });\n else if (path === '/setto' || path.startsWith('/setto/')) {\n issues.push({ at: `${at}.path`, message: '/setto belongs to the editor' });\n } else if (paths.has(path)) issues.push({ at: `${at}.path`, message: `duplicate path \"${path}\"` });\n paths.add(path);\n if (!titleKey) issues.push({ at: `${at}.titleKey`, message: 'required' });\n\n const sections: PageSection[] = [];\n const rawSections = Array.isArray(raw.sections) ? raw.sections : null;\n if (!rawSections) issues.push({ at: `${at}.sections`, message: 'must be a list' });\n (rawSections ?? []).forEach((s, j) => {\n const sat = `${at}.sections[${j}]`;\n if (!isRecord(s)) {\n issues.push({ at: sat, message: 'not an object' });\n return;\n }\n const sid = String(s.id ?? '');\n if (!ID.test(sid)) issues.push({ at: `${sat}.id`, message: `invalid id \"${sid}\"` });\n else if (sectionIds.has(sid)) issues.push({ at: `${sat}.id`, message: `duplicate section \"${sid}\"` });\n sectionIds.add(sid);\n const type = s.type;\n if (type !== undefined && !BUILTIN_SECTION_TYPES.includes(type as BuiltinSectionType)) {\n issues.push({ at: `${sat}.type`, message: `unknown section type \"${String(type)}\"` });\n }\n sections.push({\n id: sid,\n ...(type !== undefined ? { type: type as BuiltinSectionType } : {}),\n ...(s.hidden === true ? { hidden: true } : {}),\n ...(typeof s.label === 'string' && s.label.trim() ? { label: s.label.trim() } : {}),\n });\n });\n\n pages.push({\n id,\n path,\n titleKey,\n ...(raw.hidden === true ? { hidden: true } : {}),\n sections,\n });\n });\n\n const blogs = pages.flatMap((p, i) =>\n p.sections.flatMap((s, j) => (s.type === 'blog' ? [{ page: p, at: `pages[${i}].sections[${j}]` }] : [])),\n );\n if (blogs.length > 1) {\n issues.push({ at: blogs[1]!.at, message: 'a site has one blog; another blog section is already on a page' });\n }\n for (const blog of blogs) {\n if (blog.page.path === '/') issues.push({ at: blog.at, message: 'the blog cannot be the front page' });\n }\n\n const menu = parseMenu(input.menu, 'menu', issues);\n const footer = parseMenu(input.footer, 'footer', issues);\n\n if (issues.length > 0) return { ok: false, issues };\n return { ok: true, manifest: { version: PAGES_MANIFEST_VERSION, pages, menu, footer } };\n}\n\nfunction parseMenu(raw: unknown, at: MenuList, issues: ManifestIssue[]): MenuItem[] {\n if (raw === undefined) return [];\n if (!Array.isArray(raw)) {\n issues.push({ at, message: 'must be a list' });\n return [];\n }\n const ids = new Set<string>();\n const items: MenuItem[] = [];\n raw.forEach((item, i) => {\n const iat = `${at}[${i}]`;\n if (!isRecord(item)) {\n issues.push({ at: iat, message: 'not an object' });\n return;\n }\n const id = String(item.id ?? '');\n const href = String(item.href ?? '');\n const labelKey = String(item.labelKey ?? '');\n if (!ID.test(id)) issues.push({ at: `${iat}.id`, message: `invalid id \"${id}\"` });\n else if (ids.has(id)) issues.push({ at: `${iat}.id`, message: `duplicate item \"${id}\"` });\n ids.add(id);\n if (!isSafeHref(href)) issues.push({ at: `${iat}.href`, message: `invalid link \"${href}\"` });\n if (!labelKey) issues.push({ at: `${iat}.labelKey`, message: 'required' });\n items.push({ id, href, labelKey, ...(item.hidden === true ? { hidden: true } : {}) });\n });\n return items;\n}\n\n/** A path on this site, an anchor, or an http(s)/mailto/tel link. Never `javascript:`. */\nexport function isSafeHref(href: string): boolean {\n if (!href) return false;\n if (href.startsWith('/') && !href.startsWith('//')) return true;\n if (href.startsWith('#')) return true;\n return /^(https?:\\/\\/|mailto:|tel:)/i.test(href);\n}\n\n// ── Reading ─────────────────────────────────────────────────────────────────\n\n/** `/vilkar/` and `/vilkar` are one page; the empty path is the front page. */\nexport function normalisePath(path: string): string {\n const bare = (path.split(/[?#]/)[0] ?? '').replace(/\\/+$/, '');\n return bare === '' ? '/' : bare.toLowerCase();\n}\n\nexport function pageForPath(manifest: PagesManifest, path: string): PageEntry | null {\n const wanted = normalisePath(path);\n return manifest.pages.find((p) => p.path === wanted) ?? (blogSlugForPath(manifest, path) ? blogPage(manifest)!.page : null);\n}\n\n/** The page holding the site's blog, and the section on it. */\nexport function blogPage(manifest: PagesManifest): { page: PageEntry; section: PageSection } | null {\n for (const page of manifest.pages) {\n const section = page.sections.find((s) => s.type === 'blog');\n if (section) return { page, section };\n }\n return null;\n}\n\n/**\n * The post a path names: `/blogg/ny-kaffemaskin` → `ny-kaffemaskin` when the\n * blog lives at `/blogg`. One segment below the blog page and a valid slug;\n * anything else is not a post.\n */\nexport function blogSlugForPath(manifest: PagesManifest, path: string): string | null {\n const blog = blogPage(manifest);\n if (!blog || blog.page.path === '/') return null;\n const wanted = normalisePath(path);\n const prefix = `${blog.page.path}/`;\n if (!wanted.startsWith(prefix)) return null;\n const slug = wanted.slice(prefix.length);\n return slug.length <= 80 && POST_SLUG.test(slug) ? slug : null;\n}\n\nexport function pageById(manifest: PagesManifest, id: string): PageEntry | null {\n return manifest.pages.find((p) => p.id === id) ?? null;\n}\n\n/** The page a section is on, and where. */\nexport function findSection(\n manifest: PagesManifest,\n sectionId: string,\n): { page: PageEntry; index: number; section: PageSection } | null {\n for (const page of manifest.pages) {\n const index = page.sections.findIndex((s) => s.id === sectionId);\n if (index >= 0) return { page, index, section: page.sections[index]! };\n }\n return null;\n}\n\n/**\n * The links a visitor should see.\n *\n * Hidden items go, and so do items that would lead nowhere: a link to a\n * hidden page, or an anchor to a hidden section. Hiding «Tjenester» for the\n * winter should not leave a menu entry that scrolls to nothing.\n */\nexport function visibleMenu(manifest: PagesManifest, list: MenuList): MenuItem[] {\n return manifest[list].filter((item) => !item.hidden && !leadsNowhere(manifest, item.href));\n}\n\n/**\n * The links the site's owner sees, signed in on their own site.\n *\n * What a visitor sees, and one more: the blog's link while the blog is on but\n * has no posts yet. Visitors are spared a menu entry that leads to an empty\n * page; the owner gets it `dimmed`, as the way in — the empty blog is where\n * Pixel offers to write the first article. A blog link the owner hid\n * themselves once posts exist stays hidden.\n */\nexport function ownerMenu(\n manifest: PagesManifest,\n list: MenuList,\n blogEmpty: boolean,\n): Array<MenuItem & { dimmed?: true }> {\n const blog = blogPage(manifest);\n const waiting = blogEmpty && blog && !blog.page.hidden && !blog.section.hidden ? normalisePath(blog.page.path) : null;\n return manifest[list].flatMap((item) => {\n if (!item.hidden && !leadsNowhere(manifest, item.href)) return [item];\n if (waiting && item.hidden && normalisePath(item.href) === waiting) return [{ ...item, dimmed: true as const }];\n return [];\n });\n}\n\nfunction leadsNowhere(manifest: PagesManifest, href: string): boolean {\n if (!href.startsWith('/') && !href.startsWith('#')) return false;\n const [pathPart, fragment] = href.split('#') as [string, string | undefined];\n const page = pageForPath(manifest, pathPart || '/');\n if (pathPart && !page) return false; // a route the site handles in code\n if (page?.hidden) return true;\n if (!fragment) return false;\n const target = findSection(manifest, fragment);\n return target ? Boolean(target.section.hidden || target.page.hidden) : false;\n}\n\n// ── Changing ────────────────────────────────────────────────────────────────\n\nexport class ManifestError extends Error {\n constructor(\n public readonly code:\n | 'page_not_found'\n | 'section_not_found'\n | 'item_not_found'\n | 'duplicate_id'\n | 'duplicate_path'\n | 'invalid',\n message: string,\n ) {\n super(message);\n this.name = 'ManifestError';\n }\n}\n\nfunction clone(manifest: PagesManifest): PagesManifest {\n return JSON.parse(JSON.stringify(manifest)) as PagesManifest;\n}\n\nfunction mustPage(manifest: PagesManifest, pageId: string): PageEntry {\n const page = pageById(manifest, pageId);\n if (!page) throw new ManifestError('page_not_found', `no page \"${pageId}\"`);\n return page;\n}\n\n/**\n * Move a section up (negative) or down (positive) on its page.\n *\n * Skips over hidden neighbours: moving «Om oss» up past a hidden section\n * would otherwise do nothing the owner can see, and look broken. Returns the\n * manifest unchanged at either end rather than throwing — the button is\n * simply at the edge.\n */\nexport function moveSection(manifest: PagesManifest, sectionId: string, delta: -1 | 1): PagesManifest {\n const next = clone(manifest);\n const found = findSection(next, sectionId);\n if (!found) throw new ManifestError('section_not_found', `no section \"${sectionId}\"`);\n const { page, index } = found;\n let target = index + delta;\n while (target >= 0 && target < page.sections.length && page.sections[target]!.hidden) target += delta;\n if (target < 0 || target >= page.sections.length) return manifest;\n const [moved] = page.sections.splice(index, 1);\n page.sections.splice(target, 0, moved!);\n return next;\n}\n\n/** Put a section at an exact position among its page's sections. */\nexport function placeSection(manifest: PagesManifest, sectionId: string, index: number): PagesManifest {\n const next = clone(manifest);\n const found = findSection(next, sectionId);\n if (!found) throw new ManifestError('section_not_found', `no section \"${sectionId}\"`);\n const [moved] = found.page.sections.splice(found.index, 1);\n const at = Math.max(0, Math.min(index, found.page.sections.length));\n found.page.sections.splice(at, 0, moved!);\n return next;\n}\n\nexport function setSectionHidden(manifest: PagesManifest, sectionId: string, hidden: boolean): PagesManifest {\n const next = clone(manifest);\n const found = findSection(next, sectionId);\n if (!found) throw new ManifestError('section_not_found', `no section \"${sectionId}\"`);\n if (hidden) found.section.hidden = true;\n else delete found.section.hidden;\n return next;\n}\n\nexport function addSection(\n manifest: PagesManifest,\n pageId: string,\n section: PageSection,\n index?: number,\n): PagesManifest {\n if (!ID.test(section.id)) throw new ManifestError('invalid', `invalid section id \"${section.id}\"`);\n if (findSection(manifest, section.id)) {\n throw new ManifestError('duplicate_id', `section \"${section.id}\" already exists`);\n }\n const next = clone(manifest);\n const page = mustPage(next, pageId);\n const at = index === undefined ? page.sections.length : Math.max(0, Math.min(index, page.sections.length));\n page.sections.splice(at, 0, { ...section });\n return next;\n}\n\nexport function addPage(manifest: PagesManifest, page: PageEntry): PagesManifest {\n const path = normalisePath(page.path);\n if (!ID.test(page.id) || !PATH.test(path) || path === '/setto' || path.startsWith('/setto/')) {\n throw new ManifestError('invalid', `invalid page \"${page.id}\" at \"${page.path}\"`);\n }\n if (pageById(manifest, page.id)) throw new ManifestError('duplicate_id', `page \"${page.id}\" already exists`);\n if (pageForPath(manifest, path)) throw new ManifestError('duplicate_path', `a page already lives at ${path}`);\n let next = clone(manifest);\n next.pages.push({ id: page.id, path, titleKey: page.titleKey, sections: [] });\n for (const section of page.sections) next = addSection(next, page.id, section);\n return next;\n}\n\nexport function setPageHidden(manifest: PagesManifest, pageId: string, hidden: boolean): PagesManifest {\n const next = clone(manifest);\n const page = mustPage(next, pageId);\n if (page.path === '/' && hidden) throw new ManifestError('invalid', 'the front page cannot be hidden');\n if (hidden) page.hidden = true;\n else delete page.hidden;\n return next;\n}\n\n/** Add a link, or change the one with the same id. */\nexport function upsertMenuItem(\n manifest: PagesManifest,\n list: MenuList,\n item: MenuItem,\n index?: number,\n): PagesManifest {\n if (!ID.test(item.id) || !isSafeHref(item.href) || !item.labelKey) {\n throw new ManifestError('invalid', `invalid link \"${item.id}\"`);\n }\n const next = clone(manifest);\n const items = next[list];\n const existing = items.findIndex((i) => i.id === item.id);\n const clean: MenuItem = { id: item.id, href: item.href, labelKey: item.labelKey };\n if (item.hidden) clean.hidden = true;\n if (existing >= 0) items[existing] = clean;\n else items.splice(index === undefined ? items.length : Math.max(0, Math.min(index, items.length)), 0, clean);\n return next;\n}\n\nexport function moveMenuItem(manifest: PagesManifest, list: MenuList, itemId: string, delta: -1 | 1): PagesManifest {\n const next = clone(manifest);\n const items = next[list];\n const index = items.findIndex((i) => i.id === itemId);\n if (index < 0) throw new ManifestError('item_not_found', `no link \"${itemId}\" in ${list}`);\n const target = index + delta;\n if (target < 0 || target >= items.length) return manifest;\n const [moved] = items.splice(index, 1);\n items.splice(target, 0, moved!);\n return next;\n}\n\nexport function setMenuItemHidden(\n manifest: PagesManifest,\n list: MenuList,\n itemId: string,\n hidden: boolean,\n): PagesManifest {\n const next = clone(manifest);\n const item = next[list].find((i) => i.id === itemId);\n if (!item) throw new ManifestError('item_not_found', `no link \"${itemId}\" in ${list}`);\n if (hidden) item.hidden = true;\n else delete item.hidden;\n return next;\n}\n\n/**\n * One change, as data.\n *\n * What Pixel's structure tools return and what the editor applies, so a\n * suggestion from the chat and a click in the toolbar go through the same\n * functions — and a change the model gets wrong fails here, in a way the\n * owner never sees half of.\n */\nexport type ManifestOp =\n | { op: 'move_section'; sectionId: string; delta: -1 | 1 }\n | { op: 'place_section'; sectionId: string; index: number }\n | { op: 'hide_section'; sectionId: string }\n | { op: 'show_section'; sectionId: string }\n | { op: 'add_section'; pageId: string; section: PageSection; index?: number }\n | { op: 'add_page'; page: PageEntry }\n | { op: 'hide_page'; pageId: string }\n | { op: 'show_page'; pageId: string }\n | { op: 'upsert_link'; list: MenuList; item: MenuItem; index?: number }\n | { op: 'move_link'; list: MenuList; itemId: string; delta: -1 | 1 }\n | { op: 'hide_link'; list: MenuList; itemId: string }\n | { op: 'show_link'; list: MenuList; itemId: string };\n\nexport function applyOp(manifest: PagesManifest, op: ManifestOp): PagesManifest {\n switch (op.op) {\n case 'move_section':\n return moveSection(manifest, op.sectionId, op.delta);\n case 'place_section':\n return placeSection(manifest, op.sectionId, op.index);\n case 'hide_section':\n return setSectionHidden(manifest, op.sectionId, true);\n case 'show_section':\n return setSectionHidden(manifest, op.sectionId, false);\n case 'add_section':\n return addSection(manifest, op.pageId, op.section, op.index);\n case 'add_page':\n return addPage(manifest, op.page);\n case 'hide_page':\n return setPageHidden(manifest, op.pageId, true);\n case 'show_page':\n return setPageHidden(manifest, op.pageId, false);\n case 'upsert_link':\n return upsertMenuItem(manifest, op.list, op.item, op.index);\n case 'move_link':\n return moveMenuItem(manifest, op.list, op.itemId, op.delta);\n case 'hide_link':\n return setMenuItemHidden(manifest, op.list, op.itemId, true);\n case 'show_link':\n return setMenuItemHidden(manifest, op.list, op.itemId, false);\n }\n}\n\n/** Every op or none: a list that fails halfway returns the error and no manifest. */\nexport function applyOps(\n manifest: PagesManifest,\n ops: readonly ManifestOp[],\n): { ok: true; manifest: PagesManifest } | { ok: false; error: string; at: number } {\n let next = manifest;\n for (let i = 0; i < ops.length; i++) {\n try {\n next = applyOp(next, ops[i]!);\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err), at: i };\n }\n }\n return { ok: true, manifest: next };\n}\n\n// ── Built-in sections' content ──────────────────────────────────────────────\n\n/** Where a built-in section keeps its words in the locale files. */\nexport function builtinKeys(sectionId: string) {\n const base = `sections.${sectionId}`;\n return {\n heading: `${base}.heading`,\n intro: `${base}.intro`,\n items: `${base}.items`,\n itemHeading: (itemKey: string) => `${base}.items.${itemKey}.heading`,\n itemText: (itemKey: string) => `${base}.items.${itemKey}.text`,\n };\n}\n\n/** The default locale key for a page's name. */\nexport function pageTitleKey(pageId: string): string {\n return `pages.${pageId}.title`;\n}\n\n/** Stable JSON for the file, so an unchanged manifest is an unchanged file. */\nexport function serialiseManifest(manifest: PagesManifest): string {\n return JSON.stringify(manifest, null, 2) + '\\n';\n}\n","import {\n applyOps,\n parseManifest,\n serialiseManifest,\n type ManifestOp,\n type PagesManifest,\n} from '../pages/manifest';\n\nexport interface PageStoreSnapshot {\n manifest: PagesManifest | null;\n /** How many pages, sections and links differ from what is published. */\n changes: number;\n version: number;\n}\n\nexport const EMPTY_PAGE_STORE_SNAPSHOT: PageStoreSnapshot = {\n manifest: null,\n changes: 0,\n version: 0,\n};\n\ntype Listener = (snap: PageStoreSnapshot) => void;\n\n/**\n * The page manifest as the owner is editing it.\n *\n * The same shape as `ThemeStore` — current against baseline, a snapshot for\n * `useSyncExternalStore`, revert and commit — so the toolbar counts, discards\n * and publishes it the way it does colours. Unlike the other stores it holds\n * one document rather than a map of drafts: an ordering change is not a set of\n * independent keys, and comparing the whole thing is what makes moving a\n * section down and back up again a draft of nothing.\n *\n * `null` throughout for a site without a manifest — every site built before\n * pages were data. `SettoPage` then renders the sections in the order the site\n * listed them, and the structure tools stay out of the editor.\n */\nexport class PageStore {\n private data: PagesManifest | null;\n private baseline: PagesManifest | null;\n private version = 0;\n private listeners = new Set<Listener>();\n private cached: PageStoreSnapshot;\n\n constructor(initial: PagesManifest | null) {\n this.data = initial ? structuredClone(initial) : null;\n this.baseline = initial ? structuredClone(initial) : null;\n this.cached = { manifest: this.data, changes: 0, version: 0 };\n }\n\n snapshot(): PageStoreSnapshot {\n return this.cached;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** The manifest as published, to tell which sections the owner changed. */\n get baselineManifest(): PagesManifest | null {\n return this.baseline;\n }\n\n get manifest(): PagesManifest | null {\n return this.data;\n }\n\n /** True once the site has a manifest to edit. */\n has(): boolean {\n return this.data !== null;\n }\n\n /**\n * Apply changes as drafts. All of them or none: a list that fails halfway\n * leaves the page exactly as it was and says which one failed.\n */\n apply(ops: readonly ManifestOp[]): { ok: true } | { ok: false; error: string; at: number } {\n if (!this.data) return { ok: false, error: 'this site has no page manifest', at: 0 };\n const result = applyOps(this.data, ops);\n if (!result.ok) return result;\n this.data = result.manifest;\n this.bump();\n return { ok: true };\n }\n\n /**\n * Put the draft back to an earlier manifest, keeping the baseline.\n *\n * What «Angre» on one of Pixel's changes does: the panel remembers the\n * manifest from before the change and hands it back here. Checked like\n * anything else, because it has been through a round trip it did not have\n * to survive.\n */\n restore(manifest: PagesManifest): { ok: true } | { ok: false; error: string } {\n const parsed = parseManifest(manifest);\n if (!parsed.ok) return { ok: false, error: parsed.issues[0]?.message ?? 'invalid manifest' };\n this.data = parsed.manifest;\n this.bump();\n return { ok: true };\n }\n\n /**\n * Replace the baseline with what the repository holds, dropping drafts.\n *\n * Checked first: the file in the repository can be newer than this bundle,\n * or hand-edited, and a baseline this store cannot render must not replace\n * the one it can. Returns whether it was taken.\n */\n loadBaseline(next: unknown): boolean {\n const parsed = parseManifest(next);\n if (!parsed.ok) {\n console.warn('[setto] pages.json from the repository is not valid and was ignored', parsed.issues);\n return false;\n }\n this.data = parsed.manifest;\n this.baseline = structuredClone(parsed.manifest);\n this.bump();\n return true;\n }\n\n revertAll(): void {\n this.data = this.baseline ? structuredClone(this.baseline) : null;\n this.bump();\n }\n\n commit(): void {\n this.baseline = this.data ? structuredClone(this.data) : null;\n this.bump();\n }\n\n /** Number of changes, for the toolbar's count. Zero means nothing to publish. */\n size(): number {\n return this.cached.changes;\n }\n\n serialise(): string | null {\n return this.data ? serialiseManifest(this.data) : null;\n }\n\n private bump(): void {\n this.version += 1;\n this.cached = {\n manifest: this.data,\n changes: countChanges(this.baseline, this.data),\n version: this.version,\n };\n for (const fn of this.listeners) fn(this.cached);\n }\n}\n\n/**\n * Roughly how many things the owner changed: each page whose sections or\n * settings differ, each link that differs, each one added.\n *\n * Only has to be right about zero — that decides whether «Publiser» lights —\n * and plausible otherwise, because it is shown as a count.\n */\nexport function countChanges(before: PagesManifest | null, after: PagesManifest | null): number {\n if (!before || !after) return before === after ? 0 : 1;\n let changes = 0;\n const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n\n const beforePages = new Map(before.pages.map((p) => [p.id, p]));\n for (const page of after.pages) {\n const was = beforePages.get(page.id);\n if (!was) {\n changes += 1;\n continue;\n }\n if (was.path !== page.path || was.titleKey !== page.titleKey || Boolean(was.hidden) !== Boolean(page.hidden)) {\n changes += 1;\n }\n const wasSections = new Map(was.sections.map((s, i) => [s.id, { s, i }]));\n page.sections.forEach((s, i) => {\n const prior = wasSections.get(s.id);\n if (!prior || prior.i !== i || !same(prior.s, s)) changes += 1;\n });\n if (was.sections.length > page.sections.length) changes += was.sections.length - page.sections.length;\n }\n if (before.pages.length > after.pages.length) changes += before.pages.length - after.pages.length;\n\n for (const list of ['menu', 'footer'] as const) {\n const wasItems = new Map(before[list].map((item, i) => [item.id, { item, i }]));\n after[list].forEach((item, i) => {\n const prior = wasItems.get(item.id);\n if (!prior || prior.i !== i || !same(prior.item, item)) changes += 1;\n });\n if (before[list].length > after[list].length) changes += before[list].length - after[list].length;\n }\n return changes;\n}\n","import { parseManifest, type PagesManifest } from './manifest';\n\nconst cache = new WeakMap<object, PagesManifest | null>();\n\n/**\n * The manifest the site was built with, checked once.\n *\n * Read on the very first render, before the draft store exists, so the page\n * never flashes its sections in code order — or a hidden one — before the\n * store takes over. A file that fails the check is reported and ignored: the\n * page then renders the way it would without one, which is a working site.\n */\nexport function bundledManifest(raw: unknown): PagesManifest | null {\n if (!raw || typeof raw !== 'object') return null;\n const hit = cache.get(raw);\n if (hit !== undefined) return hit;\n const parsed = parseManifest(raw);\n if (!parsed.ok) {\n console.warn('[setto] pages.json is not valid and was ignored', parsed.issues);\n }\n const manifest = parsed.ok ? parsed.manifest : null;\n cache.set(raw, manifest);\n return manifest;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { Session, SupabaseClient } from '@supabase/supabase-js';\nimport type { SiteRow } from '../types';\n\nexport interface SiteAccessState {\n /** All sites the current user can access. `null` until loaded. */\n sites: SiteRow[] | null;\n /** The site matching `siteId`, or `null` if the user has no access. */\n currentSite: SiteRow | null;\n loading: boolean;\n error: string | null;\n}\n\nconst EMPTY: SiteAccessState = {\n sites: null,\n currentSite: null,\n loading: true,\n error: null,\n};\n\n/**\n * Loads the sites table for the current Supabase session and resolves whether\n * the user has access to `siteId`. Returns a stable shape across loading,\n * success, and failure so callers can read `currentSite` directly.\n */\nexport function useSiteAccess(\n /** Null until supabase-js has loaded, which it has whenever there is a session. */\n supabase: SupabaseClient | null,\n session: Session | null,\n siteId: string,\n): SiteAccessState {\n const [state, setState] = useState<SiteAccessState>(EMPTY);\n const cachedUserIdRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!session || !supabase) {\n cachedUserIdRef.current = null;\n setState({ sites: null, currentSite: null, loading: false, error: null });\n return;\n }\n\n const userId = session.user.id;\n const sameUser = cachedUserIdRef.current === userId;\n let cancelled = false;\n\n setState((prev) => {\n // Supabase emits a new session object on token refresh (e.g. window focus).\n // Keep edit mode stable instead of briefly clearing access.\n if (sameUser && prev.sites !== null && !prev.loading) {\n return prev;\n }\n return {\n ...prev,\n loading: true,\n error: null,\n sites: sameUser ? prev.sites : null,\n currentSite: sameUser ? prev.currentSite : null,\n };\n });\n\n supabase\n .from('sites')\n .select('*')\n .then(({ data, error }) => {\n if (cancelled) return;\n if (error) {\n cachedUserIdRef.current = userId;\n setState({ sites: [], currentSite: null, loading: false, error: error.message });\n return;\n }\n const rows = (data ?? []) as SiteRow[];\n const current = rows.find((s) => s.id === siteId) ?? null;\n cachedUserIdRef.current = userId;\n setState({ sites: rows, currentSite: current, loading: false, error: null });\n });\n\n return () => {\n cancelled = true;\n };\n }, [supabase, session, siteId]);\n\n return state;\n}\n","/**\n * Whether the page is being looked at by a visitor only, so a site may rewrite\n * its own text in the DOM: GSAP's SplitText, a typewriter, anything that moves\n * or replaces the nodes React put there.\n *\n * Text inside `<T>` belongs to React. Rewritten under it, React later removes\n * a node that is no longer where it left it, and the whole page goes blank:\n * that is what turning on editing did to a site whose headline SplitText had\n * split and reverted (2026-10-26). An owner can switch editing on at any\n * moment, so for them the answer is no for the whole visit.\n *\n * `null` while it is not known yet: the session is being read, or the site's\n * membership fetched. A site waits for `true` before it rewrites anything,\n * which for a visitor is a moment after the first paint.\n */\nexport function visitorView(state: {\n authLoading: boolean;\n hasSession: boolean;\n /** Null while the signed-in person's sites are being fetched. */\n sitesLoaded: boolean;\n canEdit: boolean;\n guestEdit: boolean;\n}): boolean | null {\n if (state.authLoading) return null;\n if (!state.hasSession) return !state.guestEdit;\n if (!state.sitesLoaded) return null;\n return !state.canEdit && !state.guestEdit;\n}\n","import { useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { SettoContext, useSetto } from './provider';\n\n/**\n * Setto's own interface, loaded at runtime instead of built into the site.\n *\n * The library mixes two things that have no business sharing a release. Some\n * of it renders the customer's site — `<T>`, sections, the theme — and must be\n * built in, versioned with their content, and never change under them. The\n * rest is Setto's chrome sitting on top: the preview bar, and in time the\n * editor toolbar and the dashboard. None of that is their site.\n *\n * Bundling the chrome meant every change to a button label was a rebuild and\n * redeploy of every site Setto has ever made. Four of those in one day is what\n * this exists to end.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * THIS FILE IS THE FROZEN PART.\n *\n * Everything else about the chrome can change with a single server deploy;\n * this cannot, because it ships inside the customer's bundle. So it does as\n * little as possible: publish a handshake, load a script, and get out of the\n * way. Resist adding anything here that could live on the other side of the\n * boundary — a change to this file costs a re-pin of the entire fleet, which\n * is the exact cost it was written to avoid.\n * ────────────────────────────────────────────────────────────────────────────\n *\n * It fails soft, always. A chrome bundle that will not load, or throws while\n * mounting, must leave the customer's site exactly as it found it: no bar, no\n * error, nothing. That is not politeness — the chrome renders inside somebody\n * else's page, and the worst bug this codebase has produced was a hook after\n * an early return, which white-screens the whole site rather than the bar.\n * Behind a script tag that mistake removes the bar and nothing else.\n */\n\n/** Bumped only for a breaking change to the handshake below. */\nconst CHROME_CONTRACT = 1;\n\n/** What the chrome is handed. Additive changes only; nothing may be removed. */\nexport interface SettoChromeHandshake {\n contract: number;\n /** The host's React, so the chrome bundle ships no framework of its own. */\n react: typeof React;\n reactDom: typeof ReactDOM;\n /**\n * Hand back a component and the host renders it.\n *\n * Inverted deliberately. The first cut had the chrome create its own React\n * root, which cannot work: `createRoot` lives in `react-dom/client`, not\n * `react-dom`, and React 19 removed `render` altogether — so the bundle\n * loaded, found neither, and mounted nothing at all.\n *\n * Rendering it from here is better than passing `createRoot` across would\n * have been. The chrome ends up inside the host's own tree, so its hooks are\n * the host's hooks with no second root to keep in step, and the error\n * boundary that keeps a mistake off the customer's page lives on this side\n * where it cannot be forgotten.\n */\n mount: (Component: React.ComponentType) => void;\n /**\n * The same, for the page at `/setto`.\n *\n * @deprecated Use `mountSlot('admin', …)`. Kept because a chrome bundle\n * older than this file may still call it, and the whole point of this file\n * is that it never has to change again.\n */\n mountAdmin: (Component: React.ComponentType) => void;\n /**\n * Offer a component for a named place in the host: `admin` for the page at\n * `/setto`, `toolbar` for the editor's floating menu.\n *\n * Named rather than one method per surface, because every new method here\n * costs a re-pin of the whole fleet — the exact price this file exists to\n * avoid paying. A new surface is now a string the host already understands,\n * or one it will simply ignore.\n *\n * Registering nothing leaves the host's own version in place. That is what\n * keeps a chrome bundle that fails to load, or throws while rendering, from\n * taking the editor down with it.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n mountSlot: (name: string, Component: React.ComponentType<any>) => void;\n /**\n * The host's own `useSetto`, callable from the chrome.\n *\n * This is what makes the whole arrangement cheap. The chrome renders inside\n * the provider's tree, so it can simply use the context — supabase, api,\n * session, sites, the i18n store — rather than having each field copied\n * across a handshake that could never be extended without a re-pin.\n *\n * It is a hook: obey the rules of hooks, and only call it from a component\n * this file rendered.\n */\n useSetto: () => unknown;\n config: { siteId: string; apiUrl: string; displayName?: string };\n /** Read the current state. Live: call it, never cache what it returned. */\n getState: () => {\n hasSession: boolean;\n accessToken: string | null;\n currentSite: { id: string; display_name?: string; status?: string } | null;\n sitesLoaded: boolean;\n editMode: boolean;\n /** May edit, whether or not editing now (0.44). The chrome loads the editor for it. */\n canEdit?: boolean;\n /** A signed-out visitor trying the editor on setto.no. */\n guestEdit: boolean;\n authLoading: boolean;\n };\n /** Told whenever that state changes. Returns an unsubscribe. */\n subscribe: (listener: () => void) => () => void;\n}\n\ndeclare global {\n interface Window {\n __setto__?: SettoChromeHandshake;\n __settoChromeLoaded__?: boolean;\n }\n}\n\n/** Where the chrome lives. The API host serves it, so one deploy moves it. */\nfunction chromeUrl(apiUrl: string): string {\n return `${apiUrl.replace(/\\/$/, '')}/chrome/v${CHROME_CONTRACT}.js`;\n}\n\n/**\n * Whatever the chrome asked us to draw, kept off the customer's page when it\n * misbehaves. A throw here removes the chrome and nothing else.\n */\nclass ChromeBoundary extends React.Component<\n { children: React.ReactNode; onError?: () => void },\n { dead: boolean }\n> {\n state = { dead: false };\n static getDerivedStateFromError() {\n return { dead: true };\n }\n componentDidCatch(error: unknown) {\n console.warn('[setto] chrome failed, continuing without it', error);\n try {\n this.props.onError?.();\n } catch {\n // Nothing here may throw into the host application.\n }\n }\n render() {\n return this.state.dead ? null : this.props.children;\n }\n}\n\n/**\n * Whatever the chrome has offered, by name.\n *\n * Module scope rather than context: these mount points are scattered through\n * the host — one in its router, one in a portal on the body — with no common\n * ancestor worth threading a provider through.\n */\n/*\n * Heterogeneous on purpose: the admin slot takes nothing, the form-field tools\n * take a field and three callbacks, and the registry cannot be generic over\n * all of them at once. The type is recovered at the reading end, where the\n * caller says what shape it expects.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst slots = new Map<string, React.ComponentType<any>>();\nconst slotListeners = new Set<() => void>();\n\nfunction notifySlots(): void {\n for (const listener of slotListeners) {\n try {\n listener();\n } catch {\n // A listener that throws is the chrome's problem, not the site's.\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction publishSlot(name: string, Component: React.ComponentType<any>): void {\n slots.set(name, Component);\n notifySlots();\n}\n\n/**\n * Drop a slot the chrome offered but could not render.\n *\n * The alternative is a boundary that renders nothing, which is right for an\n * overlay and wrong for a place the host had something of its own to put:\n * `/setto` would go blank rather than fall back to the sign-in it ships with.\n * Retiring the slot puts the host's version back.\n */\nfunction retireSlot(name: string): void {\n if (slots.delete(name)) notifySlots();\n}\n\n/**\n * What the host should render in a named place, or null while the chrome has\n * offered nothing — including after it offered something that threw. Callers\n * render their own version when this is null; every one of them must have one.\n *\n * Also null while supabase-js is still loading (0.47). Everything the chrome\n * offers is an editor's — the dashboard, the menu, the section and image tools\n * — and was written against a `useSetto().supabase` that always existed. The\n * library is fetched only when it is needed now, so an offered component waits\n * here, with the host's own version in its place, until the client is there;\n * asking for the component is what fetches it. For an owner it has long since\n * loaded, since there is no session without it; a guest editor pays here.\n */\nexport function useSettoChromeSlot<P extends object = Record<string, never>>(\n name: string,\n): React.ComponentType<P> | null {\n const [, force] = useState(0);\n useEffect(() => {\n const listener = () => force((n) => n + 1);\n slotListeners.add(listener);\n return () => {\n slotListeners.delete(listener);\n };\n }, []);\n const ctx = useContext(SettoContext);\n const offered = slots.get(name) as React.ComponentType<P> | undefined;\n const waiting = !!offered && !!ctx && !ctx.supabase;\n const loadSupabase = ctx?.loadSupabase;\n useEffect(() => {\n if (!waiting || !loadSupabase) return;\n loadSupabase().catch(() => {\n // Without the client the host's own version stays; nothing to report.\n });\n }, [waiting, loadSupabase]);\n const Offered = waiting ? undefined : offered;\n return useMemo(() => {\n if (!Offered) return null;\n /*\n * `createElement` rather than JSX: spreading a generic `P` into a tag\n * makes TypeScript demand it be assignable to `JSX.IntrinsicAttributes`,\n * which no caller's props are. Same element, no cast.\n */\n return function SettoChromeSlot(props: P) {\n return (\n <ChromeBoundary onError={() => retireSlot(name)}>\n {React.createElement(Offered, props)}\n </ChromeBoundary>\n );\n };\n }, [Offered, name]);\n}\n\n/** @deprecated Use `useSettoChromeSlot('admin')`. */\nexport function useSettoAdminChrome(): React.ComponentType<Record<string, never>> | null {\n return useSettoChromeSlot('admin');\n}\n\nexport function SettoChrome() {\n const setto = useSetto();\n const [Chrome, setChrome] = useState<React.ComponentType | null>(null);\n const listeners = useRef(new Set<() => void>());\n const stateRef = useRef<SettoChromeHandshake['getState']>(() => ({\n hasSession: false,\n accessToken: null,\n currentSite: null,\n sitesLoaded: false,\n editMode: false,\n canEdit: false,\n guestEdit: false,\n authLoading: true,\n }));\n\n /*\n * The newest state, every render, without re-publishing the handshake.\n *\n * The chrome holds a reference to `getState`, so what it reads has to be\n * current. Handing it a snapshot would freeze the bar at whatever was true\n * when the script happened to load.\n */\n stateRef.current = () => ({\n hasSession: !!setto.session,\n accessToken: setto.session?.access_token ?? null,\n currentSite: setto.currentSite\n ? {\n id: setto.currentSite.id,\n display_name: setto.currentSite.display_name,\n status: setto.currentSite.status,\n }\n : null,\n sitesLoaded: setto.sites !== null,\n editMode: setto.editMode,\n canEdit: setto.canEdit,\n guestEdit: setto.guestEdit,\n authLoading: setto.authLoading,\n });\n\n // Anything the chrome is watching hears about it.\n useEffect(() => {\n for (const listener of listeners.current) {\n try {\n listener();\n } catch {\n // A listener that throws is the chrome's problem, not the site's.\n }\n }\n });\n\n useEffect(() => {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n if (window.__settoChromeLoaded__) return;\n\n try {\n window.__setto__ = {\n contract: CHROME_CONTRACT,\n react: React,\n reactDom: ReactDOM,\n config: {\n siteId: setto.config.siteId,\n apiUrl: setto.config.apiUrl,\n displayName: setto.config.displayName,\n },\n getState: () => stateRef.current(),\n subscribe: (listener) => {\n listeners.current.add(listener);\n return () => listeners.current.delete(listener);\n },\n // `setChrome(() => C)`: a component is a function, and the updater form\n // is the only way to put one into state without React calling it.\n mount: (Component) => setChrome(() => Component),\n mountAdmin: (Component) => publishSlot('admin', Component),\n mountSlot: (name, Component) => publishSlot(name, Component),\n useSetto: useSetto as () => unknown,\n };\n\n const script = document.createElement('script');\n /*\n * The site is named in the URL so the server can answer differently for\n * one of them — a canary before a change reaches everybody. Deciding that\n * here would have meant a re-pin every time the channel changed; deciding\n * it there costs a deploy. This parameter exists for no other reason, and\n * it is the reason it had to be added before the contract froze.\n */\n script.src = `${chromeUrl(setto.config.apiUrl)}?site=${encodeURIComponent(setto.config.siteId)}`;\n script.async = true;\n /*\n * A failure is silence. The site is already rendered and correct; the\n * only thing missing is Setto's own furniture, and telling the\n * customer's visitors about that would be worse than the absence.\n */\n script.onerror = () => undefined;\n document.head.appendChild(script);\n window.__settoChromeLoaded__ = true;\n } catch {\n // Nothing here may throw into the host application.\n }\n // Deliberately once per page: the chrome manages its own lifetime.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (!Chrome) return null;\n return (\n <ChromeBoundary>\n <Chrome />\n </ChromeBoundary>\n );\n}\n","/**\n * Base path where the Setto login + dashboard SPA is mounted on the host site.\n * Editors reach the dashboard by visiting `sitenavn.no/setto`. The host app\n * must mount `<SettoAdminApp>` at this path (e.g. `<Route path=\"/setto/*\" …>`).\n */\nexport const SETTO_BASE = '/setto';\n\n/**\n * Site home URL used after sign-in. Edit mode itself is now driven by the\n * Supabase session + site access — no URL flag required — so this just sends\n * the editor to the public site root.\n */\nexport function siteHomeUrl(pathname = '/'): string {\n const u = new URL(window.location.href);\n u.pathname = pathname;\n u.search = '';\n return u.toString();\n}\n\nexport function isAdminRoute(): boolean {\n return window.location.pathname.startsWith(SETTO_BASE);\n}\n\n/** Setto deployment progress panel (`/setto?deployment=…`). */\nexport function isAdminDeploymentView(): boolean {\n return isAdminRoute() && new URLSearchParams(window.location.search).has('deployment');\n}\n\n/**\n * A named dashboard view (`/setto?view=forms`). Views come from the module\n * registry in `src/modules`; the dashboard shows them as tabs. Opening one\n * directly is how the editor's toolbar deep-links into the \"backend\".\n */\nexport function adminViewUrl(view: string): string {\n return `${SETTO_BASE}?view=${encodeURIComponent(view)}`;\n}\n\nexport function currentAdminView(): string | null {\n return new URLSearchParams(window.location.search).get('view');\n}\n\n/**\n * True when the visitor came to `/setto` for a specific panel — a view or a\n * deployment — rather than to sign in. Sign-in normally bounces straight to\n * the site with edit mode on; a panel request stays on the dashboard.\n */\nexport function isAdminPanelView(): boolean {\n return isAdminDeploymentView() || (isAdminRoute() && currentAdminView() !== null);\n}\n\nexport function adminRedirectUrl(): string {\n return `${window.location.origin}${SETTO_BASE}`;\n}\n\n/**\n * The intent a visitor arrived with, carried across the sign-in.\n *\n * «Neste» on the preview bar means \"take me to the checkout\", but a visitor\n * who is not signed in cannot start one — the route wants a session and proof\n * the site is theirs. Sending them to /setto loses the intent, and they come\n * back to the same bar and have to press it again.\n *\n * So the wish rides along in the query string and is honoured on the way back.\n */\nexport const CHECKOUT_INTENT = 'neste';\n\nexport function checkoutIntentUrl(): string {\n return `${SETTO_BASE}?${CHECKOUT_INTENT}=1`;\n}\n\nexport function wantsCheckout(): boolean {\n return new URLSearchParams(window.location.search).get(CHECKOUT_INTENT) === '1';\n}\n\n/** The same address without the marker, so a reload does not start it twice. */\nexport function withoutCheckoutIntent(): string {\n const u = new URL(window.location.href);\n u.searchParams.delete(CHECKOUT_INTENT);\n return u.pathname + (u.search || '') + u.hash;\n}\n","/** Diameter of the collapsed FAB and height of the expanded pill (px). */\nexport const FAB_SIZE = 52;\n\n/** Distance from the viewport edges to the FAB (px). */\nexport const FAB_INSET = 16;\n","import { useEffect } from 'react';\nimport { FAB_INSET, FAB_SIZE } from './constants';\n\nconst STYLE_ID = 'setto-edit-layout';\nconst HTML_CLASS = 'setto-edit-mode';\n\n/**\n * Applies the document-level CSS for inline edit mode. The fixed top toolbar\n * has been replaced with a floating FAB anchored bottom-right, so the host\n * page no longer needs vertical padding — only edit-affordance hover styles\n * and the portal layers above the page.\n */\nexport function useSettoDocumentLayout(active: boolean): void {\n useEffect(() => {\n if (!active) return;\n\n const html = document.documentElement;\n html.classList.add(HTML_CLASS);\n html.style.setProperty('--setto-fab-size', `${FAB_SIZE}px`);\n html.style.setProperty('--setto-fab-inset', `${FAB_INSET}px`);\n\n let styleEl = document.getElementById(STYLE_ID) as HTMLStyleElement | null;\n if (!styleEl) {\n styleEl = document.createElement('style');\n styleEl.id = STYLE_ID;\n styleEl.textContent = `\n html.setto-edit-mode {\n width: 100%;\n overflow-x: clip;\n }\n\n /*\n * Anchored by its right edge, which is also what makes the menu open\n * leftwards: the pill grows and this corner does not move, so the\n * button somebody just tapped stays under their thumb.\n */\n html.setto-edit-mode #setto-toolbar-root {\n position: fixed;\n right: var(--setto-fab-inset);\n bottom: var(--setto-fab-inset);\n z-index: 2147483647;\n }\n\n html.setto-edit-mode #setto-hint-root {\n position: fixed;\n inset: 0;\n pointer-events: none;\n z-index: 2147483645;\n }\n\n html.setto-edit-mode #setto-hint-root [data-setto-ui] {\n pointer-events: auto;\n }\n\n html.setto-edit-mode #setto-section-toolbar-root {\n position: fixed;\n inset: 0;\n pointer-events: none;\n z-index: 2147483646;\n }\n\n html.setto-edit-mode #setto-section-toolbar-root [data-setto-ui] {\n pointer-events: auto;\n }\n\n html.setto-edit-mode [data-setto-key]:hover {\n outline: 1px dashed rgba(196, 80, 42, 0.55);\n outline-offset: 2px;\n border-radius: 2px;\n }\n\n html.setto-edit-mode [data-setto-section]:hover {\n box-shadow: inset 0 0 0 1px rgba(196, 80, 42, 0.3);\n }\n `;\n document.head.appendChild(styleEl);\n }\n\n notifyLayoutChange();\n\n return () => {\n html.classList.remove(HTML_CLASS);\n html.style.removeProperty('--setto-fab-size');\n html.style.removeProperty('--setto-fab-inset');\n styleEl?.remove();\n notifyLayoutChange();\n };\n }, [active]);\n}\n\nfunction notifyLayoutChange(): void {\n requestAnimationFrame(() => {\n window.dispatchEvent(new Event('resize'));\n });\n}\n","import type { CSSProperties } from 'react';\n\ninterface SettoMarkProps {\n size?: number;\n /** Color of the \"S\" letter. Defaults to the Setto crema tone. */\n letterColor?: string;\n /** Color of the accent dot. Defaults to the Setto terracotta. */\n dotColor?: string;\n style?: CSSProperties;\n}\n\n/**\n * Setto brand mark — the foreground of the setto-site favicon (italic \"S\" with\n * a terracotta dot) on a transparent background. The FAB renders the dark\n * Blekk background itself so the mark only carries the glyphs.\n */\nexport function SettoMark({\n size = 24,\n letterColor = '#F2EBDF',\n dotColor = '#C4502A',\n style,\n}: SettoMarkProps) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 64 64\"\n width={size}\n height={size}\n aria-hidden\n style={{ display: 'block', ...style }}\n >\n <text\n x=\"32\"\n y=\"46\"\n textAnchor=\"middle\"\n fontFamily=\"Georgia, serif\"\n fontStyle=\"italic\"\n fontSize=\"42\"\n fill={letterColor}\n >\n S\n </text>\n <circle cx=\"49\" cy=\"17\" r=\"5\" fill={dotColor} />\n </svg>\n );\n}\n","import { useEffect, useState } from 'react';\nimport { FAB_SIZE } from './constants';\nimport { SettoMark } from './setto-mark';\n\n/**\n * What sits where the editor's menu goes when Setto has not sent one.\n *\n * The menu itself is served from setto-server and arrives a moment after edit\n * mode turns on, so silence is the normal state for the first few hundred\n * milliseconds and must not be reported as a fault. After that a fault is\n * exactly what it is, and the owner is standing on a page in edit mode with no\n * way to publish — so say so, and say the one thing that fixes it.\n *\n * It cannot do the menu's work: publishing goes through the same host that\n * failed to send this, so a fallback that offered a Publiser button would be\n * offering a button that cannot work.\n */\nconst GRACE_MS = 4000;\n\nexport function ToolbarUnavailable() {\n const [late, setLate] = useState(false);\n useEffect(() => {\n const timer = setTimeout(() => setLate(true), GRACE_MS);\n return () => clearTimeout(timer);\n }, []);\n if (!late) return null;\n\n return (\n <div role=\"status\" style={pillStyle}>\n <SettoMark size={22} />\n <span>Setto er ikke tilgjengelig. Last siden på nytt.</span>\n </div>\n );\n}\n\nconst pillStyle: React.CSSProperties = {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 8,\n height: FAB_SIZE,\n padding: '0 16px',\n borderRadius: FAB_SIZE / 2,\n background: '#211711',\n color: '#F2EBDF',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n fontSize: 13,\n whiteSpace: 'nowrap',\n boxShadow: '0 8px 24px rgba(33, 23, 17, 0.35), 0 2px 6px rgba(33, 23, 17, 0.2)',\n};\n","import { useEffect, useState, type ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { ThemeStore } from '../lib/theme-store';\nimport { useSettoDocumentLayout } from './document-layout';\nimport { ToolbarUnavailable } from './toolbar-fallback';\nimport { useSettoChromeSlot } from '../chrome';\n\ninterface EditModeShellProps {\n children: ReactNode;\n themeStore: ThemeStore | null;\n /** Editing: the document layout, the section tools and the link hint. */\n active: boolean;\n /**\n * The Setto menu, which an owner has whether or not they are editing: out of\n * edit mode it is only the pencil. Defaults to `active`.\n */\n menu?: boolean;\n}\n\n/**\n * Edit mode: full-width page with a floating Setto FAB anchored bottom-left.\n * Text is edited inline via contentEditable on `<T>` — no sidebar.\n *\n * Always mounted around the host app so toggling edit mode does not remount\n * page content (which would replay GSAP / scroll-driven animations).\n */\nexport function EditModeShell({ children, themeStore, active, menu = active }: EditModeShellProps) {\n useSettoDocumentLayout(active);\n\n /*\n * The editor's menu is Setto's, and Setto sends it.\n *\n * It used to be built in here, which made a change to a button label a\n * publish of this package and a rebuild of every site that pins it. Now the\n * chrome offers one and this renders it in the same portal as before —\n * inside the provider's tree, so its hooks and context are the host's.\n */\n const Toolbar = useSettoChromeSlot('toolbar');\n /*\n * The two smaller pieces of editing chrome, also Setto's and also served.\n *\n * They arrive in the same bundle as the menu, so in practice all three land\n * together. Neither has a fallback: unlike the menu, whose absence looks\n * like a broken editor, these are additive — and when they are missing the\n * menu is missing too and already says so.\n */\n const SectionTools = useSettoChromeSlot('section-toolbar');\n const LinkHint = useSettoChromeSlot('link-hint');\n const [toolbarRoot, setToolbarRoot] = useState<HTMLDivElement | null>(null);\n const [hintRoot, setHintRoot] = useState<HTMLDivElement | null>(null);\n const [sectionToolbarRoot, setSectionToolbarRoot] = useState<HTMLDivElement | null>(null);\n\n /*\n * The menu's root, placed by itself rather than by the edit-mode stylesheet:\n * out of edit mode that stylesheet is gone and the pencil still has to sit\n * in the corner.\n */\n useEffect(() => {\n if (!menu) {\n setToolbarRoot(null);\n return;\n }\n const toolbar = document.createElement('div');\n toolbar.id = 'setto-toolbar-root';\n Object.assign(toolbar.style, {\n position: 'fixed',\n right: 'var(--setto-fab-inset, 16px)',\n bottom: 'var(--setto-fab-inset, 16px)',\n zIndex: '2147483647',\n });\n document.body.appendChild(toolbar);\n setToolbarRoot(toolbar);\n return () => {\n toolbar.remove();\n };\n }, [menu]);\n\n useEffect(() => {\n if (!active) {\n setHintRoot(null);\n setSectionToolbarRoot(null);\n return;\n }\n\n const hint = document.createElement('div');\n hint.id = 'setto-hint-root';\n hint.style.pointerEvents = 'none';\n document.body.appendChild(hint);\n\n const sectionBar = document.createElement('div');\n sectionBar.id = 'setto-section-toolbar-root';\n sectionBar.style.pointerEvents = 'none';\n document.body.appendChild(sectionBar);\n\n setHintRoot(hint);\n setSectionToolbarRoot(sectionBar);\n\n return () => {\n hint.remove();\n sectionBar.remove();\n };\n }, [active]);\n\n return (\n <>\n {children}\n {menu && toolbarRoot\n ? createPortal(Toolbar ? <Toolbar /> : <ToolbarUnavailable />, toolbarRoot)\n : null}\n {active && hintRoot && LinkHint ? createPortal(<LinkHint />, hintRoot) : null}\n {active && sectionToolbarRoot && themeStore && SectionTools\n ? createPortal(<SectionTools />, sectionToolbarRoot)\n : null}\n </>\n );\n}\n\n/** @deprecated Use EditModeShell */\nexport const EditModeMount = EditModeShell;\n","/**\n * The chat's public settings: whether the site has chat at all, and how it\n * introduces itself.\n *\n * Its own file, apart from the widget, because this is the one question every\n * visitor's page asks; the widget and its Markdown renderer are fetched only\n * when the answer is yes (see `index.ts`).\n */\nexport type PublicSettings = {\n enabled: boolean;\n displayName: string | null;\n greeting: string;\n /** The owner's opening line per language; an older server omits it. */\n welcome?: { no?: string | null; en?: string | null } | null;\n /** The assistant's persona on this site; an older server omits both. */\n agentName?: string | null;\n agentAvatarUrl?: string | null;\n};\n\n/** Never on Setto's own page, where the owner's chat is the dashboard's. */\nexport function chatShownHere(pathname: string): boolean {\n return !pathname.startsWith('/setto');\n}\n\n/** The settings when chat is on, otherwise null — including when the call fails. */\nexport async function fetchEnabledChatSettings(\n apiUrl: string,\n siteId: string,\n signal?: AbortSignal,\n): Promise<PublicSettings | null> {\n try {\n const response = await fetch(\n `${apiUrl.replace(/\\/+$/, '')}/sites/${encodeURIComponent(siteId)}/chat/settings/public`,\n { headers: { Accept: 'application/json' }, signal },\n );\n if (!response.ok) return null;\n const settings = (await response.json()) as PublicSettings | null;\n return settings?.enabled ? settings : null;\n } catch {\n return null;\n }\n}\n","import { Component, createElement, lazy, Suspense, useEffect, useState, type ReactNode } from 'react';\nimport type { SettoModule } from '../module';\nimport { useSetto } from '../../provider';\nimport { chatShownHere, fetchEnabledChatSettings, type PublicSettings } from './settings';\n\nexport const chatModule: SettoModule = {\n id: 'chat',\n label: 'Chat',\n};\n\n/*\n * The widget, with its Markdown stack (react-markdown, remark-gfm, micromark),\n * is a chunk of its own: about 230 kB that every visitor of every site used to\n * download, where most sites have no chat switched on.\n */\nconst SettoChatWidget = lazy(() =>\n import('./SettoChat').then((module) => ({ default: module.SettoChatWidget })),\n);\n\n/**\n * A widget that will not load (a chunk gone after a deploy, a dropped\n * connection) or throws leaves the site as it was: no chat, no white page.\n */\nclass ChatBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {\n state = { failed: false };\n static getDerivedStateFromError() {\n return { failed: true };\n }\n componentDidCatch(error: unknown) {\n console.warn('[setto] chat failed, continuing without it', error);\n }\n render() {\n return this.state.failed ? null : this.props.children;\n }\n}\n\n/**\n * The visitor chat, when the site has it switched on.\n *\n * Asks setto-server for the public settings and fetches the widget only when\n * they say chat is on (0.47). Renders nothing until then, nothing on `/setto`,\n * and nothing at all for a site without chat. The provider mounts it already;\n * a site does not need to.\n */\nexport function SettoChat() {\n const { config } = useSetto();\n const [settings, setSettings] = useState<PublicSettings | null>(null);\n\n useEffect(() => {\n if (!chatShownHere(window.location.pathname)) return;\n let cancelled = false;\n void fetchEnabledChatSettings(config.apiUrl, config.siteId).then((next) => {\n if (!cancelled && next) setSettings(next);\n });\n return () => {\n cancelled = true;\n };\n }, [config.apiUrl, config.siteId]);\n\n if (!settings) return null;\n return createElement(\n ChatBoundary,\n null,\n createElement(Suspense, { fallback: null }, createElement(SettoChatWidget, { settings })),\n );\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { SupabaseClient, Session } from '@supabase/supabase-js';\nimport { useTranslation } from 'react-i18next';\nimport {\n browserStorage,\n needsSupabaseAtStart,\n supabaseLoader,\n supabaseStorageKey,\n} from './lib/supabase';\nimport { createApi, type SettoApi } from './lib/api';\nimport { I18nStore } from './lib/i18n-store';\nimport { AutoLanguageSwitcher, InlineLanguagesContext } from './LanguageSwitcher';\nimport { readStoredLanguage, siteLanguages } from './lib/languages';\nimport {\n alternateLinks,\n languageFromPath,\n redirectForVisitor,\n sameOriginUrl,\n} from './lib/language-routing';\nimport { AssetStore } from './lib/asset-store';\nimport { ThemeStore } from './lib/theme-store';\nimport { PageStore } from './lib/page-store';\nimport { bundledManifest } from './pages/bundled';\nimport { useSiteAccess } from './lib/use-site-access';\nimport { visitorView } from './lib/visitor-view';\nimport { SettoChrome } from './chrome';\nimport { isAdminRoute } from './lib/urls';\nimport type { SettoConfig, SiteRow } from './types';\nimport { EditModeShell } from './edit-mode/mount';\nimport { SettoChat } from './modules/chat';\n\nexport interface SettoContextValue {\n config: SettoConfig;\n /**\n * The Supabase client, or null until supabase-js has loaded (0.47).\n *\n * The library is fetched only when someone can be signed in: a session is\n * stored for this project, the page is `/setto`, a sign-in arrives in the\n * URL, the chrome offers an editor component, or `loadSupabase` is called.\n * For a visitor it stays null for the whole visit. It is never null while\n * `session` is set, and never null inside a component the chrome offered\n * through a slot. Elsewhere, check it or call `loadSupabase`.\n */\n supabase: SupabaseClient | null;\n /**\n * The Supabase client, loading supabase-js first if nothing has yet (0.47).\n * Memoised: always the same client as `supabase`. Absent on older clients.\n */\n loadSupabase: () => Promise<SupabaseClient>;\n api: SettoApi;\n session: Session | null;\n /**\n * True while the initial auth state is being read from local storage. False\n * from the first render for a visitor with no stored session (0.47).\n */\n authLoading: boolean;\n /**\n * True while the owner is editing: `canEdit`, and they chose to edit. What\n * makes text editable, shows hidden sections and draws the section tools.\n */\n editMode: boolean;\n /**\n * True when this person may edit this site: signed in, a member, the site is\n * paid for (or this is the site's support account), and this is not `/setto`. The Setto menu is drawn whenever this\n * is; outside `editMode` it shows the site as a visitor sees it.\n * Absent on a client older than 0.33, where `editMode` meant this.\n */\n canEdit: boolean;\n /** Switch editing on or off. Remembered for this site in this browser. */\n setEditing: (on: boolean) => void;\n /** Site row matching `config.siteId`, or `null` if the user has no access. */\n currentSite: SiteRow | null;\n /** All sites the user can access (loaded after sign-in). */\n sites: SiteRow[] | null;\n /**\n * Lazily created when i18next is initialised. Components that need it\n * should `if (!store) return null;` until then.\n */\n store: I18nStore | null;\n themeStore: ThemeStore | null;\n assetStore: AssetStore | null;\n /**\n * The page manifest being edited: section order, hidden sections, pages and\n * menu links. Holds `null` inside for a site that has no `pages.json`.\n * Absent on a client older than 0.29, which the chrome has to allow for.\n */\n pageStore: PageStore | null;\n /** The section the editor has selected, or null. */\n selectedSectionId: string | null;\n selectSection: (id: string | null) => void;\n /**\n * True while a signed-out visitor is trying the editor (setto.no).\n *\n * Here beside `editMode` rather than in `GuestEditProvider`'s own context\n * for the same reason the selected section is: the chrome that draws the\n * section toolbar sits above that provider and can call only `useSetto`.\n */\n guestEdit: boolean;\n setGuestEdit: (on: boolean) => void;\n}\n\n/**\n * Exported for one caller: the chrome bundle.\n *\n * The dashboard is compiled into that bundle, so its `useSetto` reads *this*\n * module's context — a different instance from the one the host provider\n * fills, which would otherwise throw \"must be used within SettoProvider\" the\n * moment it rendered. Handing it the host's value through this provider is\n * what lets the same components run on either side of the boundary.\n *\n * Not part of the public API in any other sense. Use `useSetto`.\n */\nexport const SettoContext = createContext<SettoContextValue | null>(null);\n\nexport interface SettoProviderProps {\n config: SettoConfig;\n children: ReactNode;\n}\n\n/**\n * Wraps the host app. Initialises Supabase, the API client, and listens for\n * auth changes. Mounts the edit toolbar and enables inline editing when active.\n *\n * The owner may edit (`canEdit`) when ALL of:\n * 1. There is an authenticated Supabase session.\n * 2. The user has access to `config.siteId` in the Setto sites table.\n * 3. The current path is not the `/setto` admin SPA.\n *\n * Once an editor signs in via `/setto` they stay signed in until they sign out\n * there. Whether they are editing is their own switch (`setEditing`): the\n * Setto menu's pencil turns it on, and publishing turns it off.\n */\nexport function SettoProvider({ config, children }: SettoProviderProps) {\n const { url: supabaseUrl, anonKey: supabaseAnonKey } = config.supabase;\n const loader = useMemo(\n () => supabaseLoader({ url: supabaseUrl, anonKey: supabaseAnonKey }),\n [supabaseUrl, supabaseAnonKey],\n );\n const [supabase, setSupabase] = useState<SupabaseClient | null>(() => loader.client);\n if (supabase && supabase !== loader.client) setSupabase(loader.client);\n\n const loadSupabase = useCallback(\n () =>\n loader.load().then((client) => {\n setSupabase(client);\n return client;\n }),\n [loader],\n );\n\n /*\n * The token for an API call. Only a page that has loaded supabase-js, or is\n * loading it, can have a session; anything else answers `not_authenticated`\n * without fetching the library just to find that out.\n */\n const api = useMemo(\n () =>\n createApi({\n apiUrl: config.apiUrl,\n supabase: () =>\n loader.client || loader.loading ? loader.load() : Promise.resolve(null),\n }),\n [config.apiUrl, loader],\n );\n\n /*\n * Whether someone can be signed in on this page load, which is the only time\n * the answer to \"is there a session?\" needs supabase-js (lib/supabase.ts).\n * For everybody else it is \"no\", known at once: `authLoading` is false from\n * the first render and the library is never fetched.\n */\n const [authWanted, setAuthWanted] = useState(() =>\n typeof window === 'undefined'\n ? false\n : needsSupabaseAtStart(config.supabase, {\n pathname: window.location.pathname,\n hash: window.location.hash,\n search: window.location.search,\n storage: browserStorage(),\n }),\n );\n const [authLoadFailed, setAuthLoadFailed] = useState(false);\n const [sessionRead, setSessionRead] = useState(false);\n const [session, setSession] = useState<Session | null>(null);\n const authLoading = authWanted && !authLoadFailed && (!supabase || !sessionRead);\n const [onAdminRoute, setOnAdminRoute] = useState(() =>\n typeof window === 'undefined' ? false : isAdminRoute(),\n );\n\n useEffect(() => {\n if (!authWanted || supabase) return;\n let cancelled = false;\n loadSupabase().catch((error: unknown) => {\n if (cancelled) return;\n console.warn('[setto] could not load sign-in, continuing signed out', error);\n setAuthLoadFailed(true);\n });\n return () => {\n cancelled = true;\n };\n }, [authWanted, supabase, loadSupabase]);\n\n /*\n * Signed in in another tab while this one was open: supabase-js would have\n * heard it through its own storage listener, had it been loaded.\n */\n useEffect(() => {\n if (authWanted) return;\n const prefix = supabaseStorageKey(supabaseUrl);\n const onStorage = (event: StorageEvent) => {\n if (event.key?.startsWith(prefix) && event.newValue) setAuthWanted(true);\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n }, [authWanted, supabaseUrl]);\n\n useEffect(() => {\n if (!supabase) return;\n let cancelled = false;\n supabase.auth.getSession().then(\n ({ data }) => {\n if (cancelled) return;\n setSession(data.session ?? null);\n setSessionRead(true);\n },\n () => {\n if (!cancelled) setSessionRead(true);\n },\n );\n const { data: sub } = supabase.auth.onAuthStateChange((_event, session) => {\n setSession(session);\n });\n return () => {\n cancelled = true;\n sub.subscription.unsubscribe();\n };\n }, [supabase]);\n\n // Track whether we are inside the /setto admin SPA so the inline editor stays\n // off while the dashboard is rendered. Listens to popstate; admin nav uses\n // `window.location.replace` for top-level transitions.\n useEffect(() => {\n const compute = () => setOnAdminRoute(isAdminRoute());\n compute();\n window.addEventListener('popstate', compute);\n return () => window.removeEventListener('popstate', compute);\n }, []);\n\n const access = useSiteAccess(supabase, session, config.siteId);\n\n // The i18n store hangs off the live i18next instance from react-i18next.\n const { i18n } = useTranslation();\n\n /*\n * Every language this site speaks, primary first.\n *\n * Computed rather than read straight off the config so a list that forgets\n * to name the primary language cannot make the site's own copy unreachable.\n */\n const languages = useMemo(\n () => siteLanguages(config.languages, config.languages?.[0]),\n [config.languages],\n );\n\n /*\n * The URL says which language this is.\n *\n * Not `localStorage`, which is where it lived for one release and which no\n * search engine and no shared link can see. `/priser` is Norwegian and\n * `/en/priser` is English, and both are addresses somebody can send to\n * somebody else.\n *\n * A first-time visitor whose browser asks for a language the site speaks is\n * moved to that address once — never away from one they are already at, so\n * a click on «Norsk» is not undone on the next page.\n */\n useEffect(() => {\n if (!i18n || languages.length < 2) return;\n\n const redirect = redirectForVisitor(\n window.location.pathname,\n languages,\n navigator.languages ?? [navigator.language],\n readStoredLanguage(),\n );\n if (redirect && redirect !== window.location.pathname) {\n // Only ever to somewhere on this site; see `sameOriginUrl`.\n const url = sameOriginUrl(\n redirect + window.location.search + window.location.hash,\n window.location.origin,\n );\n if (url) {\n window.location.replace(url);\n return;\n }\n }\n\n const { language } = languageFromPath(window.location.pathname, languages);\n if (language !== i18n.language) void i18n.changeLanguage(language);\n document.documentElement.lang = language;\n }, [i18n, languages]);\n\n /*\n * `hreflang`, so the two addresses are understood as one page in two\n * languages rather than two pages that happen to say similar things.\n *\n * Written from here rather than into `index.html` because only this knows\n * which path the visitor is on, and a static head cannot name the\n * alternates for a route it has never heard of.\n *\n * Unless the page already names them (0.49.0). A page the build wrote a\n * head for — a blog post, or a page a site drew ahead of time — knows\n * better than a guess from the path: an untranslated post has no English\n * address of its own (its `/en` copy points its canonical at the\n * Norwegian one), and links added here would have named it anyway.\n */\n useEffect(() => {\n if (languages.length < 2) return;\n if (document.head.querySelector('link[rel=\"alternate\"][hreflang]:not([data-setto-alternate])')) return;\n const links = alternateLinks(window.location.origin, window.location.pathname, languages);\n const added = links.map(({ hreflang, href }) => {\n const el = document.createElement('link');\n el.rel = 'alternate';\n el.hreflang = hreflang;\n el.href = href;\n el.dataset.settoAlternate = '';\n document.head.appendChild(el);\n return el;\n });\n return () => added.forEach((el) => el.remove());\n }, [languages]);\n const storeRef = useRef<I18nStore | null>(null);\n const themeStoreRef = useRef<ThemeStore | null>(null);\n const assetStoreRef = useRef<AssetStore | null>(null);\n const pageStoreRef = useRef<PageStore | null>(null);\n const [storeReady, setStoreReady] = useState(false);\n\n useEffect(() => {\n if (!i18n) return;\n storeRef.current = new I18nStore(i18n);\n themeStoreRef.current = new ThemeStore(config.theme ?? {});\n assetStoreRef.current = new AssetStore();\n pageStoreRef.current = new PageStore(bundledManifest(config.pages));\n setStoreReady(true);\n }, [i18n, config.theme, config.pages]);\n\n /*\n * A member of the site, paid for or not (Simon, 2026-10-26): a preview's\n * owner edits it before choosing a plan, and setto-server decides what that\n * costs (Pixel's larger changes are limited until there is a plan). Until\n * 0.46 only a `live` site could be edited here.\n *\n * The site's support account, which a Setto admin signs in as with\n * «Rediger» in the admin, is a member of the one site its `app_metadata`\n * names, so it passes the same way.\n */\n const canEdit =\n !!session &&\n !!access.currentSite &&\n !onAdminRoute &&\n !authLoading &&\n !access.loading;\n\n /*\n * Editing is a switch the owner holds, not the same thing as being signed in\n * (Simon, 2026-09-25). Signed in, they see their site as a visitor does with\n * only a pencil at the bottom; the pencil turns editing on, and publishing\n * turns it off again. Remembered per site in this browser so a reload while\n * editing stays editing. Off to begin with.\n */\n const [editing, setEditingState] = useState(() => readEditing(config.siteId));\n const setEditing = useCallback(\n (on: boolean) => {\n writeEditing(config.siteId, on);\n setEditingState(on);\n },\n [config.siteId],\n );\n const editMode = canEdit && editing;\n\n /*\n * Which section is selected, held here rather than in a context of its own.\n *\n * It used to have one, which was tidier until the section toolbar moved to\n * the chrome: that bundle can call exactly one hook of the host's,\n * `useSetto`, so a second context was a second thing to hand across the\n * boundary — and the way to hand it across would have been another method on\n * the loader, the one file that cannot change without a re-pin of the fleet.\n * `useSectionEdit()` still exists and still reads the same two fields.\n */\n const [selectedSectionId, setSelectedSectionId] = useState<string | null>(null);\n const selectSection = useCallback((id: string | null) => setSelectedSectionId(id), []);\n\n const [guestEdit, setGuestEdit] = useState(false);\n // Real edit mode always wins; a signed-in owner is never also a guest.\n useEffect(() => {\n if (editMode && guestEdit) setGuestEdit(false);\n }, [editMode, guestEdit]);\n useEffect(() => {\n document.documentElement.classList.toggle('setto-guest-editing', guestEdit);\n return () => document.documentElement.classList.remove('setto-guest-editing');\n }, [guestEdit]);\n\n const value: SettoContextValue = {\n config,\n supabase,\n loadSupabase,\n api,\n session,\n authLoading,\n editMode,\n canEdit,\n setEditing,\n currentSite: access.currentSite,\n sites: access.sites,\n store: storeReady ? storeRef.current : null,\n themeStore: storeReady ? themeStoreRef.current : null,\n assetStore: storeReady ? assetStoreRef.current : null,\n pageStore: storeReady ? pageStoreRef.current : null,\n selectedSectionId,\n selectSection,\n guestEdit,\n setGuestEdit,\n };\n\n // Filled in while the site's tree is drawn; read by the floating switcher drawn after it.\n const inlineLanguages = useRef({ drawn: false }).current;\n\n const editShellActive = editMode && !!value.store;\n const menuShown = canEdit && !!value.store;\n\n return (\n <SettoContext.Provider value={value}>\n <InlineLanguagesContext.Provider value={inlineLanguages}>\n <EditModeShell active={editShellActive} menu={menuShown} themeStore={value.themeStore}>\n {children}\n </EditModeShell>\n {/*\n * Setto's own furniture, fetched at runtime rather than built in.\n *\n * The bar used to live in this bundle, which meant every change to it\n * — a label, a colour, where a button led — was a rebuild and redeploy\n * of every site Setto has made. See `chrome.tsx`: what ships here now\n * is a loader that must never change, and everything interesting is a\n * server deploy away.\n */}\n {/*\n * Everywhere, including /setto.\n *\n * This guard was right when the thing behind it was the preview bar,\n * which has no business over the editor. It is wrong for the loader:\n * the chrome is now responsible for the dashboard too, so skipping it\n * on the admin route meant no handshake, no bundle, and a silent\n * fall back to the bundled copy — which is exactly what the fleet\n * showed. What may be drawn where is the chrome's decision now, and\n * the chrome is the part that can be changed without a re-pin.\n */}\n <SettoChrome />\n <SettoChat />\n {/*\n * The visitor's own language control.\n *\n * Renders nothing at all for a single-language site, which is all of\n * them today, and stands down when the site places its own\n * `<SettoLanguages inline>` somewhere in its design.\n */}\n <AutoLanguageSwitcher languages={languages} />\n </InlineLanguagesContext.Provider>\n </SettoContext.Provider>\n );\n}\n\nconst editingKey = (siteId: string) => `setto-editing:${siteId}`;\n\nfunction readEditing(siteId: string): boolean {\n try {\n return window.localStorage.getItem(editingKey(siteId)) === '1';\n } catch {\n return false;\n }\n}\n\nfunction writeEditing(siteId: string, on: boolean): void {\n try {\n if (on) window.localStorage.setItem(editingKey(siteId), '1');\n else window.localStorage.removeItem(editingKey(siteId));\n } catch {\n // Private mode: the switch lasts for this page.\n }\n}\n\nexport function useSetto(): SettoContextValue {\n const ctx = useContext(SettoContext);\n if (!ctx) {\n throw new Error('useSetto() must be used inside <SettoProvider>');\n }\n return ctx;\n}\n\n/**\n * True once it is known that nobody on this page can edit it, false for an\n * owner, null until it is known. Wait for `true` before rewriting text in the\n * DOM (SplitText and the like): see `lib/visitor-view.ts`.\n */\nexport function useVisitorView(): boolean | null {\n const { authLoading, session, sites, canEdit, guestEdit } = useSetto();\n return visitorView({ authLoading, hasSession: !!session, sitesLoaded: sites !== null, canEdit, guestEdit });\n}\n","import { createContext, useContext, useEffect, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { languageName, siteLanguages, storeLanguage } from './lib/languages';\nimport { SettoContext } from './provider';\nimport { pathForLanguage, sameOriginUrl } from './lib/language-routing';\n\n/**\n * The control a visitor uses to read the site in their own language.\n *\n * Mounted by `SettoProvider` rather than placed by the agent, and only when\n * the site actually speaks more than one language — so it costs a Norwegian\n * plumber's site nothing, and a site that gains a second language grows the\n * control without anybody editing a header.\n *\n * That decision is worth stating because it is a trade. Auto-mounting means\n * the switcher cannot sit inside a design it knows nothing about, so it sits\n * in a corner instead: quiet, small, and out of the way of whatever the agent\n * built. A site that wants it in its own header can render `<SettoLanguages>`\n * anywhere and pass `inline`, and the floating one stands down.\n *\n * Styling is inline for the same reason the editing chrome's is: this renders\n * inside a page whose stylesheet Setto did not write, and most of these sites\n * ship Tailwind's Preflight, which would otherwise strip a bare `<button>`\n * back to nothing.\n */\n\nexport interface SettoLanguagesProps {\n /**\n * Every language the site speaks, primary first. Read from the provider's\n * config when left out, which is what a site should do: the list lives in\n * `setto.config.json` and grows when a customer adds a language in Språk,\n * so a header that hard-codes it goes stale the first time they do.\n */\n languages?: readonly string[];\n /**\n * Rendered in the flow of the page rather than fixed in a corner.\n *\n * Also tells the auto-mounted copy to stand down, so a site that places its\n * own switcher does not end up with two.\n */\n inline?: boolean;\n}\n\n/** Set on `document.documentElement` while an inline switcher is on the page. */\nconst INLINE_MARKER = 'data-setto-languages-inline';\n\n/**\n * Whether an inline switcher has been drawn in this render, ahead of the\n * floating copy (the provider draws that after the site's tree). Set while\n * drawing rather than from an effect, so a page drawn on a server — and the\n * browser's first render of it — leaves the floating copy out from the start\n * (0.49.0). It was in the prerendered HTML of setto.no and vanished once the\n * page's script ran: a «Norsk» pill blinking in the corner of every page.\n */\nexport const InlineLanguagesContext = createContext<{ drawn: boolean } | null>(null);\n\nexport function SettoLanguages({ languages: given, inline = false }: SettoLanguagesProps) {\n const { i18n } = useTranslation();\n const setto = useContext(SettoContext);\n const configured = setto?.config.languages;\n const languages = given ?? siteLanguages(configured, configured?.[0]);\n const [open, setOpen] = useState(false);\n const [hover, setHover] = useState(false);\n const [surface, setSurface] = useState<{ background: string; color: string } | null>(null);\n const ref = useRef<HTMLDivElement>(null);\n const drawnInline = useContext(InlineLanguagesContext);\n if (inline && drawnInline) drawnInline.drawn = true;\n\n /*\n * Announce an inline switcher so the floating one can hide. A ref on the\n * document rather than context, because the two can be mounted by different\n * trees — the provider's own and the site's.\n */\n useEffect(() => {\n if (!inline) return;\n const root = document.documentElement;\n const count = Number(root.getAttribute(INLINE_MARKER) ?? '0') + 1;\n root.setAttribute(INLINE_MARKER, String(count));\n return () => {\n const left = Number(root.getAttribute(INLINE_MARKER) ?? '1') - 1;\n if (left > 0) root.setAttribute(INLINE_MARKER, String(left));\n else root.removeAttribute(INLINE_MARKER);\n };\n }, [inline]);\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: MouseEvent) => {\n if (!ref.current?.contains(e.target as Node)) setOpen(false);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') setOpen(false);\n };\n document.addEventListener('mousedown', onDown);\n document.addEventListener('keydown', onKey);\n return () => {\n document.removeEventListener('mousedown', onDown);\n document.removeEventListener('keydown', onKey);\n };\n }, [open]);\n\n if (languages.length < 2) return null;\n\n const current = i18n.language;\n\n /*\n * The inline list opens over somebody's header, light or dark, and cannot\n * know which from a stylesheet it did not write. So it borrows: the first\n * opaque background above it and the text colour the trigger inherited.\n */\n const toggle = () => {\n if (!open && inline && ref.current) setSurface(surroundings(ref.current));\n setOpen((o) => !o);\n };\n\n const choose = (tag: string) => {\n setOpen(false);\n if (tag === current) return;\n /*\n * Remembered so the redirect for a first-time visitor does not argue with\n * a choice they have just made — it is not what decides the language any\n * more, the address is.\n */\n storeLanguage(tag);\n\n /*\n * A real navigation rather than `changeLanguage` and a `pushState`.\n *\n * The language is in the URL now, so switching it *is* going somewhere\n * else. A full load is also the only way to be sure the page comes back\n * with the right `lang` attribute, the right alternates, and the right\n * router basename — and this client cannot reach the site's router to do\n * it any other way: `react-router` is the site's dependency, not ours.\n * Switching language is a rare, deliberate act; a page load is an honest\n * price for it.\n */\n const target = pathForLanguage(window.location.pathname, tag, languages);\n // Never off the site, whatever the address bar held. See `normalise`.\n const url = sameOriginUrl(target + window.location.search + window.location.hash, window.location.origin);\n if (url) window.location.assign(url);\n };\n\n return (\n <div ref={ref} style={inline ? inlineWrapStyle : floatingWrapStyle}>\n <button\n type=\"button\"\n onClick={toggle}\n onMouseEnter={() => setHover(true)}\n onMouseLeave={() => setHover(false)}\n aria-expanded={open}\n aria-haspopup=\"listbox\"\n aria-label={`Språk: ${languageName(current)}`}\n title={inline ? languageName(current) : undefined}\n style={inline ? { ...inlineTriggerStyle, opacity: hover || open ? 1 : inlineTriggerStyle.opacity } : floatingTriggerStyle}\n >\n <GlobeIcon />\n {inline ? shortCode(current) : languageName(current)}\n </button>\n\n {open ? (\n <ul\n role=\"listbox\"\n style={\n inline\n ? { ...inlineListStyle, ...(surface ? { background: surface.background, color: surface.color } : {}) }\n : floatingListStyle\n }\n >\n {languages.map((tag) => (\n <li key={tag}>\n <button\n type=\"button\"\n role=\"option\"\n aria-selected={tag === current}\n onClick={() => choose(tag)}\n style={{\n ...optionStyle,\n ...(inline ? { color: 'inherit' } : {}),\n fontWeight: tag === current ? 600 : 400,\n }}\n >\n {languageName(tag)}\n </button>\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n}\n\n/**\n * The floating copy, mounted by the provider.\n *\n * Renders nothing when the site places its own, and nothing when there is only\n * one language to be in.\n */\nexport function AutoLanguageSwitcher({ languages }: { languages: readonly string[] }) {\n const drawnInline = useContext(InlineLanguagesContext);\n const [inlineElsewhere, setInlineElsewhere] = useState(() => drawnInline?.drawn ?? false);\n\n useEffect(() => {\n const check = () => setInlineElsewhere(document.documentElement.hasAttribute(INLINE_MARKER));\n check();\n // The site's own switcher may mount after this one; watch rather than\n // read once, or a page ends up with both for its first frame and forever.\n const observer = new MutationObserver(check);\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [INLINE_MARKER],\n });\n return () => observer.disconnect();\n }, []);\n\n if (inlineElsewhere || languages.length < 2) return null;\n return <SettoLanguages languages={languages} />;\n}\n\n/** «NO», «EN», «PT-BR» — as short as a theme icon, the full name is in the label and the list. */\nfunction shortCode(tag: string): string {\n return tag.toUpperCase();\n}\n\n/** The first opaque background above `el`, and the text colour it has. */\nfunction surroundings(el: HTMLElement): { background: string; color: string } {\n const color = getComputedStyle(el).color;\n for (let node: HTMLElement | null = el; node; node = node.parentElement) {\n const background = getComputedStyle(node).backgroundColor;\n if (background && !/^(transparent|rgba\\(.*,\\s*0\\))$/.test(background)) return { background, color };\n }\n return { background: '#ffffff', color: '#1a1a1a' };\n}\n\n/**\n * A globe.\n *\n * «A文» was tried here and reverted: it is the mark browsers use, but it is\n * not one people recognise on a plumber's website, and an icon that has to be\n * explained has already failed. The globe is imprecise — it says «the\n * internet» as readily as it says «language» — and it is what everybody\n * already reads as a language control, which on a small business's site\n * matters more than being right.\n */\nfunction GlobeIcon() {\n return (\n <svg\n width=\"15\"\n height=\"15\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.8\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M3 12h18M12 3c2.4 2.6 3.6 5.6 3.6 9s-1.2 6.4-3.6 9c-2.4-2.6-3.6-5.6-3.6-9S9.6 5.6 12 3z\" />\n </svg>\n );\n}\n\n/*\n * Bottom-left, because the editor's own button is bottom-right and a customer\n * signing in should not find two round things fighting over one corner.\n */\nconst floatingWrapStyle: React.CSSProperties = {\n position: 'fixed',\n left: 'max(16px, env(safe-area-inset-left))',\n bottom: 'max(16px, env(safe-area-inset-bottom))',\n zIndex: 2147482000,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nconst inlineWrapStyle: React.CSSProperties = {\n position: 'relative',\n display: 'inline-block',\n fontFamily: 'inherit',\n};\n\nconst triggerBase: React.CSSProperties = {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 7,\n minHeight: 40,\n fontSize: 13.5,\n fontWeight: 500,\n lineHeight: 1,\n cursor: 'pointer',\n};\n\n/*\n * The floating copy has to be seen against a page it knows nothing about, so\n * it brings its own pill: a translucent ground, a hairline and a little lift.\n */\nconst floatingTriggerStyle: React.CSSProperties = {\n ...triggerBase,\n padding: '8px 14px',\n borderRadius: 999,\n border: '1px solid rgba(127, 127, 127, 0.32)',\n background: 'rgba(255, 255, 255, 0.82)',\n backdropFilter: 'blur(8px)',\n WebkitBackdropFilter: 'blur(8px)',\n color: '#1a1a1a',\n boxShadow: '0 4px 14px rgba(0, 0, 0, 0.12)',\n};\n\n/*\n * Placed in somebody's own header, it brings nothing.\n *\n * No ground, no border, no shadow, and `currentColor` — a control that draws\n * its own pill inside a header that has already decided what a control looks\n * like is two designs arguing. Language is a setting, not an action, so it\n * should read quieter than the buttons beside it, not louder.\n */\nconst inlineTriggerStyle: React.CSSProperties = {\n ...triggerBase,\n gap: 5,\n minHeight: 36,\n padding: '6px 6px',\n border: 0,\n borderRadius: 8,\n background: 'transparent',\n color: 'inherit',\n fontSize: 12,\n fontWeight: 500,\n letterSpacing: '0.06em',\n opacity: 0.7,\n transition: 'opacity 160ms ease',\n};\n\nconst listBase: React.CSSProperties = {\n position: 'absolute',\n margin: 0,\n padding: 4,\n listStyle: 'none',\n minWidth: 150,\n borderRadius: 12,\n border: '1px solid rgba(127, 127, 127, 0.24)',\n background: '#ffffff',\n boxShadow: '0 12px 32px rgba(0, 0, 0, 0.18)',\n zIndex: 1,\n};\n\nconst floatingListStyle: React.CSSProperties = { ...listBase, left: 0, bottom: 'calc(100% + 8px)' };\n/* Right-aligned: an inline switcher sits at the end of a header, beside the theme button. */\nconst inlineListStyle: React.CSSProperties = { ...listBase, right: 0, top: 'calc(100% + 8px)' };\n\nconst optionStyle: React.CSSProperties = {\n display: 'block',\n width: '100%',\n minHeight: 40,\n padding: '9px 12px',\n border: 0,\n borderRadius: 8,\n background: 'transparent',\n color: '#1a1a1a',\n fontSize: 13.5,\n textAlign: 'left',\n cursor: 'pointer',\n};\n","import { createPortal } from 'react-dom';\nimport type { ReactNode } from 'react';\nimport { useSettoChromeSlot } from './chrome';\nimport { useSetto } from './provider';\n\n/**\n * Lets visitors inline-edit a marketing site (e.g. setto.no) without auth —\n * text, section/block colours, icons and list items. Changes are session-only\n * and never published. Real Setto edit mode always takes precedence.\n *\n * A provider in name only since 2026-09-09: the state moved into the main\n * context so the chrome could see it, and what is left here is the one thing\n * guest mode adds — the section toolbar, over a page nobody is signed in to.\n * The component comes from Setto like the rest of the editing chrome, so there\n * is nothing to draw until it arrives, and nothing to draw at all if it does\n * not. That is the right failure for a demo.\n */\nexport function GuestEditProvider({ children }: { children: ReactNode }) {\n const { guestEdit, themeStore } = useSetto();\n const SectionTools = useSettoChromeSlot('section-toolbar');\n\n return (\n <>\n {children}\n {guestEdit && themeStore && SectionTools\n ? createPortal(<SectionTools />, document.body)\n : null}\n </>\n );\n}\n\nexport interface GuestEditContextValue {\n active: boolean;\n start: () => void;\n stop: () => void;\n}\n\nexport function useGuestEdit(): GuestEditContextValue {\n const { guestEdit, setGuestEdit, selectSection } = useSetto();\n return {\n active: guestEdit,\n start: () => setGuestEdit(true),\n stop: () => {\n setGuestEdit(false);\n selectSection(null);\n },\n };\n}\n","/** Editable text inside a navigation target (link or button), excluding language toggles. */\nexport function isLinkContext(el: HTMLElement): boolean {\n const key = el.getAttribute('data-setto-key');\n if (key?.startsWith('lang.')) return false;\n if (el.closest('[data-setto-no-hint]')) return false;\n return !!(el.closest('a[href]') || el.closest('button'));\n}\n\n/** Same as Ctrl/Cmd+click — follow the parent link or trigger the parent button. */\nexport function activateLinkContext(el: HTMLElement): void {\n const anchor = el.closest('a[href]');\n if (anchor instanceof HTMLAnchorElement) {\n anchor.click();\n return;\n }\n const button = el.closest('button');\n if (button instanceof HTMLButtonElement) {\n button.click();\n }\n}\n","import { useLayoutEffect, useRef, useState, type RefObject } from 'react';\nimport { createPortal } from 'react-dom';\nimport { activateLinkContext } from '../lib/link-context';\n\nconst MARGIN = 10;\nconst OFFSET = 8;\nconst MIN_TOUCH = 44;\n\ninterface LinkActionChipProps {\n anchorRef: RefObject<HTMLElement | null>;\n visible: boolean;\n}\n\nfunction placeChip(anchor: DOMRect, width: number, height: number): { left: number; top: number } {\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n\n let left = anchor.left + anchor.width / 2 - width / 2;\n let top = anchor.bottom + OFFSET;\n\n if (left + width > vw - MARGIN) left = vw - width - MARGIN;\n if (left < MARGIN) left = MARGIN;\n\n if (top + height > vh - MARGIN) {\n top = anchor.top - height - OFFSET;\n }\n if (top < MARGIN) top = MARGIN;\n\n return { left, top };\n}\n\n/**\n * Touch-only chip shown when editable link/button text is focused.\n * Replaces Ctrl/Cmd+click on coarse-pointer devices.\n */\nexport function LinkActionChip({ anchorRef, visible }: LinkActionChipProps) {\n const chipRef = useRef<HTMLButtonElement>(null);\n const [position, setPosition] = useState<{ left: number; top: number } | null>(null);\n\n useLayoutEffect(() => {\n if (!visible || !anchorRef.current) {\n setPosition(null);\n return;\n }\n\n const update = () => {\n const el = anchorRef.current;\n const chip = chipRef.current;\n if (!el) return;\n const rect = el.getBoundingClientRect();\n const width = chip?.offsetWidth ?? 120;\n const height = chip?.offsetHeight ?? MIN_TOUCH;\n setPosition(placeChip(rect, width, height));\n };\n\n update();\n window.addEventListener('scroll', update, true);\n window.addEventListener('resize', update);\n return () => {\n window.removeEventListener('scroll', update, true);\n window.removeEventListener('resize', update);\n };\n }, [visible, anchorRef]);\n\n if (!visible || !anchorRef.current) return null;\n\n const host = document.getElementById('setto-hint-root') ?? document.body;\n\n const style: React.CSSProperties = {\n position: 'fixed',\n left: position?.left ?? 0,\n top: position?.top ?? 0,\n visibility: position ? 'visible' : 'hidden',\n minHeight: MIN_TOUCH,\n minWidth: MIN_TOUCH,\n padding: '10px 14px',\n background: '#1a1a1a',\n color: '#fff',\n fontSize: 13,\n fontWeight: 500,\n border: 'none',\n borderRadius: 8,\n boxShadow: '0 4px 16px rgba(0,0,0,0.2)',\n fontFamily: 'system-ui, sans-serif',\n whiteSpace: 'nowrap',\n touchAction: 'manipulation',\n zIndex: 2147483647,\n };\n\n return createPortal(\n <button\n ref={chipRef}\n type=\"button\"\n data-setto-ui\n style={style}\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n const el = anchorRef.current;\n if (el) activateLinkContext(el);\n el?.blur();\n }}\n >\n Naviger ↗\n </button>,\n host,\n );\n}\n","/** Place the text caret at viewport coordinates inside a contentEditable element. */\nexport function placeCaretAtPoint(x: number, y: number, el: HTMLElement): void {\n el.focus();\n\n const doc = el.ownerDocument;\n const selection = doc.getSelection();\n if (!selection) return;\n\n const range = rangeFromPoint(doc, x, y);\n if (!range) return;\n\n if (!el.contains(range.startContainer)) {\n range.selectNodeContents(el);\n range.collapse(false);\n }\n\n selection.removeAllRanges();\n selection.addRange(range);\n}\n\nfunction rangeFromPoint(doc: Document, x: number, y: number): Range | null {\n if (doc.caretRangeFromPoint) {\n return doc.caretRangeFromPoint(x, y);\n }\n\n const legacy = doc as Document & {\n caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;\n };\n const pos = legacy.caretPositionFromPoint?.(x, y);\n if (!pos) return null;\n\n const range = doc.createRange();\n range.setStart(pos.offsetNode, pos.offset);\n range.collapse(true);\n return range;\n}\n","import { useSyncExternalStore } from 'react';\n\nconst QUERY = '(hover: none) and (pointer: coarse)';\n\nfunction subscribe(onChange: () => void): () => void {\n const mq = window.matchMedia(QUERY);\n mq.addEventListener('change', onChange);\n return () => mq.removeEventListener('change', onChange);\n}\n\nfunction getSnapshot(): boolean {\n return window.matchMedia(QUERY).matches;\n}\n\n/** True on touch-first devices (phones, tablets without hover). */\nexport function useCoarsePointer(): boolean {\n return useSyncExternalStore(subscribe, getSnapshot, () => false);\n}\n","import { useTranslation } from 'react-i18next';\nimport {\n useEffect,\n useRef,\n useState,\n type ClipboardEvent,\n type FocusEvent,\n type FormEvent,\n type KeyboardEvent,\n type MouseEvent,\n} from 'react';\nimport { LinkActionChip } from './edit-mode/link-action-chip';\nimport { isLinkContext } from './lib/link-context';\nimport { placeCaretAtPoint } from './lib/place-caret-at-point';\nimport { useCoarsePointer } from './lib/use-coarse-pointer';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\n\nexport interface TProps {\n /** The dotted translation key, e.g. 'hero.headline'. */\n k: string;\n}\n\n/**\n * Renders a translation key. In edit mode the text is contentEditable inline;\n * changes flow into the draft store for the active language.\n */\nexport function T({ k }: TProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guestEdit = useGuestEdit();\n const editable = editMode || guestEdit.active;\n const ref = useRef<HTMLSpanElement>(null);\n const [focused, setFocused] = useState(false);\n const [linkContext, setLinkContext] = useState(false);\n const coarsePointer = useCoarsePointer();\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const value = store ? store.get(k, i18n.language) : t(k);\n\n useEffect(() => {\n const el = ref.current;\n if (!el || focused || !editable) return;\n if (el.textContent !== value) el.textContent = value;\n }, [value, focused, editable]);\n\n if (!editable) return <>{value}</>;\n\n const handleMouseDown = (e: MouseEvent<HTMLSpanElement>) => {\n e.stopPropagation();\n const el = e.currentTarget;\n if (!isLinkContext(el)) return;\n if (e.ctrlKey || e.metaKey) return;\n e.preventDefault();\n };\n\n const handleMouseUp = (e: MouseEvent<HTMLSpanElement>) => {\n if (e.button !== 0) return;\n e.stopPropagation();\n const el = e.currentTarget;\n if (isLinkContext(el) && (e.ctrlKey || e.metaKey)) return;\n if (isLinkContext(el)) {\n placeCaretAtPoint(e.clientX, e.clientY, el);\n }\n };\n\n const handleClick = (e: MouseEvent<HTMLSpanElement>) => {\n e.stopPropagation();\n const el = e.currentTarget;\n if (isLinkContext(el) && (e.ctrlKey || e.metaKey)) return;\n if (isLinkContext(el)) {\n e.preventDefault();\n }\n };\n\n /** Block parent <button>/<a> activation (Space/Enter) while typing. */\n const handleKeyDown = (e: KeyboardEvent<HTMLSpanElement>) => {\n if (!isLinkContext(e.currentTarget)) return;\n e.stopPropagation();\n };\n\n const handleKeyUp = (e: KeyboardEvent<HTMLSpanElement>) => {\n if (!isLinkContext(e.currentTarget)) return;\n if (e.key === ' ' || e.key === 'Enter') {\n e.preventDefault();\n e.stopPropagation();\n }\n };\n\n const commit = (el: HTMLSpanElement) => {\n const text = el.textContent ?? '';\n store?.set(k, i18n.language, text);\n };\n\n const handleBlur = (e: FocusEvent<HTMLSpanElement>) => {\n setFocused(false);\n setLinkContext(false);\n commit(e.currentTarget);\n };\n\n const handleInput = (e: FormEvent<HTMLSpanElement>) => {\n store?.set(k, i18n.language, e.currentTarget.textContent ?? '');\n };\n\n const handlePaste = (e: ClipboardEvent<HTMLSpanElement>) => {\n e.preventDefault();\n const text = e.clipboardData.getData('text/plain');\n if (!text) return;\n const el = e.currentTarget;\n el.focus();\n document.execCommand('insertText', false, text);\n store?.set(k, i18n.language, el.textContent ?? '');\n };\n\n const lang = toBcp47(i18n.language);\n\n const showLinkChip = coarsePointer && focused && linkContext;\n\n return (\n <>\n <span\n ref={ref}\n data-setto-key={k}\n contentEditable\n suppressContentEditableWarning\n lang={lang}\n spellCheck={false}\n role=\"textbox\"\n tabIndex={0}\n onFocus={(e) => {\n setFocused(true);\n setLinkContext(isLinkContext(e.currentTarget));\n }}\n onBlur={handleBlur}\n onInput={handleInput}\n onPaste={handlePaste}\n onMouseDown={handleMouseDown}\n onMouseUp={handleMouseUp}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n onKeyUp={handleKeyUp}\n style={{\n cursor: 'text',\n color: 'inherit',\n outline: focused\n ? editMode\n ? '2px solid #640AFF'\n : '2px solid #C4502A'\n : undefined,\n outlineOffset: 2,\n borderRadius: 2,\n transition: 'outline-color 120ms',\n }}\n />\n {showLinkChip ? <LinkActionChip anchorRef={ref} visible={focused} /> : null}\n </>\n );\n}\n\n/** Map i18next language codes to BCP 47 for browser spellcheck. */\nfunction toBcp47(code: string): string {\n const base = (code.split('-')[0] ?? code).toLowerCase();\n if (base === 'no' || base === 'nb' || base === 'nn') return 'nb-NO';\n if (base === 'en') return 'en';\n return code;\n}\n","import { useSetto } from './provider';\n\n/**\n * Which section the editor has selected.\n *\n * A context of its own until 2026-09-09, when the section toolbar moved out to\n * the chrome served by setto-server. That bundle can call exactly one hook of\n * the host's — `useSetto` — so the state moved into the main context and this\n * became an adapter. Kept because `SettoSection` and `SettoBlock` read it on\n * every render of every page, and renaming that in thirteen pinned sites buys\n * nothing.\n */\nexport interface SectionEditContextValue {\n selectedId: string | null;\n selectSection: (id: string | null) => void;\n}\n\nexport function useSectionEdit(): SectionEditContextValue {\n const { selectedSectionId, selectSection } = useSetto();\n return { selectedId: selectedSectionId, selectSection };\n}\n","import type { CSSProperties, MouseEvent } from 'react';\n\n/** Returns true when the click target is editable text or Setto UI chrome. */\nexport function isTextEditClick(target: HTMLElement): boolean {\n if (target.closest('[data-setto-key]')) return true;\n if (target.closest('[data-setto-ui]')) return true;\n if (target.closest('[data-setto-icon]')) return true;\n if (target.closest('[data-setto-image]')) return true;\n if (target.closest('[data-setto-repeater]')) return true;\n let node: HTMLElement | null = target;\n while (node) {\n if (\n node.matches('h1,h2,h3,h4,h5,h6,p,li,figcaption') &&\n node.querySelector('[data-setto-key]')\n ) {\n return true;\n }\n node = node.parentElement;\n }\n return false;\n}\n\n/** True when the click landed on a nested theme target inside `container`. */\nexport function isNestedThemeTarget(\n target: HTMLElement,\n container: HTMLElement,\n): boolean {\n const hit = target.closest('[data-setto-section]');\n return !!(hit && hit !== container);\n}\n\nexport function handleThemeTargetClick(\n e: MouseEvent<HTMLElement>,\n editable: boolean,\n themeId: string,\n selected: boolean,\n selectSection: (id: string | null) => void,\n onClick?: (e: MouseEvent<HTMLElement>) => void,\n): void {\n onClick?.(e);\n if (!editable || e.defaultPrevented) return;\n\n const target = e.target as HTMLElement;\n if (isTextEditClick(target)) return;\n if (target.closest('a[href], button, input, textarea, select')) return;\n\n e.preventDefault();\n e.stopPropagation();\n selectSection(selected ? null : themeId);\n}\n\nexport function themeTargetEditStyle(\n editable: boolean,\n selected: boolean,\n accent = '#640AFF',\n): CSSProperties {\n if (!editable) return {};\n return {\n cursor: 'pointer',\n outline: selected ? `2px solid ${accent}` : undefined,\n outlineOffset: selected ? -2 : undefined,\n };\n}\n","import { useSyncExternalStore } from 'react';\nimport { useSetto } from './provider';\nimport { EMPTY_THEME_STORE_SNAPSHOT } from './lib/theme-store';\n\n/** Returns the current colour tokens for a section (live in edit mode). */\nexport function useSectionTheme(sectionId: string): Record<string, string> {\n const { themeStore, config } = useSetto();\n\n const version = useSyncExternalStore(\n (cb) => themeStore?.subscribe(() => cb()) ?? (() => {}),\n () => themeStore?.snapshot().version ?? EMPTY_THEME_STORE_SNAPSHOT.version,\n () => EMPTY_THEME_STORE_SNAPSHOT.version,\n );\n\n void version;\n\n if (themeStore) return themeStore.getSection(sectionId);\n return config.theme?.[sectionId] ?? {};\n}\n","import {\n forwardRef,\n useCallback,\n type ComponentPropsWithoutRef,\n type MouseEvent,\n} from 'react';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\nimport { useSectionEdit } from './section-context';\nimport {\n handleThemeTargetClick,\n isNestedThemeTarget,\n themeTargetEditStyle,\n} from './theme-target-utils';\nimport { useSectionTheme } from './use-section-theme';\n\nexport interface SettoSectionProps extends ComponentPropsWithoutRef<'section'> {\n /** Theme key, e.g. 'values'. */\n sectionId: string;\n}\n\n/**\n * Wraps a page section with theme-driven background colour and edit-mode\n * selection. Click the section chrome (not editable text or nested blocks)\n * to open the colour toolbar.\n *\n * The section also carries `id={sectionId}`, which is what makes a header's\n * `href=\"#produkter\"` land anywhere. Every generated site so far wrote that nav\n * and shipped it dead: the only handle on the element was\n * `data-setto-section`, an attribute no fragment identifier can address, and a\n * menu that silently does nothing looks exactly like a menu that works until\n * somebody taps it. An explicit `id` prop still wins — it is spread after this\n * one — so a page that needs a different anchor can say so.\n */\nexport const SettoSection = forwardRef<HTMLElement, SettoSectionProps>(\n function SettoSection({ sectionId, className, style, children, onClick, ...rest }, ref) {\n const { editMode } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const accent = editMode ? '#640AFF' : '#C4502A';\n const { selectedId, selectSection } = useSectionEdit();\n const colors = useSectionTheme(sectionId);\n const selected = selectedId === sectionId;\n\n const handleClick = useCallback(\n (e: MouseEvent<HTMLElement>) => {\n if (editable) {\n const target = e.target as HTMLElement;\n if (isNestedThemeTarget(target, e.currentTarget)) return;\n }\n handleThemeTargetClick(e, editable, sectionId, selected, selectSection, onClick);\n },\n [editable, onClick, selectSection, selected, sectionId],\n );\n\n const mergedStyle = {\n ...style,\n ...(colors.background ? { backgroundColor: colors.background } : {}),\n ...themeTargetEditStyle(editable, selected, accent),\n };\n\n return (\n <section\n ref={ref}\n id={sectionId}\n data-setto-section={sectionId}\n className={className}\n style={mergedStyle}\n onClick={handleClick}\n {...rest}\n >\n {children}\n </section>\n );\n },\n);\n","import {\n forwardRef,\n useCallback,\n type ComponentPropsWithoutRef,\n type MouseEvent,\n} from 'react';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\nimport { useSectionEdit } from './section-context';\nimport { handleThemeTargetClick, themeTargetEditStyle } from './theme-target-utils';\nimport { useSectionTheme } from './use-section-theme';\n\nexport interface SettoBlockProps extends ComponentPropsWithoutRef<'div'> {\n /** Theme key in sections.json, e.g. 'innovationCard'. */\n blockId: string;\n}\n\n/**\n * Themeable block (card, panel) inside a section. Click the block chrome to\n * edit its colours; click text to edit copy.\n */\nexport const SettoBlock = forwardRef<HTMLDivElement, SettoBlockProps>(\n function SettoBlock({ blockId, className, style, children, onClick, ...rest }, ref) {\n const { editMode } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const accent = editMode ? '#640AFF' : '#C4502A';\n const { selectedId, selectSection } = useSectionEdit();\n const colors = useSectionTheme(blockId);\n const selected = selectedId === blockId;\n\n const handleClick = useCallback(\n (e: MouseEvent<HTMLDivElement>) => {\n handleThemeTargetClick(\n e as MouseEvent<HTMLElement>,\n editable,\n blockId,\n selected,\n selectSection,\n onClick as ((e: MouseEvent<HTMLElement>) => void) | undefined,\n );\n },\n [editable, blockId, selected, selectSection, onClick],\n );\n\n const mergedStyle = {\n ...style,\n ...(colors.background ? { backgroundColor: colors.background } : {}),\n ...themeTargetEditStyle(editable, selected, accent),\n };\n\n return (\n <div\n ref={ref}\n data-setto-section={blockId}\n className={className}\n style={mergedStyle}\n onClick={handleClick}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n","import {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nexport interface PopoverPosition {\n top: number;\n left: number;\n}\n\ninterface FloatingPopoverProps {\n open: boolean;\n anchorRef: React.RefObject<HTMLElement | null>;\n onClose: () => void;\n ariaLabel: string;\n children: ReactNode;\n style?: CSSProperties;\n minWidth?: number;\n}\n\n/** Anchored popover portal used by icon picker and similar edit UI. */\nexport function FloatingPopover({\n open,\n anchorRef,\n onClose,\n ariaLabel,\n children,\n style,\n minWidth = 280,\n}: FloatingPopoverProps) {\n const popoverRef = useRef<HTMLDivElement>(null);\n const [pos, setPos] = useState<PopoverPosition | null>(null);\n\n useLayoutEffect(() => {\n if (!open || !anchorRef.current) {\n setPos(null);\n return;\n }\n\n const update = () => {\n const anchor = anchorRef.current;\n const pop = popoverRef.current;\n if (!anchor) return;\n\n const rect = anchor.getBoundingClientRect();\n const popoverH = pop?.offsetHeight ?? 200;\n const popoverW = pop?.offsetWidth ?? minWidth;\n\n let top = rect.bottom + 6;\n let left = rect.left;\n\n if (left + popoverW > window.innerWidth - 8) {\n left = window.innerWidth - popoverW - 8;\n }\n if (left < 8) left = 8;\n if (top + popoverH > window.innerHeight - 8) {\n top = rect.top - popoverH - 6;\n }\n if (top < 8) top = rect.bottom + 6;\n\n setPos({ top, left });\n };\n\n update();\n requestAnimationFrame(update);\n window.addEventListener('scroll', update, true);\n window.addEventListener('resize', update);\n return () => {\n window.removeEventListener('scroll', update, true);\n window.removeEventListener('resize', update);\n };\n }, [open, anchorRef, minWidth]);\n\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose();\n };\n window.addEventListener('keydown', onKey);\n return () => window.removeEventListener('keydown', onKey);\n }, [open, onClose]);\n\n useEffect(() => {\n if (!open) return;\n const close = (e: MouseEvent) => {\n const target = e.target as Node;\n if (anchorRef.current?.contains(target)) return;\n if (popoverRef.current?.contains(target)) return;\n onClose();\n };\n document.addEventListener('mousedown', close);\n return () => document.removeEventListener('mousedown', close);\n }, [open, onClose, anchorRef]);\n\n if (!open) return null;\n\n return createPortal(\n <div\n ref={popoverRef}\n role=\"dialog\"\n aria-label={ariaLabel}\n data-setto-ui\n style={{\n position: 'fixed',\n top: pos?.top ?? -9999,\n left: pos?.left ?? 0,\n visibility: pos ? 'visible' : 'hidden',\n zIndex: 2147483647,\n background: '#fff',\n border: '1px solid #e0e0e0',\n borderRadius: 8,\n boxShadow: '0 8px 24px rgba(0,0,0,0.15)',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n ...style,\n }}\n onMouseDown={(e) => e.stopPropagation()}\n onClick={(e) => e.stopPropagation()}\n >\n {children}\n </div>,\n document.body,\n );\n}\n","import {\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type CSSProperties,\n type MouseEvent,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { FloatingPopover } from './edit-mode/floating-popover';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\n\nexport interface SettoIconProps {\n /** i18n key storing the Lucide icon name, e.g. `problem.cards.complicated.icon`. */\n k: string;\n /** Map of icon name → Lucide component (provided by the host site). */\n icons: Record<string, ComponentType<SettoIconRenderProps>>;\n size?: number;\n className?: string;\n style?: CSSProperties;\n}\n\nexport interface SettoIconRenderProps {\n size?: number;\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * Renders an icon whose identity is stored in i18n. In edit mode, click to open\n * an icon browser and pick a replacement.\n */\nexport function SettoIcon({ k, icons, size = 24, className, style }: SettoIconProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const accent = editMode ? '#640AFF' : '#C4502A';\n const anchorRef = useRef<HTMLSpanElement>(null);\n const [open, setOpen] = useState(false);\n const [search, setSearch] = useState('');\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const iconName = store ? store.get(k, i18n.language) : t(k);\n const Icon = icons[iconName] ?? icons[Object.keys(icons)[0] ?? ''] ?? null;\n\n if (!Icon) return null;\n\n if (!editable) {\n return <Icon size={size} className={className} style={style} />;\n }\n\n const handleClick = (e: MouseEvent<HTMLSpanElement>) => {\n e.stopPropagation();\n e.preventDefault();\n setOpen((v) => !v);\n };\n\n const filtered = Object.entries(icons).filter(([name]) =>\n name.toLowerCase().includes(search.toLowerCase()),\n );\n\n return (\n <>\n <span\n ref={anchorRef}\n data-setto-icon\n data-setto-key={k}\n role=\"button\"\n tabIndex={0}\n aria-label=\"Velg ikon\"\n onClick={handleClick}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n setOpen((v) => !v);\n }\n }}\n style={{\n display: 'inline-flex',\n cursor: 'pointer',\n outline: open ? `2px solid ${accent}` : undefined,\n outlineOffset: 2,\n borderRadius: 4,\n }}\n >\n <Icon size={size} className={className} style={style} />\n </span>\n\n <FloatingPopover\n open={open}\n anchorRef={anchorRef}\n onClose={() => {\n setOpen(false);\n setSearch('');\n }}\n ariaLabel=\"Ikonvelger\"\n minWidth={320}\n style={{ padding: 12, maxWidth: 360 }}\n >\n <input\n type=\"search\"\n value={search}\n onChange={(e) => setSearch(e.target.value)}\n placeholder=\"Søk ikon…\"\n data-setto-ui\n style={{\n width: '100%',\n boxSizing: 'border-box',\n padding: '8px 10px',\n marginBottom: 10,\n border: '1px solid #e0e0e0',\n borderRadius: 6,\n fontSize: 13,\n }}\n />\n <div\n style={{\n display: 'grid',\n gridTemplateColumns: 'repeat(6, 1fr)',\n gap: 4,\n maxHeight: 240,\n overflowY: 'auto',\n }}\n >\n {filtered.map(([name, Item]) => {\n const selected = name === iconName;\n return (\n <button\n key={name}\n type=\"button\"\n title={name}\n data-setto-ui\n onClick={() => {\n store?.set(k, i18n.language, name);\n setOpen(false);\n setSearch('');\n }}\n style={{\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: 8,\n background: selected ? '#f5f3ff' : 'transparent',\n border: selected ? '1px solid #640AFF' : '1px solid transparent',\n borderRadius: 6,\n cursor: 'pointer',\n color: style?.color ?? 'currentColor',\n }}\n >\n <Item size={20} />\n </button>\n );\n })}\n </div>\n </FloatingPopover>\n </>\n );\n}\n","/**\n * Setto's public media store: the `setto-media` Vercel Blob store, where blog\n * photographs live instead of in each site's repo (R24). setto-server writes\n * to it (`blog/<siteId>/<hash>/<name>.<ext>`), a post refers to the URL, and\n * the site's Vercel Image Optimization resizes it through the\n * `remotePatterns` entry in `settoVercelImagesConfig`.\n *\n * One store for every site, so its host is a constant. It changes only if the\n * store is replaced — then here, in the server's token, and in each site's\n * `vercel.json`, together.\n */\nexport const SETTO_MEDIA_HOST = '3adyw42hy72dtzjo.public.blob.vercel-storage.com';\n\n/** Where blog photographs sit in the store. */\nexport const SETTO_MEDIA_BLOG_PREFIX = '/blog/';\n\n/** A blog photograph in Setto's media store: https, that host, under `/blog/`. */\nexport function isSettoMediaUrl(src: string | null | undefined): src is string {\n if (!src) return false;\n try {\n const url = new URL(src);\n return (\n url.protocol === 'https:' &&\n url.hostname === SETTO_MEDIA_HOST &&\n !url.username &&\n !url.password &&\n url.port === '' &&\n url.pathname.startsWith(SETTO_MEDIA_BLOG_PREFIX)\n );\n } catch {\n return false;\n }\n}\n","/**\n * Images through Vercel's Image Optimization, for sites that turned it on.\n *\n * A site keeps one original per image in its repository; the CDN makes each\n * width on first request, in AVIF or WebP as the browser accepts, and caches\n * it by the file's content. A site turns it on with two things that must\n * agree: `\"images\": { \"optimize\": true }` in `setto.config.json`, and an\n * `images` block in `vercel.json` whose `sizes` and `qualities` are exactly\n * the constants below — Vercel refuses a `w` or `q` it was not given. The\n * block, for copying: `settoVercelImagesConfig`.\n *\n * Blog photographs are the one exception to \"a file of this site's own\": they\n * live in Setto's media store (`./media.ts`) and reach the optimizer through\n * the block's `remotePatterns` entry. A site whose `vercel.json` predates that\n * entry gets a refusal from the optimizer, and `SettoImage` falls back to the\n * original, as it does for any failed variant.\n */\n\nimport { SETTO_MEDIA_BLOG_PREFIX, SETTO_MEDIA_HOST, isSettoMediaUrl } from './media';\n\nconst escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/** Phone, phone at 2–3×, tablet, laptop, wide and retina desktop. */\nexport const SETTO_IMAGE_WIDTHS = [384, 640, 828, 1080, 1440, 1920, 2560] as const;\n\n/** One quality for every image, so each width is one cached variant rather than several. */\nexport const SETTO_IMAGE_QUALITY = 75;\n\n/** The `images` block of `vercel.json` that matches `SettoImage`. */\nexport const settoVercelImagesConfig = {\n sizes: [...SETTO_IMAGE_WIDTHS],\n qualities: [SETTO_IMAGE_QUALITY],\n formats: ['image/avif', 'image/webp'],\n localPatterns: [{ pathname: '^/images/.*$', search: '' }],\n // Vercel reads hostname and pathname as regular expressions; anchored so a\n // look-alike host cannot borrow the optimizer. Checked on a deployment\n // (R24): this form resizes, an unlisted host or path is refused with 400.\n remotePatterns: [\n {\n protocol: 'https',\n hostname: `^${escapeRegExp(SETTO_MEDIA_HOST)}$`,\n pathname: `^${escapeRegExp(SETTO_MEDIA_BLOG_PREFIX)}.*$`,\n },\n ],\n minimumCacheTTL: 2678400,\n} as const;\n\n/** The formats Vercel transforms; anything else (SVG, GIF) is served as it is. */\nconst OPTIMIZABLE = /\\.(jpe?g|png|webp|avif)$/i;\n\n/**\n * Whether an image can go through the optimizer: a file of this site's own,\n * under `/images/`, or a blog photograph in Setto's media store, in a format\n * it transforms. A draft's `blob:` preview, any other external address, an\n * SVG logo and a moving GIF cannot.\n */\nexport function isOptimizable(src: string | null | undefined): src is string {\n if (!src) return false;\n if (src.startsWith('/images/')) return OPTIMIZABLE.test(src.split(/[?#]/)[0]!);\n return isSettoMediaUrl(src) && OPTIMIZABLE.test(new URL(src).pathname);\n}\n\n/**\n * Where there is no optimizer to ask: the Vite dev server and a local\n * preview. A deployment elsewhere without one (a build sandbox) is caught by\n * the image's own error instead.\n */\nexport function hasNoOptimizer(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname.endsWith('.localhost');\n}\n\nexport function optimizedUrl(src: string, width: number): string {\n return `/_vercel/image?url=${encodeURIComponent(src)}&w=${width}&q=${SETTO_IMAGE_QUALITY}`;\n}\n\nexport function optimizedSrcSet(src: string): string {\n return SETTO_IMAGE_WIDTHS.map((w) => `${optimizedUrl(src, w)} ${w}w`).join(', ');\n}\n","import {\n useEffect,\n useRef,\n useState,\n type ChangeEvent,\n type ImgHTMLAttributes,\n type MouseEvent,\n type SyntheticEvent,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { generateSettoImagePaths } from './lib/image-paths';\nimport { hasNoOptimizer, isOptimizable, optimizedSrcSet, optimizedUrl } from './lib/optimized-image';\nimport type { I18nStore } from './lib/i18n-store';\nimport { useSetto } from './provider';\nimport { useSettoChromeSlot } from './chrome';\n\nexport interface SettoImageProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {\n /** i18n key for the public URL path, e.g. `hero.illustrationSrc`. */\n srcKey: string;\n}\n\n/**\n * What the served chrome is handed to draw over an image in edit mode: the\n * picker with stock photographs, the camera, an upload and «prøv lykken».\n *\n * The chrome only ever gives the image a file. Where it came from — a\n * phone's camera or Unsplash — is the chrome's business; how it becomes a\n * draft and a published path is this component's, so every source ends up\n * under `public/images/setto/` the same way.\n */\nexport interface ImageToolsProps {\n srcKey: string;\n alt?: string;\n /** The pointer is over the image. */\n hovered: boolean;\n /** An unpublished replacement is showing. */\n hasDraft: boolean;\n busy: boolean;\n /** The rendered image, for its size and its place on the page. */\n imageEl: HTMLImageElement | null;\n applyFile: (file: File) => Promise<void>;\n revert: () => void;\n}\n\nconst ACCEPT = 'image/png,image/jpeg,image/webp,image/svg+xml';\n\nfunction setSrcAllLanguages(\n store: I18nStore,\n i18n: ReturnType<typeof useTranslation>['i18n'],\n srcKey: string,\n value: string,\n): void {\n const langs = i18n.languages?.length ? i18n.languages : [i18n.language];\n for (const lng of langs) {\n store.set(srcKey, lng, value);\n }\n}\n\n/**\n * The image as a visitor gets it.\n *\n * On a site with optimization on, a `srcSet` of widths from Vercel's\n * optimizer, so a phone fetches a phone-sized WebP or AVIF instead of the\n * 2000-pixel original. `sizes` is the site's to give where the image is\n * narrower than the screen; without it the browser assumes the full width,\n * which is never too small, only sometimes larger than needed. If the\n * optimizer does not answer — a build sandbox has none, a plan can run out —\n * the image falls back to its original, so an image is never lost to it.\n * Edit mode never gets here: it shows drafts, which the optimizer cannot see.\n */\nfunction PublishedImage({\n src,\n optimize,\n sizes,\n srcSet,\n onError,\n ...rest\n}: ImgHTMLAttributes<HTMLImageElement> & { src: string; optimize: boolean }) {\n const [direct, setDirect] = useState(false);\n const optimized =\n optimize &&\n !direct &&\n !srcSet &&\n isOptimizable(src) &&\n !(typeof window !== 'undefined' && hasNoOptimizer(window.location.hostname));\n\n if (!optimized) return <img src={src} srcSet={srcSet} sizes={sizes} onError={onError} {...rest} />;\n return (\n <img\n src={optimizedUrl(src, 1080)}\n srcSet={optimizedSrcSet(src)}\n sizes={sizes ?? '100vw'}\n onError={(e: SyntheticEvent<HTMLImageElement, Event>) => {\n setDirect(true);\n onError?.(e);\n }}\n {...rest}\n />\n );\n}\n\n/**\n * Renders an image whose src is stored in i18n. In edit mode, hover to upload\n * a replacement — saved under `public/images/setto/` on publish.\n */\nexport function SettoImage({ srcKey, alt, className, style, ...rest }: SettoImageProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store, assetStore, config } = useSetto();\n const fileRef = useRef<HTMLInputElement>(null);\n const [hovered, setHovered] = useState(false);\n const [uploading, setUploading] = useState(false);\n const imgRef = useRef<HTMLImageElement>(null);\n const Tools = useSettoChromeSlot<ImageToolsProps>('image-tools');\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const [, forceAssets] = useState(0);\n useEffect(() => {\n if (!assetStore) return;\n return assetStore.subscribe(() => forceAssets((x) => x + 1));\n }, [assetStore]);\n\n const srcPath = store ? store.get(srcKey, i18n.language) : t(srcKey);\n const previewUrl = assetStore?.getPreviewUrl(srcKey);\n const src = previewUrl ?? srcPath;\n\n if (!editMode) {\n return (\n <PublishedImage\n src={srcPath}\n optimize={config.images?.optimize === true}\n alt={alt}\n className={className}\n style={style}\n {...rest}\n />\n );\n }\n\n const isFullWidth = className?.includes('w-full');\n const isFullHeight = className?.includes('h-full');\n\n const openFilePicker = (e: MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n if (!uploading) fileRef.current?.click();\n };\n\n const applyFile = async (file: File) => {\n if (!assetStore || !store) return;\n setUploading(true);\n try {\n const originalPublicPath = store.original(srcKey, i18n.language);\n const { repoPath, publicPath } = generateSettoImagePaths(srcKey, file);\n await assetStore.set({\n srcKey,\n originalPublicPath,\n repoPath,\n publicPath,\n file,\n });\n setSrcAllLanguages(store, i18n, srcKey, publicPath);\n } finally {\n setUploading(false);\n }\n };\n\n const handleFile = async (e: ChangeEvent<HTMLInputElement>) => {\n const file = e.target.files?.[0];\n e.target.value = '';\n if (file) await applyFile(file);\n };\n\n const revert = () => {\n if (!assetStore || !store) return;\n const original = assetStore.revert(srcKey);\n if (original !== null) {\n setSrcAllLanguages(store, i18n, srcKey, original);\n }\n };\n\n const handleRevert = (e: MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n if (!assetStore || !store) return;\n const original = assetStore.revert(srcKey);\n if (original !== null) {\n setSrcAllLanguages(store, i18n, srcKey, original);\n }\n };\n\n return (\n <>\n <span\n data-setto-image\n data-setto-src-key={srcKey}\n data-setto-ui\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n style={{\n display: isFullWidth || isFullHeight ? 'block' : 'inline-block',\n width: isFullWidth ? '100%' : undefined,\n height: isFullHeight ? '100%' : undefined,\n position: 'relative',\n outline: hovered ? '2px solid #640AFF' : undefined,\n outlineOffset: 2,\n borderRadius: 4,\n }}\n >\n <img ref={imgRef} src={src} alt={alt} className={className} style={style} {...rest} />\n\n {Tools ? (\n <Tools\n srcKey={srcKey}\n alt={alt}\n hovered={hovered}\n hasDraft={Boolean(previewUrl)}\n busy={uploading}\n imageEl={imgRef.current}\n applyFile={applyFile}\n revert={revert}\n />\n ) : null}\n\n {previewUrl && !hovered && !Tools ? (\n <span\n aria-hidden\n data-setto-ui\n style={{\n position: 'absolute',\n top: 4,\n right: 4,\n background: '#640AFF',\n color: '#fff',\n fontSize: 10,\n padding: '2px 6px',\n borderRadius: 4,\n fontFamily: 'system-ui, sans-serif',\n pointerEvents: 'none',\n }}\n >\n Nytt bilde\n </span>\n ) : null}\n\n {hovered && !Tools ? (\n <span\n data-setto-ui\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 8,\n background: 'rgba(0, 0, 0, 0.45)',\n borderRadius: 4,\n }}\n >\n <button\n type=\"button\"\n data-setto-ui\n disabled={uploading}\n onClick={openFilePicker}\n onMouseDown={(e) => e.stopPropagation()}\n style={{\n padding: '10px 18px',\n background: '#fff',\n color: '#222',\n border: 'none',\n borderRadius: 6,\n fontSize: 13,\n fontWeight: 500,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: uploading ? 'wait' : 'pointer',\n boxShadow: '0 2px 8px rgba(0,0,0,0.2)',\n }}\n >\n {uploading ? 'Laster opp…' : 'Velg fil…'}\n </button>\n {previewUrl ? (\n <button\n type=\"button\"\n data-setto-ui\n disabled={uploading}\n onClick={handleRevert}\n onMouseDown={(e) => e.stopPropagation()}\n style={{\n padding: '6px 12px',\n background: 'transparent',\n color: '#fff',\n border: '1px solid rgba(255,255,255,0.6)',\n borderRadius: 6,\n fontSize: 12,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: uploading ? 'wait' : 'pointer',\n }}\n >\n Angre\n </button>\n ) : null}\n </span>\n ) : null}\n </span>\n\n <input\n ref={fileRef}\n type=\"file\"\n accept={ACCEPT}\n hidden\n onChange={handleFile}\n />\n </>\n );\n}\n","import { Fragment, useEffect, useState, type CSSProperties, type ReactNode } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useGuestEdit } from './guest-edit';\nimport { useSetto } from './provider';\n\nexport interface SettoRepeaterProps {\n /** List prefix in i18n, e.g. `faq.items`. */\n itemsKey: string;\n /** Default field values for a newly added item. */\n defaultItem: Record<string, string>;\n /** Label shown on add/remove controls. */\n itemLabel?: string;\n children: (itemKey: string, index: number) => ReactNode;\n className?: string;\n}\n\nconst STYLE_ID = 'setto-repeater-styles';\n\n/** Hover-reveal styles for the remove button — injected once per document. */\nfunction useRepeaterStyles() {\n useEffect(() => {\n if (document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = `\n .setto-repeater-remove {\n opacity: 0;\n transition: opacity 120ms ease;\n }\n .setto-repeater-item:hover .setto-repeater-remove,\n .setto-repeater-remove:focus-visible {\n opacity: 1;\n }\n @media (hover: none) {\n .setto-repeater-remove { opacity: 1; }\n }\n `;\n document.head.appendChild(el);\n }, []);\n}\n\n/**\n * Renders a dynamic list from i18n. In edit mode, editors can add items (button\n * at the end of the list) and remove items (round × revealed on hover).\n *\n * The published site gets no per-item wrapper — only the editor does.\n *\n * The wrapper exists to give the remove button something to be absolutely\n * positioned against, which is edit chrome and has no business in the output.\n * Leaving it in cost real layout: an item styled `border-b py-7 first:pt-0` is\n * the *only* child of its own wrapper, so `:first-child` matched every item and\n * `pt-0` won on all of them — every row in a repeated list sat flush on the\n * rule above it instead of clearing it by 28px. The same trap catches `last:`,\n * `odd:`, `even:` and `:not(:last-child)`; `last:border-b-0` would have erased\n * every divider on the page.\n *\n * Worse, it was invisible while authoring: in edit mode the remove button is\n * rendered before the children, so the item is not `:first-child` there and the\n * padding appears. The editor showed the correct layout and the published site\n * shipped the broken one. Dropping the wrapper from the published output is\n * what brings the two back into agreement.\n */\nexport function SettoRepeater({\n itemsKey,\n defaultItem,\n itemLabel = 'element',\n children,\n className,\n}: SettoRepeaterProps) {\n const { i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guest = useGuestEdit();\n const editable = editMode || guest.active;\n const lng = i18n.language;\n\n useRepeaterStyles();\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const keys = store ? store.getListKeys(itemsKey, lng) : [];\n\n const handleAdd = () => {\n store?.addListItem(itemsKey, lng, defaultItem);\n };\n\n const handleRemove = (itemKey: string) => {\n if (keys.length <= 1) return;\n store?.removeListItem(itemsKey, itemKey, lng);\n };\n\n const canRemove = keys.length > 1;\n\n return (\n <div className={className} data-setto-repeater>\n {keys.map((itemKey, index) =>\n editable ? (\n <div key={itemKey} className=\"setto-repeater-item\" style={{ position: 'relative' }}>\n {canRemove ? (\n <button\n type=\"button\"\n data-setto-ui\n className=\"setto-repeater-remove\"\n aria-label={`Fjern ${itemLabel}`}\n title={`Fjern ${itemLabel}`}\n onClick={(e) => {\n e.stopPropagation();\n handleRemove(itemKey);\n }}\n style={removeBtnStyle}\n >\n ×\n </button>\n ) : null}\n {children(itemKey, index)}\n </div>\n ) : (\n <Fragment key={itemKey}>{children(itemKey, index)}</Fragment>\n ),\n )}\n\n {editable ? (\n <div\n data-setto-ui\n style={{\n display: 'flex',\n justifyContent: 'flex-end',\n marginTop: 8,\n }}\n >\n <button\n type=\"button\"\n data-setto-ui\n onClick={(e) => {\n e.stopPropagation();\n handleAdd();\n }}\n style={addBtnStyle}\n >\n + Legg til {itemLabel}\n </button>\n </div>\n ) : null}\n </div>\n );\n}\n\nconst addBtnStyle: CSSProperties = {\n padding: '6px 10px',\n background: '#f7f7f7',\n border: '1px solid #e0e0e0',\n borderRadius: 6,\n fontSize: 12,\n color: '#444',\n cursor: 'pointer',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nconst removeBtnStyle: CSSProperties = {\n position: 'absolute',\n top: 4,\n right: 4,\n zIndex: 2,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n width: 24,\n height: 24,\n padding: 0,\n background: '#ffffff',\n border: '1px solid #e0e0e0',\n borderRadius: '50%',\n fontSize: 16,\n lineHeight: 1,\n color: '#444',\n cursor: 'pointer',\n boxShadow: '0 1px 4px rgba(0,0,0,0.18)',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n","/**\n * A page's own title and description, shared by the build (`settoBlog()`\n * writes `<route>/index.html` with them) and the browser (`SettoPage` sets\n * `document.title`), so the head a crawler reads without JavaScript and the\n * one it reads after rendering are the same answer.\n *\n * Pure and dependency-free: the browser bundle and the Node plugin both\n * import it.\n */\n\n/**\n * The `<meta name>` the build writes on every page it gives a head of its\n * own: the front page's title, which a page's title is built on. Without it\n * the browser could only take `document.title` as the base, which on such a\n * page is already the page's own title, and «Priser · Priser · …» follows.\n */\nexport const TITLE_BASE_META = 'setto:title-base';\n\n/** A run of four or more capitals and not one small letter: «DIN FRISØR AS». */\nexport const isAllCaps = (value: string) => !/\\p{Ll}/u.test(value) && /\\p{Lu}{4,}/u.test(value);\n\n/** «Nordvik Rør» from «Nordvik Rør – rørlegger i Ålesund». */\nexport function nameFromTitle(title: string | undefined): string | undefined {\n if (!title) return undefined;\n const separator = /\\s(?:–|—|\\||-)\\s/.exec(title);\n const name = (separator ? title.slice(0, separator.index) : title).replace(/\\s+/g, ' ').trim();\n return name && !isAllCaps(name) ? name : undefined;\n}\n\n/**\n * A page's title from its own (`pages.priser`: «Priser») and the front\n * page's («Sportsparken Vegsund – aktivitetspark i Ålesund»):\n * «Priser · Sportsparken Vegsund – aktivitetspark i Ålesund».\n *\n * A page title that already names the business («Prisar – Hundeidvik\n * Familiepark») is a whole title and is used as it is.\n */\nexport function pageTitle(title: string | undefined | null, base: string | undefined | null): string {\n const own = title?.replace(/\\s+/g, ' ').trim() ?? '';\n const front = base?.replace(/\\s+/g, ' ').trim() ?? '';\n if (!own) return front;\n if (!front || own === front) return own;\n const name = nameFromTitle(front);\n if (name && own.toLowerCase().includes(name.toLowerCase())) return own;\n return `${own} · ${front}`;\n}\n\n/**\n * Where a page's description lives: beside a title key that ends in\n * `.title` (`pages.prisar.title` → `pages.prisar.description`). A title key\n * that is a string of its own (`pages.priser`) has nowhere beside it, and the\n * page takes the site's description.\n */\nexport function descriptionKeyFor(titleKey: string): string | null {\n return titleKey.endsWith('.title') ? `${titleKey.slice(0, -'.title'.length)}.description` : null;\n}\n","import {\n Fragment,\n useEffect,\n useRef,\n useSyncExternalStore,\n type ComponentType,\n type CSSProperties,\n type ReactNode,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useSetto } from '../provider';\nimport { useSettoChromeSlot } from '../chrome';\nimport { SettoSection } from '../SettoSection';\nimport { SettoRepeater } from '../SettoRepeater';\nimport { T } from '../T';\nimport { EMPTY_PAGE_STORE_SNAPSHOT } from '../lib/page-store';\nimport { bundledManifest } from './bundled';\nimport {\n builtinKeys,\n pageById,\n pageForPath,\n ownerMenu,\n visibleMenu,\n type BuiltinSectionType,\n type MenuItem,\n type MenuList,\n type PageEntry,\n type PageSection,\n type PagesManifest,\n} from './manifest';\nimport { SettoBlogLatest, SettoBlogSection } from '../blog/SettoBlog';\nimport { pageTitle, TITLE_BASE_META } from './head';\n\n/**\n * The manifest as it stands now, drafts included, re-rendering on change.\n * `null` on a site that has none.\n */\nexport function usePageManifest(): PagesManifest | null {\n const { pageStore, config } = useSetto();\n const snap = useSyncExternalStore(\n (cb) => pageStore?.subscribe(() => cb()) ?? (() => {}),\n () => pageStore?.snapshot() ?? EMPTY_PAGE_STORE_SNAPSHOT,\n () => pageStore?.snapshot() ?? EMPTY_PAGE_STORE_SNAPSHOT,\n );\n // Before the store exists — the first render — the bundled file is the truth.\n return pageStore ? snap.manifest : bundledManifest(config.pages);\n}\n\n/**\n * The links a menu or footer should show, or `null` when the site has no\n * manifest and its own hard-coded list is still the truth.\n *\n * Already filtered: hidden links, links to hidden pages and anchors to hidden\n * sections are gone. Render each label with `<T k={item.labelKey} />`.\n *\n * The signed-in owner also gets the blog's link while the blog has no posts\n * (`ownerMenu`), marked `dimmed` and drawn faded by a stylesheet this hook\n * adds, so no site's navbar has to know about it.\n */\nexport function useSettoMenu(list: MenuList = 'menu'): Array<MenuItem & { dimmed?: true }> | null {\n const manifest = usePageManifest();\n const { canEdit, config } = useSetto();\n const blogEmpty = (config.blog?.posts.length ?? 0) === 0;\n const items: Array<MenuItem & { dimmed?: true }> | null = manifest\n ? canEdit\n ? ownerMenu(manifest, list, blogEmpty)\n : visibleMenu(manifest, list)\n : null;\n const dimmed = items?.filter((item) => item.dimmed).map((item) => item.href) ?? [];\n useDimmedLinks(dimmed, config.languages ?? []);\n return items;\n}\n\nconst DIM_STYLE_ID = 'setto-dimmed-links';\n\n/*\n * One stylesheet for every menu on the page. A site draws `useSettoMenu` in\n * several places — the menu, the footer, a phone's drawer — and each says\n * what it dims; the sheet is the union, so a footer with nothing to dim does\n * not undo the menu's.\n */\nconst dimmedBy = new Map<object, string[]>();\n\nfunction drawDimmedLinks() {\n if (typeof document === 'undefined') return;\n const selectors = [...new Set([...dimmedBy.values()].flat())];\n let style = document.getElementById(DIM_STYLE_ID);\n if (!selectors.length) {\n style?.remove();\n return;\n }\n if (!style) {\n style = document.createElement('style');\n style.id = DIM_STYLE_ID;\n document.head.appendChild(style);\n }\n style.textContent = `${selectors.join(',')}{opacity:.45;transition:opacity .15s}${selectors.map((s) => `${s}:hover`).join(',')}{opacity:.8}`;\n}\n\n/** Fades the owner-only links wherever the site draws them, in every language's prefix. */\nfunction useDimmedLinks(hrefs: string[], languages: string[]) {\n const key = hrefs.join('|');\n const langs = languages.join(',');\n useEffect(() => {\n if (!key) return;\n const mine = {};\n dimmedBy.set(\n mine,\n key.split('|').flatMap((href) => [\n `a[href=\"${href}\"]`,\n ...langs\n .split(',')\n .slice(1)\n .filter(Boolean)\n .map((language) => `a[href=\"/${language}${href}\"]`),\n ]),\n );\n drawDimmedLinks();\n return () => {\n dimmedBy.delete(mine);\n drawDimmedLinks();\n };\n }, [key, langs]);\n}\n\n/** What a built-in section's renderer is given. */\nexport interface BuiltinSectionProps {\n sectionId: string;\n /** The first visible section on a page gets the page's `h1`. */\n first: boolean;\n}\n\nexport interface SettoPageProps {\n /** The page to render. Wins over `path`. */\n pageId?: string;\n /** Or the one living at this path — the router's pathname, for a catch-all route. */\n path?: string;\n /**\n * The site's own sections, by section id.\n *\n * The manifest decides their order and which are hidden. A component listed\n * here that the manifest does not mention is rendered after the rest, so a\n * section added in code never silently disappears.\n */\n sections?: Record<string, ComponentType>;\n /** A site's own look for a built-in section type. */\n builtins?: Partial<Record<BuiltinSectionType, ComponentType<BuiltinSectionProps>>>;\n /** Shown when no page lives at `path`, or a visitor reaches a hidden one. */\n fallback?: ReactNode;\n}\n\n/**\n * A page, drawn from the manifest.\n *\n * Two ways in. A page the site wrote in code names itself:\n *\n * <SettoPage pageId=\"home\" sections={{ hero: Hero, services: Services }} />\n *\n * and a catch-all route renders whatever the owner added since:\n *\n * <Route path=\"*\" element={<SettoPage path={pathname} fallback={<NotFound />} />} />\n *\n * Without a manifest it renders `sections` in the order given, which is what\n * the page did before it had one.\n */\nexport function SettoPage({ pageId, path, sections = {}, builtins, fallback = null }: SettoPageProps) {\n const manifest = usePageManifest();\n const { editMode } = useSetto();\n\n if (!manifest) {\n if (!pageId && path !== undefined && path !== '/' && path !== '') return <>{fallback}</>;\n return (\n <>\n {Object.entries(sections).map(([id, Component]) => (\n <Component key={id} />\n ))}\n </>\n );\n }\n\n const page = pageId ? pageById(manifest, pageId) : pageForPath(manifest, path ?? '/');\n if (!page) {\n // A page written in code, not yet in the manifest: render it as it was.\n if (pageId) {\n return (\n <>\n {Object.entries(sections).map(([id, Component]) => (\n <Component key={id} />\n ))}\n </>\n );\n }\n return <>{fallback}</>;\n }\n if (page.hidden && !editMode) return <>{fallback}</>;\n\n return (\n <PageBody page={page} sections={sections} builtins={builtins} editMode={editMode} manifest={manifest} />\n );\n}\n\nfunction PageBody({\n page,\n sections,\n builtins,\n editMode,\n manifest,\n}: {\n page: PageEntry;\n sections: Record<string, ComponentType>;\n builtins?: SettoPageProps['builtins'];\n editMode: boolean;\n manifest: PagesManifest;\n}) {\n usePageTitle(page);\n const HiddenPageNote = useSettoChromeSlot<{ pageId: string }>('hidden-page');\n\n const listed = new Set(manifest.pages.flatMap((p) => p.sections.map((s) => s.id)));\n const unlisted = Object.keys(sections).filter((id) => !listed.has(id));\n const firstVisible = page.sections.find((s) => !s.hidden && (s.type || sections[s.id]))?.id;\n\n return (\n <>\n {page.hidden && editMode ? (\n HiddenPageNote ? <HiddenPageNote pageId={page.id} /> : <HiddenNote text=\"Denne siden er skjult for besøkende.\" />\n ) : null}\n {page.sections.map((section) => (\n <Fragment key={section.id}>\n {renderSection(section, sections, builtins, editMode, section.id === firstVisible)}\n </Fragment>\n ))}\n {unlisted.map((id) => {\n const Component = sections[id]!;\n return <Component key={id} />;\n })}\n </>\n );\n}\n\nfunction renderSection(\n section: PageSection,\n sections: Record<string, ComponentType>,\n builtins: SettoPageProps['builtins'],\n editMode: boolean,\n first: boolean,\n): ReactNode {\n if (section.hidden) {\n return editMode ? <HiddenSection section={section} /> : null;\n }\n if (section.type) {\n const Builtin = builtins?.[section.type] ?? BUILTIN_RENDERERS[section.type];\n return <Builtin sectionId={section.id} first={first} />;\n }\n const Component = sections[section.id];\n if (!Component) {\n warnOnce(section.id);\n return null;\n }\n return <Component />;\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(id: string) {\n if (warned.has(id)) return;\n warned.add(id);\n console.warn(`[setto] section \"${id}\" is in pages.json but the page does not provide it`);\n}\n\n/**\n * A hidden section, as the owner sees it: a line saying it is there and a\n * way to bring it back. The chrome draws the real one; this is what shows\n * when it has not arrived.\n */\nfunction HiddenSection({ section }: { section: PageSection }) {\n const { pageStore } = useSetto();\n const Offered = useSettoChromeSlot<{ sectionId: string; label: string }>('hidden-section');\n const label = section.label ?? section.id;\n if (Offered) return <Offered sectionId={section.id} label={label} />;\n return (\n <div data-setto-ui style={hiddenBarStyle}>\n <span>Skjult: {label}</span>\n {pageStore ? (\n <button\n type=\"button\"\n data-setto-ui\n style={hiddenBtnStyle}\n onClick={() => pageStore.apply([{ op: 'show_section', sectionId: section.id }])}\n >\n Vis\n </button>\n ) : null}\n </div>\n );\n}\n\nfunction HiddenNote({ text }: { text: string }) {\n return (\n <div data-setto-ui style={hiddenBarStyle}>\n <span>{text}</span>\n </div>\n );\n}\n\n/** The tab says which page this is, for every page but the front. */\n/**\n * The tab says which page this is: `pageTitle(<page>, <front page>)`, the\n * title the build wrote into this page's own `index.html` (0.50.0). The\n * front page's title is read from `<meta name=\"setto:title-base\">` where the\n * build wrote one — on such a page `document.title` is already the page's\n * own title, and building on it gave «Priser · Priser · …».\n */\nfunction usePageTitle(page: PageEntry) {\n const { t } = useTranslation();\n const original = useRef<string | null>(null);\n const title = page.path === '/' ? null : t(page.titleKey);\n useEffect(() => {\n if (!title || typeof document === 'undefined') return;\n original.current ??=\n document.querySelector<HTMLMetaElement>(`meta[name=\"${TITLE_BASE_META}\"]`)?.content || document.title;\n const base = original.current;\n document.title = pageTitle(title, base);\n return () => {\n document.title = base;\n };\n }, [title]);\n}\n\n// ── Built-in sections ───────────────────────────────────────────────────────\n\n/**\n * Headings and paragraphs, for terms, privacy and the like.\n *\n * Styled inline and from the page it sits in — its font, its colours — because\n * the library cannot know the site's Tailwind classes, and a Tailwind class\n * written here would be purged from the site's CSS anyway. A site that wants\n * its own look passes `builtins={{ text: MyText }}`.\n */\nexport function SettoTextSection({ sectionId, first }: BuiltinSectionProps) {\n const keys = builtinKeys(sectionId);\n const { i18n } = useTranslation();\n const { store, editMode } = useSetto();\n const intro = store ? store.get(keys.intro, i18n.language) : i18n.t(keys.intro, { defaultValue: '' });\n const Heading = first ? 'h1' : 'h2';\n\n return (\n <SettoSection sectionId={sectionId} style={textSectionStyle}>\n <div style={textInnerStyle}>\n <Heading style={first ? textH1Style : textH2Style}>\n <T k={keys.heading} />\n </Heading>\n {intro || editMode ? (\n <p style={textIntroStyle}>\n <T k={keys.intro} />\n </p>\n ) : null}\n <SettoRepeater\n itemsKey={keys.items}\n defaultItem={{ heading: 'Overskrift', text: 'Tekst' }}\n itemLabel=\"avsnitt\"\n >\n {(itemKey) => <TextItem sectionId={sectionId} itemKey={itemKey} />}\n </SettoRepeater>\n </div>\n </SettoSection>\n );\n}\n\nfunction TextItem({ sectionId, itemKey }: { sectionId: string; itemKey: string }) {\n const keys = builtinKeys(sectionId);\n const { i18n } = useTranslation();\n const { store, editMode } = useSetto();\n const heading = store\n ? store.get(keys.itemHeading(itemKey), i18n.language)\n : i18n.t(keys.itemHeading(itemKey), { defaultValue: '' });\n return (\n <div style={textItemStyle}>\n {heading || editMode ? (\n <h3 style={textH3Style}>\n <T k={keys.itemHeading(itemKey)} />\n </h3>\n ) : null}\n <p style={textParagraphStyle}>\n <T k={keys.itemText(itemKey)} />\n </p>\n </div>\n );\n}\n\nconst BUILTIN_RENDERERS: Record<BuiltinSectionType, ComponentType<BuiltinSectionProps>> = {\n text: SettoTextSection,\n blog: SettoBlogSection,\n 'blog-latest': SettoBlogLatest,\n};\n\n// ── Styles ──────────────────────────────────────────────────────────────────\n\nconst textSectionStyle: CSSProperties = { padding: 'clamp(48px, 8vw, 96px) 16px' };\nconst textInnerStyle: CSSProperties = { maxWidth: '68ch', margin: '0 auto' };\nconst textH1Style: CSSProperties = {\n fontFamily: 'var(--setto-display-font, inherit)',\n fontSize: 'clamp(2rem, 4vw, 2.75rem)',\n lineHeight: 1.15,\n fontWeight: 600,\n margin: '0 0 0.75em',\n};\nconst textH2Style: CSSProperties = { ...textH1Style, fontSize: 'clamp(1.5rem, 3vw, 2rem)' };\nconst textH3Style: CSSProperties = {\n fontFamily: 'var(--setto-display-font, inherit)',\n fontSize: '1.125rem',\n lineHeight: 1.3,\n fontWeight: 600,\n margin: '0 0 0.4em',\n};\nconst textIntroStyle: CSSProperties = { fontSize: '1.125rem', lineHeight: 1.6, opacity: 0.85, margin: '0 0 2em' };\nconst textItemStyle: CSSProperties = { margin: '0 0 1.75em' };\nconst textParagraphStyle: CSSProperties = { lineHeight: 1.7, margin: 0, whiteSpace: 'pre-line' };\n\nconst hiddenBarStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 12,\n padding: '10px 16px',\n margin: '4px 0',\n border: '1px dashed rgba(100, 10, 255, 0.45)',\n borderRadius: 8,\n background: 'rgba(100, 10, 255, 0.05)',\n color: '#3b2a66',\n font: '500 13px system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\nconst hiddenBtnStyle: CSSProperties = {\n border: 'none',\n borderRadius: 999,\n padding: '4px 12px',\n background: '#640AFF',\n color: '#fff',\n font: '600 12px system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: 'pointer',\n};\n","/**\n * The blog post contract, version 1.\n *\n * A post is an MDX file in the site's repo, at\n * `src/content/blog/<slug>.<locale>.mdx`. The file is the record, so its shape\n * is a contract between everything that touches it: Pixel, which writes it;\n * setto-server, which validates and commits it; the click-to-edit path, which\n * patches one paragraph or one image in it; and this library, which renders\n * it. A redesign of the blog may change how a component looks, never its name,\n * its props or where posts live — old posts must keep rendering.\n *\n * MDX compiles to JavaScript, and these files are written by a model and\n * patched by owners. So the contract is closed: frontmatter with known keys,\n * CommonMark (plus GFM tables and strikethrough), and the four components\n * below with quoted string props. No `import`, no `export`, no `{…}`. A post\n * is data that happens to use JSX syntax, and is rendered from its syntax\n * tree — it is never compiled and never run.\n *\n * Changing anything here is a contract change: bump `BLOG_CONTRACT_VERSION`\n * and migrate the posts that exist, in the same release.\n */\n\nexport const BLOG_CONTRACT_VERSION = 1;\n\n/** Where published posts live, relative to the site repo root. */\nexport const BLOG_DIR = 'src/content/blog';\n\n/** The public route the blog is served under. */\nexport const BLOG_ROUTE = '/blogg';\n\n/** Lowercase words joined by single hyphens: `ny-kaffemaskin-i-butikken`. */\nexport const BLOG_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nexport const BLOG_SLUG_MAX = 80;\n\n/** A site language code, as the locale files use them: `no`, `en`, `sv`. */\nexport const BLOG_LOCALE_PATTERN = /^[a-z]{2,3}$/;\n\n/** Hard ceiling on a post file, so a runaway generation cannot be committed. */\nexport const BLOG_MAX_SOURCE_LENGTH = 200_000;\n\nexport interface BlogFrontmatter {\n /** The post's only top-level heading; the body starts at `##`. */\n title: string;\n /** The lead under the title, the meta description and the share text. */\n description: string;\n /** Publication date, `YYYY-MM-DD`. */\n date: string;\n /** Must match the file name. */\n slug: string;\n /** Must match the file name. */\n locale: string;\n /** Cover image (https), also the share image. Optional: the site's own is the fallback. */\n cover?: string;\n tags?: string[];\n}\n\nexport const BLOG_FRONTMATTER_KEYS = [\n 'title',\n 'description',\n 'date',\n 'slug',\n 'locale',\n 'cover',\n 'tags',\n] as const satisfies readonly (keyof BlogFrontmatter)[];\n\nexport const BLOG_TITLE_MAX = 120;\nexport const BLOG_DESCRIPTION_MAX = 300;\nexport const BLOG_TAGS_MAX = 8;\nexport const BLOG_TAG_MAX = 40;\n\nexport type BlogPropKind = 'text' | 'image-url' | 'youtube-id' | 'enum';\n\nexport interface BlogPropSpec {\n kind: BlogPropKind;\n required: boolean;\n /** For `text`: the longest value accepted. */\n max?: number;\n /** For `enum`: the accepted values. */\n values?: readonly string[];\n}\n\n/**\n * What a component may contain:\n * - `none`: self-closing, no children;\n * - `images`: only `<Image>` elements (a gallery);\n * - `markdown`: paragraphs and lists with inline formatting, no headings and\n * no components.\n */\nexport type BlogChildren = 'none' | 'images' | 'markdown';\n\nexport interface BlogComponentSpec {\n props: Readonly<Record<string, BlogPropSpec>>;\n children: BlogChildren;\n}\n\nexport const BLOG_GALLERY_MIN = 2;\nexport const BLOG_GALLERY_MAX = 24;\n\nexport const BLOG_COMPONENTS = {\n Image: {\n props: {\n src: { kind: 'image-url', required: true },\n alt: { kind: 'text', required: true, max: 300 },\n caption: { kind: 'text', required: false, max: 300 },\n },\n children: 'none',\n },\n Gallery: {\n props: {\n caption: { kind: 'text', required: false, max: 300 },\n },\n children: 'images',\n },\n YouTube: {\n props: {\n /** The 11-character video id, never a URL: no other embed can be smuggled in. */\n id: { kind: 'youtube-id', required: true },\n title: { kind: 'text', required: false, max: 200 },\n },\n children: 'none',\n },\n Callout: {\n props: {\n tone: { kind: 'enum', required: false, values: ['info', 'tip', 'warning'] },\n },\n children: 'markdown',\n },\n} as const satisfies Record<string, BlogComponentSpec>;\n\nexport type BlogComponentName = keyof typeof BLOG_COMPONENTS;\n\nexport const BLOG_COMPONENT_NAMES = Object.keys(BLOG_COMPONENTS) as BlogComponentName[];\n\nexport function isBlogComponentName(name: string): name is BlogComponentName {\n return Object.prototype.hasOwnProperty.call(BLOG_COMPONENTS, name);\n}\n\nexport const YOUTUBE_ID_PATTERN = /^[A-Za-z0-9_-]{11}$/;\n\n/** Link targets a post may use. Anything else, `javascript:` included, is refused. */\nexport const BLOG_LINK_SCHEMES = ['https:', 'http:', 'mailto:', 'tel:'] as const;\n\nexport function isValidBlogSlug(slug: string): boolean {\n return slug.length <= BLOG_SLUG_MAX && BLOG_SLUG_PATTERN.test(slug);\n}\n\nexport function isValidBlogLocale(locale: string): boolean {\n return BLOG_LOCALE_PATTERN.test(locale);\n}\n\n/** `src/content/blog/<slug>.<locale>.mdx`. Throws on a slug or locale the contract refuses. */\nexport function blogPostPath(slug: string, locale: string): string {\n if (!isValidBlogSlug(slug)) throw new Error(`Invalid blog slug \"${slug}\"`);\n if (!isValidBlogLocale(locale)) throw new Error(`Invalid blog locale \"${locale}\"`);\n return `${BLOG_DIR}/${slug}.${locale}.mdx`;\n}\n\n/** The slug and locale a post path names, or null if it is not a post path. */\nexport function parseBlogPostPath(path: string): { slug: string; locale: string } | null {\n const prefix = `${BLOG_DIR}/`;\n if (!path.startsWith(prefix)) return null;\n const match = /^([^/]+)\\.([^./]+)\\.mdx$/.exec(path.slice(prefix.length));\n if (!match) return null;\n const [, slug = '', locale = ''] = match;\n return isValidBlogSlug(slug) && isValidBlogLocale(locale) ? { slug, locale } : null;\n}\n\n/** The public URL path of a post. */\nexport function blogPostRoute(slug: string): string {\n return `${BLOG_ROUTE}/${slug}`;\n}\n","/**\n * The posts a site's build hands to the library, and how a page chooses among\n * them. No parser and no React: the build (`@setto/client/vite`) has already\n * validated every file against the contract and turned its body into a syntax\n * tree, so the browser only walks data.\n */\nimport type { Root } from 'mdast';\nimport type { BlogFrontmatter } from './contract';\n\n/** A post as the list knows it: its frontmatter, and nothing to download. */\nexport type BlogPostSummary = BlogFrontmatter;\n\n/** A post as its page knows it: frontmatter and the body's syntax tree. */\nexport interface BlogPostData {\n frontmatter: BlogFrontmatter;\n body: Root;\n}\n\n/**\n * What `virtual:setto-blog` exports and `SettoConfig.blog` carries. Bodies are\n * loaded one at a time, so a site with a hundred posts does not ship a\n * hundred articles to read one.\n */\nexport interface SettoBlogData {\n posts: readonly BlogPostSummary[];\n load(slug: string, locale: string): Promise<BlogPostData | null>;\n}\n\n/** Newest first; a tie breaks on slug so the order never flickers. */\nexport function byDateDesc(a: BlogPostSummary, b: BlogPostSummary): number {\n return a.date === b.date ? a.slug.localeCompare(b.slug) : a.date < b.date ? 1 : -1;\n}\n\n/**\n * One entry per post, in the reader's language where it exists and in the\n * site's own otherwise. A post written only in Norwegian still shows to an\n * English reader — untranslated is better than missing.\n */\nexport function postsForLanguage(\n posts: readonly BlogPostSummary[],\n language: string,\n fallbackLanguage: string,\n): BlogPostSummary[] {\n const bySlug = new Map<string, BlogPostSummary>();\n for (const post of posts) {\n const current = bySlug.get(post.slug);\n if (!current || rank(post, language, fallbackLanguage) < rank(current, language, fallbackLanguage)) {\n bySlug.set(post.slug, post);\n }\n }\n return [...bySlug.values()].sort(byDateDesc);\n}\n\n/** The version of one post to show this reader, or null if there is none. */\nexport function postForSlug(\n posts: readonly BlogPostSummary[],\n slug: string,\n language: string,\n fallbackLanguage: string,\n): BlogPostSummary | null {\n return postsForLanguage(posts.filter((p) => p.slug === slug), language, fallbackLanguage)[0] ?? null;\n}\n\nfunction rank(post: BlogPostSummary, language: string, fallbackLanguage: string): number {\n if (post.locale === language) return 0;\n if (post.locale === fallbackLanguage) return 1;\n return 2;\n}\n\n/** `2026-10-01` as «1. oktober 2026» or «1 October 2026». */\nexport function formatPostDate(date: string, language: string): string {\n const parsed = new Date(`${date}T12:00:00Z`);\n if (Number.isNaN(parsed.getTime())) return date;\n const locale = language === 'no' || language === 'nb' || language === 'nn' ? 'nb-NO' : language;\n try {\n return new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' }).format(parsed);\n } catch {\n return date;\n }\n}\n","/**\n * The few words the blog says itself — around the posts, never in them. In\n * Norwegian and English; any other language reads English, which is what a\n * visitor who chose it can most likely read.\n */\nconst NO = {\n blog: 'Blogg',\n latest: 'Fra bloggen',\n allPosts: 'Alle innlegg',\n readMore: 'Les mer',\n back: 'Alle innlegg',\n empty: 'Ingen innlegg ennå.',\n notFound: 'Fant ikke innlegget.',\n loading: 'Henter innlegget …',\n share: 'Del',\n moreShare: 'Flere valg …',\n copyLink: 'Kopier lenke',\n copied: 'Lenken er kopiert',\n email: 'E-post',\n video: 'Video',\n play: 'Spill av',\n};\n\nexport type BlogStrings = typeof NO;\n\nconst EN: BlogStrings = {\n blog: 'Blog',\n latest: 'From the blog',\n allPosts: 'All posts',\n readMore: 'Read more',\n back: 'All posts',\n empty: 'No posts yet.',\n notFound: 'That post could not be found.',\n loading: 'Loading the post …',\n share: 'Share',\n moreShare: 'More …',\n copyLink: 'Copy link',\n copied: 'Link copied',\n email: 'Email',\n video: 'Video',\n play: 'Play',\n};\n\nexport function blogStrings(language: string): BlogStrings {\n return language === 'no' || language === 'nb' || language === 'nn' ? NO : EN;\n}\n","/**\n * A post's body, drawn from its syntax tree.\n *\n * Every node the contract admits has a case here and nothing else does: no\n * `dangerouslySetInnerHTML`, no evaluation, no component looked up by a name\n * the file chose. A node the contract would have refused — which the build\n * already refused — renders as nothing. Links are checked again on the way\n * out, because a renderer should not trust that the gate ran.\n */\nimport { useState, type ReactNode } from 'react';\nimport type { Nodes, PhrasingContent, RootContent, Table } from 'mdast';\nimport type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';\nimport { useSetto } from '../provider';\nimport { hasNoOptimizer, isOptimizable, optimizedSrcSet, optimizedUrl } from '../lib/optimized-image';\nimport { isSafeHref } from '../pages/manifest';\nimport { YOUTUBE_ID_PATTERN } from './contract';\nimport { blogStrings } from './strings';\n\nexport function BlogBody({ nodes, language }: { nodes: readonly RootContent[]; language: string }) {\n return <>{nodes.map((node, i) => renderFlow(node, i, language))}</>;\n}\n\n/**\n * Where a draft's node sits in its file, for the owner's click-to-fix.\n *\n * A draft comes from setto-server with `at: [start, end)` on each node in\n * place of mdast's `position`; a published post never has it. The chrome\n * finds the clickable blocks by this attribute, so the renderer stays the one\n * that draws posts and drafts alike.\n */\nfunction at(node: unknown): { 'data-setto-at'?: string } {\n const range = (node as { at?: unknown }).at;\n return Array.isArray(range) && range.length === 2 && range.every((n) => Number.isInteger(n))\n ? { 'data-setto-at': `${range[0]}:${range[1]}` }\n : {};\n}\n\n/** A draft's photo: its place, and what the owner's photo editor starts from. */\nfunction atImage(node: unknown, alt: string): Record<string, string> {\n const where = at(node);\n return where['data-setto-at'] ? { ...where, 'data-setto-kind': 'image', 'data-setto-alt': alt } : {};\n}\n\nfunction renderFlow(node: Nodes, key: number, language: string): ReactNode {\n switch (node.type) {\n case 'paragraph':\n return (\n <p key={key} {...at(node)}>\n {renderPhrasing(node.children)}\n </p>\n );\n case 'heading': {\n const Tag = node.depth === 2 ? 'h2' : node.depth === 3 ? 'h3' : 'h4';\n return (\n <Tag key={key} {...at(node)}>\n {renderPhrasing(node.children)}\n </Tag>\n );\n }\n case 'list': {\n const items = node.children.map((item, i) => (\n <li key={i}>{item.children.map((child, j) => renderListChild(child, j, item.spread === true, language))}</li>\n ));\n return node.ordered ? (\n <ol key={key} start={node.start ?? undefined}>\n {items}\n </ol>\n ) : (\n <ul key={key}>{items}</ul>\n );\n }\n case 'blockquote':\n return <blockquote key={key}>{node.children.map((child, i) => renderFlow(child, i, language))}</blockquote>;\n case 'thematicBreak':\n return <hr key={key} />;\n case 'code':\n return (\n <pre key={key}>\n <code>{node.value}</code>\n </pre>\n );\n case 'table':\n return <BlogTable key={key} table={node} />;\n case 'mdxJsxFlowElement':\n return <BlogComponent key={key} element={node} language={language} />;\n default:\n return null;\n }\n}\n\n/** A tight list's paragraphs are just its text, as Markdown means them. */\nfunction renderListChild(child: Nodes, key: number, spread: boolean, language: string): ReactNode {\n if (child.type === 'paragraph' && !spread)\n return (\n <span key={key} {...at(child)}>\n {renderPhrasing(child.children)}\n </span>\n );\n return renderFlow(child, key, language);\n}\n\nfunction renderPhrasing(children: readonly PhrasingContent[]): ReactNode {\n return children.map((child, i) => {\n switch (child.type) {\n case 'text':\n return child.value;\n case 'emphasis':\n return <em key={i}>{renderPhrasing(child.children)}</em>;\n case 'strong':\n return <strong key={i}>{renderPhrasing(child.children)}</strong>;\n case 'delete':\n return <del key={i}>{renderPhrasing(child.children)}</del>;\n case 'inlineCode':\n return <code key={i}>{child.value}</code>;\n case 'break':\n return <br key={i} />;\n case 'link': {\n const safe = isSafeHref(child.url);\n if (!safe) return <span key={i}>{renderPhrasing(child.children)}</span>;\n const external = /^https?:\\/\\//i.test(child.url);\n return (\n <a key={i} href={child.url} {...(external ? { rel: 'noopener noreferrer' } : {})}>\n {renderPhrasing(child.children)}\n </a>\n );\n }\n default:\n return null;\n }\n });\n}\n\nfunction BlogTable({ table }: { table: Table }) {\n const [head, ...rows] = table.children;\n const align = (i: number) => table.align?.[i] ?? undefined;\n return (\n <div className=\"setto-blog__table\">\n <table>\n {head ? (\n <thead>\n <tr>\n {head.children.map((cell, i) => (\n <th key={i} style={{ textAlign: align(i) }}>\n {renderPhrasing(cell.children)}\n </th>\n ))}\n </tr>\n </thead>\n ) : null}\n <tbody>\n {rows.map((row, r) => (\n <tr key={r}>\n {row.children.map((cell, i) => (\n <td key={i} style={{ textAlign: align(i) }}>\n {renderPhrasing(cell.children)}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\n// ── The four components ──────────────────────────────────────────────────────\n\nfunction attrs(element: MdxJsxFlowElement): Record<string, string> {\n const out: Record<string, string> = {};\n for (const attribute of element.attributes) {\n const a = attribute as MdxJsxAttribute;\n if (a.type === 'mdxJsxAttribute' && typeof a.value === 'string') out[a.name] = a.value;\n }\n return out;\n}\n\nfunction BlogComponent({ element, language }: { element: MdxJsxFlowElement; language: string }) {\n const props = attrs(element);\n switch (element.name) {\n case 'Image':\n return props.src && props.alt !== undefined ? (\n <figure className=\"setto-blog__figure\" {...atImage(element, props.alt)}>\n <BlogImg src={props.src} alt={props.alt} sizes=\"(min-width: 760px) 720px, 100vw\" />\n {props.caption ? <figcaption>{props.caption}</figcaption> : null}\n </figure>\n ) : null;\n case 'Gallery': {\n const images = element.children.filter(\n (child): child is MdxJsxFlowElement => child.type === 'mdxJsxFlowElement' && child.name === 'Image',\n );\n return (\n <figure className=\"setto-blog__gallery\">\n <div className=\"setto-blog__gallery-grid\">\n {images.map((image, i) => {\n const a = attrs(image);\n return a.src ? (\n <figure key={i} className=\"setto-blog__gallery-item\" {...atImage(image, a.alt ?? '')}>\n <BlogImg src={a.src} alt={a.alt ?? ''} sizes=\"(min-width: 760px) 360px, 50vw\" />\n {a.caption ? <figcaption>{a.caption}</figcaption> : null}\n </figure>\n ) : null;\n })}\n </div>\n {props.caption ? <figcaption>{props.caption}</figcaption> : null}\n </figure>\n );\n }\n case 'YouTube':\n return props.id && YOUTUBE_ID_PATTERN.test(props.id) ? (\n <YouTubeEmbed id={props.id} title={props.title} language={language} />\n ) : null;\n case 'Callout':\n return (\n <aside className=\"setto-blog__callout\" data-tone={props.tone ?? 'info'}>\n {element.children.map((child, i) => renderFlow(child as Nodes, i, language))}\n </aside>\n );\n default:\n return null;\n }\n}\n\n/**\n * An image, resized by the site's optimizer when it has one and the image is\n * one it may read (`isOptimizable`: this site's own, or a blog photograph in\n * Setto's media store). If a variant fails, the original is shown instead.\n */\nexport function BlogImg({ src, alt, sizes, className }: { src: string; alt: string; sizes: string; className?: string }) {\n const { config } = useSetto();\n const [failed, setFailed] = useState(false);\n const optimize =\n config.images?.optimize === true &&\n !failed &&\n isOptimizable(src) &&\n !(typeof window !== 'undefined' && hasNoOptimizer(window.location.hostname));\n if (!optimize) return <img src={src} alt={alt} loading=\"lazy\" decoding=\"async\" className={className} />;\n return (\n <img\n src={optimizedUrl(src, 1080)}\n srcSet={optimizedSrcSet(src)}\n sizes={sizes}\n alt={alt}\n loading=\"lazy\"\n decoding=\"async\"\n className={className}\n onError={() => setFailed(true)}\n />\n );\n}\n\n/**\n * A YouTube video that costs the reader nothing until they ask for it: a\n * still and a play button, and only on a click the player itself, from\n * YouTube's no-cookie domain.\n */\nfunction YouTubeEmbed({ id, title, language }: { id: string; title?: string; language: string }) {\n const [playing, setPlaying] = useState(false);\n const strings = blogStrings(language);\n const label = title ?? strings.video;\n return (\n <figure className=\"setto-blog__video\">\n <div className=\"setto-blog__video-frame\">\n {playing ? (\n <iframe\n src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0`}\n title={label}\n allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n allowFullScreen\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n ) : (\n <button type=\"button\" className=\"setto-blog__video-play\" onClick={() => setPlaying(true)} aria-label={`${strings.play}: ${label}`}>\n <img src={`https://i.ytimg.com/vi/${id}/hqdefault.jpg`} alt=\"\" loading=\"lazy\" decoding=\"async\" />\n <span aria-hidden=\"true\" className=\"setto-blog__video-icon\">\n <svg viewBox=\"0 0 68 48\" width=\"68\" height=\"48\">\n <path d=\"M66.5 7.7A8.5 8.5 0 0 0 60.5 1.7C55.2.3 34 .3 34 .3s-21.2 0-26.5 1.4A8.5 8.5 0 0 0 1.5 7.7C.1 13 .1 24 .1 24s0 11 1.4 16.3a8.5 8.5 0 0 0 6 6c5.3 1.4 26.5 1.4 26.5 1.4s21.2 0 26.5-1.4a8.5 8.5 0 0 0 6-6C67.9 35 67.9 24 67.9 24s0-11-1.4-16.3z\" fill=\"#f00\" />\n <path d=\"M45 24 27 14v20\" fill=\"#fff\" />\n </svg>\n </span>\n </button>\n )}\n </div>\n {title ? <figcaption>{title}</figcaption> : null}\n </figure>\n );\n}\n","/**\n * The blog's two built-in sections (R24).\n *\n * `blog` lives on the blog page and draws either the list of posts or, at\n * `<page path>/<slug>`, one post. `blog-latest` is a band of the newest posts\n * for the front page. Both read the posts the site's build bundles\n * (`SettoConfig.blog`, from `virtual:setto-blog`). The band draws nothing\n * without them; the blog page says there are none yet.\n *\n * The owner, signed in on their own site, also gets the `blog-owner` chrome\n * slot at the top of the blog page: Pixel's welcome on an empty blog, the\n * article Pixel is writing, and a draft waiting for approval — drawn here, in\n * the site's own blog design, by `BlogDraft`, so what the owner approves is\n * what readers will see.\n *\n * The look is the site's: type and colour are inherited, and the stylesheet\n * below only gives shape — scoped under `.setto-blog` so Tailwind's reset\n * cannot strip it, and at zero specificity for colour so the site always\n * wins. However a redesign restyles these classes, the posts keep rendering:\n * the file contract is what may not change.\n */\nimport {\n useEffect,\n useInsertionEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport type { RootContent } from 'mdast';\nimport { useTranslation } from 'react-i18next';\nimport { useSetto } from '../provider';\nimport { useSettoChromeSlot } from '../chrome';\nimport { languageFromPath } from '../lib/language-routing';\nimport { SettoSection } from '../SettoSection';\nimport { blogPage, blogSlugForPath, findSection, normalisePath, type PagesManifest } from '../pages/manifest';\nimport { usePageManifest, type BuiltinSectionProps } from '../pages/SettoPage';\nimport { BLOG_ROUTE, isValidBlogSlug, type BlogFrontmatter } from './contract';\nimport { formatPostDate, postForSlug, postsForLanguage, type BlogPostData, type BlogPostSummary } from './data';\nimport { BlogBody, BlogImg } from './render';\nimport { blogStrings, type BlogStrings } from './strings';\n\nconst LATEST_COUNT = 3;\n\nfunction useBlogContext(path?: string) {\n const { config } = useSetto();\n const { i18n, t } = useTranslation();\n const manifest = usePageManifest();\n const language = i18n.language || config.languages?.[0] || 'no';\n const fallbackLanguage = config.languages?.[0] ?? 'no';\n const languages = config.languages ?? [fallbackLanguage];\n /*\n * A site in two languages serves the second under a prefix (`/en/blogg/…`)\n * and gives the router that prefix as its basename. The blog reads the\n * address without it, and writes its links with it, so an English reader\n * stays in English.\n *\n * The address is the `path` a site hands over (its router's location, the\n * prefix already taken off) when it has one: on a server, or in the first\n * render of a page the build drew, there is no `window.location` to read\n * that would agree with it. Without one, the browser's address, as before.\n * The prefix comes from the browser's address where there is one, and from\n * the language being drawn where there is not.\n */\n const route =\n typeof window === 'undefined'\n ? { basename: language === fallbackLanguage || !languages.includes(language) ? '' : `/${language}`, rest: '/' }\n : languageFromPath(window.location.pathname, languages);\n const href = (to: string) => `${route.basename}${to}`;\n return { config, t, manifest, language, fallbackLanguage, strings: blogStrings(language), path: path ?? route.rest, href };\n}\n\nfunction blogPathOf(manifest: PagesManifest | null): string {\n return (manifest && blogPage(manifest)?.page.path) || BLOG_ROUTE;\n}\n\n// ── `blog` ───────────────────────────────────────────────────────────────────\n\nexport function SettoBlogSection({ sectionId, first }: BuiltinSectionProps) {\n useBlogStyles();\n const ctx = useBlogContext();\n const slug = ctx.manifest ? blogSlugForPath(ctx.manifest, ctx.path) : null;\n const page = ctx.manifest ? findSection(ctx.manifest, sectionId)?.page : undefined;\n const title = page ? ctx.t(page.titleKey, { defaultValue: ctx.strings.blog }) : ctx.strings.blog;\n const blogPath = blogPathOf(ctx.manifest);\n const inner = useRef<HTMLDivElement>(null);\n const clear = useClearFixedHeader(inner, first);\n\n return (\n <SettoSection sectionId={sectionId} className=\"setto-blog\">\n <div className=\"setto-blog__inner\" ref={inner} style={clear ? { paddingTop: clear } : undefined}>\n {slug ? (\n <BlogPostView slug={slug} blogPath={blogPath} ctx={ctx} />\n ) : (\n <BlogIndexView title={title} first={first} blogPath={blogPath} ctx={ctx} />\n )}\n </div>\n </SettoSection>\n );\n}\n\n/**\n * The blog for a site that routes by hand instead of through `pages.json`\n * (setto.no): mount it on `<basePath>` and `<basePath>/*`, and pass the same\n * path to `settoBlog({ blogPath })`.\n *\n * <Route path=\"/blogg/*\" element={<SettoBlog basePath=\"/blogg\" />} />\n *\n * Both of the rest are optional, and are what a page drawn ahead of time\n * needs to come out the same on the server and in the browser's first render\n * (0.49.0), so `hydrateRoot` can take it over:\n *\n * <SettoBlog basePath=\"/blogg\" path={useLocation().pathname} initialPost={post} />\n *\n * - `path`: the address within the router (`useLocation().pathname`, the\n * language prefix already taken off). Without it the blog reads\n * `window.location`, which a server does not have.\n * - `initialPost`: the post being shown, already loaded (`blog.load(slug,\n * locale)`). Used when it is the one this address shows, in place of\n * fetching it in an effect; without it the post's first render is «Henter\n * innlegget …», as before.\n */\nexport function SettoBlog({\n basePath = BLOG_ROUTE,\n title,\n path,\n initialPost,\n}: {\n basePath?: string;\n title?: string;\n path?: string;\n initialPost?: BlogPostData | null;\n}) {\n useBlogStyles();\n const ctx = useBlogContext(path);\n const base = normalisePath(basePath);\n const here = normalisePath(ctx.path);\n const rest = here.startsWith(`${base}/`) ? here.slice(base.length + 1) : '';\n const slug = rest && isValidBlogSlug(rest) ? rest : null;\n const inner = useRef<HTMLDivElement>(null);\n const clear = useClearFixedHeader(inner, true);\n return (\n <section className=\"setto-blog\">\n <div className=\"setto-blog__inner\" ref={inner} style={clear ? { paddingTop: clear } : undefined}>\n {slug ? (\n <BlogPostView slug={slug} blogPath={base} ctx={ctx} initialPost={initialPost} />\n ) : (\n <BlogIndexView title={title ?? ctx.strings.blog} first blogPath={base} ctx={ctx} />\n )}\n </div>\n </section>\n );\n}\n\n/**\n * Room for a fixed header. The blog page starts at the top of the page, and\n * sites differ: some pad their pages below a fixed header, some do not, and\n * on a phone the header can be taller than the section's own padding. So the\n * first section measures: whatever fixed element covers the top of the\n * viewport, and how far its bottom reaches past where the content starts —\n * that much, plus a little air, and nothing when the site already made room.\n */\nfunction useClearFixedHeader(ref: RefObject<HTMLElement | null>, enabled: boolean): number {\n const [clear, setClear] = useState(0);\n useLayoutEffect(() => {\n if (!enabled || typeof window === 'undefined') return;\n const measure = () => {\n const el = ref.current;\n if (!el) return;\n const covering = document\n .elementsFromPoint(window.innerWidth / 2, 1)\n .map((node) => fixedAncestor(node))\n .find((node): node is HTMLElement => node !== null && !node.contains(el));\n // A fixed header's bottom is a distance from the top of the window; the\n // content's start is a distance from the top of the page. At the top of\n // the page the two are comparable, and padding added inside `el` does\n // not move `el` itself, so this does not feed back on its own answer.\n const headerBottom = covering ? covering.getBoundingClientRect().bottom : 0;\n const start = el.getBoundingClientRect().top + window.scrollY;\n const overlap = Math.ceil(headerBottom + 16 - start);\n setClear(overlap > 0 ? overlap : 0);\n };\n measure();\n window.addEventListener('resize', measure);\n return () => window.removeEventListener('resize', measure);\n }, [ref, enabled]);\n return clear;\n}\n\nfunction fixedAncestor(node: Element): HTMLElement | null {\n for (let at: Element | null = node; at && at !== document.body; at = at.parentElement) {\n if (getComputedStyle(at).position === 'fixed') return at as HTMLElement;\n }\n return null;\n}\n\ntype Ctx = ReturnType<typeof useBlogContext>;\n\n/** A post not yet published, as setto-server sends it: the frontmatter and the body's tree, each node with `at`. */\nexport interface BlogDraftData {\n frontmatter: BlogFrontmatter;\n body: { children: RootContent[] };\n}\n\n/** What the chrome's `blog-owner` slot is given. */\nexport interface BlogOwnerSlotProps {\n blogPath: string;\n language: string;\n /** Published posts in this language, as of the site's last build. */\n posts: number;\n /** Draws a draft in the site's own blog design; title, lead and cover carry `data-setto-field`. */\n Draft: ComponentType<{ draft: BlogDraftData }>;\n}\n\nfunction BlogIndexView({ title, first, blogPath, ctx }: { title: string; first: boolean; blogPath: string; ctx: Ctx }) {\n const posts = ctx.config.blog ? postsForLanguage(ctx.config.blog.posts, ctx.language, ctx.fallbackLanguage) : [];\n const Heading = first ? 'h1' : 'h2';\n const { canEdit } = useSetto();\n const Owner = useSettoChromeSlot<BlogOwnerSlotProps>('blog-owner');\n return (\n <>\n <Heading className=\"setto-blog__title\">{title}</Heading>\n {canEdit && Owner ? (\n <div className=\"setto-blog__owner\" data-setto-ui=\"\">\n <Owner blogPath={blogPath} language={ctx.language} posts={posts.length} Draft={BlogDraft} />\n </div>\n ) : null}\n {posts.length === 0 ? (\n <p className=\"setto-blog__empty\">{ctx.strings.empty}</p>\n ) : (\n <div className=\"setto-blog__list\">\n {posts.map((post) => (\n <PostCard key={post.slug} post={post} blogPath={blogPath} ctx={ctx} headingLevel={first ? 'h2' : 'h3'} />\n ))}\n </div>\n )}\n </>\n );\n}\n\nfunction PostCard({\n post,\n blogPath,\n ctx,\n headingLevel,\n}: {\n post: BlogPostSummary;\n blogPath: string;\n ctx: Ctx;\n headingLevel: 'h2' | 'h3';\n}) {\n const Heading = headingLevel;\n const href = ctx.href(`${blogPath}/${post.slug}`);\n return (\n <article className=\"setto-blog__card\">\n {post.cover ? (\n <a href={href} className=\"setto-blog__card-cover\" tabIndex={-1} aria-hidden=\"true\">\n <BlogImg src={post.cover} alt=\"\" sizes=\"(min-width: 960px) 360px, (min-width: 640px) 50vw, 100vw\" />\n </a>\n ) : null}\n <div className=\"setto-blog__card-body\">\n <time className=\"setto-blog__date\" dateTime={post.date}>\n {formatPostDate(post.date, ctx.language)}\n </time>\n <Heading className=\"setto-blog__card-title\">\n <a href={href}>{post.title}</a>\n </Heading>\n <p className=\"setto-blog__card-lead\">{post.description}</p>\n <a href={href} className=\"setto-blog__more\" aria-label={`${ctx.strings.readMore}: ${post.title}`}>\n {ctx.strings.readMore} <span aria-hidden=\"true\">→</span>\n </a>\n </div>\n </article>\n );\n}\n\n/** Whether a loaded post is the version `summary` names. */\nfunction isPostFor(post: BlogPostData | null | undefined, summary: BlogPostSummary | null): post is BlogPostData {\n return !!post && !!summary && post.frontmatter.slug === summary.slug && post.frontmatter.locale === summary.locale;\n}\n\nfunction BlogPostView({\n slug,\n blogPath,\n ctx,\n initialPost,\n}: {\n slug: string;\n blogPath: string;\n ctx: Ctx;\n initialPost?: BlogPostData | null;\n}) {\n const blog = ctx.config.blog;\n const summary = blog ? postForSlug(blog.posts, slug, ctx.language, ctx.fallbackLanguage) : null;\n // A post handed over already loaded is drawn at once, and the same on the\n // server as in the browser's first render; anything else is fetched.\n const [post, setPost] = useState<BlogPostData | null>(() => (isPostFor(initialPost, summary) ? initialPost : null));\n const [state, setState] = useState<'loading' | 'ready' | 'missing'>(() =>\n !summary ? 'missing' : isPostFor(initialPost, summary) ? 'ready' : 'loading',\n );\n\n useEffect(() => {\n if (!blog || !summary) {\n setState('missing');\n return;\n }\n if (isPostFor(initialPost, summary)) {\n setPost(initialPost);\n setState('ready');\n return;\n }\n let live = true;\n setState('loading');\n blog\n .load(summary.slug, summary.locale)\n .then((loaded) => {\n if (!live) return;\n setPost(loaded);\n setState(loaded ? 'ready' : 'missing');\n })\n .catch(() => live && setState('missing'));\n return () => {\n live = false;\n };\n // `initialPost` only counts while it is this post; the slug and locale say when that changes.\n }, [blog, summary?.slug, summary?.locale]);\n\n usePostTitle(summary?.title ?? null, ctx.config.displayName);\n\n const back = (\n <a href={ctx.href(blogPath)} className=\"setto-blog__back\">\n <span aria-hidden=\"true\">←</span> {ctx.strings.back}\n </a>\n );\n\n if (!summary || state === 'missing') {\n return (\n <div className=\"setto-blog__post\">\n {back}\n <p className=\"setto-blog__empty\">{ctx.strings.notFound}</p>\n </div>\n );\n }\n\n const fm = post?.frontmatter ?? summary;\n return (\n <PostArticle frontmatter={fm} ctx={ctx} before={back} after={<ShareBar title={fm.title} strings={ctx.strings} />}>\n {state === 'ready' && isPostFor(post, summary) ? (\n <BlogBody nodes={post.body.children} language={ctx.language} />\n ) : (\n <p className=\"setto-blog__loading\" aria-live=\"polite\">\n {ctx.strings.loading}\n </p>\n )}\n </PostArticle>\n );\n}\n\n/** One post's page: the header, the cover and the text. Published posts and drafts alike. */\nfunction PostArticle({\n frontmatter: fm,\n ctx,\n before,\n after,\n draft = false,\n children,\n}: {\n frontmatter: Pick<BlogFrontmatter, 'title' | 'description' | 'date' | 'locale' | 'cover'>;\n ctx: Ctx;\n before?: ReactNode;\n after?: ReactNode;\n draft?: boolean;\n children: ReactNode;\n}) {\n const field = (name: string) => (draft ? { 'data-setto-field': name } : {});\n const Title = draft ? 'h2' : 'h1';\n return (\n <article className=\"setto-blog__post\" lang={fm.locale}>\n {before}\n <header className=\"setto-blog__post-header\">\n <time className=\"setto-blog__date\" dateTime={fm.date}>\n {formatPostDate(fm.date, ctx.language)}\n </time>\n <Title className=\"setto-blog__post-title\" {...field('title')}>\n {fm.title}\n </Title>\n <p className=\"setto-blog__lead\" {...field('description')}>\n {fm.description}\n </p>\n </header>\n {fm.cover ? (\n <figure className=\"setto-blog__cover\" {...field('cover')}>\n <BlogImg src={fm.cover} alt=\"\" sizes=\"(min-width: 1040px) 960px, 100vw\" />\n </figure>\n ) : null}\n <div className=\"setto-blog__prose\">{children}</div>\n {after}\n </article>\n );\n}\n\n/** A draft, as it will read once published. Given to the chrome's `blog-owner` slot. */\nexport function BlogDraft({ draft }: { draft: BlogDraftData }) {\n useBlogStyles();\n const ctx = useBlogContext();\n return (\n <PostArticle frontmatter={draft.frontmatter} ctx={ctx} draft>\n <BlogBody nodes={draft.body.children} language={ctx.language} />\n </PostArticle>\n );\n}\n\n/**\n * The tab says which post this is. Set after the page's own title effect —\n * a child's effect runs before its parent's, so this waits a tick.\n */\nfunction usePostTitle(title: string | null, siteName: string | undefined) {\n useEffect(() => {\n if (!title || typeof document === 'undefined') return;\n const previous = document.title;\n const timer = window.setTimeout(() => {\n document.title = siteName ? `${title} · ${siteName}` : title;\n }, 0);\n return () => {\n window.clearTimeout(timer);\n document.title = previous;\n };\n }, [title, siteName]);\n}\n\n/**\n * Plain links to each service's own share page, and the phone's share sheet\n * where there is one. No SDK, no script from Facebook, nothing loaded until\n * a reader taps.\n */\nfunction ShareBar({ title, strings }: { title: string; strings: BlogStrings }) {\n const [copied, setCopied] = useState(false);\n const [native, setNative] = useState(false);\n /*\n * The address is read once the bar is on the page, not while drawing it:\n * a server has none, and a link drawn with one in the browser but not on\n * the server is one `hydrateRoot` keeps the server's version of, so the\n * share links would have pointed nowhere.\n */\n const [url, setUrl] = useState('');\n useEffect(() => {\n setNative(typeof navigator !== 'undefined' && typeof navigator.share === 'function');\n setUrl(`${window.location.origin}${window.location.pathname}`);\n }, []);\n const u = encodeURIComponent(url);\n const t = encodeURIComponent(title);\n\n return (\n <div className=\"setto-blog__share\" aria-label={strings.share}>\n <span className=\"setto-blog__share-label\">{strings.share}</span>\n {native ? (\n <button type=\"button\" onClick={() => void navigator.share({ title, url }).catch(() => undefined)}>\n {strings.moreShare}\n </button>\n ) : null}\n <a href={`https://www.facebook.com/sharer/sharer.php?u=${u}`} target=\"_blank\" rel=\"noopener noreferrer\">\n Facebook\n </a>\n <a href={`https://www.linkedin.com/sharing/share-offsite/?url=${u}`} target=\"_blank\" rel=\"noopener noreferrer\">\n LinkedIn\n </a>\n <a href={`mailto:?subject=${t}&body=${u}`}>{strings.email}</a>\n <button\n type=\"button\"\n onClick={() => {\n void navigator.clipboard?.writeText(url).then(() => {\n setCopied(true);\n window.setTimeout(() => setCopied(false), 2000);\n });\n }}\n >\n {copied ? strings.copied : strings.copyLink}\n </button>\n </div>\n );\n}\n\n// ── `blog-latest` ────────────────────────────────────────────────────────────\n\nexport function SettoBlogLatest({ sectionId, first }: BuiltinSectionProps) {\n useBlogStyles();\n const ctx = useBlogContext();\n if (!ctx.config.blog) return null;\n const posts = postsForLanguage(ctx.config.blog.posts, ctx.language, ctx.fallbackLanguage).slice(0, LATEST_COUNT);\n if (posts.length === 0) return null;\n const blogPath = blogPathOf(ctx.manifest);\n const Heading = first ? 'h1' : 'h2';\n return (\n <SettoSection sectionId={sectionId} className=\"setto-blog setto-blog--latest\">\n <div className=\"setto-blog__inner setto-blog__inner--wide\">\n <div className=\"setto-blog__latest-head\">\n <Heading className=\"setto-blog__title\">{ctx.strings.latest}</Heading>\n <a href={ctx.href(blogPath)} className=\"setto-blog__more\">\n {ctx.strings.allPosts} <span aria-hidden=\"true\">→</span>\n </a>\n </div>\n <div className=\"setto-blog__list\">\n {posts.map((post) => (\n <PostCard key={post.slug} post={post} blogPath={blogPath} ctx={ctx} headingLevel=\"h3\" />\n ))}\n </div>\n </div>\n </SettoSection>\n );\n}\n\n// ── Styles ───────────────────────────────────────────────────────────────────\n\nconst STYLE_ID = 'setto-blog-styles';\n\n/**\n * Shape is scoped `.setto-blog :where(…)` (one class: beats Preflight's\n * element resets); colour stays at zero specificity so the site's own wins.\n * Same split, same reason, as the form's sheet.\n */\nexport const BLOG_CSS = `\n.setto-blog{padding:clamp(48px,8vw,96px) 16px}\n.setto-blog :where(.setto-blog__inner){max-width:68ch;margin:0 auto}\n.setto-blog :where(.setto-blog__inner--wide){max-width:1120px}\n.setto-blog :where(.setto-blog__title){font-family:var(--setto-display-font,inherit);font-size:clamp(2rem,4vw,2.75rem);line-height:1.15;font-weight:600;margin:0 0 .75em}\n.setto-blog :where(.setto-blog__list){display:grid;gap:clamp(1.5rem,3vw,2.5rem);grid-template-columns:repeat(auto-fill,minmax(min(100%,300px),1fr))}\n.setto-blog :where(.setto-blog__card){display:grid;gap:.9rem;align-content:start}\n.setto-blog :where(.setto-blog__card-cover){display:block;overflow:hidden;border-radius:.9rem;aspect-ratio:16/10}\n.setto-blog :where(.setto-blog__card-cover img,.setto-blog__cover img,.setto-blog__figure img,.setto-blog__gallery-item img){display:block;width:100%;height:100%;object-fit:cover}\n.setto-blog :where(.setto-blog__card-body){display:grid;gap:.45rem}\n.setto-blog :where(.setto-blog__card-title){font-family:var(--setto-display-font,inherit);font-size:1.3rem;line-height:1.25;font-weight:600;margin:0}\n.setto-blog :where(.setto-blog__card-lead){margin:0;line-height:1.55}\n.setto-blog :where(.setto-blog__date){font-size:.875rem;letter-spacing:.01em}\n.setto-blog :where(.setto-blog__more,.setto-blog__back){display:inline-flex;gap:.35em;align-items:center;font-weight:500;width:fit-content}\n.setto-blog :where(.setto-blog__back){margin-bottom:2rem}\n.setto-blog :where(.setto-blog__latest-head){display:flex;flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:.5rem 1.5rem;margin-bottom:1.75rem}\n.setto-blog :where(.setto-blog__latest-head .setto-blog__title){margin:0}\n.setto-blog :where(.setto-blog__post-header){display:grid;gap:.6rem;margin-bottom:2rem}\n.setto-blog :where(.setto-blog__post-title){font-family:var(--setto-display-font,inherit);font-size:clamp(2rem,5vw,3rem);line-height:1.1;font-weight:600;margin:0}\n.setto-blog :where(.setto-blog__lead){font-size:1.2rem;line-height:1.5;margin:0}\n.setto-blog :where(.setto-blog__cover){margin:0 0 2.5rem;overflow:hidden;border-radius:1rem;aspect-ratio:16/9}\n.setto-blog :where(.setto-blog__prose){font-size:1.075rem;line-height:1.7}\n.setto-blog :where(.setto-blog__prose > * + *){margin-top:1.15em}\n.setto-blog :where(.setto-blog__prose h2,.setto-blog__prose h3,.setto-blog__prose h4){font-family:var(--setto-display-font,inherit);line-height:1.25;font-weight:600;margin:1.8em 0 0}\n.setto-blog :where(.setto-blog__prose h2){font-size:1.6rem}\n.setto-blog :where(.setto-blog__prose h3){font-size:1.3rem}\n.setto-blog :where(.setto-blog__prose h4){font-size:1.1rem}\n.setto-blog :where(.setto-blog__prose ul,.setto-blog__prose ol){padding-left:1.4em}\n.setto-blog :where(.setto-blog__prose ul){list-style:disc}\n.setto-blog :where(.setto-blog__prose ol){list-style:decimal}\n.setto-blog :where(.setto-blog__prose li + li){margin-top:.35em}\n.setto-blog :where(.setto-blog__prose blockquote){margin-left:0;padding-left:1.1em;border-left-width:3px;border-left-style:solid;font-style:italic}\n.setto-blog :where(.setto-blog__prose pre){overflow-x:auto;padding:1em;border-radius:.6rem;font-size:.9em}\n.setto-blog :where(.setto-blog__prose code){font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.92em}\n.setto-blog :where(.setto-blog__prose hr){border:0;border-top-width:1px;border-top-style:solid;margin:2.5em 0}\n.setto-blog :where(.setto-blog__prose a){text-decoration:underline;text-underline-offset:.18em}\n.setto-blog :where(.setto-blog__table){overflow-x:auto}\n.setto-blog :where(.setto-blog__table table){border-collapse:collapse;width:100%;font-size:.95em}\n.setto-blog :where(.setto-blog__table th,.setto-blog__table td){padding:.55em .8em;border-bottom-width:1px;border-bottom-style:solid;text-align:left}\n.setto-blog :where(.setto-blog__figure,.setto-blog__gallery,.setto-blog__video){margin:2em 0}\n.setto-blog :where(.setto-blog__figure img){border-radius:.8rem;height:auto}\n.setto-blog :where(figcaption){font-size:.9rem;margin-top:.6em;opacity:.75}\n.setto-blog :where(.setto-blog__gallery-grid){display:grid;gap:.6rem;grid-template-columns:repeat(auto-fit,minmax(min(100%,150px),1fr))}\n.setto-blog :where(.setto-blog__gallery-item){margin:0}\n.setto-blog :where(.setto-blog__gallery-item img){border-radius:.6rem;aspect-ratio:4/3}\n.setto-blog :where(.setto-blog__video-frame){position:relative;aspect-ratio:16/9;border-radius:.8rem;overflow:hidden}\n.setto-blog :where(.setto-blog__video-frame iframe){position:absolute;inset:0;width:100%;height:100%;border:0}\n.setto-blog :where(.setto-blog__video-play){position:absolute;inset:0;width:100%;height:100%;padding:0;border:0;cursor:pointer;display:grid;place-items:center}\n.setto-blog :where(.setto-blog__video-play img){position:absolute;inset:0;width:100%;height:100%;object-fit:cover}\n.setto-blog :where(.setto-blog__video-icon){position:relative;display:block;line-height:0}\n.setto-blog :where(.setto-blog__callout){padding:1.1em 1.3em;border-radius:.8rem;border-left-width:4px;border-left-style:solid}\n.setto-blog :where(.setto-blog__callout > * + *){margin-top:.7em}\n.setto-blog :where(.setto-blog__callout ul,.setto-blog__callout ol){padding-left:1.3em;list-style:disc}\n.setto-blog :where(.setto-blog__share){display:flex;flex-wrap:wrap;gap:.5rem .9rem;align-items:center;margin-top:3rem;padding-top:1.5rem;border-top-width:1px;border-top-style:solid}\n.setto-blog :where(.setto-blog__share-label){font-weight:600}\n.setto-blog :where(.setto-blog__share a,.setto-blog__share button){font:inherit;padding:.35rem .85rem;border-radius:999px;border-width:1px;border-style:solid;cursor:pointer;text-decoration:none;line-height:1.4}\n.setto-blog :where(.setto-blog__empty,.setto-blog__loading){opacity:.75}\n:where(.setto-blog){color:inherit}\n:where(.setto-blog__date){opacity:.7}\n:where(.setto-blog a){color:inherit}\n:where(.setto-blog__prose blockquote,.setto-blog__prose hr,.setto-blog__table th,.setto-blog__table td,.setto-blog__share){border-color:color-mix(in srgb,currentColor 18%,transparent)}\n:where(.setto-blog__prose pre,.setto-blog__card-cover){background:color-mix(in srgb,currentColor 6%,transparent)}\n:where(.setto-blog__share a,.setto-blog__share button){border-color:color-mix(in srgb,currentColor 30%,transparent);background:transparent;color:inherit}\n:where(.setto-blog__callout){background:color-mix(in srgb,currentColor 5%,transparent);border-left-color:color-mix(in srgb,currentColor 40%,transparent)}\n:where(.setto-blog__callout[data-tone=\"tip\"]){border-left-color:#0f7b4f}\n:where(.setto-blog__callout[data-tone=\"warning\"]){border-left-color:#b54708}\n:where(.setto-blog__video-frame){background:#000}\n`;\n\nfunction useBlogStyles() {\n useInsertionEffect(() => {\n if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = BLOG_CSS;\n document.head.appendChild(el);\n }, []);\n}\n\n","import type { i18n as I18nType, TFunction } from 'i18next';\nimport { collectKeysUnder, getNested } from '../../lib/nested-resource';\n\n/**\n * What a form is made of, and where that lives.\n *\n * A form's fields are content, not code. They sit in the locale bundle under\n * `form.<formId>.fields.<n>` as an ordinary Setto list — the same shape a\n * repeater uses — so the editor can add, remove, reorder and relabel them\n * with the draft store it already has, and publishing writes them to\n * `no.json` through the path that already exists. Nothing new has to be\n * stored, fetched or deployed for a form to change.\n *\n * \"form\": {\n * \"kontakt\": {\n * \"submit\": \"Send\", \"success\": \"Takk! …\", \"error\": \"Noe gikk galt.\",\n * \"fields\": {\n * \"1\": { \"name\": \"navn\", \"type\": \"text\", \"label\": \"Navn\", \"required\": \"true\" },\n * \"2\": { \"name\": \"epost\", \"type\": \"email\", \"label\": \"E-post\", \"required\": \"true\" },\n * \"3\": { \"name\": \"tjeneste\", \"type\": \"select\", \"label\": \"Hva gjelder det?\",\n * \"options\": \"Tak\\nVindu\\nAnnet\" },\n * \"4\": { \"name\": \"melding\", \"type\": \"textarea\", \"label\": \"Melding\" }\n * }\n * }\n * }\n *\n * Every value is a string because every locale value is: `required` is\n * `\"true\"`, `options` is one per line. `label`, `placeholder` and `options`\n * are per language; `name`, `type` and `required` are the same in all of them.\n */\n\nexport const FORM_FIELD_TYPES = [\n 'text',\n 'email',\n 'tel',\n 'number',\n 'url',\n 'date',\n 'textarea',\n 'select',\n 'radio',\n 'checkbox',\n 'checkboxes',\n] as const;\n\nexport type FormFieldType = (typeof FORM_FIELD_TYPES)[number];\n\n/** What the editor calls each type. */\nexport const FORM_FIELD_TYPE_LABELS: Record<FormFieldType, string> = {\n text: 'Kort tekst',\n email: 'E-post',\n tel: 'Telefon',\n number: 'Tall',\n url: 'Nettadresse',\n date: 'Dato',\n textarea: 'Lang tekst',\n select: 'Nedtrekksliste',\n radio: 'Ett valg',\n checkbox: 'Avkrysning',\n checkboxes: 'Flere valg',\n};\n\n/** Field props that are the same in every language. */\nexport const STRUCTURAL_FIELD_PROPS = ['name', 'type', 'required'] as const;\n\nexport function isFormFieldType(value: unknown): value is FormFieldType {\n return typeof value === 'string' && (FORM_FIELD_TYPES as readonly string[]).includes(value);\n}\n\nexport function fieldTypeHasOptions(type: FormFieldType): boolean {\n return type === 'select' || type === 'radio' || type === 'checkboxes';\n}\n\nexport function fieldTypeHasPlaceholder(type: FormFieldType): boolean {\n return !fieldTypeHasOptions(type) && type !== 'checkbox' && type !== 'date';\n}\n\n/** A field as the form renders it, whichever source it came from. */\nexport interface ResolvedFormField {\n /** Item key under `form.<id>.fields` — absent when the field came from props. */\n itemKey?: string;\n name: string;\n type: FormFieldType;\n /** i18n key the label is rendered (and inline-edited) through. */\n labelKey: string;\n label: string;\n placeholder: string;\n required: boolean;\n options: string[];\n}\n\nexport function formFieldsPrefix(formId: string): string {\n return `form.${formId}.fields`;\n}\n\nexport function parseOptions(value: string | undefined): string[] {\n if (!value) return [];\n return value\n .split('\\n')\n .map((o) => o.trim())\n .filter((o) => o !== '');\n}\n\nfunction readString(item: Record<string, unknown>, prop: string): string {\n const value = item[prop];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Fields as the locale bundle defines them, or null when no loaded language\n * has a `fields` list for this form and it should fall back to whatever the\n * host passed. The current language is read first, then i18next's fallback\n * chain, so a second language that has not translated the form still gets\n * its structure. Items without a name are skipped: they are the empty husks a\n * half-finished edit can leave behind, not fields.\n */\nexport function readLocaleFields(\n i18n: I18nType,\n lng: string,\n formId: string,\n ns = 'translation',\n): ResolvedFormField[] | null {\n const prefix = formFieldsPrefix(formId);\n const candidates = [lng, ...(i18n.languages ?? [])].filter((l, i, all) => all.indexOf(l) === i);\n let bundle: Record<string, unknown> | undefined;\n let list: unknown;\n for (const candidate of candidates) {\n const b = i18n.getResourceBundle(candidate, ns) as Record<string, unknown> | undefined;\n const l = getNested(b, prefix);\n if (l && typeof l === 'object' && !Array.isArray(l)) {\n bundle = b;\n list = l;\n break;\n }\n }\n if (!list) return null;\n\n const fields: ResolvedFormField[] = [];\n for (const itemKey of collectKeysUnder(bundle, prefix)) {\n const item = (list as Record<string, unknown>)[itemKey];\n if (!item || typeof item !== 'object') continue;\n const record = item as Record<string, unknown>;\n const name = readString(record, 'name').trim();\n if (!name) continue;\n const type = isFormFieldType(record.type) ? record.type : 'text';\n fields.push({\n itemKey,\n name,\n type,\n labelKey: `${prefix}.${itemKey}.label`,\n label: readString(record, 'label'),\n placeholder: readString(record, 'placeholder'),\n required: readString(record, 'required') === 'true',\n options: parseOptions(readString(record, 'options')),\n });\n }\n return fields;\n}\n\n/** The host-supplied shape a form can still be given as a prop. */\nexport interface FormFieldProp {\n /** Submitted form field name. */\n name: string;\n type: FormFieldType;\n required?: boolean;\n /** i18n key for the field label. */\n labelKey: string;\n /** i18n key for the placeholder text. */\n placeholderKey?: string;\n /** i18n key for the options of a select/radio/checkboxes field, one per line. */\n optionsKey?: string;\n}\n\nexport function resolvePropFields(fields: FormFieldProp[], t: TFunction): ResolvedFormField[] {\n return fields.map((field) => ({\n name: field.name,\n type: isFormFieldType(field.type) ? field.type : 'text',\n labelKey: field.labelKey,\n label: t(field.labelKey, { defaultValue: '' }),\n placeholder: field.placeholderKey ? t(field.placeholderKey, { defaultValue: '' }) : '',\n required: field.required === true,\n options: field.optionsKey ? parseOptions(t(field.optionsKey, { defaultValue: '' })) : [],\n }));\n}\n\n/** `Hva gjelder det?` → `hva-gjelder-det`; falls back to `felt`. */\nexport function slugifyFieldName(label: string): string {\n const slug = label\n .toLowerCase()\n .replace(/æ/g, 'ae')\n .replace(/ø/g, 'o')\n .replace(/å/g, 'a')\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^a-z0-9_]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n return slug || 'felt';\n}\n\n/** A name no existing field uses. */\nexport function uniqueFieldName(base: string, taken: Iterable<string>): string {\n const used = new Set(taken);\n if (!used.has(base)) return base;\n let n = 2;\n while (used.has(`${base}-${n}`)) n += 1;\n return `${base}-${n}`;\n}\n\nexport type FormValue = string | boolean | string[];\nexport type FormValues = Record<string, FormValue>;\n\nexport function emptyValue(type: FormFieldType): FormValue {\n if (type === 'checkbox') return false;\n if (type === 'checkboxes') return [];\n return '';\n}\n\nexport function emptyValues(fields: ResolvedFormField[]): FormValues {\n return Object.fromEntries(fields.map((f) => [f.name, emptyValue(f.type)]));\n}\n\nfunction isBlank(value: FormValue | undefined): boolean {\n if (value === undefined) return true;\n if (typeof value === 'string') return value.trim() === '';\n if (typeof value === 'boolean') return !value;\n return value.length === 0;\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\nconst URL_RE = /^(https?:\\/\\/)?[^\\s/$.?#].[^\\s]*$/i;\n\nexport type FieldErrorCode = 'required' | 'email' | 'url' | 'number';\n\n/** Norwegian fallbacks; a site overrides them via `form.validation.<code>`. */\nexport const FIELD_ERROR_DEFAULTS: Record<FieldErrorCode, string> = {\n required: 'Må fylles ut',\n email: 'Skriv inn en gyldig e-postadresse',\n url: 'Skriv inn en gyldig nettadresse',\n number: 'Skriv inn et tall',\n};\n\nexport function validateValues(\n fields: ResolvedFormField[],\n values: FormValues,\n): Record<string, FieldErrorCode> {\n const errors: Record<string, FieldErrorCode> = {};\n for (const field of fields) {\n const value = values[field.name];\n if (field.required && isBlank(value)) {\n errors[field.name] = 'required';\n continue;\n }\n if (typeof value !== 'string' || value.trim() === '') continue;\n if (field.type === 'email' && !EMAIL_RE.test(value.trim())) errors[field.name] = 'email';\n if (field.type === 'url' && !URL_RE.test(value.trim())) errors[field.name] = 'url';\n if (field.type === 'number' && Number.isNaN(Number(value.trim()))) errors[field.name] = 'number';\n }\n return errors;\n}\n\n/**\n * The body `SettoForm` posts to setto-server. See `form-submission.ts` there.\n *\n * `hp` and `elapsed` are the bot signals: the honeypot's value (a person\n * cannot see the field, so anything in it came from a script) and the\n * milliseconds between the visitor's first touch of the form and submit\n * (a script fills a form in tens of milliseconds; a person cannot).\n */\nexport interface SubmissionEnvelope {\n data: FormValues;\n labels: Record<string, string>;\n order: string[];\n title?: string;\n page?: string;\n hp: string;\n elapsed: number;\n}\n\nexport function buildEnvelope(\n fields: ResolvedFormField[],\n values: FormValues,\n extra: { title?: string; page?: string; hp: string; elapsed: number },\n): SubmissionEnvelope {\n const data: FormValues = {};\n const labels: Record<string, string> = {};\n for (const field of fields) {\n const value = values[field.name] ?? emptyValue(field.type);\n data[field.name] = typeof value === 'string' ? value.trim() : value;\n if (field.label.trim()) labels[field.name] = field.label.trim();\n }\n return {\n data,\n labels,\n order: fields.map((f) => f.name),\n ...(extra.title ? { title: extra.title } : {}),\n ...(extra.page ? { page: extra.page } : {}),\n hp: extra.hp,\n elapsed: Math.max(0, Math.round(extra.elapsed)),\n };\n}\n\n/** Where a site's forms go unless the host says otherwise. */\nexport function settoSubmissionUrl(apiUrl: string, siteId: string, formId: string): string {\n return `${apiUrl.replace(/\\/+$/, '')}/sites/${encodeURIComponent(siteId)}/forms/${encodeURIComponent(formId)}/submissions`;\n}\n","import {\n useEffect,\n useId,\n useInsertionEffect,\n useRef,\n useState,\n type ChangeEvent,\n type CSSProperties,\n type FormEvent,\n type ReactNode,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { T } from '../../T';\nimport { useGuestEdit } from '../../guest-edit';\nimport { useSetto } from '../../provider';\nimport { useSettoChromeSlot } from '../../chrome';\nimport type { FieldPatch, FormFieldToolsProps } from './field-tools';\nimport {\n buildEnvelope,\n emptyValue,\n FIELD_ERROR_DEFAULTS,\n formFieldsPrefix,\n readLocaleFields,\n resolvePropFields,\n settoSubmissionUrl,\n slugifyFieldName,\n uniqueFieldName,\n validateValues,\n type FieldErrorCode,\n type FormFieldProp,\n type FormValue,\n type FormValues,\n type ResolvedFormField,\n} from './fields';\n\n/**\n * A form the site owner can change and a visitor can trust.\n *\n * Fields come from the locale (`form.<id>.fields`, see `fields.ts`) and fall\n * back to the `fields` prop until the editor first touches them, at which\n * point the prop fields are copied into the locale and the locale wins. From\n * then on adding, removing, reordering and relabelling are ordinary drafts.\n *\n * Submissions go to setto-server, which stores them and emails the site's\n * recipients. A site with its own backend passes `endpoint` and gets the bare\n * values instead. Either way the visitor sees the form replaced by the\n * success message — with focus moved to it, so it is announced as well as\n * seen.\n *\n * Bots: a honeypot input a person never sees, the time from first touch to\n * submit, and controlled inputs (a script that pokes `.value` never changes\n * React state, so it submits an empty form). The server adds an Origin check,\n * a per-site and per-address rate limit, and a link-count heuristic. None of\n * it asks the visitor to prove anything.\n */\n\nexport interface SettoFormClassNames {\n form?: string;\n field?: string;\n label?: string;\n input?: string;\n textarea?: string;\n select?: string;\n /** Wrapper around a radio / checkbox group's options. */\n options?: string;\n /** One radio / checkbox option (the label element). */\n option?: string;\n /** A single checkbox field (the label element). */\n checkbox?: string;\n actions?: string;\n button?: string;\n success?: string;\n error?: string;\n fieldError?: string;\n}\n\nexport interface SettoFormProps {\n /** Scopes the form's i18n keys and identifies it in the inbox. */\n formId: string;\n /** Seed fields, used until the locale has a `form.<id>.fields` list. */\n fields?: FormFieldProp[];\n /**\n * POST target for a site with its own backend; receives the bare values as\n * JSON. Leave unset to submit to Setto.\n */\n endpoint?: string;\n /** @deprecated Ignored — forms post to Setto unless `endpoint` is set. */\n endpointKey?: string;\n /** Class on the `<form>` (and the success panel that replaces it). */\n className?: string;\n /** Classes per part; the `setto-form__*` classes stay for CSS hooks. */\n classNames?: SettoFormClassNames;\n}\n\ntype Status = 'idle' | 'submitting' | 'success' | 'error';\n\nconst HONEYPOT_NAME = 'website';\n\nconst warnedEndpointKeys = new Set<string>();\n\nfunction cx(...parts: Array<string | undefined | false | null>): string {\n return parts.filter(Boolean).join(' ');\n}\n\nexport function SettoForm({\n formId,\n fields: propFields,\n endpoint,\n endpointKey,\n className,\n classNames = {},\n}: SettoFormProps) {\n const { t, i18n } = useTranslation();\n const { config, editMode, store } = useSetto();\n /*\n * The editing tools for a field come from Setto, not from this bundle.\n *\n * The form itself is the customer's — it renders their fields and takes\n * their visitors' submissions, and has to keep working with Setto\n * unreachable. What sits on top of it in edit mode is Setto's furniture, so\n * it is served like the rest of it and simply absent when it has not\n * arrived.\n */\n const FieldTools = useSettoChromeSlot<FormFieldToolsProps>('form-field-tools');\n const guestEdit = useGuestEdit();\n const editable = editMode || guestEdit.active;\n const lng = i18n.language;\n const uid = useId();\n useFormStyles();\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n useEffect(() => {\n if (endpointKey && !warnedEndpointKeys.has(formId)) {\n warnedEndpointKeys.add(formId);\n console.warn(\n `[setto] <SettoForm formId=\"${formId}\"> passes endpointKey, which is no longer used. ` +\n 'Forms submit to Setto; pass `endpoint` for a custom backend.',\n );\n }\n }, [endpointKey, formId]);\n\n const localeFields = readLocaleFields(i18n, lng, formId);\n const fields = localeFields ?? resolvePropFields(propFields ?? [], t);\n const fromLocale = localeFields !== null;\n const prefix = formFieldsPrefix(formId);\n\n const [values, setValues] = useState<FormValues>({});\n const [errors, setErrors] = useState<Record<string, FieldErrorCode>>({});\n const [status, setStatus] = useState<Status>('idle');\n const [justAdded, setJustAdded] = useState<string | null>(null);\n const formRef = useRef<HTMLFormElement>(null);\n const successRef = useRef<HTMLDivElement>(null);\n const honeypotRef = useRef<HTMLInputElement>(null);\n const startedAt = useRef<number | null>(null);\n\n useEffect(() => {\n if (status === 'success') successRef.current?.focus({ preventScroll: false });\n }, [status]);\n\n const valueOf = (field: ResolvedFormField): FormValue =>\n values[field.name] ?? emptyValue(field.type);\n\n const setValue = (name: string, value: FormValue) => {\n setValues((prev) => ({ ...prev, [name]: value }));\n setErrors((prev) => {\n if (!(name in prev)) return prev;\n const next = { ...prev };\n delete next[name];\n return next;\n });\n };\n\n const markStarted = () => {\n if (startedAt.current === null) startedAt.current = performance.now();\n };\n\n const submitKey = `form.${formId}.submit`;\n const successKey = `form.${formId}.success`;\n const errorKey = `form.${formId}.error`;\n const title = t(`form.${formId}.title`, { defaultValue: '' }) || undefined;\n\n const onSubmit = async (e: FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n if (status === 'submitting') return;\n\n const nextErrors = validateValues(fields, values);\n setErrors(nextErrors);\n const firstInvalid = fields.find((f) => nextErrors[f.name]);\n if (firstInvalid) {\n const el = formRef.current?.querySelector<HTMLElement>(\n `[data-setto-field=\"${cssEscape(firstInvalid.name)}\"] [name]`,\n );\n el?.focus();\n return;\n }\n\n setStatus('submitting');\n const elapsed = startedAt.current === null ? 0 : performance.now() - startedAt.current;\n const envelope = buildEnvelope(fields, values, {\n title,\n page: typeof window !== 'undefined' ? window.location.href : undefined,\n hp: honeypotRef.current?.value ?? '',\n elapsed,\n });\n\n try {\n const url = endpoint || settoSubmissionUrl(config.apiUrl, config.siteId, formId);\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(endpoint ? envelope.data : envelope),\n });\n if (!res.ok) throw new Error(`Form submission failed: ${res.status}`);\n setStatus('success');\n setValues({});\n startedAt.current = null;\n } catch (err) {\n console.error('[setto] form submission failed', err);\n setStatus('error');\n }\n };\n\n /* ── Editing the field set ── */\n\n /**\n * Copies prop fields into the locale the first time the editor changes the\n * structure. Returns each field's item key so the change that triggered the\n * copy can find its target.\n */\n const ensureLocaleFields = (): Map<string, string> => {\n const keys = new Map<string, string>();\n if (!store) return keys;\n if (fromLocale) {\n for (const f of fields) if (f.itemKey) keys.set(f.name, f.itemKey);\n return keys;\n }\n const langs = i18n.languages?.length ? i18n.languages : [lng];\n for (const prop of propFields ?? []) {\n const itemKey = store.addListItem(prefix, lng, {\n name: prop.name,\n type: prop.type,\n ...(prop.required ? { required: 'true' } : {}),\n });\n for (const lang of langs) {\n const ft = i18n.getFixedT(lang);\n const label = ft(prop.labelKey, { defaultValue: '' });\n if (label) store.set(`${prefix}.${itemKey}.label`, lang, label);\n const placeholder = prop.placeholderKey ? ft(prop.placeholderKey, { defaultValue: '' }) : '';\n if (placeholder) store.set(`${prefix}.${itemKey}.placeholder`, lang, placeholder);\n const options = prop.optionsKey ? ft(prop.optionsKey, { defaultValue: '' }) : '';\n if (options) store.set(`${prefix}.${itemKey}.options`, lang, options);\n }\n keys.set(prop.name, itemKey);\n }\n return keys;\n };\n\n const itemKeyFor = (field: ResolvedFormField): string | undefined =>\n field.itemKey ?? ensureLocaleFields().get(field.name);\n\n const allLanguages = (): string[] => (i18n.languages?.length ? [...i18n.languages] : [lng]);\n\n const setEverywhere = (key: string, value: string | undefined) => {\n for (const lang of allLanguages()) {\n if (value === undefined || value === '') store!.delete(key, lang);\n else store!.set(key, lang, value);\n }\n };\n\n const addField = () => {\n if (!store) return;\n store.batch(() => {\n ensureLocaleFields();\n const taken = fields.map((f) => f.name);\n const itemKey = store.addListItem(prefix, lng, {\n name: uniqueFieldName('felt', taken),\n type: 'text',\n });\n for (const lang of allLanguages()) store.set(`${prefix}.${itemKey}.label`, lang, 'Nytt felt');\n setJustAdded(itemKey);\n });\n };\n\n const moveField = (field: ResolvedFormField, direction: -1 | 1) => {\n if (!store) return;\n store.batch(() => {\n const itemKey = itemKeyFor(field);\n if (itemKey) store.moveListItem(prefix, itemKey, direction, lng);\n });\n };\n\n const removeField = (field: ResolvedFormField) => {\n if (!store || fields.length <= 1) return;\n store.batch(() => {\n const itemKey = itemKeyFor(field);\n if (itemKey) store.removeListItem(prefix, itemKey, lng);\n });\n };\n\n const updateField = (field: ResolvedFormField, patch: FieldPatch) => {\n if (!store) return;\n store.batch(() => {\n const itemKey = itemKeyFor(field);\n if (!itemKey) return;\n const item = `${prefix}.${itemKey}`;\n const others = fields.filter((f) => f !== field).map((f) => f.name);\n\n if (patch.type !== undefined) setEverywhere(`${item}.type`, patch.type);\n if (patch.required !== undefined) {\n setEverywhere(`${item}.required`, patch.required ? 'true' : undefined);\n }\n if (patch.name !== undefined) {\n setEverywhere(`${item}.name`, uniqueFieldName(slugifyFieldName(patch.name), others));\n }\n if (patch.label !== undefined) {\n store.set(`${item}.label`, lng, patch.label);\n // A field still carrying its generated name takes one from the label.\n if (patch.name === undefined && /^felt(-\\d+)?$/.test(field.name) && patch.label.trim()) {\n setEverywhere(`${item}.name`, uniqueFieldName(slugifyFieldName(patch.label), others));\n }\n }\n if (patch.placeholder !== undefined) {\n if (patch.placeholder) store.set(`${item}.placeholder`, lng, patch.placeholder);\n else store.delete(`${item}.placeholder`, lng);\n }\n if (patch.options !== undefined) {\n if (patch.options.trim()) store.set(`${item}.options`, lng, patch.options);\n else store.delete(`${item}.options`, lng);\n }\n });\n };\n\n /* ── Render ── */\n\n if (status === 'success') {\n return (\n <div\n ref={successRef}\n tabIndex={-1}\n role=\"status\"\n aria-live=\"polite\"\n data-setto-form={formId}\n data-setto-form-status=\"success\"\n className={cx('setto-form__success', className, classNames.success)}\n >\n <CheckIcon />\n <p className=\"setto-form__success-text\">\n <T k={successKey} />\n </p>\n <button\n type=\"button\"\n className=\"setto-form__again\"\n onClick={() => {\n setStatus('idle');\n setErrors({});\n }}\n >\n {t('form.again', { defaultValue: 'Send en ny melding' })}\n </button>\n </div>\n );\n }\n\n const submitting = status === 'submitting';\n\n return (\n <form\n ref={formRef}\n data-setto-form={formId}\n className={cx('setto-form', className, classNames.form)}\n onSubmit={onSubmit}\n onFocusCapture={markStarted}\n onPointerDownCapture={markStarted}\n onKeyDownCapture={markStarted}\n noValidate\n >\n {fields.map((field, index) => {\n const id = `${uid}-${field.name}`;\n const error = errors[field.name];\n const errorId = error ? `${id}-error` : undefined;\n return (\n <div\n key={field.itemKey ?? field.name}\n data-setto-field={field.name}\n className={cx('setto-form__field', `setto-form__field--${field.type}`, classNames.field)}\n >\n <FieldControl\n field={field}\n id={id}\n value={valueOf(field)}\n editable={editable}\n invalid={error !== undefined}\n describedBy={errorId}\n classNames={classNames}\n placeholderFallback={t('form.choose', { defaultValue: 'Velg …' })}\n onChange={(value) => setValue(field.name, value)}\n />\n {error ? (\n <p id={errorId} className={cx('setto-form__field-error', classNames.fieldError)}>\n {t(`form.validation.${error}`, { defaultValue: FIELD_ERROR_DEFAULTS[error] })}\n </p>\n ) : null}\n {editable && store && FieldTools ? (\n <FieldTools\n field={field}\n index={index}\n count={fields.length}\n autoOpen={justAdded !== null && justAdded === field.itemKey}\n onMove={(direction) => moveField(field, direction)}\n onRemove={() => removeField(field)}\n onChange={(patch) => updateField(field, patch)}\n />\n ) : null}\n </div>\n );\n })}\n\n {editable && store ? (\n <button\n type=\"button\"\n data-setto-ui\n className=\"setto-form__add-field\"\n style={addFieldStyle}\n onClick={addField}\n >\n + Legg til felt\n </button>\n ) : null}\n\n <div className=\"setto-form__hp\" aria-hidden=\"true\">\n <label htmlFor={`${uid}-${HONEYPOT_NAME}`}>Nettside</label>\n <input\n ref={honeypotRef}\n id={`${uid}-${HONEYPOT_NAME}`}\n type=\"text\"\n name={HONEYPOT_NAME}\n tabIndex={-1}\n autoComplete=\"off\"\n defaultValue=\"\"\n />\n </div>\n\n <div className={cx('setto-form__actions', classNames.actions)}>\n <button\n type=\"submit\"\n className={cx('setto-form__button', classNames.button)}\n disabled={submitting}\n aria-busy={submitting || undefined}\n >\n {submitting ? t('form.sending', { defaultValue: 'Sender …' }) : <T k={submitKey} />}\n </button>\n {status === 'error' ? (\n <p role=\"alert\" data-setto-form-status=\"error\" className={cx('setto-form__error', classNames.error)}>\n <T k={errorKey} />\n </p>\n ) : null}\n </div>\n\n {editable ? (\n <div className=\"setto-form__edit-previews\" style={previewStyle}>\n <div>\n <span style={previewHintStyle}>Etter innsending vises:</span> <T k={successKey} />\n </div>\n {status !== 'error' ? (\n <div>\n <span style={previewHintStyle}>Ved feil vises:</span> <T k={errorKey} />\n </div>\n ) : null}\n </div>\n ) : null}\n </form>\n );\n}\n\n/* ─────────── Field rendering ─────────── */\n\ninterface FieldControlProps {\n field: ResolvedFormField;\n id: string;\n value: FormValue;\n editable: boolean;\n invalid: boolean;\n describedBy?: string;\n classNames: SettoFormClassNames;\n placeholderFallback: string;\n onChange: (value: FormValue) => void;\n}\n\nfunction FieldControl({\n field,\n id,\n value,\n editable,\n invalid,\n describedBy,\n classNames,\n placeholderFallback,\n onChange,\n}: FieldControlProps) {\n const labelId = `${id}-label`;\n // Native `required` for the semantics (the form is noValidate, so the\n // browser announces it but never blocks); our own messages do the rest.\n const aria = {\n 'aria-invalid': invalid || undefined,\n 'aria-describedby': describedBy,\n required: field.required || undefined,\n };\n\n const labelText = (\n <>\n <T k={field.labelKey} />\n {field.required ? (\n <span aria-hidden=\"true\" className=\"setto-form__required\">\n *\n </span>\n ) : null}\n </>\n );\n\n if (field.type === 'checkbox') {\n const checked = value === true;\n return (\n <FieldLabel\n editable={editable}\n htmlFor={id}\n id={labelId}\n className={cx('setto-form__check', classNames.checkbox)}\n >\n <input\n id={id}\n type=\"checkbox\"\n name={field.name}\n checked={checked}\n onChange={(e) => onChange(e.target.checked)}\n {...(editable ? { 'aria-labelledby': labelId } : {})}\n {...aria}\n />\n <span>{labelText}</span>\n </FieldLabel>\n );\n }\n\n if (field.type === 'radio' || field.type === 'checkboxes') {\n const multiple = field.type === 'checkboxes';\n const selected = multiple ? (Array.isArray(value) ? value : []) : value;\n const toggle = (option: string, on: boolean) => {\n if (!multiple) {\n onChange(option);\n return;\n }\n const set = new Set(Array.isArray(selected) ? selected : []);\n if (on) set.add(option);\n else set.delete(option);\n onChange(field.options.filter((o) => set.has(o)));\n };\n return (\n <fieldset\n className=\"setto-form__fieldset\"\n role={multiple ? undefined : 'radiogroup'}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy}\n aria-required={!multiple && field.required ? true : undefined}\n >\n <legend className={cx('setto-form__legend', classNames.label)}>{labelText}</legend>\n <div className={cx('setto-form__options', classNames.options)}>\n {field.options.map((option, i) => {\n const optionId = `${id}-${i}`;\n const on = multiple ? (selected as string[]).includes(option) : selected === option;\n return (\n <label key={option} htmlFor={optionId} className={cx('setto-form__option', classNames.option)}>\n <input\n id={optionId}\n type={multiple ? 'checkbox' : 'radio'}\n name={field.name}\n value={option}\n checked={on}\n required={!multiple && field.required ? true : undefined}\n onChange={(e) => toggle(option, e.target.checked)}\n />\n <span>{option}</span>\n </label>\n );\n })}\n </div>\n </fieldset>\n );\n }\n\n const text = typeof value === 'string' ? value : '';\n const labelled = editable ? { 'aria-labelledby': labelId } : {};\n\n let control: ReactNode;\n if (field.type === 'textarea') {\n control = (\n <textarea\n id={id}\n name={field.name}\n value={text}\n rows={5}\n placeholder={field.placeholder || undefined}\n onChange={(e: ChangeEvent<HTMLTextAreaElement>) => onChange(e.target.value)}\n className={cx('setto-form__textarea', classNames.textarea)}\n {...labelled}\n {...aria}\n />\n );\n } else if (field.type === 'select') {\n control = (\n <select\n id={id}\n name={field.name}\n value={text}\n onChange={(e: ChangeEvent<HTMLSelectElement>) => onChange(e.target.value)}\n className={cx('setto-form__select', classNames.select)}\n {...labelled}\n {...aria}\n >\n <option value=\"\" disabled={field.required}>\n {field.placeholder || placeholderFallback}\n </option>\n {field.options.map((option) => (\n <option key={option} value={option}>\n {option}\n </option>\n ))}\n </select>\n );\n } else {\n control = (\n <input\n id={id}\n type={inputType(field)}\n name={field.name}\n value={text}\n placeholder={field.placeholder || undefined}\n inputMode={inputMode(field)}\n autoComplete={autoCompleteFor(field)}\n onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.target.value)}\n className={cx('setto-form__input', classNames.input)}\n {...labelled}\n {...aria}\n />\n );\n }\n\n return (\n <>\n <FieldLabel\n editable={editable}\n htmlFor={id}\n id={labelId}\n className={cx('setto-form__label', classNames.label)}\n >\n {labelText}\n </FieldLabel>\n {control}\n </>\n );\n}\n\n/**\n * A `<label for>` in the published site; a `<span id>` (and `aria-labelledby`\n * on the control) while editing, because clicking a label focuses its control\n * and would take the caret away from the text the editor is trying to change.\n */\nfunction FieldLabel({\n editable,\n htmlFor,\n id,\n className,\n children,\n}: {\n editable: boolean;\n htmlFor: string;\n id: string;\n className: string;\n children: ReactNode;\n}) {\n if (editable) {\n return (\n <span id={id} className={className}>\n {children}\n </span>\n );\n }\n return (\n <label htmlFor={htmlFor} className={className}>\n {children}\n </label>\n );\n}\n\nfunction inputType(field: ResolvedFormField): string {\n switch (field.type) {\n case 'email':\n case 'tel':\n case 'url':\n case 'date':\n return field.type;\n case 'number':\n // A text input with a numeric keyboard: no spinner, and values such as\n // \"+47 …\" or \"12,5\" are validated by us rather than refused by the browser.\n return 'text';\n default:\n return 'text';\n }\n}\n\nfunction inputMode(field: ResolvedFormField): 'email' | 'tel' | 'url' | 'decimal' | undefined {\n switch (field.type) {\n case 'email':\n return 'email';\n case 'tel':\n return 'tel';\n case 'url':\n return 'url';\n case 'number':\n return 'decimal';\n default:\n return undefined;\n }\n}\n\nfunction autoCompleteFor(field: ResolvedFormField): string | undefined {\n if (field.type === 'email') return 'email';\n if (field.type === 'tel') return 'tel';\n if (field.type === 'url') return 'url';\n if (/^(navn|name|fullt?[-_]?navn|full[-_]?name)$/i.test(field.name)) return 'name';\n if (/^(firma|bedrift|company|organisasjon|organization)$/i.test(field.name)) return 'organization';\n return undefined;\n}\n\nfunction cssEscape(value: string): string {\n return typeof CSS !== 'undefined' && typeof CSS.escape === 'function'\n ? CSS.escape(value)\n : value.replace(/[\"\\\\]/g, '\\\\$&');\n}\n\nfunction CheckIcon() {\n return (\n <svg\n className=\"setto-form__success-icon\"\n viewBox=\"0 0 40 40\"\n fill=\"none\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <circle cx=\"20\" cy=\"20\" r=\"19\" stroke=\"currentColor\" strokeWidth=\"2\" />\n <path\n d=\"M12 20.5l5.5 5.5L28 15\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\n/* ─────────── Baseline styles ─────────── */\n\nconst STYLE_ID = 'setto-form-styles';\n\n/**\n * Enough that an unstyled form looks intentional, while still losing to\n * anything the site says on purpose. Colours lean on `currentColor`, so the\n * form follows whatever section it sits in, light or dark.\n *\n * Every rule is scoped under `.setto-form`, which is not decoration: written\n * at the zero specificity of a bare `:where()`, these rules lost to Tailwind's\n * Preflight — `button, input, optgroup, select, textarea { padding: 0 }` is an\n * element selector, and an element selector outranks nothing at all. Every\n * generated site ships Preflight, so every form went out with no padding on\n * its fields or its button. Simon, on a real site: \"the form in the bottom\n * seems unstyled.\"\n *\n * So the sheet is in two halves, and which half a property lands in is decided\n * by who it has to beat.\n *\n * SHAPE — padding, width, radius, the things Preflight strips — is scoped\n * `.setto-form :where(…)`. That scores one class, which beats an element\n * selector, and puts back exactly what the reset took away.\n *\n * COLOUR — background, border colour, text colour — stays at zero specificity,\n * because here the site really must win. The generator emits `bg-card` and\n * `text-foreground` on these very elements, and scoping those under a class\n * would tie on weight and then beat them on order, quietly discarding the\n * palette the build chose. Shape is ours; colour is theirs.\n */\nexport const BASE_CSS = `\n.setto-form{display:grid;gap:1.1rem;position:relative}\n.setto-form :where(.setto-form__field){display:grid;gap:.4rem;position:relative}\n.setto-form :where(.setto-form__label,.setto-form__legend){font-weight:500;line-height:1.3;padding:0}\n.setto-form :where(.setto-form__required){opacity:.6;margin-left:.15em}\n.setto-form :where(.setto-form__input,.setto-form__textarea,.setto-form__select){width:100%;box-sizing:border-box;padding:.7rem .85rem;border-width:1px;border-style:solid;border-radius:.6rem;font:inherit;line-height:1.4}\n.setto-form :where(.setto-form__textarea){min-height:7.5rem;resize:vertical}\n.setto-form :where(.setto-form__fieldset){border:0;padding:0;margin:0;min-width:0;display:grid;gap:.5rem}\n.setto-form :where(.setto-form__options){display:grid;gap:.5rem}\n.setto-form :where(.setto-form__option,.setto-form__check){display:flex;gap:.6rem;align-items:flex-start;line-height:1.4;cursor:pointer;font-weight:400}\n.setto-form :where(.setto-form__option input,.setto-form__check input){margin:.25em 0 0;flex:none;accent-color:currentColor}\n.setto-form :where(.setto-form__actions){display:flex;flex-wrap:wrap;gap:.75rem 1rem;align-items:center}\n.setto-form :where(.setto-form__button){cursor:pointer;font:inherit;font-weight:500;padding:.75rem 1.4rem;border-radius:999px;border-width:1px;border-style:solid}\n.setto-form :where(.setto-form__success){display:grid;gap:.75rem;justify-items:start;outline:none}\n.setto-form :where(.setto-form__success-icon){width:2.5rem;height:2.5rem}\n.setto-form :where(.setto-form__success-text){margin:0;font-size:1.05em}\n.setto-form :where(.setto-form__hp){position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none}\n:where(.setto-form__input,.setto-form__textarea,.setto-form__select){border-color:color-mix(in srgb,currentColor 28%,transparent);background:color-mix(in srgb,currentColor 4%,transparent);color:inherit}\n:where(.setto-form__input,.setto-form__textarea,.setto-form__select)::placeholder{color:inherit;opacity:.5}\n:where(.setto-form__input,.setto-form__textarea,.setto-form__select):focus-visible{outline:2px solid currentColor;outline-offset:1px}\n:where(.setto-form__button){border-color:currentColor;background:transparent;color:inherit}\n:where(.setto-form__button:disabled){opacity:.6;cursor:progress}\n:where(.setto-form__field-error,.setto-form__error){font-size:.875rem;color:#b42318;margin:0}\n:where(.setto-form__success-icon){color:#0f7b4f}\n:where(.setto-form__again){background:none;border:0;padding:0;color:inherit;text-decoration:underline;cursor:pointer;font:inherit;opacity:.8;width:fit-content;max-width:100%;text-align:inherit}\n:where(.setto-form [aria-invalid=\"true\"]){border-color:#b42318}\n`;\n\nfunction useFormStyles() {\n useInsertionEffect(() => {\n if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;\n const el = document.createElement('style');\n el.id = STYLE_ID;\n el.textContent = BASE_CSS;\n document.head.appendChild(el);\n }, []);\n}\n\nconst addFieldStyle: CSSProperties = {\n justifySelf: 'start',\n padding: '6px 12px',\n border: '1px dashed #999',\n borderRadius: 999,\n background: 'rgba(255,255,255,0.85)',\n color: '#333',\n fontSize: 13,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n cursor: 'pointer',\n};\n\nconst previewStyle: CSSProperties = {\n display: 'grid',\n gap: 6,\n padding: '10px 12px',\n border: '1px dashed rgba(100,10,255,0.35)',\n borderRadius: 8,\n fontSize: '0.9em',\n lineHeight: 1.4,\n};\n\nconst previewHintStyle: CSSProperties = {\n color: '#640AFF',\n fontSize: 11,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n textTransform: 'uppercase',\n letterSpacing: '0.04em',\n marginRight: 4,\n};\n","import type { SettoModule } from '../module';\n\n/**\n * The forms module: a form primitive the site renders, and the api segment\n * behind it. Server side lives in setto-server `src/modules/forms`, and so\n * does the inbox the customer reads submissions in.\n */\nexport const formsModule: SettoModule = {\n id: 'forms',\n label: 'Skjemaer',\n};\n\nexport { SettoForm } from './SettoForm';\nexport type { SettoFormProps, SettoFormClassNames } from './SettoForm';\nexport type { FormSettings, FormSubmissionRow, FormsApi } from './api';\nexport {\n FORM_FIELD_TYPES,\n FORM_FIELD_TYPE_LABELS,\n fieldTypeHasOptions,\n fieldTypeHasPlaceholder,\n formFieldsPrefix,\n isFormFieldType,\n readLocaleFields,\n settoSubmissionUrl,\n} from './fields';\nexport type {\n FormFieldProp,\n FormFieldType,\n FormValue,\n FormValues,\n ResolvedFormField,\n SubmissionEnvelope,\n} from './fields';\n","import type { SettoModule } from '../module';\n\n/**\n * The customer's own domain.\n *\n * A dashboard tab rather than a step in the conversation: a domain is a\n * setting somebody returns to — when they finally buy the name, when they move\n * registrar, when a record gets deleted by accident — and the conversation\n * that built the site is not somewhere anybody goes back to.\n *\n * Only the tab is here. The panel behind it is served from setto-server, which\n * is also where the DNS instructions are worked out.\n */\nexport const domainModule: SettoModule = {\n id: 'domain',\n label: 'Domene',\n};\n","import { chatModule } from './chat';\nimport { domainModule } from './domain';\nimport { formsModule } from './forms';\nimport type { SettoModule } from './module';\n\nexport type { SettoModule } from './module';\n\n/** Every module the dashboard shows, in tab order. Setto draws the tabs. */\nexport const SETTO_MODULES: readonly SettoModule[] = [formsModule, chatModule, domainModule];\n\nexport function findModule(id: string | null): SettoModule | undefined {\n return id ? SETTO_MODULES.find((m) => m.id === id) : undefined;\n}\n","import { useTranslation } from 'react-i18next';\nimport { useSetto } from './provider';\n\nexport interface SettoVideoProps {\n /** i18n key holding the video URL (YouTube, Vimeo, or direct MP4). */\n srcKey: string;\n /** Optional i18n key holding a poster image URL (HTML5 video only). */\n posterKey?: string;\n title?: string;\n className?: string;\n}\n\n/**\n * Renders a video from a URL stored in i18n. YouTube and Vimeo URLs become\n * iframe embeds; everything else renders as an HTML5 `<video>` element.\n *\n * Editors can change the URL via the i18n draft store (a dedicated picker\n * UI may follow; until then it's swap-via-publish like other content).\n */\nexport function SettoVideo({ srcKey, posterKey, title, className }: SettoVideoProps) {\n const { t, i18n } = useTranslation();\n const { store } = useSetto();\n\n const src = store ? store.get(srcKey, i18n.language) : t(srcKey, { defaultValue: '' });\n const poster = posterKey\n ? store\n ? store.get(posterKey, i18n.language)\n : t(posterKey, { defaultValue: '' })\n : undefined;\n\n if (!src) {\n return (\n <div\n className={className}\n data-setto-video={srcKey}\n data-setto-video-empty=\"1\"\n />\n );\n }\n\n const embed = toEmbedUrl(src);\n if (embed) {\n return (\n <iframe\n className={className}\n src={embed}\n title={title ?? 'Video'}\n loading=\"lazy\"\n allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n allowFullScreen\n data-setto-video={srcKey}\n />\n );\n }\n\n return (\n <video\n className={className}\n src={src}\n poster={poster}\n controls\n preload=\"metadata\"\n data-setto-video={srcKey}\n />\n );\n}\n\nfunction toEmbedUrl(url: string): string | null {\n try {\n const u = new URL(url);\n if (u.hostname === 'youtu.be') {\n return `https://www.youtube.com/embed/${u.pathname.slice(1)}`;\n }\n if (u.hostname.endsWith('youtube.com')) {\n const v = u.searchParams.get('v');\n if (v) return `https://www.youtube.com/embed/${v}`;\n if (u.pathname.startsWith('/embed/')) return url;\n }\n if (u.hostname.endsWith('vimeo.com')) {\n const id = u.pathname.split('/').filter(Boolean).pop();\n if (id && /^\\d+$/.test(id)) return `https://player.vimeo.com/video/${id}`;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import type { MapLocation } from '../map-tools';\nimport type { I18nStore } from './i18n-store';\n\n/**\n * Where a `SettoMap` points, and how that becomes an OpenStreetMap embed.\n *\n * The location is content, stored under the map's key in every locale file:\n * `{ lat, lng, zoom, title }`, all strings, because every other value in those\n * files is. Pure on purpose — the component, the editor's tools and the tests\n * all agree on one reading of what the build agent wrote.\n */\n\n/** What a locale file holds under a map's key. Every field may be missing. */\nexport interface RawMapContent {\n lat?: unknown;\n lng?: unknown;\n zoom?: unknown;\n}\n\nexport const MAP_MIN_ZOOM = 1;\nexport const MAP_MAX_ZOOM = 19;\nexport const MAP_DEFAULT_ZOOM = 15;\nexport const MAP_DEFAULT_TITLE = 'Kart';\n\n/** Web mercator stops here; a map centred further north cannot be drawn. */\nexport const MERCATOR_MAX_LAT = 85.0511287798066;\n\n/**\n * The frame the zoom is chosen for.\n *\n * The embed is told a bounding box, not a zoom, and fits that box into\n * whatever size the iframe has. A box sized for a small frame keeps the zoom\n * the owner chose on anything larger — a phone-width map or a wide `h-72` band\n * both open at it — where a box sized for a desktop would zoom a phone out.\n */\nexport const MAP_ASSUMED_WIDTH = 320;\nexport const MAP_ASSUMED_HEIGHT = 240;\n\nconst TILE_SIZE = 256;\n\n/**\n * A coordinate as the locale spells it.\n *\n * Strict about shape, because `Number('')` is 0 and a map of the Gulf of\n * Guinea is the wrong way to say a value is missing. A decimal comma is\n * accepted: the owner is Norwegian and so is their keyboard.\n */\nexport function parseCoordinate(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value !== 'string') return null;\n const text = value.trim().replace(',', '.');\n if (!/^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$/.test(text)) return null;\n const n = Number(text);\n return Number.isFinite(n) ? n : null;\n}\n\n/**\n * The zoom, forgiving where the coordinates are not.\n *\n * A missing or unreadable zoom still gives a usable map, so it falls back to\n * the default; a readable one out of range is clamped and rounded rather than\n * thrown away.\n */\nexport function parseZoom(value: unknown): number {\n const n = parseCoordinate(value);\n if (n === null) return MAP_DEFAULT_ZOOM;\n return Math.min(MAP_MAX_ZOOM, Math.max(MAP_MIN_ZOOM, Math.round(n)));\n}\n\n/** A location, or null when the coordinates are missing, unreadable or off the map. */\nexport function parseMapLocation(raw: RawMapContent | null | undefined): MapLocation | null {\n if (!raw) return null;\n const lat = parseCoordinate(raw.lat);\n const lng = parseCoordinate(raw.lng);\n if (lat === null || lng === null) return null;\n if (Math.abs(lat) > MERCATOR_MAX_LAT || Math.abs(lng) > 180) return null;\n return { lat, lng, zoom: parseZoom(raw.zoom) };\n}\n\n/** Six decimals is about ten centimetres; more is noise in a content file. */\nexport function formatCoordinate(n: number): string {\n const fixed = n.toFixed(6);\n const trimmed = fixed.includes('.') ? fixed.replace(/0+$/, '').replace(/\\.$/, '') : fixed;\n return trimmed === '-0' ? '0' : trimmed;\n}\n\n/** The strings a location is stored as. */\nexport function serialiseMapLocation(location: MapLocation): {\n lat: string;\n lng: string;\n zoom: string;\n} {\n return {\n lat: formatCoordinate(location.lat),\n lng: formatCoordinate(location.lng),\n zoom: String(parseZoom(location.zoom)),\n };\n}\n\nfunction worldSize(zoom: number): number {\n return TILE_SIZE * 2 ** zoom;\n}\n\nfunction latToWorldY(lat: number, zoom: number): number {\n const clamped = Math.max(-MERCATOR_MAX_LAT, Math.min(MERCATOR_MAX_LAT, lat));\n const sin = Math.sin((clamped * Math.PI) / 180);\n return (0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * worldSize(zoom);\n}\n\nfunction worldYToLat(y: number, zoom: number): number {\n const n = Math.PI - (2 * Math.PI * y) / worldSize(zoom);\n return (180 / Math.PI) * Math.atan(Math.sinh(n));\n}\n\nexport interface MapBbox {\n minLng: number;\n minLat: number;\n maxLng: number;\n maxLat: number;\n}\n\n/**\n * The box a frame of `width` × `height` pixels would show, centred on the\n * location at its zoom. Longitude is linear in web mercator; latitude is not,\n * so it goes through world pixels and back.\n */\nexport function mapBbox(\n location: MapLocation,\n width: number = MAP_ASSUMED_WIDTH,\n height: number = MAP_ASSUMED_HEIGHT,\n): MapBbox {\n const degreesPerPixel = 360 / worldSize(location.zoom);\n const halfLng = (width / 2) * degreesPerPixel;\n const y = latToWorldY(location.lat, location.zoom);\n const max = worldSize(location.zoom);\n return {\n minLng: Math.max(-180, location.lng - halfLng),\n maxLng: Math.min(180, location.lng + halfLng),\n minLat: worldYToLat(Math.min(max, y + height / 2), location.zoom),\n maxLat: worldYToLat(Math.max(0, y - height / 2), location.zoom),\n };\n}\n\n/** The OpenStreetMap embed for a location, marker on the point itself. */\nexport function mapEmbedUrl(location: MapLocation): string {\n const box = mapBbox(location);\n const bbox = [box.minLng, box.minLat, box.maxLng, box.maxLat].map(formatCoordinate).join(',');\n const marker = `${formatCoordinate(location.lat)},${formatCoordinate(location.lng)}`;\n return `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${marker}`;\n}\n\n/**\n * Write a location to every language at once.\n *\n * A place is not translated, so the same numbers go into each locale, the way\n * `SettoImage` writes an image path. The title is left alone: that one is\n * words, and belongs to each language.\n */\nexport function writeMapLocation(\n store: Pick<I18nStore, 'set' | 'batch'>,\n languages: readonly string[],\n key: string,\n location: MapLocation,\n): void {\n const values = serialiseMapLocation(location);\n store.batch(() => {\n for (const lng of languages) {\n store.set(`${key}.lat`, lng, values.lat);\n store.set(`${key}.lng`, lng, values.lng);\n store.set(`${key}.zoom`, lng, values.zoom);\n }\n });\n}\n","import { useEffect, useState, type CSSProperties } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useSettoChromeSlot } from './chrome';\nimport { useGuestEdit } from './guest-edit';\nimport {\n MAP_DEFAULT_TITLE,\n mapEmbedUrl,\n parseMapLocation,\n writeMapLocation,\n} from './lib/map-location';\nimport type { MapToolsProps } from './map-tools';\nimport { useSetto } from './provider';\n\nexport interface SettoMapProps {\n /**\n * i18n key prefix holding `lat`, `lng`, optional `zoom` (1–19, default 15)\n * and optional `title`. A static string literal, like every other key.\n */\n k: string;\n className?: string;\n style?: CSSProperties;\n /** The iframe's loading strategy. Default `lazy`. */\n loading?: 'lazy' | 'eager';\n}\n\n/**\n * A map whose location is content.\n *\n * Rendered as an OpenStreetMap embed with a marker on the point, because a\n * hand-written embed with a guessed pin in the middle of a fjord is what the\n * build agent produced without it, and nobody could move that pin. Here the\n * point lives in the locale, so it publishes like text, and in edit mode the\n * tools Setto serves (`map-tools`) sit over the map to move it.\n *\n * The wrapper carries the site's classes in both modes and the iframe fills\n * it, so a map sized with `h-72 w-full` is the same box whether or not anybody\n * is editing. Without a usable location the wrapper renders empty — no iframe\n * pointing at 0,0 — and still takes the tools, so the owner can set one.\n */\nexport function SettoMap({ k, className, style, loading = 'lazy' }: SettoMapProps) {\n const { t, i18n } = useTranslation();\n const { editMode, store } = useSetto();\n const guestEdit = useGuestEdit();\n const editable = editMode || guestEdit.active;\n /*\n * The tools come from Setto, not from this bundle: the map is the\n * customer's and has to render with Setto unreachable, and when the chrome\n * has not arrived there is simply nothing drawn on top of it.\n */\n const MapTools = useSettoChromeSlot<MapToolsProps>('map-tools');\n\n const [, force] = useState(0);\n useEffect(() => {\n if (!store) return;\n return store.subscribe(() => force((x) => x + 1));\n }, [store]);\n\n const lng = i18n.language;\n const read = (field: string): string => {\n const key = `${k}.${field}`;\n // The draft layer first; then i18next, which falls back across languages.\n return (store?.get(key, lng) || t(key, { defaultValue: '' })) as string;\n };\n\n const location = parseMapLocation({ lat: read('lat'), lng: read('lng'), zoom: read('zoom') });\n const title = read('title') || MAP_DEFAULT_TITLE;\n const tools =\n editable && store && MapTools ? (\n <MapTools\n location={location}\n onChange={(next) => writeMapLocation(store, store.languages(lng), k, next)}\n />\n ) : null;\n\n if (!location) {\n return (\n <div className={className} style={style} data-setto-map={k} data-setto-map-empty=\"1\">\n {tools ? <div style={fillStyle}>{tools}</div> : null}\n </div>\n );\n }\n\n return (\n <div className={className} style={style} data-setto-map={k}>\n <div style={fillStyle}>\n <iframe\n src={mapEmbedUrl(location)}\n title={title}\n loading={loading}\n referrerPolicy=\"strict-origin-when-cross-origin\"\n style={iframeStyle}\n />\n {tools}\n </div>\n </div>\n );\n}\n\n/*\n * Positioned inside the wrapper rather than on it: the site's classes may\n * already position the wrapper (`absolute inset-0`), and an inline `relative`\n * would silently override them. The radius is inherited so `rounded-xl` on\n * the wrapper clips the map the way it would clip an image.\n */\nconst fillStyle: CSSProperties = {\n position: 'relative',\n width: '100%',\n height: '100%',\n borderRadius: 'inherit',\n overflow: 'hidden',\n};\n\nconst iframeStyle: CSSProperties = {\n display: 'block',\n width: '100%',\n height: '100%',\n border: 0,\n};\n","import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport type { AnimationPreset } from './block-tree/schema';\n\nexport interface SettoAnimationProps {\n preset: AnimationPreset;\n /** Delay before play, in milliseconds. */\n delay?: number;\n /** Duration in milliseconds. Defaults per preset. */\n duration?: number;\n className?: string;\n children: ReactNode;\n}\n\nconst DEFAULT_DURATION: Record<AnimationPreset, number> = {\n fadeIn: 600,\n slideUp: 700,\n stagger: 700,\n scrollReveal: 700,\n};\n\n/**\n * Lightweight, CSS-driven reveal wrapper. Triggers once when scrolled into\n * view (or immediately, for non-scroll presets). Honors\n * `prefers-reduced-motion`, falls back to plain children with no animation.\n *\n * Hosts that use GSAP (carryon.no, setto-site) should keep their own\n * `data-reveal` system; this primitive exists so generated layout trees\n * have a portable animation primitive without dragging GSAP into the\n * setto-client bundle.\n */\nexport function SettoAnimation({\n preset,\n delay = 0,\n duration,\n className,\n children,\n}: SettoAnimationProps) {\n const ref = useRef<HTMLDivElement>(null);\n const [visible, setVisible] = useState(preset === 'fadeIn' || preset === 'slideUp');\n\n useEffect(() => {\n if (preset === 'fadeIn' || preset === 'slideUp') {\n const t = window.setTimeout(() => setVisible(true), delay);\n return () => window.clearTimeout(t);\n }\n const el = ref.current;\n if (!el || typeof IntersectionObserver === 'undefined') {\n setVisible(true);\n return;\n }\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n setVisible(true);\n io.disconnect();\n }\n }\n },\n { threshold: 0.15 },\n );\n io.observe(el);\n return () => io.disconnect();\n }, [preset, delay]);\n\n const reduced =\n typeof window !== 'undefined' &&\n window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n\n const ms = duration ?? DEFAULT_DURATION[preset];\n const transition = reduced\n ? undefined\n : `opacity ${ms}ms ease-out ${delay}ms, transform ${ms}ms ease-out ${delay}ms`;\n\n const hiddenTransform = preset === 'slideUp' || preset === 'scrollReveal' ? 'translateY(24px)' : 'none';\n const style = reduced\n ? undefined\n : {\n opacity: visible ? 1 : 0,\n transform: visible ? 'none' : hiddenTransform,\n transition,\n willChange: 'opacity, transform',\n };\n\n if (preset === 'stagger') {\n return (\n <div\n ref={ref}\n className={className}\n data-setto-animation={preset}\n data-setto-animation-visible={visible ? '1' : '0'}\n >\n {wrapChildrenForStagger(children, visible, ms, delay, reduced)}\n </div>\n );\n }\n\n return (\n <div\n ref={ref}\n className={className}\n style={style}\n data-setto-animation={preset}\n data-setto-animation-visible={visible ? '1' : '0'}\n >\n {children}\n </div>\n );\n}\n\nfunction wrapChildrenForStagger(\n children: ReactNode,\n visible: boolean,\n ms: number,\n baseDelay: number,\n reduced: boolean,\n): ReactNode {\n if (reduced) return children;\n const arr = Array.isArray(children) ? children : [children];\n const step = 80;\n return arr.map((child, i) => (\n <div\n key={i}\n style={{\n opacity: visible ? 1 : 0,\n transform: visible ? 'none' : 'translateY(16px)',\n transition: `opacity ${ms}ms ease-out ${baseDelay + i * step}ms, transform ${ms}ms ease-out ${baseDelay + i * step}ms`,\n }}\n >\n {child}\n </div>\n ));\n}\n","import { useEffect, useState, type ReactNode } from 'react';\nimport { siteHomeUrl } from '../lib/urls';\nimport { useSetto } from '../provider';\n\ntype Mode = 'signin' | 'forgot' | 'set_password';\n\nexport interface AuthGateProps {\n /** Rendered after a session is established. */\n children: ReactNode;\n}\n\nfunction authCallbackType(): 'invite' | 'recovery' | null {\n const hash = window.location.hash.replace(/^#/, '');\n if (!hash) return null;\n const type = new URLSearchParams(hash).get('type');\n if (type === 'invite' || type === 'recovery') return type;\n return null;\n}\n\nfunction clearAuthHashFromUrl() {\n const { pathname, search } = window.location;\n window.history.replaceState(null, '', pathname + search);\n}\n\nfunction consumeInviteErrorFromUrl(): string | null {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('setto_invite_error');\n if (!code) return null;\n params.delete('setto_invite_error');\n const qs = params.toString();\n window.history.replaceState(null, '', `${window.location.pathname}${qs ? `?${qs}` : ''}`);\n return code === 'invalid'\n ? 'Lenken er ugyldig eller utløpt. Be om en ny nullstilling eller invitasjon.'\n : 'Kunne ikke aktivere lenken.';\n}\n\n/**\n * Wraps `children` with Supabase email/password login. Sign-up is disabled;\n * editors are invited by platform admins. Supports password reset and invite\n * links from Supabase email.\n */\nexport function AuthGate({ children }: AuthGateProps) {\n const { supabase: loaded, loadSupabase, api, config, session, authLoading } = useSetto();\n // Loaded by the time the form is shown, unless the host's router brought us here.\n const client = async () => loaded ?? (await loadSupabase());\n const [mode, setMode] = useState<Mode>('signin');\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n const [confirmPassword, setConfirmPassword] = useState('');\n const [error, setError] = useState<string | null>(null);\n const [info, setInfo] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n\n useEffect(() => {\n const inviteError = consumeInviteErrorFromUrl();\n if (inviteError) {\n setError(inviteError);\n setMode('signin');\n return;\n }\n const callback = authCallbackType();\n if (callback) setMode('set_password');\n }, []);\n\n if (authLoading) {\n return <div style={loadingStyle}>Laster …</div>;\n }\n\n if (session && mode !== 'set_password') return <>{children}</>;\n\n if (mode === 'set_password' && !session) {\n return (\n <div style={loadingStyle}>\n {authCallbackType()\n ? 'Aktiverer invitasjon …'\n : 'Åpne lenken fra e-posten for å sette passord.'}\n </div>\n );\n }\n\n const submitSignIn = async (e: React.FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n setInfo(null);\n try {\n const supabase = await client();\n const result = await supabase.auth.signInWithPassword({ email, password });\n if (result.error) throw result.error;\n if (result.data.session) {\n await supabase.auth.setSession({\n access_token: result.data.session.access_token,\n refresh_token: result.data.session.refresh_token,\n });\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Ukjent feil');\n } finally {\n setBusy(false);\n }\n };\n\n const submitForgot = async (e: React.FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setError(null);\n setInfo(null);\n try {\n await api.requestPasswordReset(config.siteId, email);\n setInfo('Vi har sendt en lenke for å nullstille passordet. Sjekk innboksen.');\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Ukjent feil');\n } finally {\n setBusy(false);\n }\n };\n\n const submitSetPassword = async (e: React.FormEvent) => {\n e.preventDefault();\n if (password !== confirmPassword) {\n setError('Passordene er ikke like.');\n return;\n }\n if (password.length < 8) {\n setError('Passordet må være minst 8 tegn.');\n return;\n }\n setBusy(true);\n setError(null);\n setInfo(null);\n try {\n const supabase = await client();\n const { error: updateError } = await supabase.auth.updateUser({ password });\n if (updateError) throw updateError;\n clearAuthHashFromUrl();\n const { data: sessionData } = await supabase.auth.getSession();\n if (sessionData.session) {\n window.location.replace(siteHomeUrl());\n return;\n }\n setMode('signin');\n setPassword('');\n setConfirmPassword('');\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Ukjent feil');\n } finally {\n setBusy(false);\n }\n };\n\n if (mode === 'set_password') {\n const callback = authCallbackType();\n return (\n <div style={shellStyle}>\n <form onSubmit={submitSetPassword} style={formStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <p style={{ margin: 0, color: '#888', fontSize: 13 }}>\n {callback === 'invite'\n ? 'Velg et passord for å fullføre invitasjonen.'\n : 'Velg et nytt passord.'}\n </p>\n <input\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n placeholder=\"Nytt passord\"\n autoComplete=\"new-password\"\n required\n minLength={8}\n style={inputStyle}\n />\n <input\n type=\"password\"\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n placeholder=\"Gjenta passord\"\n autoComplete=\"new-password\"\n required\n minLength={8}\n style={inputStyle}\n />\n {error ? <div style={{ color: '#ff7a7a', fontSize: 12 }}>{error}</div> : null}\n {info ? <div style={{ color: '#9fd89f', fontSize: 12 }}>{info}</div> : null}\n <button type=\"submit\" disabled={busy} style={btnStyle}>\n {busy ? '...' : 'Lagre passord'}\n </button>\n </form>\n </div>\n );\n }\n\n if (mode === 'forgot') {\n return (\n <div style={shellStyle}>\n <form onSubmit={submitForgot} style={formStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <p style={{ margin: 0, color: '#888', fontSize: 13 }}>\n Skriv inn e-posten din, så sender vi en lenke for å nullstille passordet.\n </p>\n <input\n type=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n placeholder=\"E-post\"\n autoComplete=\"email\"\n required\n style={inputStyle}\n />\n {error ? <div style={{ color: '#ff7a7a', fontSize: 12 }}>{error}</div> : null}\n {info ? <div style={{ color: '#9fd89f', fontSize: 12 }}>{info}</div> : null}\n <button type=\"submit\" disabled={busy} style={btnStyle}>\n {busy ? '...' : 'Send lenke'}\n </button>\n <button\n type=\"button\"\n onClick={() => {\n setMode('signin');\n setError(null);\n setInfo(null);\n }}\n style={linkStyle}\n >\n Tilbake til innlogging\n </button>\n </form>\n </div>\n );\n }\n\n return (\n <div style={shellStyle}>\n <form onSubmit={submitSignIn} style={formStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <p style={{ margin: 0, color: '#888', fontSize: 13 }}>\n Logg inn for å redigere innholdet. Har du fått invitasjon, bruk lenken i e-posten\n første gang.\n </p>\n <input\n type=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n placeholder=\"E-post\"\n autoComplete=\"email\"\n required\n style={inputStyle}\n />\n <input\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n placeholder=\"Passord\"\n autoComplete=\"current-password\"\n required\n style={inputStyle}\n />\n {error ? <div style={{ color: '#ff7a7a', fontSize: 12 }}>{error}</div> : null}\n {info ? <div style={{ color: '#9fd89f', fontSize: 12 }}>{info}</div> : null}\n <button type=\"submit\" disabled={busy} style={btnStyle}>\n {busy ? '...' : 'Logg inn'}\n </button>\n <button\n type=\"button\"\n onClick={() => {\n setMode('forgot');\n setError(null);\n setInfo(null);\n }}\n style={linkStyle}\n >\n Glemt passord?\n </button>\n </form>\n </div>\n );\n}\n\nconst shellStyle: React.CSSProperties = {\n minHeight: '100dvh',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#0a0a0d',\n color: '#fff',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nconst formStyle: React.CSSProperties = {\n display: 'flex',\n flexDirection: 'column',\n gap: 12,\n width: 320,\n background: '#15151a',\n padding: 24,\n borderRadius: 12,\n boxShadow: '0 12px 40px rgba(0,0,0,0.4)',\n};\n\nconst inputStyle: React.CSSProperties = {\n background: '#1f1f25',\n color: '#fff',\n border: '1px solid #2a2a32',\n borderRadius: 6,\n padding: '10px 12px',\n fontSize: 14,\n};\n\nconst btnStyle: React.CSSProperties = {\n background: '#640AFF',\n color: '#fff',\n border: 'none',\n borderRadius: 6,\n padding: '10px 12px',\n fontSize: 14,\n fontWeight: 500,\n cursor: 'pointer',\n};\n\nconst linkStyle: React.CSSProperties = {\n background: 'transparent',\n color: '#bda6ff',\n border: 'none',\n fontSize: 12,\n cursor: 'pointer',\n};\n\nconst loadingStyle: React.CSSProperties = {\n ...shellStyle,\n fontSize: 14,\n color: '#888',\n};\n","import type { CSSProperties } from 'react';\n\n/**\n * The dashboard's look, shared by the shell and every module view so a new\n * module's panel reads as part of the same place.\n */\n\nexport const shellStyle: CSSProperties = {\n minHeight: '100dvh',\n background: '#0a0a0d',\n color: '#fff',\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n\nexport const headerStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n padding: '16px 24px',\n borderBottom: '1px solid #1c1c22',\n};\n\nexport const mainStyle: CSSProperties = {\n maxWidth: 720,\n margin: '0 auto',\n padding: 24,\n display: 'flex',\n flexDirection: 'column',\n gap: 16,\n};\n\nexport const cardStyle: CSSProperties = {\n background: '#15151a',\n borderRadius: 12,\n padding: 20,\n display: 'flex',\n flexDirection: 'column',\n gap: 12,\n};\n\nexport const panelStyle: CSSProperties = {\n background: '#1a1a20',\n borderRadius: 8,\n padding: 14,\n display: 'flex',\n flexDirection: 'column',\n gap: 10,\n};\n\nexport const rowStyle: CSSProperties = {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n background: '#1a1a20',\n padding: '6px 10px',\n borderRadius: 6,\n};\n\nexport const mutedStyle: CSSProperties = {\n color: '#888',\n fontSize: 13,\n margin: 0,\n};\n\nexport const errStyle: CSSProperties = {\n color: '#ff7a7a',\n fontSize: 13,\n margin: 0,\n};\n\nexport const subheadingStyle: CSSProperties = {\n margin: 0,\n fontSize: 14,\n color: '#aaa',\n};\n\nexport const primaryBtnStyle: CSSProperties = {\n display: 'inline-block',\n background: '#640AFF',\n color: '#fff',\n border: 'none',\n borderRadius: 6,\n padding: '10px 14px',\n fontSize: 14,\n fontWeight: 500,\n textDecoration: 'none',\n cursor: 'pointer',\n};\n\nexport const secondaryBtnStyle: CSSProperties = {\n background: 'transparent',\n color: '#bda6ff',\n border: '1px solid #2a2a32',\n borderRadius: 6,\n padding: '6px 10px',\n fontSize: 12,\n cursor: 'pointer',\n};\n\nexport const dangerBtnStyle: CSSProperties = {\n alignSelf: 'flex-start',\n background: 'transparent',\n color: '#ff7a7a',\n border: '1px solid #4a3030',\n borderRadius: 6,\n padding: '8px 14px',\n fontSize: 13,\n cursor: 'pointer',\n};\n\nexport const inputStyle: CSSProperties = {\n width: '100%',\n boxSizing: 'border-box',\n background: '#0f0f13',\n color: '#fff',\n border: '1px solid #2a2a32',\n borderRadius: 6,\n padding: '8px 10px',\n fontSize: 13,\n fontFamily: 'inherit',\n};\n\nexport const tabBarStyle: CSSProperties = {\n display: 'flex',\n gap: 4,\n borderBottom: '1px solid #1c1c22',\n paddingBottom: 0,\n};\n\nexport function tabStyle(active: boolean): CSSProperties {\n return {\n background: 'transparent',\n border: 'none',\n borderBottom: active ? '2px solid #640AFF' : '2px solid transparent',\n color: active ? '#fff' : '#888',\n padding: '8px 12px',\n fontSize: 13,\n fontWeight: 500,\n cursor: 'pointer',\n marginBottom: -1,\n };\n}\n","import { useEffect, useRef } from 'react';\nimport { AuthGate } from '../edit-mode/auth-gate';\nimport { CHECKOUT_INTENT, isAdminPanelView, siteHomeUrl, wantsCheckout } from '../lib/urls';\nimport { useSettoAdminChrome } from '../chrome';\nimport { useSetto } from '../provider';\nimport {\n cardStyle,\n headerStyle,\n mainStyle,\n mutedStyle,\n primaryBtnStyle,\n secondaryBtnStyle,\n shellStyle,\n} from './styles';\n\n/**\n * The page at `/setto`. Mount it under a route like `<Route path=\"/setto/*\" …>`.\n *\n * What draws it lives in setto-server now, not here. The chrome bundle offers a\n * dashboard at runtime — publish history, the forms inbox, the domain panel —\n * and that is what fills this route, so changing any of it is one deploy of\n * Setto rather than a rebuild of every site it has ever made.\n *\n * What stays behind is the door: sign in, and get back to the site to edit.\n * That much has to work from the site's own bundle, because it is the only way\n * in and because the bug that takes the chrome down could be mine. Everything\n * past the door is Setto's, needs Setto to be reachable to do anything at all,\n * and is better absent than drawn from a copy that has been quietly rotting in\n * a pinned version since the day the site was built.\n */\nexport function SettoAdminApp() {\n const Chrome = useSettoAdminChrome();\n const { supabase, loadSupabase } = useSetto();\n /*\n * The sign-in needs supabase-js, which a page load on `/setto` fetches from\n * the start; this is for arriving here by the host's own router instead.\n */\n useEffect(() => {\n if (supabase) return;\n loadSupabase().catch(() => {\n // The gate's own submit tries again and says what went wrong.\n });\n }, [supabase, loadSupabase]);\n if (Chrome) return <Chrome />;\n\n return (\n <AuthGate>\n <SiteDoor />\n </AuthGate>\n );\n}\n\nfunction SiteDoor() {\n const { supabase, session, sites, currentSite, config } = useSetto();\n const redirectAfterSignIn = useRef(false);\n\n useEffect(() => {\n if (!supabase) return;\n const { data: sub } = supabase.auth.onAuthStateChange((event) => {\n if (event === 'SIGNED_IN' && !isAdminPanelView()) {\n redirectAfterSignIn.current = true;\n }\n });\n return () => sub.subscription.unsubscribe();\n }, [supabase]);\n\n useEffect(() => {\n if (!redirectAfterSignIn.current || !session || sites === null || isAdminPanelView()) {\n return;\n }\n if (currentSite) {\n redirectAfterSignIn.current = false;\n /*\n * Back to the site, carrying whatever they came to do.\n *\n * Somebody who pressed «Neste» on the preview bar wanted the checkout,\n * not the front page; without the marker they land where they started\n * and have to press the same button again, now that they are signed in.\n */\n window.location.replace(\n wantsCheckout() ? `${siteHomeUrl()}?${CHECKOUT_INTENT}=1` : siteHomeUrl(),\n );\n return;\n }\n redirectAfterSignIn.current = false;\n }, [session, sites, currentSite]);\n\n if (redirectAfterSignIn.current && session && (sites === null || currentSite)) {\n return <div style={loadingRedirectStyle}>Åpner redigering …</div>;\n }\n\n return (\n <div style={shellStyle}>\n <header style={headerStyle}>\n <h1 style={{ margin: 0, fontSize: 22 }}>Setto</h1>\n <SignOutButton />\n </header>\n\n <main style={mainStyle}>\n {sites === null ? <p style={mutedStyle}>Laster sider…</p> : null}\n\n {currentSite ? (\n <section style={cardStyle}>\n <h2 style={{ margin: 0, fontSize: 18 }}>{currentSite.display_name}</h2>\n <div style={{ display: 'flex', gap: 8 }}>\n <a href={siteHomeUrl()} style={primaryBtnStyle}>\n Begynn å redigere\n </a>\n </div>\n {/*\n Only ever seen when the chrome did not load, so it says what is\n missing rather than pretending the page is complete. Naming the\n panels matters: somebody who came for the skjema-innboksen needs\n to know it exists and is coming back, not wonder where it went.\n */}\n <p style={mutedStyle}>\n Publiseringer, skjemaer og domene er ikke tilgjengelig akkurat nå. Last siden på\n nytt om litt — redigering virker som vanlig i mellomtiden.\n </p>\n </section>\n ) : sites && sites.length === 0 ? (\n <p style={mutedStyle}>\n Du er ikke medlem av noen sider ennå. Be administratoren legge deg til.\n </p>\n ) : null}\n\n {sites && !currentSite && sites.length > 0 ? (\n <section style={cardStyle}>\n <p style={mutedStyle}>\n Du er logget inn på denne siden ({config.siteId}), men er ikke medlem her. Spør\n administrator om tilgang.\n </p>\n </section>\n ) : null}\n </main>\n </div>\n );\n}\n\nfunction SignOutButton() {\n const { supabase } = useSetto();\n return (\n <button onClick={() => void supabase?.auth.signOut()} style={secondaryBtnStyle}>\n Logg ut\n </button>\n );\n}\n\nconst loadingRedirectStyle: React.CSSProperties = {\n minHeight: '100dvh',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#0a0a0d',\n color: '#888',\n fontSize: 14,\n fontFamily: 'system-ui, -apple-system, \"Segoe UI\", sans-serif',\n};\n","/**\n * Per-type metadata for block-tree nodes.\n *\n * The renderer dispatches on node `type`; the validator and key extractor\n * consult this registry for allowed children, required content keys, and\n * whether a type carries a theme id.\n */\n\nimport type { BlockNode, BlockNodeType } from './schema';\n\nexport interface BlockTypeMeta {\n /**\n * Allowed child types. `null` means the node is a leaf; `'any'` means any\n * other type may appear as a child.\n */\n allowedChildren: BlockNodeType[] | 'any' | null;\n /** True when the node has a theme id (used in `sections.json`). */\n themed: boolean;\n /** True when this node participates as a `SectionToolbar` target. */\n selectable: boolean;\n}\n\nexport const BLOCK_REGISTRY: Record<BlockNodeType, BlockTypeMeta> = {\n section: { allowedChildren: 'any', themed: true, selectable: true },\n block: { allowedChildren: 'any', themed: true, selectable: true },\n container: { allowedChildren: 'any', themed: false, selectable: false },\n animation: { allowedChildren: 'any', themed: false, selectable: false },\n repeater: { allowedChildren: 'any', themed: false, selectable: false },\n text: { allowedChildren: null, themed: false, selectable: false },\n image: { allowedChildren: null, themed: false, selectable: false },\n icon: { allowedChildren: null, themed: false, selectable: false },\n form: { allowedChildren: null, themed: false, selectable: false },\n video: { allowedChildren: null, themed: false, selectable: false },\n};\n\n/** All known block types, kept in sync with `BLOCK_REGISTRY`. */\nexport const BLOCK_TYPES: readonly BlockNodeType[] = Object.keys(\n BLOCK_REGISTRY,\n) as BlockNodeType[];\n\n/** Returns the children of a node, or an empty array for leaves. */\nexport function nodeChildren(node: BlockNode): BlockNode[] {\n switch (node.type) {\n case 'section':\n case 'block':\n case 'container':\n case 'animation':\n return node.children;\n case 'repeater':\n return node.itemTemplate;\n default:\n return [];\n }\n}\n","/**\n * Runtime validator for block trees.\n *\n * Used by both `setto-client` (when loading a `home.layout.json` at boot)\n * and `setto-agent` (after generation, before sandbox build). No external\n * dependencies so we can ship to host sites without bundle bloat.\n */\n\nimport { BLOCK_REGISTRY, nodeChildren } from './registry';\nimport { FORM_FIELD_TYPES, isFormFieldType } from '../modules/forms/fields';\nimport type { BlockNode, BlockNodeType, BlockTree, FormField } from './schema';\n\nexport interface ValidationIssue {\n /** Dotted path to the offending node, e.g. `root[2].children[0]`. */\n path: string;\n message: string;\n}\n\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; issues: ValidationIssue[] };\n\nconst ANIMATION_PRESETS = ['fadeIn', 'slideUp', 'stagger', 'scrollReveal'] as const;\n\n/**\n * Validates a parsed block tree. Returns the first batch of issues found —\n * the goal is enough detail for a fixer model to act on, not exhaustive\n * reporting.\n */\nexport function validateBlockTree(input: unknown): ValidationResult {\n const issues: ValidationIssue[] = [];\n\n if (!isRecord(input)) {\n return fail('$', 'Block tree must be an object');\n }\n if (input.version !== '1') {\n issues.push({ path: '$.version', message: 'Expected version \"1\"' });\n }\n if (!Array.isArray(input.root)) {\n return fail('$.root', 'root must be an array of block nodes');\n }\n\n const seenIds = new Set<string>();\n for (let i = 0; i < input.root.length; i++) {\n validateNode(input.root[i], `root[${i}]`, seenIds, issues);\n }\n\n return issues.length ? { ok: false, issues } : { ok: true };\n}\n\nfunction validateNode(\n raw: unknown,\n path: string,\n seenIds: Set<string>,\n issues: ValidationIssue[],\n): void {\n if (!isRecord(raw)) {\n issues.push({ path, message: 'Node must be an object' });\n return;\n }\n const type = raw.type;\n if (typeof type !== 'string' || !(type in BLOCK_REGISTRY)) {\n issues.push({ path, message: `Unknown block type \"${String(type)}\"` });\n return;\n }\n if (typeof raw.id !== 'string' || raw.id.length === 0) {\n issues.push({ path, message: 'Node is missing a non-empty string id' });\n } else if (seenIds.has(raw.id)) {\n issues.push({ path, message: `Duplicate node id \"${raw.id}\"` });\n } else {\n seenIds.add(raw.id);\n }\n if (raw.className !== undefined && typeof raw.className !== 'string') {\n issues.push({ path: `${path}.className`, message: 'className must be a string' });\n }\n\n validateTypeSpecific(raw, type as BlockNodeType, path, issues);\n\n // Leaf types must not carry a `children` array on the raw object.\n const meta = BLOCK_REGISTRY[type as BlockNodeType];\n if (\n meta.allowedChildren === null &&\n Array.isArray(raw.children) &&\n (raw.children as unknown[]).length > 0\n ) {\n issues.push({ path, message: `Type \"${type}\" cannot have children` });\n return;\n }\n\n const children = nodeChildren(raw as unknown as BlockNode);\n if (meta.allowedChildren === null && children.length > 0) {\n issues.push({ path, message: `Type \"${type}\" cannot have children` });\n return;\n }\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n const childPath =\n type === 'repeater' ? `${path}.itemTemplate[${i}]` : `${path}.children[${i}]`;\n validateNode(child, childPath, seenIds, issues);\n if (\n meta.allowedChildren !== 'any' &&\n meta.allowedChildren !== null &&\n isRecord(child) &&\n typeof child.type === 'string' &&\n !meta.allowedChildren.includes(child.type as BlockNodeType)\n ) {\n issues.push({\n path: childPath,\n message: `Type \"${child.type}\" not allowed inside \"${type}\"`,\n });\n }\n }\n}\n\nfunction validateTypeSpecific(\n raw: Record<string, unknown>,\n type: BlockNodeType,\n path: string,\n issues: ValidationIssue[],\n): void {\n switch (type) {\n case 'section':\n requireString(raw, 'sectionId', path, issues);\n requireArray(raw, 'children', path, issues);\n break;\n case 'block':\n requireString(raw, 'blockId', path, issues);\n requireArray(raw, 'children', path, issues);\n break;\n case 'container':\n requireArray(raw, 'children', path, issues);\n break;\n case 'text':\n requireString(raw, 'k', path, issues);\n break;\n case 'image':\n requireString(raw, 'srcKey', path, issues);\n break;\n case 'icon':\n requireString(raw, 'k', path, issues);\n break;\n case 'repeater':\n requireString(raw, 'itemsKey', path, issues);\n requireArray(raw, 'itemTemplate', path, issues);\n if (!isRecord(raw.defaultItem)) {\n issues.push({\n path: `${path}.defaultItem`,\n message: 'defaultItem must be an object mapping field names to default strings',\n });\n } else {\n for (const [field, value] of Object.entries(raw.defaultItem)) {\n if (typeof value !== 'string') {\n issues.push({\n path: `${path}.defaultItem.${field}`,\n message: 'defaultItem values must be strings',\n });\n }\n }\n }\n break;\n case 'form':\n requireString(raw, 'formId', path, issues);\n // Fields may live in the locale instead (`form.<id>.fields`), so a\n // missing prop is fine; a present one has to be well-formed.\n if (raw.fields !== undefined) {\n if (!Array.isArray(raw.fields)) {\n issues.push({ path: `${path}.fields`, message: 'form.fields must be an array' });\n break;\n }\n for (let i = 0; i < raw.fields.length; i++) {\n validateFormField(raw.fields[i], `${path}.fields[${i}]`, issues);\n }\n }\n if (raw.endpoint !== undefined && typeof raw.endpoint !== 'string') {\n issues.push({ path: `${path}.endpoint`, message: 'form.endpoint must be a string' });\n }\n break;\n case 'video':\n requireString(raw, 'srcKey', path, issues);\n break;\n case 'animation':\n requireArray(raw, 'children', path, issues);\n if (typeof raw.preset !== 'string' || !ANIMATION_PRESETS.includes(raw.preset as never)) {\n issues.push({\n path: `${path}.preset`,\n message: `preset must be one of ${ANIMATION_PRESETS.join(', ')}`,\n });\n }\n break;\n }\n}\n\nfunction validateFormField(\n raw: unknown,\n path: string,\n issues: ValidationIssue[],\n): void {\n if (!isRecord(raw)) {\n issues.push({ path, message: 'field must be an object' });\n return;\n }\n if (typeof raw.name !== 'string' || raw.name.length === 0) {\n issues.push({ path: `${path}.name`, message: 'field.name must be a non-empty string' });\n }\n if (!isFormFieldType(raw.type)) {\n issues.push({\n path: `${path}.type`,\n message: `field.type must be one of ${FORM_FIELD_TYPES.join(', ')}`,\n });\n }\n requireString(raw as Record<string, unknown>, 'labelKey', path, issues);\n}\n\nfunction requireString(\n raw: Record<string, unknown>,\n field: string,\n path: string,\n issues: ValidationIssue[],\n): void {\n const value = raw[field];\n if (typeof value !== 'string' || value.length === 0) {\n issues.push({ path: `${path}.${field}`, message: `${field} must be a non-empty string` });\n }\n}\n\nfunction requireArray(\n raw: Record<string, unknown>,\n field: string,\n path: string,\n issues: ValidationIssue[],\n): void {\n if (!Array.isArray(raw[field])) {\n issues.push({ path: `${path}.${field}`, message: `${field} must be an array` });\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction fail(path: string, message: string): ValidationResult {\n return { ok: false, issues: [{ path, message }] };\n}\n\n/** Narrowing helper: validates and returns a typed tree, or throws. */\nexport function parseBlockTree(input: unknown): BlockTree {\n const result = validateBlockTree(input);\n if (!result.ok) {\n const first = result.issues[0];\n const detail = first ? `${first.path}: ${first.message}` : 'unknown';\n throw new Error(`Invalid block tree at ${detail}`);\n }\n return input as BlockTree;\n}\n\nexport type { FormField };\n","import {\n createContext,\n useContext,\n type ComponentType,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport { T } from '../T';\nimport { SettoSection } from '../SettoSection';\nimport { SettoBlock } from '../SettoBlock';\nimport { SettoRepeater } from '../SettoRepeater';\nimport { SettoImage } from '../SettoImage';\nimport { SettoIcon, type SettoIconRenderProps } from '../SettoIcon';\nimport { SettoForm } from '../modules/forms/SettoForm';\nimport { SettoVideo } from '../SettoVideo';\nimport { SettoAnimation } from '../SettoAnimation';\nimport { validateBlockTree } from './validate';\nimport type {\n BlockNode,\n BlockTree,\n ContainerTag,\n TextAs,\n} from './schema';\n\nexport interface SettoBlockTreeProps {\n /** Validated block tree, typically parsed from `home.layout.json`. */\n tree: BlockTree;\n /**\n * Icon registry consumed by `SettoIcon` nodes — the same map a host would\n * pass directly to `<SettoIcon icons={…}>`.\n */\n icons: Record<string, ComponentType<SettoIconRenderProps>>;\n /**\n * When true (default), validates the tree and throws on schema errors.\n * Disable in production after a one-time boot check.\n */\n validate?: boolean;\n}\n\ninterface IconRegistry {\n icons: Record<string, ComponentType<SettoIconRenderProps>>;\n}\n\nconst IconRegistryContext = createContext<IconRegistry | null>(null);\n\ninterface RepeaterScope {\n /** i18n prefix, e.g. 'faq.items'. */\n itemsKey: string;\n /** Current item key — '1', '2', ... */\n itemKey: string;\n}\n\nconst RepeaterScopeContext = createContext<RepeaterScope | null>(null);\n\n/**\n * Renders a block tree by dispatching each node to the matching Setto\n * primitive. Inside a `repeater`, leaf nodes use keys relative to the item;\n * the renderer composes them with the active scope so the agent can author\n * trees without knowing per-item suffixes.\n */\nexport function SettoBlockTree({ tree, icons, validate = true }: SettoBlockTreeProps) {\n if (validate) {\n const result = validateBlockTree(tree);\n if (!result.ok) {\n const first = result.issues[0];\n const detail = first ? `${first.path}: ${first.message}` : 'unknown';\n throw new Error(`Invalid block tree at ${detail}`);\n }\n }\n\n return (\n <IconRegistryContext.Provider value={{ icons }}>\n {tree.root.map((node) => (\n <RenderNode key={node.id} node={node} />\n ))}\n </IconRegistryContext.Provider>\n );\n}\n\nfunction RenderNode({ node }: { node: BlockNode }): ReactElement | null {\n switch (node.type) {\n case 'section':\n return (\n <SettoSection sectionId={node.sectionId} className={node.className}>\n {renderChildren(node.children)}\n </SettoSection>\n );\n\n case 'block':\n return (\n <SettoBlock blockId={node.blockId} className={node.className}>\n {renderChildren(node.children)}\n </SettoBlock>\n );\n\n case 'container':\n return renderContainer(node.tag ?? 'div', node.className, renderChildren(node.children));\n\n case 'animation':\n return (\n <SettoAnimation\n preset={node.preset}\n delay={node.delay}\n duration={node.duration}\n className={node.className}\n >\n {renderChildren(node.children)}\n </SettoAnimation>\n );\n\n case 'repeater':\n return (\n <SettoRepeater\n itemsKey={node.itemsKey}\n defaultItem={node.defaultItem}\n itemLabel={node.itemLabel}\n className={node.className}\n >\n {(itemKey) => (\n <RepeaterScopeContext.Provider\n value={{ itemsKey: node.itemsKey, itemKey }}\n >\n {renderChildren(node.itemTemplate)}\n </RepeaterScopeContext.Provider>\n )}\n </SettoRepeater>\n );\n\n case 'text':\n return <TextLeaf node={node} />;\n\n case 'image':\n return <ImageLeaf node={node} />;\n\n case 'icon':\n return <IconLeaf node={node} />;\n\n case 'form':\n return (\n <SettoForm\n formId={node.formId}\n fields={node.fields}\n endpoint={node.endpoint}\n className={node.className}\n />\n );\n\n case 'video':\n return <VideoLeaf node={node} />;\n }\n}\n\nfunction renderChildren(children: BlockNode[]): ReactNode {\n return children.map((child) => <RenderNode key={child.id} node={child} />);\n}\n\nfunction TextLeaf({ node }: { node: Extract<BlockNode, { type: 'text' }> }) {\n const k = useScopedKey(node.k);\n const inner = <T k={k} />;\n if (!node.as) {\n return node.className ? <span className={node.className}>{inner}</span> : inner;\n }\n return renderTag(node.as, node.className, inner);\n}\n\nfunction ImageLeaf({ node }: { node: Extract<BlockNode, { type: 'image' }> }) {\n const srcKey = useScopedKey(node.srcKey);\n return <SettoImage srcKey={srcKey} alt={node.alt} className={node.className} />;\n}\n\nfunction VideoLeaf({ node }: { node: Extract<BlockNode, { type: 'video' }> }) {\n const srcKey = useScopedKey(node.srcKey);\n const posterKey = useScopedKey(node.posterKey ?? '');\n return (\n <SettoVideo\n srcKey={srcKey}\n posterKey={node.posterKey ? posterKey : undefined}\n title={node.title}\n className={node.className}\n />\n );\n}\n\nfunction IconLeaf({ node }: { node: Extract<BlockNode, { type: 'icon' }> }) {\n const registry = useContext(IconRegistryContext);\n const k = useScopedKey(node.k);\n if (!registry) {\n throw new Error('SettoBlockTree must be mounted with an `icons` prop for icon nodes');\n }\n return (\n <SettoIcon\n k={k}\n icons={registry.icons}\n size={node.size}\n className={node.className}\n />\n );\n}\n\nfunction useScopedKey(key: string): string {\n const scope = useContext(RepeaterScopeContext);\n if (!scope) return key;\n return `${scope.itemsKey}.${scope.itemKey}.${key}`;\n}\n\nfunction renderTag(\n tag: TextAs,\n className: string | undefined,\n children: ReactNode,\n): ReactElement {\n switch (tag) {\n case 'h1': return <h1 className={className}>{children}</h1>;\n case 'h2': return <h2 className={className}>{children}</h2>;\n case 'h3': return <h3 className={className}>{children}</h3>;\n case 'h4': return <h4 className={className}>{children}</h4>;\n case 'h5': return <h5 className={className}>{children}</h5>;\n case 'h6': return <h6 className={className}>{children}</h6>;\n case 'p': return <p className={className}>{children}</p>;\n case 'span': return <span className={className}>{children}</span>;\n case 'div': return <div className={className}>{children}</div>;\n case 'label': return <label className={className}>{children}</label>;\n case 'em': return <em className={className}>{children}</em>;\n case 'strong': return <strong className={className}>{children}</strong>;\n }\n}\n\nfunction renderContainer(\n tag: ContainerTag,\n className: string | undefined,\n children: ReactNode,\n): ReactElement {\n switch (tag) {\n case 'div': return <div className={className}>{children}</div>;\n case 'section': return <section className={className}>{children}</section>;\n case 'header': return <header className={className}>{children}</header>;\n case 'footer': return <footer className={className}>{children}</footer>;\n case 'main': return <main className={className}>{children}</main>;\n case 'aside': return <aside className={className}>{children}</aside>;\n case 'nav': return <nav className={className}>{children}</nav>;\n case 'article': return <article className={className}>{children}</article>;\n case 'ul': return <ul className={className}>{children}</ul>;\n case 'ol': return <ol className={className}>{children}</ol>;\n case 'li': return <li className={className}>{children}</li>;\n case 'p': return <p className={className}>{children}</p>;\n case 'span': return <span className={className}>{children}</span>;\n }\n}\n","/**\n * Walks a block tree and reports the i18n keys, theme ids, and required\n * sample-locale entries it expects. The agent uses this output to validate\n * that the generated `no.json` covers everything the tree references.\n */\n\nimport type { BlockNode, BlockTree, RepeaterNode } from './schema';\n\nexport interface ContentKeyRequirements {\n /** Plain i18n keys that must exist with a string value. */\n keys: Set<string>;\n /**\n * Section / block theme ids referenced by the tree. The deterministic\n * sections.json overlay and section-schemas.ts must include each id.\n */\n themeIds: Set<string>;\n /**\n * Repeater requirements — at least one item entry must exist in the\n * locale under `itemsKey`, with every field from `defaultItem`.\n */\n repeaters: Array<{\n itemsKey: string;\n fields: string[];\n /**\n * Item-relative keys produced by walking the item template. The\n * validator checks every existing locale item has these keys.\n */\n itemKeys: string[];\n }>;\n}\n\n/** Returns content requirements for an already-validated tree. */\nexport function extractContentKeys(tree: BlockTree): ContentKeyRequirements {\n const out: ContentKeyRequirements = {\n keys: new Set(),\n themeIds: new Set(),\n repeaters: [],\n };\n for (const node of tree.root) {\n walk(node, out, null);\n }\n return out;\n}\n\nfunction walk(\n node: BlockNode,\n out: ContentKeyRequirements,\n repeaterCtx: { itemsKey: string } | null,\n): void {\n switch (node.type) {\n case 'section':\n out.themeIds.add(node.sectionId);\n for (const child of node.children) walk(child, out, repeaterCtx);\n return;\n case 'block':\n out.themeIds.add(node.blockId);\n for (const child of node.children) walk(child, out, repeaterCtx);\n return;\n case 'container':\n case 'animation':\n for (const child of node.children) walk(child, out, repeaterCtx);\n return;\n case 'text':\n out.keys.add(scopedKey(node.k, repeaterCtx));\n return;\n case 'image':\n out.keys.add(scopedKey(node.srcKey, repeaterCtx));\n return;\n case 'icon':\n out.keys.add(scopedKey(node.k, repeaterCtx));\n return;\n case 'video':\n out.keys.add(scopedKey(node.srcKey, repeaterCtx));\n if (node.posterKey) out.keys.add(scopedKey(node.posterKey, repeaterCtx));\n return;\n case 'form':\n out.keys.add(`form.${node.formId}.submit`);\n out.keys.add(`form.${node.formId}.success`);\n out.keys.add(`form.${node.formId}.error`);\n for (const field of node.fields ?? []) {\n out.keys.add(field.labelKey);\n if (field.placeholderKey) out.keys.add(field.placeholderKey);\n if (field.optionsKey) out.keys.add(field.optionsKey);\n }\n return;\n case 'repeater':\n recordRepeater(node, out);\n // Repeater inner nodes resolve relative to the item key, so we\n // don't add their content paths into `keys` — coverage is checked\n // per existing locale item via `itemKeys`.\n for (const child of node.itemTemplate) {\n walk(child, out, { itemsKey: node.itemsKey });\n }\n return;\n }\n}\n\nfunction scopedKey(\n key: string,\n repeaterCtx: { itemsKey: string } | null,\n): string {\n if (!repeaterCtx) return key;\n // Inside a repeater, leaf nodes use keys relative to the item.\n // For validation we collect them under the item template instead.\n return `${repeaterCtx.itemsKey}.*.${key}`;\n}\n\nfunction recordRepeater(node: RepeaterNode, out: ContentKeyRequirements): void {\n const fields = Object.keys(node.defaultItem);\n const itemKeys: string[] = [];\n collectRelativeKeys(node.itemTemplate, '', itemKeys);\n out.repeaters.push({\n itemsKey: node.itemsKey,\n fields,\n itemKeys,\n });\n}\n\nfunction collectRelativeKeys(\n nodes: BlockNode[],\n prefix: string,\n out: string[],\n): void {\n for (const node of nodes) {\n switch (node.type) {\n case 'text':\n case 'icon':\n out.push(prefix ? `${prefix}.${node.k}` : node.k);\n break;\n case 'image':\n out.push(prefix ? `${prefix}.${node.srcKey}` : node.srcKey);\n break;\n case 'video':\n out.push(prefix ? `${prefix}.${node.srcKey}` : node.srcKey);\n if (node.posterKey) {\n out.push(prefix ? `${prefix}.${node.posterKey}` : node.posterKey);\n }\n break;\n case 'section':\n case 'block':\n case 'container':\n case 'animation':\n collectRelativeKeys(node.children, prefix, out);\n break;\n case 'repeater':\n // Nested repeaters are valid but their inner keys are scoped under\n // a different prefix at runtime — not part of the outer template.\n break;\n case 'form':\n // Forms inside repeaters are uncommon and use the form's own scope.\n break;\n }\n }\n}\n"],"names":["res","walk","isRecord","at","Component","STYLE_ID","session","SettoSection","SettoBlock","Fragment","shellStyle"],"mappings":";;;;;;AAiBA,MAAM,cAAc;AAGb,MAAM,mBAAmB;AAMhC,MAAM,WAAmC;AAAA,EACvC,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AACN;AAGO,SAAS,aAAa,KAAqB;AAChD,QAAM,OAAO,IAAI,YAAA,EAAc,MAAM,GAAG,EAAE,CAAC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