Using the app's UI components and Tailwind in a plugin frontend
A plugin frontend is bundled on its own and cannot import $lib, but every shared UI
component of the app is available through the host: window.__potionui.components.<Name>
exposes mount(el, props), update(instance, props) and unmount(instance). Components
load on first use, so mount returns immediately and the component appears once its code
has arrived; update calls made in between are merged.
On this page
Registered names: every component of $lib/components/ui/ (Button, IconButton,
CopyButton, Card, PageHeader, PageTitle, Badge, Kbd, Input, InputGroup,
Spinner, PageContainer, EmptyState, LoadErrorState, SegmentedControl, Pagination,
Switch, Alert, UserPicker, AdminOnlyMark), every component of $lib/components/detail/
(DetailLayout, DetailHeader, DetailBody, DetailSection, DetailFooter, DetailTabs,
DetailField, KVGrid, KVItem), every component of $lib/components/library/
(LibraryPage, LibraryShell, LibraryFilterBar, LibraryEntryCard, LibraryDensityToggle,
LibraryFilterChipRow, FilterPopoverFrame), plus Tooltip and Icon. A new component
dropped into one of those folders is registered automatically. DynamicForm renders a preset's
form outside the Generate page: pass presetId, mode, variant, initialData and
onFormDataChange(data), and optionally audience ('simple' or 'advanced') to show that
audience's fields without changing the user's own Simple/Advanced choice. window.__potionui.confirm({title?, message, variant?, confirmLabel?, cancelLabel?}) opens the app's confirm dialog and resolves to a
boolean: true from the confirm button, false from the cancel button, Escape or the backdrop.
confirmLabel and cancelLabel rename the two buttons ('Confirm' and 'Cancel' by default).
window.__potionui.notifications.toast(level, message) shows a toast.
window.__potionui.api makes authenticated requests to the app, so a plugin never reads the
token from localStorage or builds an Authorization header. api.fetch(path, init?) takes an
absolute app path and an init of {method, headers, body, signal, timeout, onUploadProgress} and resolves to a
standard Response, so ok, status, json() and blob() work as with fetch;
api.json(path, init?) resolves to the parsed body, or null when the body is not JSON. A 4xx
or 5xx answer resolves with its body rather than throwing; only a network failure rejects (a
TypeError, or an AbortError when signal aborts). A refreshed session token is adopted, a
401 ends the session as it does for core pages (except on /api/auth/login and
/api/auth/register), and cookies are sent. Calls time out after 30 seconds; pass timeout: 0
for a long request. A FormData body is sent as multipart with no timeout, and a Blob body
or a file download works through api.fetch the same way. onUploadProgress(loaded, total) is
called as the body goes up (total is 0 when the browser does not know the size). The
response body is read in full before the Response resolves: there is no streaming.
Because registration is automatic, the props of every component in ui/, detail/ and
library/ are a public contract: a plugin may pass any of them, so renaming or removing one
breaks plugins that use it. Treat such a change as an API change and note it in the changelog;
a component that must stay private belongs outside those folders.
Button no longer takes a title prop and IconButton sets no native title: an IconButton
shows its label in the host tooltip by itself (see "Icon buttons with a tooltip" below), and any
other control is wrapped in the host Tooltip (props={{ text }}) to show a hover hint. IconButton
accepts variant: 'overlay' for controls that sit over media and forwards extra attributes
such as data-* to its button. Tooltip also opens on keyboard focus, closes on Escape,
describes its trigger with aria-describedby while open, and takes truncateOnly: true to
show only when its content is cut off.
Snippet props cannot cross the bundle boundary, so pass children as a string or as
(el) => cleanup? that fills the slot element. Any other snippet prop takes { slot: string | (el) => cleanup? }.
In a Svelte plugin component, content/plugins/sdk/HostUi.svelte does the mounting,
updating and cleanup for you, and its markup children are projected into the host component:
<script>
import HostUi from '../../../../sdk/HostUi.svelte';
let clicks = $state(0);
</script>
<HostUi name="Button" props={{ variant: 'primary', onclick: () => (clicks += 1) }}>
Clicked {clicks} times
</HostUi>
<HostUi name="Tooltip" props={{ text: 'Rendered by the host' }}>
<span class="text-fg-muted">Hover me</span>
</HostUi>Tailwind classes written in a plugin's frontend/src/**/*.{svelte,js,ts} (marketplace and
local) and in content/plugins/sdk/ are scanned by the app's Tailwind build, so the semantic
token classes (bg-surface-2, text-fg-muted, border-line, ...) and arbitrary values work
in plugin markup. Rebuild the app frontend after adding new classes. Use the token classes only,
as in the app.
Shipping a stylesheet with a plugin page#
The app's Tailwind build only sees the plugins that are on disk when it runs. A plugin added
later, to content/plugins/local/ of a Docker image or of an install whose frontend was built
before, finds only the classes the app happens to use itself, and its layout breaks wherever it
uses others. Such a plugin ships its own stylesheet with its page.
A page plugin whose frontend/src/ holds <Component>.css, next to the <Component>.svelte
that index.js imports, gets frontend/dist/<Component>.css from scripts/build-plugins.mjs.
The build compiles that file with Tailwind, using the app's frontend/tailwind.config.js as a
preset (same theme, tokens, type scale and focus-visible variants), over the plugin's own
frontend/src/**/*.{svelte,js,ts} only, with Tailwind's base styles off. @tailwind utilities;
is usually the whole file; plain CSS rules may follow it. A release build minifies the sheet as
it minifies the bundle. Compiling it needs the app frontend's packages (npm ci in
frontend/); a plugin without the file does not.
The build puts every rule under the page of the plugin: .p-4 becomes
:where([data-potionui-plugin="video-producer"]) .p-4, :root, html and body at the start
of a selector become the page element itself, and keyframes keep their names. The sheet holds no
token values: its rules read the app's CSS variables (--surface-2, --fg-muted, ...), so it
follows the light and dark themes like the app does.
The scope sits in :where(), so it adds no specificity: a rule of the sheet weighs what the same
utility weighs in the app's own CSS, and the sheet, adopted after the app's, wins only ties. A
host component rendered in the page (a Button of hostComponents) keeps its hover:,
focus-visible: and disabled: styles when the plugin uses the same base utility, since those
variants weigh more than a bare class. One tie remains: a responsive variant weighs what a bare
class weighs, so a host component whose element carries px-3 md:px-4 keeps px-3 at every
width once the plugin uses px-3 anywhere, because the sheet's px-3 comes after the app's
md:px-4. :where() needs Chrome or Edge 88, Firefox 78 or Safari 14; the app's own
focus-visible: variant already uses it, and in Firefox and Safari adopting a constructed
stylesheet needs more (Firefox 101, Safari 16.4).
GET /api/plugins/pages/{route} answers stylesheet, the path of <Component>.css in
frontend/dist/ when the file is there, null otherwise. The plugin page route fetches the
sheet with the bundle, keeps only the rules that stay inside the page element, adopts the sheet
before it mounts the page, and removes it when the page unmounts. A kept style rule has
selectors that each start with the plugin's :where([data-potionui-plugin="<id>"]), the scope
alone inside :where(), followed by nothing, a descendant or a child combinator, and holds no
nested rules; @media, @supports, @container and @layer blocks are looked into,
@keyframes and @font-face are kept, and everything else (@import, @page, a selector that
starts elsewhere or reaches a sibling of the page, a style rule with nested rules) is dropped,
with a console warning in development. The sheet therefore applies to the plugin page only, and
to nothing once the user leaves it.
Limits of the page stylesheet:
- Content outside the page element. Content the plugin moves out of its page element, such
as its own dropdown or modal portalled to
document.body, gets nothing from the sheet. Render it with the host components, which carry the app's own classes, or give its root the attributedata-potionui-pluginwith the plugin id, which brings the sheet to the root's descendants but not to the root itself. The plugins of this repository do not show the problem because the app's Tailwind build still scans them. - Selectors on the document root. Only
:root,htmlandbodywritten alone at the start of a selector become the page element.:root[data-theme='light'] .x,html.dark .x,body:hover .x, and any selector that depends on an ancestor of the page element such as[data-theme='light'] .x, stay in the sheet under the page, where they never match, and no warning says so. They are not supported: the utilities read the app's tokens and already follow the theme. - CSS nesting. Nesting in the plain CSS written after
@tailwind utilities;is not supported: the scope prefix breaks&rules, and the page drops any style rule that holds nested rules. - Global names.
@keyframesand@font-facenames are global while the page is open: a plugin's@keyframes spinreplaces the app'sspin, and afont-familyit declares applies wherever the app uses that name. Prefix your own names with the plugin id (@keyframes video-producer-pulse). - Responsive variants of host components. As said above, a host component's
md:px-4loses to the sheet'spx-3when the component's element carries both and the plugin usespx-3. The host components that change a utility at a breakpoint are the page layout ones (PageHeader,PageContainer,PageTitle) and several ofdetail/andlibrary/;Buttonand the other controls ofui/do not.
A plugin without the file, which is every plugin in this repository, gets stylesheet: null
and loads as before.
Adding your own icons#
Every host component that takes an icon name (Icon, Button, IconButton, the items of
SegmentedControl, ...) looks the name up in the app's icon library. A plugin adds its own
icons with window.__potionui.registerIcon(name, paths):
window.__potionui.registerIcon('my-plugin-clapperboard', [
'M4 11v8a1 1 0 001 1h14a1 1 0 001-1v-8H4z',
'M4 11l1.5-6 15 3.5-.9 2.5'
]);paths is the d attribute of one <path> (a string) or of several (an array), drawn
like the app's own icons: a 24×24 view box, stroked with currentColor, no fill.
registerIcon returns true when the icon was added. It returns false and changes nothing
when the name already exists, whether it is one of the app's icons or one a plugin
registered earlier, or when the name or one of the paths is empty: a plugin can never replace
an icon the app or another plugin relies on. Prefix your names with your plugin's id to stay
clear of names the app may add later.
An icon can be registered at any time: an Icon already on screen under that name (showing
the first letter of the name as its fallback) redraws itself with the new paths. The
registration lasts until the page is reloaded, so register your icons when your plugin
starts, for example at the top of mountPlugin.
registerIcon is absent on hosts that predate it; call it as
window.__potionui.registerIcon?.(...).
Icon buttons with a tooltip#
Each HostUi is its own Svelte root, so a host IconButton mounted inside a host Tooltip
through two HostUi does not know it is inside one: it shows its own label tooltip and the
user gets two. Give the tooltip to the IconButton itself instead:
<HostUi
name="IconButton"
props={{ icon: 'film', label: 'Render', tooltip: 'Render the selected take', kbd: ['Shift', 'R'], onclick: render }}
/>tooltip— the tooltip text. Without it the tooltip showslabel.kbd— a keyboard shortcut shown in the tooltip, as one string ('Ctrl+K') or one string per key (['Shift', 'R']). It is only displayed: handling the keys is up to your page (see "Keyboard shortcuts on a plugin page"). A screen reader reads it after the tooltip text, the keys joined with+.
Both props are consumed by the button: unlike other extra props (data-*), they never reach the
DOM as attributes. The tooltip attaches to the button itself, with no wrapper element, so class
and layout apply to the button as usual, and label stays its accessible name (aria-label).
Inside a Tooltip of the same Svelte tree, an IconButton shows no tooltip of its own, so
tooltip and kbd are not shown there either.
A list page like History and Models#
LibraryPage is the app's list-page frame with props only, so a plugin page looks and behaves
like the other list pages: the page title with its count, a left rail of sections with counts
(use it for status filters), the search box, an optional sort select, a primary action button, and
your content below. Pass the content as children.
| Prop | Meaning |
|---|---|
title, titleLabel | title heads the section rail; titleLabel is the page title (default: the active section's label). |
persistKey | Remembers whether the rail is collapsed. |
sections, section, onSelectSection(id), sectionCounts | The rail: [{id, label, icon}], the active id, a callback, and {id: count}. One section hides the rail. |
count | The count shown next to the page title. |
q, onQueryChange(value), searchPlaceholder, searchHint | The search box; / focuses it. |
sortBy, sortOptions, onSortChange(value) | sortOptions is [{value, label}]; omit it to hide the select. |
primaryLabel, primaryIcon, primaryLoading, primaryDisabled, onPrimary | The primary action; no label, no button. |
heightClass | Defaults to h-full, so the page fills its container. |
<HostUi
name="LibraryPage"
props={{
title: 'Widgets',
titleLabel: 'Widgets',
persistKey: 'my-plugin:list',
sections, section, onSelectSection, sectionCounts,
q, onQueryChange, searchPlaceholder: 'Search widgets',
primaryLabel: 'New widget', primaryIcon: 'plus', onPrimary: create
}}
>
<MyCards />
</HostUi>LibraryFilterBar is also mountable on its own for a custom frame; it renders the search box,
the Filters popover (pass popover as { slot }) and the sort select without a wrapper.
Showing a generation in the details modal#
GenerationDetailsModal is the History details view. Mount it with generationId (plus
initialFileIndex, and isOpen, onClose) to show any generation a plugin knows the id of.
Two optional props let a plugin walk a list and add its own controls, both as plain data:
| Prop | Meaning |
|---|---|
onNavigate(direction), hasPrevious, hasNext, position: {index, total} | Shows the previous/next generation controls and Shift+Left/Right. On navigation the plugin updates generationId and initialFileIndex through update. |
onFileChange({generationId, fileIndex, fileId}) | Called when the file on screen changes, including the first time it is known (and when the user steps between a generation's files). |
extraSections | Sections added to the side panel under Information: [{id, title, icon?, rows?: [{id, label, checked, disabled?, onToggle(checked)}], actions?: [{id, label, icon?, onClick}]}]. Pass a new array through update to change them. |
const modal = window.__potionui.components.GenerationDetailsModal;
const handle = modal.mount(el, {
isOpen: true,
generationId,
initialFileIndex: 0,
onClose: () => modal.unmount(handle),
extraSections: [{ id: 'next', title: 'Send to', rows: [{ id: 'a', label: 'Upscale', checked: false, onToggle: (on) => pick('a', on) }] }]
});Media pickers#
Every place the app picks existing media (media loader fields, the editors, kits, Elixirs) opens
one picker, MediaPickerModal: source tabs History, Library and Kits on the title row, one
filter row (search, kind, collection, tags, favourites, a Filters popover, sort, tile size), a
grid that scrolls on its own and a one-row footer with numeric pagination. Single select has no
confirm button: a click on a tile picks it. Multi select adds a checkbox to every tile, an
n of m selected count and a confirm button. The tile size (S / M / L) is the setting the
History and Library pages already use.
GenerationHistoryModal and UploadLibraryModal stay as documented below: they are the same
picker with the source fixed (History or Library, no tab strip), with the same props, callbacks
and key shapes they have always had. MediaPickerModal is available to plugins the same way
(window.__potionui.components.MediaPickerModal, loaded on first use):
| Prop | Meaning |
|---|---|
isOpen, onClose, title | As for the two wrappers. The default title is Choose image, Choose video and so on. |
sources | Any of ['history', 'library', 'kits'], default ['history', 'library']. One entry hides the tab strip. |
initialSource | The tab shown on open. |
mediaType, mediaTypes | The kind, or the kinds, that are listed. The kind switch is shown only when more than one is listed. |
selectableMediaTypes | Kinds that can be selected; other listed files are dimmed with the reason. |
multiple, maxCount | Multi select, and an optional cap. Unselected tiles are dimmed with Limit of n reached at the cap. |
selectedKeys, onSelectionChange(keys, items), onConfirm(keys, items), confirmLabel | As documented below; confirmLabel replaces Use selected. |
onPick(item) | Single select: called with one item (the shape below) for every source. |
kits | {accepted?, mediaRoom?, loadedIds?, onLoad?(kits)}. With onLoad and multiple, a kit card gets a checkbox that means "use the whole kit" and counts the kit's acceptable items against maxCount; onLoad receives the kit details on confirm. |
On the Kits tab a kit is a card: it opens to its items, which are picked like any other tile;
items and kits the caller cannot take are dimmed with the reason. A picked kit item has
origin: {kind: 'kit', kitId, itemId}, kitItem and kit, and the key kit:<itemId>; a whole
kit is the key kit:all:<kitId>, which is never reported through onConfirm.
Media pickers with multi-select#
GenerationHistoryModal and UploadLibraryModal are mountable from a plugin
(window.__potionui.components.<Name>, props below; UploadLibraryModal loads on first use).
Both keep their single-select behaviour unless multiple is set:
| Prop | Meaning |
|---|---|
isOpen, onClose, title, mediaType | As for single-select. mediaType filters what is listed. |
onSelect | Single select only: (generation, file) from GenerationHistoryModal, (item) from UploadLibraryModal. The host closes the picker. |
multiple | Switches to multi-select: every file gets its own checkbox, a selected count and Cancel / Use selected buttons. onSelect is not called. |
selectedKeys | The selection, as a string array. Optional; when given the picker follows it, so a plugin can keep the selection across closing and reopening, and across switching between the two pickers. |
onSelectionChange(keys, items) | Called on every toggle with the new keys and the picked items the picker has seen. |
onConfirm(keys, items) | Called by Use selected, which is disabled while nothing is selected; the picker then calls onClose. |
selectableMediaTypes | ['image'], ['video'] or both. Other files stay listed but dimmed, with the reason under them. |
Keys are generation_id:file_id in History (every file of a generation is selectable on its own)
and the item id in the Library. Each item is {key, mediaType, filename, origin, generation?, file?, item?}, where origin is {kind: 'history', generationId, fileId} or {kind: 'library', itemId}.
Cancel, the close button, Escape and the backdrop all restore the selection the picker was opened
with before calling onClose. Selected keys survive paging, searching and filtering. items always
lines up with keys: for a file the picker has not loaded since it was mounted, the item carries
only key and origin, and mediaType and filename are null.
const picker = window.__potionui.components.UploadLibraryModal;
const el = document.body.appendChild(document.createElement('div'));
let keys = [];
const handle = picker.mount(el, {
isOpen: true,
multiple: true,
selectedKeys: keys,
selectableMediaTypes: ['image', 'video'],
onSelectionChange: (next) => { keys = next; },
onConfirm: (next, items) => useMedia(items),
onClose: () => picker.unmount(handle)
});Graph canvases with @xyflow/svelte#
@xyflow/svelte is part of the plugin toolchain (content/plugins/package.json), at the same
version as the app (pinned exactly in both). A plugin imports it like any other dependency
(import { SvelteFlow, Background } from '@xyflow/svelte') and it is bundled into the plugin's
own dist (about 250 kB minified). The build writes only .js there, apart from the page
stylesheet described above, so the library's stylesheet is not shipped as a file: copy what you
need from @xyflow/svelte/dist/style.css into the component's <style> block, using
:global(...) selectors.