Concrete
Reference

Islands

Writing the client half of a section — what a `"use client"` module must declare, what its props may be, and what it may reach on a published page.

An island is a "use client" module a section imports. The build splits it into its own chunk, the renderer emits a marker where the section placed it, and the browser runtime hydrates that marker against the markup the server already produced.

Two declarations are the whole contract. export const editor = { live } is required of every island and says whether it runs its published behaviour inside the editor canvas or stays its static first frame — an explicit false is a decision, and a missing field was an accident wearing a decision's clothes. export const serverFrame = false is optional and says the module produces no meaningful markup with no DOM and no effects, so the build omits its implementation from the renderer instead of loading a graph to emit an empty box. The two are checked together: an island with no server frame that is also not live is a permanent blank hole, and the pair is a type error.

Props cross the boundary as JSON. A binding is plain JSON by construction, so an island takes one as an ordinary prop and imports no schema.

Most of what is below is machinery — the marker, its attributes, the props codec. An island author writes editor, serverFrame, the three hooks, and, on a published page, submitLead. The rest is here because it is exported, and because a host or a test occasionally has to read the same DOM the runtime does.

useEditor

Signature

import { useEditor } from "@homepages/concrete";

function Panel() {
  const { inCanvas, selection } = useEditor();
  return <p>{inCanvas && selection?.kind === "slot" ? selection.slotId : ""}</p>;
}

Constraints

Always hydration-safe: during server rendering, on a published page, and under an incompatible bridge protocol it returns { inCanvas: false, selection: null }. It never throws — a canvas on a newer protocol degrades to published-page behaviour with one console warning, because an island bundle is immutable once published and version skew is normal.

selection is already scoped to the island's own section instance: a selection anywhere else reads as null, and the identity is stable across publishes, so it is safe as an effect dependency. Never resolve the instance yourself, and never read the canvas's internal globals — that is islands/no-editor-globals.

Every read of inCanvas that changes behaviour carries an editor-reason: comment on the line above it (islands/editor-reason). The canvas is not a preview mode to branch around; a difference has to be worth stating.

Example

"use client";

import { useEditor } from "@homepages/concrete";
import type { IslandEditor } from "@homepages/concrete";
import { useState } from "react";

export const editor = { live: true } satisfies IslandEditor;

export default function Carousel({ slides }: { slides: number }) {
  const [at, setAt] = useState(0);
  const { selection } = useEditor();
  // editor-reason: selecting a slide in the sidebar must scroll the carousel to it,
  // or the editor is editing a row nobody can see.
  const shown = selection?.kind === "slot" && selection.itemIndex !== undefined ? selection.itemIndex : at;
  return <button onClick={() => setAt((shown + 1) % slides)}>{shown}</button>;
}

Rules that apply

islands/editor-declaration, islands/editor-reason, islands/no-editor-globals.

useCaptureReady

Signature

import { useCaptureReady } from "@homepages/concrete";

function Map() {
  const ready: () => void = useCaptureReady();
  return <div ref={() => ready()} />;
}

Constraints

Call it only from an island that keeps painting after mount — a map engine loading tiles, an async decode. Calling the hook takes a capture hold at mount; invoke the returned callback when the last pixel is painted. It is identity-stable and idempotent, an unmounted island releases automatically, and a branch with nothing to draw calls it immediately.

Never call it for an island that paints everything during mount: not calling the hook is the default contract, and a hold nobody releases stalls the shutter. Where nothing captures — the editor canvas, a published website — the hold is never read, so the hook costs nothing.

Example

"use client";

import { useCaptureReady } from "@homepages/concrete";
import type { IslandEditor } from "@homepages/concrete";
import { useEffect, useRef } from "react";

export const editor = { live: false } satisfies IslandEditor;

declare function createMap(el: HTMLElement): { once(event: "idle", fn: () => void): void };

export default function SiteMap() {
  const host = useRef<HTMLDivElement>(null);
  const ready = useCaptureReady();
  useEffect(() => {
    if (host.current === null) return ready();
    createMap(host.current).once("idle", ready);
  }, [ready]);
  return <div ref={host} className="aspect-video w-full" />;
}

Rules that apply

islands/server-frame.

useIslandId

Signature

import { useIslandId } from "@homepages/concrete";

function Disclosure() {
  const id = useIslandId();
  return <button aria-controls={`${id}-panel`} id={`${id}-button`} />;
}

Constraints

Always this and never React's own id hook, for any id an island puts on its own markup: the server renders a whole section under one prefix and the browser hydrates a subtree rooted at one marker, so the two counters diverge by construction and React's id would report that divergence as a hydration mismatch. This returns the id the marker carries, which both renders agree on.

Only an island may call it — islands/island-ids enforces both halves. A section calling it would mint one constant for every instance of itself on a page. In the tooling venues that render a section's module graph directly it returns a fixed value, because nothing there hydrates and no id is ever compared.

Example

"use client";

import { useIslandId } from "@homepages/concrete";
import type { IslandEditor } from "@homepages/concrete";
import { useState } from "react";

export const editor = { live: true } satisfies IslandEditor;

export default function UnitFilter({ units }: { units: string[] }) {
  const id = useIslandId();
  const [open, setOpen] = useState(false);
  return (
    <div>
      <button id={`${id}-toggle`} aria-controls={`${id}-list`} aria-expanded={open} onClick={() => setOpen(!open)}>
        Units
      </button>
      <ul id={`${id}-list`} hidden={!open}>
        {units.map((unit) => (
          <li key={unit}>{unit}</li>
        ))}
      </ul>
    </div>
  );
}

Rules that apply

islands/island-ids.

IslandMarker

Signature

import { IslandMarker } from "@homepages/concrete";

<IslandMarker islandKey="hero:UnitFilter" islandId="hero-1~hero:UnitFilter#0" props={{ units: 3 }}>
  {null}
</IslandMarker>;

Parameters

islandKey is <section-key>:<ComponentName>, the key the browser loader resolves the module by. islandId is unique in the document and stable across re-renders — compose it with islandId. props must be strictly JSON-serializable. children are the client component's server-rendered output, and omitting them declares the island frameless.

Constraints

A section never writes this. Whatever wraps a "use client" import emits it, and it is the one place the island DOM shape exists: a layout-invisible custom element plus a sibling JSON script carrying the props.

A bad prop throws IslandPropsError here, at render time, naming the path — which is why islands/serializable-props exists to catch it at lint instead.

Example

import { IslandMarker, islandId } from "@homepages/concrete";

declare const Filter: (props: { units: number }) => React.ReactNode;

export function wrapped(scope: string, units: number) {
  const id = islandId(scope, "hero:UnitFilter", 0);
  return (
    <IslandMarker islandKey="hero:UnitFilter" islandId={id} props={{ units }}>
      <Filter units={units} />
    </IslandMarker>
  );
}

Rules that apply

islands/serializable-props.

islandId

Signature

import { islandId } from "@homepages/concrete";

const id: string = islandId("hero-1", "hero:UnitFilter", 0);

Parameters

scope is the emitter's per-section-instance identity, islandKey the island's key, and the third argument the ordinal of this island within that instance.

Constraints

Always composed with the scope. Without it, two instances of one section on a page mint the same id and the browser runtime hydrates one marker's props into the other. The ordinal separates two islands of the same key inside one instance.

This is the emitter's id, not the author's: an island reads the id it was given through useIslandId.

Example

import { islandId } from "@homepages/concrete";

const first: string = islandId("gallery-1", "gallery:Slider", 0);
const second: string = islandId("gallery-2", "gallery:Slider", 0);
const distinct: boolean = first !== second;

serializeIslandProps

Signature

import { serializeIslandProps } from "@homepages/concrete";

const payload: string = serializeIslandProps({ units: 3, label: "Units" });

Constraints

Validates, then encodes. A prop that is not JSON — a function, a class instance, a Date, NaN — throws IslandPropsError naming the offending path, and the top-level value must be a plain object rather than an array or a bare value.

Every < is emitted as its unicode escape, so no string value can close the payload's script tag. Never re-implement this: the payload is a wire format the browser runtime reads back with deserializeIslandProps.

Example

import { IslandPropsError, serializeIslandProps } from "@homepages/concrete";

export function encode(props: Record<string, unknown>): string | null {
  try {
    return serializeIslandProps(props);
  } catch (error) {
    if (error instanceof IslandPropsError) return null;
    throw error;
  }
}

Rules that apply

islands/serializable-props.

deserializeIslandProps

Signature

import { deserializeIslandProps } from "@homepages/concrete";

const props: Record<string, unknown> = deserializeIslandProps('{"units":3}');

Constraints

The other half of the codec. Anything that is not a JSON object — invalid JSON, an array, a bare value — throws IslandPropsError.

Used by the browser runtime against the marker's sibling payload. A section or an island has no reason to call it: an island receives its props as props.

Example

import { ATTR_ISLAND_PROPS, deserializeIslandProps } from "@homepages/concrete";

export function propsFor(id: string): Record<string, unknown> {
  const script = document.querySelector(`script[${ATTR_ISLAND_PROPS}="${id}"]`);
  return deserializeIslandProps(script?.textContent ?? "{}");
}

IslandPropsError

Signature

import { IslandPropsError } from "@homepages/concrete";

const error = new IslandPropsError("props.onPick is a function");
const name: string = error.name; // "IslandPropsError"

Constraints

Thrown by both halves of the codec, and by nothing else. It means a prop could not cross the server-to-browser boundary, or a payload could not be read back.

Never catch it to carry on: it is a defect in what a section passed an island, not a runtime condition. Catch it only to report it.

Example

import { IslandPropsError, serializeIslandProps } from "@homepages/concrete";

export function why(props: Record<string, unknown>): string | null {
  try {
    serializeIslandProps(props);
    return null;
  } catch (error) {
    return error instanceof IslandPropsError ? error.message : null;
  }
}

ISLAND_ELEMENT

Signature

import { ISLAND_ELEMENT } from "@homepages/concrete";

const tag: string = ISLAND_ELEMENT; // "tr-island"

Constraints

The custom element that wraps an island's server-rendered output. It is layout-invisible — display: contents — so it contributes no box and an island's own markup keeps the layout its section gave it.

Never style it and never select on it from a section's CSS. Read it to find islands in a document.

Example

import { ISLAND_ELEMENT } from "@homepages/concrete";

export function islandsIn(root: ParentNode): Element[] {
  return Array.from(root.querySelectorAll(ISLAND_ELEMENT));
}

ATTR_ISLAND_KEY

Signature

import { ATTR_ISLAND_KEY } from "@homepages/concrete";

const attribute: string = ATTR_ISLAND_KEY; // "data-tr-island"

Constraints

The island's key on its marker, <section-key>:<ComponentName> — what the browser loader resolves the module by. The component name half comes from the module's own export, so renaming the component renames the key and the build re-emits both sides together.

Example

import { ATTR_ISLAND_KEY, ISLAND_ELEMENT } from "@homepages/concrete";

export function keysOn(root: ParentNode): string[] {
  return Array.from(root.querySelectorAll(`${ISLAND_ELEMENT}[${ATTR_ISLAND_KEY}]`), (el) =>
    el.getAttribute(ATTR_ISLAND_KEY) ?? "",
  );
}

ATTR_ISLAND_ID

Signature

import { ATTR_ISLAND_ID } from "@homepages/concrete";

const attribute: string = ATTR_ISLAND_ID; // "data-tr-island-id"

Constraints

The island's id on its marker: unique in the document, stable across re-renders of the same island, and the value its props payload is addressed by. It is also what useIslandId hands the island after the browser has taken it over.

Example

import { ATTR_ISLAND_ID } from "@homepages/concrete";

export function idOf(marker: Element): string | null {
  return marker.getAttribute(ATTR_ISLAND_ID);
}

ATTR_ISLAND_PROPS

Signature

import { ATTR_ISLAND_PROPS } from "@homepages/concrete";

const attribute: string = ATTR_ISLAND_PROPS; // "data-tr-island-props"

Constraints

Carried by the <script type="application/json"> sibling of a marker; its value is the island id whose props the script holds. The pairing is minted in one render, so a marker and its payload cannot come apart.

Example

import { ATTR_ISLAND_PROPS, deserializeIslandProps } from "@homepages/concrete";

export function payloadFor(id: string): Record<string, unknown> | null {
  const script = document.querySelector(`script[${ATTR_ISLAND_PROPS}="${id}"]`);
  return script === null ? null : deserializeIslandProps(script.textContent ?? "{}");
}

ATTR_ISLAND_FRAMELESS

Signature

import { ATTR_ISLAND_FRAMELESS } from "@homepages/concrete";

const attribute: string = ATTR_ISLAND_FRAMELESS; // "data-tr-island-frameless"

Constraints

A value-less presence flag on a marker holding no server-rendered output: the browser mounts that island fresh rather than hydrating it against markup that was never emitted.

It is derived from the marker's children, never passed. The loader has to decide how to mount a marker before the island's module has loaded, so the DOM has to carry the answer — a second "I am frameless" prop would be one more thing to keep in step, and a disagreement is exactly the hydration mismatch this prevents. An island that declares serverFrame = false and still renders content on the server is islands/server-frame.

Example

import { ATTR_ISLAND_FRAMELESS } from "@homepages/concrete";

export function hydrates(marker: Element): boolean {
  return !marker.hasAttribute(ATTR_ISLAND_FRAMELESS);
}

Rules that apply

islands/server-frame.

EDITOR_BRIDGE_PROP

Signature

import { EDITOR_BRIDGE_PROP } from "@homepages/concrete";

const property: string = EDITOR_BRIDGE_PROP; // "__trEditorBridge"

Constraints

The window property an editor canvas publishes its bridge on, absent on published pages. The host constructs the bridge before hydrating any island; hooks only read it.

Never read it from an island — that is islands/no-editor-globals, and useEditor is the surface. It is exported for the canvas host, which is the one thing that writes it.

Example

import { EDITOR_BRIDGE_PROP } from "@homepages/concrete";

export function inEditorCanvas(): boolean {
  return typeof window !== "undefined" && EDITOR_BRIDGE_PROP in window;
}

Rules that apply

islands/no-editor-globals.

EDITOR_BRIDGE_PROTOCOL

Signature

import { EDITOR_BRIDGE_PROTOCOL } from "@homepages/concrete";

const protocol: number = EDITOR_BRIDGE_PROTOCOL;

Constraints

The bridge protocol this runtime speaks. A published island bundle is immutable, so the two sides may only diverge additively: bridge fields are added, never changed or removed, and this bumps only on an unavoidable break.

A hook meeting a bridge on a different protocol degrades to published-page behaviour with a console warning — never a throw. Nothing an island writes should branch on this number.

Example

import { EDITOR_BRIDGE_PROTOCOL } from "@homepages/concrete";

export function compatible(bridgeProtocol: number): boolean {
  return bridgeProtocol === EDITOR_BRIDGE_PROTOCOL;
}

ISLAND_CAPTURE_HOLDS_GLOBAL

Signature

import { ISLAND_CAPTURE_HOLDS_GLOBAL } from "@homepages/concrete";

const property: string = ISLAND_CAPTURE_HOLDS_GLOBAL; // "__trCaptureHolds"

Constraints

The window property holding the page's open capture holds, as a set of promises. useCaptureReady takes one; a capture host drains the set before the shutter.

Window-level and not module state, deliberately: an island bundle and the page's runtime chunk are separate module graphs, so nothing else crosses between them. An island reaches this through the hook, never directly.

Example

import { ISLAND_CAPTURE_HOLDS_GLOBAL } from "@homepages/concrete";

export async function whenPainted(): Promise<void> {
  const holds = (window as unknown as Record<string, Set<Promise<void>> | undefined>)[
    ISLAND_CAPTURE_HOLDS_GLOBAL
  ];
  await Promise.all([...(holds ?? [])]);
}

submitLead

Signature

import { submitLead } from "@homepages/concrete/browser";

const result = await submitLead({ email: "buyer@example.com", message: "Interested" });
const sent: boolean = result.ok;

Parameters

The first argument is the lead: email is required, name, phone and message optional, and extra carries any additional field the form collects. The options take source (attribution overrides, or false to send none), config (defaults to readSiteConfig(), null forces preview behaviour), fetch and retries (default 2).

Constraints

Always this, never a hand-built request: it wraps the ingest contract end to end — signing, the idempotency key, source attribution, retry on network errors and 5xx only, and the size limit — and changing either half would break sites already live on older versions.

It never throws; inspect the result. Field precedence into the payload is extra below the named contact fields below the source attribution, so extra can add fields and never shadow them. Off a published page — the editor canvas, local preview — there is no site config, so nothing is sent and the result is { ok: true, simulated: true }. A lead the server accepts is also announced page-wide as LEAD_EVENT.

Example

"use client";

import type { IslandEditor } from "@homepages/concrete";
import { submitLead } from "@homepages/concrete/browser";
import { useState } from "react";

export const editor = { live: false } satisfies IslandEditor;

export default function ContactForm() {
  const [note, setNote] = useState("");
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const email = new FormData(event.currentTarget).get("email");
        void submitLead({ email: String(email ?? "") }).then((result) => {
          setNote(result.ok ? "Thanks — we'll be in touch." : result.message);
        });
      }}
    >
      <input name="email" type="email" required />
      <button type="submit">Send</button>
      <p aria-live="polite">{note}</p>
    </form>
  );
}

readSiteConfig

Signature

import { readSiteConfig } from "@homepages/concrete/browser";

const config = readSiteConfig();
const base: string | undefined = config?.ingestBase;

Constraints

Reads the per-site config a published page embeds. It returns null when the element is absent or any of the three fields is missing — which is the editor canvas and local preview, and is why submitLead simulates there instead of failing.

Never cache the result across pages, and never ship one: the config belongs to the published site, not to the template.

Example

import { readSiteConfig } from "@homepages/concrete/browser";

export function published(): boolean {
  return readSiteConfig() !== null;
}

signedIngestHeaders

Signature

import { readSiteConfig, signedIngestHeaders } from "@homepages/concrete/browser";

const config = readSiteConfig();
const headers = config === null ? {} : await signedIngestHeaders(config, '{"fields":{}}');

Parameters

The site config, and the exact request body string the headers will be sent with.

Constraints

Reach for this only for an ingest endpoint submitLead does not cover. The signature covers the body bytes, so the string signed and the string sent must be the same one — never re-serialize in between.

Sign per attempt: ingest rejects a timestamp more than five minutes off, so a retry after a backoff needs fresh headers over the same body.

Example

import { readSiteConfig, signedIngestHeaders } from "@homepages/concrete/browser";

export async function post(path: string, body: string): Promise<Response | null> {
  const config = readSiteConfig();
  if (config === null) return null;
  const headers = await signedIngestHeaders(config, body);
  return fetch(`${config.ingestBase}${path}`, { method: "POST", headers, body });
}

hmacHex

Signature

import { hmacHex } from "@homepages/concrete/browser";

const signature: string = await hmacHex("a1b2c3", "1700000000.{}");

Parameters

A hex-encoded secret and the message to sign. Returns HMAC-SHA256 as lowercase hex.

Constraints

The primitive underneath signedIngestHeaders, exported for an endpoint that signs something other than the ingest message. It is a wire contract, not a utility: the message shape is the server's, not yours.

Example

import { hmacHex } from "@homepages/concrete/browser";

export async function sign(secret: string, body: string): Promise<string> {
  const ts = Math.floor(Date.now() / 1000).toString();
  return hmacHex(secret, `${ts}.${body}`);
}

captureSource

Signature

import { captureSource } from "@homepages/concrete/browser";

const source = captureSource(document.referrer, location.search, location.href);

Parameters

A referrer, a query string and the current URL. It returns the attribution fields it could read: the bare referring hostname, the three UTM parameters it finds, and the page the lead came from.

Constraints

submitLead calls this for you off the live document. Call it directly only to assemble a source override by hand.

Attribution is best-effort by design: a malformed referrer reads as a direct visit rather than dropping the key, and an unparseable query string contributes nothing. UTM values are truncated.

Example

import { captureSource, submitLead } from "@homepages/concrete/browser";

export async function sendFromCampaign(email: string): Promise<boolean> {
  const source = captureSource("", "utm_source=postcard", location.href);
  const result = await submitLead({ email }, { source });
  return result.ok;
}

buildLeadBody

Signature

import { buildLeadBody, captureSource } from "@homepages/concrete/browser";

const body: string = buildLeadBody({ email: "buyer@example.com" }, captureSource("", "", "https://example.com/"));

Parameters

The lead and its resolved attribution.

Constraints

The returned string is signed and sent verbatim — the signature covers those exact bytes. Never re-serialize what this returns.

Exported for an endpoint composing its own request; submitLead builds and sends the body itself.

Example

import { buildLeadBody, readSiteConfig, signedIngestHeaders } from "@homepages/concrete/browser";

export async function send(email: string): Promise<boolean> {
  const config = readSiteConfig();
  if (config === null) return false;
  const body = buildLeadBody({ email }, {});
  const headers = await signedIngestHeaders(config, body);
  const response = await fetch(`${config.ingestBase}/leads/ingest`, { method: "POST", headers, body });
  return response.ok;
}

LEAD_EVENT

Signature

import { LEAD_EVENT } from "@homepages/concrete/browser";

const eventName: string = LEAD_EVENT; // "homepages:lead"

Constraints

Dispatched on window once a lead is accepted — not on a failure, and not on a simulated submission. Its detail carries the trimmed email.

A template never dispatches it. It is how a published page's connected integrations learn a lead was captured, and an island may listen to it to react in the page.

Example

import { LEAD_EVENT } from "@homepages/concrete/browser";

export function onLead(handler: (email: string) => void): () => void {
  const listener = (event: Event) => {
    handler((event as CustomEvent<{ email: string }>).detail.email);
  };
  window.addEventListener(LEAD_EVENT, listener);
  return () => window.removeEventListener(LEAD_EVENT, listener);
}

See also

Primitives for the server half of a section's markup, the rest of the reference, and every rule.