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.
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.
{
"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) => RenderExtensionuseApi<Target>()Api<Target>useQuery<Data>()Data…QueryData that sessions types generates.useTranslate()(key, replacements?) => stringtranslate(key, replacements) for your translations/<locale>.json strings; the component renders again when the viewer’s language changes.useLocale()stringuseModel(create, deps?)<Model>((api) => Model) => Modelstart({signal}) method, it is called after mount and the signal aborts on unmount.useSignal(value)Signal<T>useComputed(compute)ReadonlySignal<T>useSignalEffect(effect)(() => void | (() => void)) => voiduseSignalValue(signal)<T>(signal: ReadonlySignal<T>) => Tsignal · computed · effect · batch · untracked@preact/signals-coreimport {
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.
@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.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.
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.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.
<Stack><sessions-stack><Grid><sessions-grid><Section><sessions-section><Heading><sessions-heading><Text><sessions-text><Link><sessions-link><Button><sessions-button>to is set.<Banner><sessions-banner><Badge><sessions-badge><Image><sessions-image><Embed><sessions-embed><DisclosureGroup><sessions-disclosure-group>sessions-disclosure rows with dividers between them.<Disclosure><sessions-disclosure><TextField><sessions-text-field><Form><sessions-form><Select><sessions-select>sessions-option children.<Option><sessions-option>sessions-select.<Switch><sessions-switch><DetailRow><sessions-detail-row>*.row target renders.<DetailRowSkeleton><sessions-detail-row-skeleton><SkeletonText><sessions-skeleton-text><SkeletonHeading><sessions-skeleton-heading>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.