Mounting a widget
Reference for grist-widget-sdk/app: mountGristWidget(), the inside- and outside-Grist pages, the light/dark theme, and the deploy channel helpers.
grist-widget-sdk/app does what a widget's src/main.tsx otherwise wires
by hand: it renders the widget inside Grist, shows a page of its own when the
widget is opened anywhere else, and keeps the light/dark theme on <html>.
// src/main.tsx
import { mountGristWidget } from "grist-widget-sdk/app"
import "./index.css"
import * as entry from "./app/App"
mountGristWidget(entry, { dev: import.meta.env.DEV })This is the whole of a scaffolded widget's src/main.tsx. A widget
scaffolded before create-grist-widget 0.3.26 wires it by hand:
create-grist-widget upgrade
switches it.
The entry module
mountGristWidget(entry, { dev, root }) reads what src/app/App.tsx
exports (GristWidgetEntry). Everything a widget customises is there, in its
own file, so src/main.tsx is the same in every widget and
create-grist-widget upgrade rewrites it without losing anything.
| Export | ||
|---|---|---|
default | required | The widget component. React.lazy() works. |
widget | required | The declaration, from defineGristWidget(): access, columns, title and description (the page's title and meta tags), reportUrl (see When something goes wrong) and languages (see In the widget's language). |
Settings | optional | The widget's settings fields. With it, Grist shows "Open configuration" for the widget, and mountGristWidget() draws a full-panel Settings view while the configuration is open (Widget options). |
Alerts, LocalDevPage, ReleasePage | optional | Replace the SDK's alerts or pages (see the options below). export const Alerts = null renders the widget alone. |
mountGristWidget(config)
Renders into #root (or config.root) and returns { unmount }. What it
renders depends on where the page is open:
- Inside Grist (the page is in an iframe): the widget, inside
<GristWidgetProvider options>and<GristBoundary>. The boundary gates on"canRender"whenoptions.columnsdeclares columns, so the widget waits for them to be mapped, and on"ready"otherwise. - Outside Grist, where there's nothing to connect to:
LocalDevPageon the dev server (dev: true), andReleasePageon a deployed URL.
import { lazy } from "react"
import type { UseGristOptions } from "grist-widget-sdk"
import { mountGristWidget } from "grist-widget-sdk/app"
const options: UseGristOptions = { requiredAccess: "read table" }
// A lazily loaded widget: its code (a map library, say) loads only inside Grist.
const App = lazy(() => import("./widget").then((m) => ({ default: m.Widget })))
mountGristWidget({ App, options, dev: false })| Option | Default | |
|---|---|---|
App | required | The widget component. React.lazy() works. |
options | required | The declaration's options (widget.options), passed to GristWidgetProvider. |
metadata | none | { title, description, reportUrl, languages }: the page's title and meta tags, where to report a problem, and the widget's languages. mountGristWidget(entry) takes it from the declaration. |
dev | false | Pass import.meta.env.DEV. Outside Grist, it picks LocalDevPage over ReleasePage. |
Alerts | the SDK's alerts | Wraps the widget inside Grist, under the boundary. The default lists what needs the user's attention (column mapping, access level, failed writes, an unlinked section) above the widget. null renders the widget alone. |
Settings | none | The widget's settings fields, drawn in the SDK's Settings view while the configuration is open; hasCustomOptions then defaults to true. |
LocalDevPage | the SDK's page | Shown outside Grist on the dev server: it points at pnpm test and the dev loop. |
ReleasePage | the SDK's page | Shown outside Grist on a deployed URL: links to every channel and version, and the URL to paste into Grist. Receives { channel }. |
root | "#root" | The element to render into, or its selector. |
mountGristWidget() throws if the root element doesn't exist.
The default pages and alerts name the widget after the page's <title>, and
style themselves with shadcn's CSS variables (--background, --foreground,
--border, --radius, …) with neutral fallbacks, so they follow the widget's
theme without depending on its Tailwind config. They only surround the
widget: nothing inside App is styled by the SDK.
When something goes wrong
Inside Grist, two things show when the widget has a problem:
- A failed write is one of the alerts above the widget, with Grist's error.
- A widget that throws while rendering is replaced by "The widget stopped
working", with a button that reloads it, instead of a blank panel. The
error stays uncaught: the console shows it, and a
renderWithGristtest of a widget that throws still fails.
Both link "Report a problem" when the declaration has a reportUrl, an http
or https URL that opens in a new tab: an issue form, say, prefilled with the
widget and its version.
import { defineGristWidget } from "grist-widget-sdk"
// The version the build carries: Vite's `define` sets it from package.json, say.
declare const __WIDGET_VERSION__: string
const report = new URLSearchParams({ template: "widget-bug.yml", widget: "kanban-board", version: __WIDGET_VERSION__ })
export const widget = defineGristWidget({
title: "Kanban board",
requiredAccess: "full",
reportUrl: `https://github.com/acme/widgets/issues/new?${report}`,
})Nothing is sent anywhere: the person opens the link and writes what they choose. A URL that isn't http or https is ignored, and so is a missing one.
In the widget's language
The screens before the widget renders, the alerts above it, "Report a
problem" and "The widget stopped working" speak English or French. They
take the first of the person's browser languages that the widget declares
in languages and the SDK speaks; the French quotes Grist's own French
labels ("Accès complet au document").
import { defineGristWidget } from "grist-widget-sdk"
export const widget = defineGristWidget({
title: "Kanban board",
requiredAccess: "full",
languages: ["en", "fr"],
})Without languages, the widget is English and so is the chrome, whatever
the browser prefers. A widget that lists only other languages gets English
chrome. renderWithGrist(<App />, { widget, rows }) uses the same rule, so
a test can check the French screens.
<GristWidgetApp>
The same tree as a component, with the same props minus root: for a page
that manages its own React root, or a test.
import { renderWithGrist, screen } from "grist-widget-sdk/emulator/testing"
import { GristWidgetApp } from "grist-widget-sdk/app"
function Widget() {
return <p>Hello from Grist</p>
}
renderWithGrist(<GristWidgetApp App={Widget} options={{ requiredAccess: "read table" }} />)
await screen.findByText("Hello from Grist")Theme
The page keeps light or dark on <html class>, which Tailwind's dark:
variant (and shadcn's tokens) read.
- Inside Grist, the widget follows Grist's theme. Until Grist has sent it, the OS setting applies.
- Outside Grist, the OS setting applies by default. A choice made with
setTheme()is saved inlocalStorage, and thedkey switches between light and dark (except while typing in a field).
useTheme()
For components that need the theme in JavaScript, such as a toaster or a
chart. Its shape matches shadcn's useTheme(), so a shadcn component can
import it in place of the template's theme provider.
import { useTheme } from "grist-widget-sdk/app"
function ThemeLabel() {
const { theme, resolvedTheme } = useTheme()
return <span>{theme === "system" ? `system (${resolvedTheme})` : theme}</span>
}type UseThemeResult = {
theme: "light" | "dark" | "system" // inside Grist: Grist's theme, "system" until it arrives
resolvedTheme: "light" | "dark" // what <html class> carries
setTheme: (theme: "light" | "dark" | "system") => void // does nothing inside Grist
}Rendered without mountGristWidget() (a unit test, for instance), it reports
the system theme instead of throwing.
Deploy channels
A widget's deploy pipeline publishes the same build at its root and at
/latest/, a preview at /dev/, and each release at /v<version>/, with a
versions.json listing the releases. The widget catalog serves each release
at /<version>/ and the newest of each major at /v<major>/, its install
URL. These helpers serve a page shown outside Grist, such as a custom
ReleasePage. The default one says, on /dev/, not to paste that URL into
a document: it follows every change before its release.
import { useReleasedVersions } from "grist-widget-sdk/app"
// Export it from src/app/App.tsx as ReleasePage.
export function ReleasePage() {
const { versions, error } = useReleasedVersions()
if (error) return <p>The list of releases couldn't be read.</p>
return (
<ul>
{(versions ?? []).map((v) => (
<li key={v.version}>
{v.version}, {new Date(v.publishedAt).toLocaleDateString()}
</li>
))}
</ul>
)
}parseDeployPath(pathname)
import { parseDeployPath, deployChannelLabel } from "grist-widget-sdk/app"
parseDeployPath("/my-widget/v1.2.0/")
// { channel: { kind: "version", version: "1.2.0" }, basePath: "/my-widget/" }
parseDeployPath("/widgets/map/v0/")
// { channel: { kind: "major", major: 0 }, basePath: "/widgets/map/" }
deployChannelLabel({ kind: "dev" }) // "dev"A path without a channel segment (the deployed root, or the dev server) is
latest.
useReleasedVersions(pathname?)
Fetches versions.json from the base path of pathname (the current page by
default).
type UseReleasedVersionsResult = {
versions: { version: string; publishedAt: string }[] | null // null until loaded
error: boolean
}