aicoded.dev

TypeScript API: the ssr object

Live values and page calls work without any script. Write one in index.ts when a page needs more: showing why a value was refused, reacting to a lost connection, calling a page call, or writing a value that no input holds. The page's generated reactive_gen.ts gives the script a typed ssr object.

The generated file

A page with live values or page calls gets reactive_gen.ts next to its template:

export type ReadVars = {
  displayName: string;
  visitorsOnline: number;
  visitorsTone: string;
};

export type WriteVars = {
  displayName: string;
};

export type Calls = Record<string, never>;

export interface CallError {
  status: number;
  message: string;
}

export const ssr = …;

The page's script imports it:

import { ssr } from "./reactive_gen";

The build strips the types without checking them, so a mistake shows in your editor, not in aicoded check.

The ssr object

Call What it does
ssr.get(name) the text last shown for the live value name, or undefined
ssr.on(name, (value) => …) runs the callback each time the live value name is shown again
ssr.set(name, value) writes a client-writable value; only names in WriteVars
ssr.onError((name, message) => …) runs when the server refuses a written value
ssr.call(name, args) runs a page call; see page calls
ssr.onConnect(() => …) runs each time the live connection opens
ssr.onDisconnect((code) => …) runs each time it closes, with the WebSocket close code

Every on… returns a function that removes the callback.

An example

The home page of the people example shows why a display name was refused, clears the message when a name is accepted, and reads data the template passed with <ssr:json>:

import { ssr } from "./reactive_gen";

const error = document.getElementById("display-name-error");
ssr.onError((name, message) => {
  if (name === "displayName" && error) error.textContent = message;
});
ssr.on("displayName", () => {
  if (error) error.textContent = "";
});

const langs: string[] = JSON.parse(document.getElementById("langs-data")?.textContent ?? "[]");
const note = document.getElementById("script-note");
if (note) note.textContent = `A script read ${langs.length} languages from the page.`;

The connection

See also

Markdown · Source on GitHub · framework f46741f