Skip to content

Preact & React

Write an extension as components. @sessions/apps/preact and @sessions/apps/react give you the same extension(), a typed component for every element, hooks for the API, and signals — so an extension’s state lives in one model, the way Sessions’ own code keeps it.

Preact@sessions/apps/preactReact@sessions/apps/react

Setup

Add the framework next to @sessions/apps — both are optional peer dependencies, so a DOM-only app installs neither.

Set jsxImportSource to preact or react in your tsconfig.json. sessions build bundles with the framework each module imports from.

Preact is the smaller of the two by a wide margin, and every extension bundle is downloaded by the people who see it. Prefer it unless you are bringing React code with you.
package.json
{
  "name": "studio-notes",
  "private": true,
  "type": "module",
  "scripts": {
    "types": "sessions types",
    "build": "sessions build",
    "push": "sessions push",
    "publish:app": "sessions publish"
  },
  "devDependencies": {
    "@sessions/apps": "github:SessionsCode/Sessions#sessions-apps/v0.1.0",
    "preact": "^10.29.0"
  }
}

extension() and hooks

Everything reads the target’s API from context, so components deep in your tree can reach it.

extension(target, render)(target, (api) => JSX) => RenderExtension
Declares a target’s module. Pass the target and a function returning your root component; the result is the module’s default export.
useApi<Target>()Api<Target>
The target’s API. Pass the target as a type argument for its exact shape.
useQuery<Data>()Data
The live query’s result; the component renders again when Sessions re-runs the query. Type it with the …QueryData that sessions types generates.
useTranslate()(key, replacements?) => string
translate(key, replacements) for your translations/<locale>.json strings; the component renders again when the viewer’s language changes.
useLocale()string
The viewer’s locale; the component renders again when it changes.
useModel(create, deps?)<Model>((api) => Model) => Model
The extension’s model: one object, made once from the API by the function you pass, holding state as signals and actions as methods. If it has a start({signal}) method, it is called after mount and the signal aborts on unmount.
useSignal(value)Signal<T>
A signal owned by the component, made once.
useComputed(compute)ReadonlySignal<T>
A computed signal owned by the component.
useSignalEffect(effect)(() => void | (() => void)) => void
An effect that runs again whenever a signal it reads changes, while the component is mounted.
useSignalValue(signal)<T>(signal: ReadonlySignal<T>) => T
Any signal’s current value, rendering again when it changes. What React components use to read a model.
signal · computed · effect · batch · untracked@preact/signals-core
The signals primitives themselves, re-exported so a model can be written without another dependency.
business target
import {
  extension,
  useApi,
  useQuery,
  useSignal,
  useTranslate,
  Button,
  Stack,
  TextField,
} from '@sessions/apps/preact';

import saveNote from './SaveNoteMutation.graphql';
import type {SessionNoteQueryData} from './SessionNoteQuery.graphql';

export default extension('business.session.details.block', () => <NoteEditor />);

function NoteEditor() {
  const api = useApi<'business.session.details.block'>();
  const {session} = useQuery<SessionNoteQueryData>();
  const translate = useTranslate();
  // Signals: reading `.value` while rendering re-renders on change.
  const draft = useSignal(session?.note?.value ?? '');
  const saving = useSignal(false);

  async function save() {
    saving.value = true;
    // Typed by the .graphql.d.ts: variables are checked, data is typed.
    const result = await api.mutate(saveNote, {
      variables: {owner: {id: api.session.id}, value: draft.value},
    });
    saving.value = false;
    const failed = result.errors != null || !!result.data?.setMetadata.errors.length;
    api.ui.toast(translate(failed ? 'saveFailed' : 'saved'), {
      tone: failed ? 'critical' : undefined,
    });
  }

  return (
    <Stack gap="small">
      <TextField
        label={translate('label', {activity: session?.activity.name ?? ''})}
        value={draft.value}
        multiline
        onInput={(value) => (draft.value = value)}
      />
      <Button emphasis="strong" loading={saving.value} onClick={save}>
        {translate('save')}
      </Button>
    </Stack>
  );
}

Signals

A signal is a value that tells whoever read it when it changes. api.query and api.localization.locale are signals, and so is any state you keep with signal, computed or the useSignal hooks.

In Preact, reading .value while rendering subscribes the component: it renders again when that signal changes, and only then. No dependency arrays, no setters to thread through props.

React has no such hook into rendering, so read a signal with useSignalValue(signal) — or, for a model, have it expose one computed of everything the view needs and read that.

The signals come from @preact/signals-core, re-exported by both entries: import signal, computed, batch and friends from @sessions/apps/preact or @sessions/apps/react, never from a second copy.
counter.tsx
import {useSignal, useComputed, Button, Text} from '@sessions/apps/preact';

function Counter() {
  const count = useSignal(0);
  const label = useComputed(() => `Pressed ${count.value} times`);

  // Reading .value while rendering subscribes this component:
  // it renders again whenever count changes, and only then.
  return (
    <>
      <Text>{label.value}</Text>
      <Button onClick={() => count.value++}>Press</Button>
    </>
  );
}

One model per extension

Keep an extension’s state and actions in one class, made once with useModel((api) => new Model(api)). It is the pattern Sessions’ own pages use: components stay small and declarative, and everything the extension knows or does is in one file you can read top to bottom.

Private signals hold the state; getters read them, so a component that reads a getter subscribes to what it reads; methods change the state (in a batch when they change several signals) and call api.mutate.

Never copy the live query into the model’s own state. Read it from api.query in a computed, and it stays current — after your own mutation, and after anyone else’s.

Give the model a start({signal}) method for work that must not run while rendering — a first fetch, a timer, a listener — and stop it when the signal aborts.

Annotate useModel’s parameter with your target’s API type — (api: NoteApi) => new NoteModel(api) — and the model is typed end to end, live query included.
session-note
import {batch, computed, signal, type Api} from '@sessions/apps/preact';

import saveNote from './SaveNoteMutation.graphql';
import type {SessionNoteQueryData} from './SessionNoteQuery.graphql';

export type NoteApi = Api<'business.session.details.block', SessionNoteQueryData>;

/** Everything the note editor knows and does, made once per extension. */
export class NoteModel {
  readonly #api: NoteApi;
  readonly #draft = signal('');
  readonly #saving = signal(false);

  /** The saved note — read from the live query, never copied. */
  readonly #saved = computed(
    () => this.#api.query.value.session?.note?.value ?? '',
  );

  constructor(api: NoteApi) {
    this.#api = api;
    this.#draft.value = this.#saved.peek();
  }

  get draft() {
    return this.#draft.value;
  }

  get hasChanged() {
    return this.#draft.value.trim() !== this.#saved.value;
  }

  get isSaving() {
    return this.#saving.value;
  }

  setDraft(value: string) {
    this.#draft.value = value;
  }

  async save() {
    this.#saving.value = true;
    try {
      const result = await this.#api.mutate(saveNote, {
        variables: {owner: {id: this.#api.session.id}, value: this.#draft.value},
      });
      const message =
        result.errors?.[0]?.message ?? result.data?.setMetadata.errors[0]?.message;
      if (message) this.#api.ui.toast(message, {tone: 'critical'});
    } finally {
      this.#saving.value = false;
    }
  }
}

Components

One component per element, named for it. Props are the element’s attributes in camelCase, and events are on props that receive the event’s detail.

Component → element
<Stack><sessions-stack>
A column (or row) of children with even spacing.
<Grid><sessions-grid>
Equal columns that stack on a narrow container.
<Section><sessions-section>
A titled group with an optional action beside the title.
<Heading><sessions-heading>
A heading at the level the surrounding section implies.
<Text><sessions-text>
Inline text.
<Link><sessions-link>
An inline text link.
<Button><sessions-button>
A button, or a link styled as one when to is set.
<Banner><sessions-banner>
A callout with a heading and a body.
<Badge><sessions-badge>
A small status label.
<Image><sessions-image>
An image with an accessible description.
<Embed><sessions-embed>
A Spotify, Apple Music or YouTube player in a sandboxed frame.
<DisclosureGroup><sessions-disclosure-group>
Stacks sessions-disclosure rows with dividers between them.
<Disclosure><sessions-disclosure>
A row that expands to reveal its children.
<TextField><sessions-text-field>
A single-line (or multiline) text input.
<Form><sessions-form>
Fields saved together, with the host’s Save.
<Select><sessions-select>
A dropdown of sessions-option children.
<Option><sessions-option>
One choice in an sessions-select.
<Switch><sessions-switch>
An on/off toggle with a label.
<DetailRow><sessions-detail-row>
One row in a list of facts — what a *.row target renders.
<DetailRowSkeleton><sessions-detail-row-skeleton>
A detail row while its title loads.
<SkeletonText><sessions-skeleton-text>
A text placeholder while data loads.
<SkeletonHeading><sessions-skeleton-heading>
A heading placeholder while data loads.

A presence attribute such as disabled or multiline is a boolean prop. An async onClick keeps the button in its loading state until it settles, and an async onSubmit does the same for the form’s submit button.

How it runs

The framework renders into the remote DOM in the sandbox, exactly as a DOM extension does; the host maps each element onto a Sessions component. Your components never reach the host page.

React DOM expects a few browser details the sandbox does not have; @sessions/apps/react provides them before React loads. Inline styles are accepted and ignored — the host owns styling.