Skip to content
playactor
Esc
↑↓navigate↵open⌘Jpreview
On this page

The api handle

What a plugin can reach through api, its typed handle on the app, from activate, contributions, pages, layouts and components, and the host components it renders.

api is typed by the plugin’s manifest: service keys, page names and preference values all autocomplete, and a misspelt one doesn’t compile.

// activate gets it, and every contribution function as its last argument
definePlugin(manifest, {
  activate(api) { /* … */ },
  search: { videos: { label: 'Videos', search: (query, context, api) => searchVideos(api, query) } },
})

// pages and layouts get it as a prop
function ShowPage({ api, params }: PageProps<typeof manifest, 'show'>) {}

// any component under the plugin reads it
const api = usePlugin(manifest)

api.services

One handle per service in the manifest.

const pc = api.services.pocketcasts

await pc.fetch(url)                  // anonymous, held to the service's hosts
await pc.account.fetch(url)          // adds the bearer token (and Twitch's Client-Id), refreshes once on 401/403
await pc.nativeJson(url, { headers })// a native GET, redirects followed, gzip decoded, parsed as JSON
pc.socket(url)                       // a reconnecting WebSocket, wss only, held to the service's hosts
  • account exists only on services with a login or oauth account.
  • account.fetch throws NotConnectedError while signed out.
  • useAccount(pc.account) returns { connected } and follows sign-in and sign-out live.

Sockets

socket(url) opens a WebSocket that reconnects on its own, with backoff and a connection timeout. Declare its host in the service’s hosts like any other:

twitch: { hosts: ['api.twitch.tv', 'eventsub.wss.twitch.tv'], account: oauth.device({ …, scopes }) },
let next = 'wss://eventsub.wss.twitch.tv/ws'
const socket = api.services.twitch.socket(() => next) // asked again before every reconnect

const stopMessages = socket.onMessage(text => handle(JSON.parse(text)))
const stopStatus = socket.onStatus(status => setStatus(status)) // 'connecting' | 'open' | 'reconnecting' | 'closed'
socket.status   // where it stands now
socket.send(text) // text frames; sent while not open, it goes on the next open
socket.close()  // for good: no reconnect, listeners hear 'closed' last
  • The URL is a string, a function, or an async function. A function is called before each connect, so a server that names the next URL (Twitch’s reconnect_url) is followed by changing what it returns.
  • Only wss: on the service’s hosts. The host checks every URL, the first and each reconnect’s. A string that fails throws PluginHostError from socket(). A function that answers one closes the socket (closed), and it isn’t asked again.
  • Opening a second socket while the first is still open is fine, for a handover: open the new one, close the old once the new one says it’s ready.
  • An open marks the service’s health chip working. A drop or a failed connect marks it unreachable. A close with code 1000 or 4000–4999 is the server’s choice, not an outage.
  • The host closes every socket a plugin opened when the plugin is disabled, updated or removed. Close your own when the component that needs it unmounts:
useEffect(() => {
  const socket = api.services.twitch.socket(url)
  const stop = socket.onMessage(onMessage)
  return () => {
    stop()
    socket.close()
  }
}, [url])

api.data

api.data.preferences.get()            // typed values from the manifest's fields
usePreferences(api)                   // the same, re-rendering on change
api.data.collections.channels         // the plugin's synced TanStack DB collections
api.data.transaction([a, b], () => {})// one write across several collections
api.data.workspaceId()                // the userId synced rows carry
api.data.storage.key('denylist')      // a namespaced key for localStorage

api.queries

TanStack Query options keyed under the plugin, with the host’s retry and offline policy. Disabling the plugin removes them.

useQuery(
  api.queries.options({
    key: ['archived', podcastUuid],
    account: 'pocketcasts',          // removed on disconnect too
    persist: true,                   // kept on disk across restarts
    staleTime: 60_000,               // archives move; without this, a week
    fn: ({ signal }) => client.archived(podcastUuid, signal),
  }),
)

A persist lookup refetches weekly unless it sets staleTime, and stays on disk for 30 days, so an old answer shows at once while a fresh one loads. Set staleTime only for data that really changes.

Or name the lookup’s cache class with cache, and set neither persist nor staleTime:

import { kept, session } from '@playactor/plugin'

api.queries.options({ key: ['tags'], cache: kept({ fresh: '1d' }), fn })   // on disk, asked again daily
api.queries.infinite({ key: ['search', q], cache: session({ fresh: '30m' }), fn, … })  // memory only

api.queries.infinite(…) is the paged version (session only), and api.queries.fetch(…) reads the cache from outside React.

api.app

api.app.navigate({ page: 'show', params: { podcastUuid } })
api.app.back()
api.app.openLink(url)                           // in the browser; a failure toasts
api.app.copyLink(url)                           // to the clipboard, toasting "Link copied"
api.app.toast.success('Subscribed')              // also message, info, error; every toast has a close button
await api.app.library.acquireMovie(movie)       // adds it and opens its page
useTmdbMovies(api, [603, 550])                  // TMDB movies from the app's shared cache
await api.app.downloads.start([source])         // download web videos at the user's quality; a live one, or your own ref, throws
await api.app.downloads.cancel(source.ref)      // stop a queued, running or failed one; false when none was
await api.app.downloads.purge(source.ref)       // take the file off this Mac; the video stays; false with no file here
useDownloadProgress(api, source.ref)            // 0–100 while it downloads, else null; live
await api.app.games.download({ ref, title, payload }) // a game's files into the Games folder, below
api.app.player.warm(source)                     // resolve a likely next play so it starts at once
api.app.player.seek(source, 580)                // jump the playing video to 9:40; false when another is playing
api.app.web.source(video)                       // a web video, kept as a title in the host's web namespace, below
api.app.web.progress(source)                    // its Watch later; useWebProgress in a page
await api.app.media.keep(source)                // the video as a title in the library (with its stream copy); returns its id
await api.app.media.keep(source, { take: false }) // a title outside the library, for Save or a queue
api.app.media.progress(titleId).save(312, 1204) // its one place, whichever page plays it; also get, finish, clear, unwatch
api.app.media.saved(titleId).set(true)          // Watch › Web's Saved: the title on the watchlist
await api.app.web.resolve(url)                  // host yt-dlp metadata/cache → source or safe failure
api.app.web.library.getSnapshot()               // shared Web rows, excluding removed videos; useWebLibrary in a page
api.app.web.card(video)                         // a library video's card, as Watch › Web draws it
api.app.web.actions(open)                       // its verbs over picks: a collection's `actions`
await api.app.music.play(album, { from: 2 })    // the plugin's own album into Music, playing from its third track
await api.app.music.download(album)             // its tracks onto this Mac, to play offline
await api.app.books.play(book, { from: 2 })     // the plugin's own book into Books, playing from its place, else its third part
await api.app.books.download(book)              // its parts onto this Mac, to play offline
await api.app.audio.live(stream)                // a live stream in the audio bar, below
api.app.audio.onLive(listener)                  // your live streams starting and naming songs; returns the unsubscribe
await api.app.library.add(files, { folder })   // photos and videos on this Mac, copied into the library
api.app.library.added                           // your added files whose title is in the library: a live query
await api.app.home.add(videos, { folder })      // video files only, the same way
await api.app.home.poster(path)                 // a frame of a video file on this Mac, for a card's art

warm is fire-and-forget and repeats are free: call it when a play is likely, such as the pointer resting on a video’s card. A source already downloaded plays from disk and isn’t resolved. seek moves the player only when source is what it is playing, streamed or from disk, so a timestamp in a page’s text can call it without checking.

useDownloadProgress (from @playactor/plugin, over api.app.downloads.progress) is live and never stored: it follows yt-dlp while the download runs and goes back to null when it finishes, fails or is cancelled. api.app.downloads.files says whether the file is queued, downloading, failed or on this Mac, and its updatedAt when it landed. A downloaded file is one more copy of the video’s version, so Storage lists, moves and removes it like any other; once it’s removed and no download runs, the video has no row. Only a web video downloads: start throws for a live one or your own ref. It lists the plugin’s own sources’ downloads and the web videos of the site a source names: YouTube’s are web:youtube:<id>.

Games on this Mac

A plugin that lists games says how one is fetched with its games contribution, and asks for it here. The host owns the rest: a folder in Downloads while it fetches, the game’s own folder under Games (Settings › Storage) once it lands, progress, cancel, and the row on the Downloads page. payload is stored, so a download a quit cut short is fetched again when the app next opens.

const ref = { ns: 'games', id: game.id }          // one of the manifest's `sources`
const copy = api.app.games.get(ref)               // this Mac's copy, or undefined
const percent = useGameProgress(api, ref)         // 0–100 while it downloads, else null

await api.app.games.download({ ref, title: game.title, payload: upload })
await api.app.games.cancel(ref)                   // stop a download, or forget a failed one
await api.app.games.reveal(ref)                   // its folder in Finder; false when it isn't here
api.app.games.copies                              // every copy of the plugin's, live

A copy is { id, state, folder, files, error, at }. state is downloading, ready, failed (with error) or missing: it landed, and its folder has since gone or its drive is unplugged. download leaves a game that is downloading or already here as it is, and fetches a failed or missing one again. Nothing in the app deletes a file under Games, and another plugin’s ref throws. error is stored as the fetch failed: { code, message }. message is your PluginFailure’s phrase, which your page translates with usePluginText as it renders, so it follows a language switch. It is null when the host stopped the download itself, and code says why: offline, no-files, import, source and so on.

Toasts

api.app.toast draws the app’s own toasts, so a plugin’s look like the app’s and carry its close button. Import nothing from sonner.

api.app.toast.message(`Unsubscribing ${name}`, {
  duration: 10_000,
  action: { label: 'Undo', run: () => undo(ids) },
})

// With `image` or `open` it's a card: the picture beside the words, and a
// click opens that page of the plugin's.
api.app.toast.success(video.title, {
  description: 'Saved',
  image: video.thumbnailUrl,
  open: { page: 'video', params: { videoId: video.id } },
})

const progress = api.app.toast.loading('Adding 3 videos')
progress.success('Added 3 videos') // or progress.error(...), in place

open takes the plugin’s own pages, typed like api.app.navigate. A card has no action. api.app.toast needs the release after 0.1.46.

Web videos

A video yt-dlp plays is a title in the host’s web namespace, the same one a pasted link opens: one resume, one Continue and one Watch later, whether the video was pasted or opened from the plugin. It becomes a title the first time the person plays, saves, queues, downloads or clips it, with a version and a stream copy the host’s yt-dlp plays, whatever plugins are on; a video nobody touched stays the plugin’s own row. The host’s player keeps its place on the title, its subtitles’ track, visibility and delay on the version, and its channel’s speed; the plugin passes none of them.

// yt-dlp's extractor key and its id for the video: the key is `twitchvod:v2241`
const source = api.app.web.source({
  extractor: 'TwitchVod',
  id: `v${videoId}`,
  url: `https://www.twitch.tv/videos/${videoId}`,
  channel: login,                                // yt-dlp's channel_id, else uploader_id
  meta: { title, subtitle: name, posterUrl, durationSeconds },
})
const { saved, toggleSaved } = useWebProgress(api, source)

<Player source={source} />
  • extractor and id are what yt-dlp’s own answer for url reports (extractor_key and id); a different pair is a different row from the one a pasted link opens.
  • channel is the channel’s id as yt-dlp reports it (channel_id, else uploader_id; a Twitch login). A speed picked on one of its videos is where the next one starts, opened from the plugin or pasted. Without it the video plays at 1× and no speed is kept.
  • useWebProgress (from @playactor/plugin) binds api.app.web.progress(source) once per mount and writes the meta the source had. Key the page by the video and mount it once the meta is known. saved follows the row live.
  • A card whose source is the video and which sets no progress draws the row’s bar and watched mark, and its ⋯ gains Clear progress and Mark watched while it’s started (see Lists).
  • toggleSaved toasts the outcome. api.app.downloads, api.app.player.warm and api.app.player.seek take the source like the plugin’s own. Playing or downloading the source keeps it as a title; nothing else is needed.

api.app.media reaches the title outside the player, for a plugin that marks videos from its own lists (YouTube’s Mark watched, its Watch later):

const titleId = await api.app.media.keep(source)   // minted once, in the library; the same id every time
const progress = api.app.media.progress(titleId)
progress.get()                                     // { positionSeconds, durationSeconds, watchedAt, lastPlayedAt }, or null before it's kept
await progress.finish()                            // watched, its place cleared; also save, clear, unwatch

const later = await api.app.media.keep(source, { take: false }) // outside the library
await api.app.media.saved(later).set(true)         // last on the watchlist, as Watch › Web's Saved
await api.app.media.saved(later).playNext()        // first on it (added if it isn't)
await api.app.media.saved(later).moveAfter(other)  // a drop: right after another listed title; null for first
await api.app.media.saved(later).set(false)        // off it; its progress and copies stay

A write to a title not kept yet does nothing, so keep the video first. Keep a video when the person acts on it, never for a feed: a title is something they touched. A keep is a take by default: playing, downloading, clipping or marking a video puts its title in the library and takes it off the watchlist, as with a movie. Pass take: false for an act that isn’t one (Save, a queue). A title in the library is on no watchlist, so saved(titleId).set(true) on one adds nothing.

The watchlist is one ordered list across every site and kind: an add goes last, Play next first, and a site’s Watch later is that list filtered to its own videos, in its order. Read it from api.app.web.library:

const isMine = (v: WebLibraryVideo) => v.source.key.startsWith('youtube:')   // module level
const later = useWebLibrary(api, isMine).filter(v => v.savedAt != null).toSorted(bySavedPosition)

Pass card and the video opens on the card a movie opens on, until the first play: the art, the title, the facts, the body, the labelled rows, and Play (or Space). It shows only when there’s nothing to resume, and again at the end with Watch again. Once it plays, the card’s facts, body and rows are the drawer’s About tab, as a movie’s are. tabs add more panels to the player’s bottom drawer. next is what plays after it, such as an item’s next part: at the end it comes up in the corner as an episode’s next does, and its button plays it as it fills. Give such a video card with cover: false, so it plays on open as an episode does and still has its About tab (this needs the release after 0.1.54):

<Player
  source={source}
  card={{
    art: { src: posterUrl, frame: 'landscape', fit: 'contain' }, // 'poster' is 2:3
    facts: [creator, year, '1h 12m'],                            // null and false skipped
    body: description,
    rows: [{ label: 'License', value: <LicenseLink /> }],
  }}
  tabs={[{ id: 'notes', label: 'Notes', body: <Notes … /> }]}
/>

<Player
  source={part}
  facts={[<ItemLink />, 'Part 3 of 12']}
  card={{ facts: [creator, year], body: description, cover: false }}
  next={{ title: 'Part 4', facts: ['9 min'], art: still, onPlay: () => play(nextFile) }}
/>

useNextInList() gives the card after this one in the list it was opened from, as it showed: Downloads as the person sorted and filtered it, a channel’s grid, a search’s results. The media kit records the list when one of its cards (MediaGrid, MediaTiles, MediaRowList, MediaListPage) opens a page, and forgets it when the person leaves that page; playing the next one walks on through the list. It’s null for a page opened any other way (a deep link, ⌘K, the phone) and after the list’s last. YouTube passes it as next when its When a video ends preference is Play the next one:

const fromList = useNextInList()
<Player source={source} next={autoplay === 'next' ? (fromList ?? undefined) : undefined} />

Resolving and listing Web videos

api.app.web.resolve(url) uses the same resolver and query cache as a pasted Web link. It returns { ok: true, source }, or { ok: false, reason } where reason is unsupported, collection, login, rate-limited, unavailable, network or failed. These reasons are best-effort classifications of provider errors; use them for recovery copy. Resolving alone writes no library row. Collections are rejected: this API opens one video. A successful source carries its live flag; decide whether to offer live playback before mounting Player.

api.app.web.library exposes the current workspace’s web videos kept as titles, every plugin’s and every pasted link’s. Each entry contains source, savedAt (when it went on the watchlist), savedPosition (its place there, lowest first; bySavedPosition sorts by it), addedAt and playback (positionSeconds, lastWatchedAt, watchedAt), read from the title. Times are epoch milliseconds; missing state is null. The snapshot keeps its reference until rows change and excludes soft deletions. useWebLibrary (from @playactor/plugin) follows it live, narrowed to the plugin’s own videos, and api.app.web.card draws each one as Watch › Web does, with api.app.web.actions(open) its verbs:

const mine = (video: WebLibraryVideo) => isMySite(video.source.url)
const play = (video: WebLibraryVideo) => open(video.source.url)

const videos = useWebLibrary(api, mine)
const actions = useMemo(() => api.app.web.actions(play), [])
<MediaListPage items={videos} actions={actions} card={video => api.app.web.card(video)} … />

The card has the thumbnail, length, uploader, progress and watched mark, and warms the stream on hover. Its click is Play, and its menu, from actions, offers Play, Watch later, Clear progress, Open on site and Copy link, then the file’s own verbs (see Actions); over several picks, Watch later, Mark watched and Clear progress reach them all. To add a verb, wrap the builder: kindActions('web-video', picks => { const web = actions(picks); return { ...web, menu: [...web.menu, [verb.favorite(starred, star)]] } }).

Filter this catalog for the plugin’s own sites rather than keeping another Watch later or playback collection. Declare the filter outside the component so the list keeps its reference. A player uses useWebProgress for its Watch later. The catalog reads stored rows and runs no network refresh. resolve and library need Playactor 0.1.39 or later, card 0.1.40, next (and TitleHero, MediaRowList column, MediaToolbar facets, matchTracks, api.app.music) the release after 0.1.43, MediaRowList frame="none" and api.app.books the release after 0.1.44, api.app.home the release after 0.1.45, api.app.home.poster, MediaRowList divided and MediaGrid detail the release after 0.1.50, api.app.home.poster on photos, MediaGrid selectable and a card’s glyph the release after 0.1.53, a row’s art.faces and MediaAvatar the release after 0.1.54, MediaPreview the release after 0.1.56, the host keeping a Web video’s place, subtitles and channel speed (and WebVideoSpec.channel) the release after 0.2.10, api.app.library.add and api.app.library.added the release after 0.2.24, api.app.media and web videos as titles the release after 0.2.25, actions over picks, api.app.web.actions and MediaRowTiles (SDK 8) the release after 0.3.0, and api.app.music.download the release after 0.6.0.

Albums of your own

An album only your source holds (a concert, a 78, a netlabel EP) plays in Music as any album does. api.app.music.play puts it in the library, each track streaming from your album source (a sources entry with kinds: ['album'], its copies located like a matched release’s), and opens its page there playing from from:

await api.app.music.play(
  {
    ref: { ns: 'archive', id: item.id },          // one of your own refs: the album's key
    title: item.title,
    artists: [item.creator],                      // names; they link nowhere
    year: item.year,
    art: posterUrl(item.id),
    tracks: item.tracks.map(t => ({
      disc: t.disc,
      position: t.position,
      source: trackSource(item.id, t.file),       // its title and length are the source's meta
    })),
  },
  { from: index }
)
  • Landing it again writes nothing, so Play can call it every time. A track is its album’s at its disc and position: landing the album in another format (FLAC after MP3) adds each format’s file to the same track, never a second track.
  • The album has no MusicBrainz ids, so it has no Similar, wishlist or discography; its cover is art.
  • api.app.music.download(album) lands the album the same way without playing it, then fetches each track not on this Mac into Music/<Artist>/<Album> (<Year>)/ under the download folder, named as the library files a track (05 Scarlet Begonias.flac). Each file is that track’s copy. Downloaded in the format it streams in, the album plays offline; a track that holds both formats plays one of its files, as a release album’s track does. Progress shows in Downloads.
  • Both throw for another plugin’s ref and for a plugin without an album source; play also throws for a from past the last track.

Books of your own

A book only your source holds (a LibriVox reading, a lecture series) plays in Books as any book does. api.app.books.play puts it in Books, each part streaming from your source (the first sources entry the plugin declares), and opens its page there playing from its saved place, or from part from when it has none:

await api.app.books.play(
  {
    ref: { ns: 'archive', id: item.id },          // one of your own refs: the book's key
    title: item.title,
    authors: [item.creator],                      // names
    narrators: readers,
    year: item.year,
    art: posterUrl(item.id),
    parts: sections.map(s => ({
      position: s.position,                       // play order
      source: partSource(item.id, s.file),        // its title (its chapter's) and length are the source's meta
    })),
  },
  { from: index }
)
  • Each part is one chapter, titled by its source’s meta.title. A part without durationSeconds can’t be placed in the book.
  • It lands as an audiobook: a recording, keyed by your ref. Playactor then files it under its book (the work, from Open Library) by your title and first authors entry, when both match, and Books shows it there; without a match it shows on its own. The shape you pass is unchanged.
  • Landing it again writes nothing, so Play can call it every time. It is never looked up on Audible: your facts are its facts.
  • An item the library already holds as an album stays an album, and play throws.
  • api.app.books.download(book) lands the book the same way without opening it, then fetches each part not on this Mac into Books/<Author> - <Title>/ under the download folder. Each file is that part’s copy, so the book plays offline and keeps its place and chapters. Progress shows in Downloads.
  • Both throw for another plugin’s ref and for a plugin without a source; play also throws for a from past the last part.

Live audio

A live audio stream (an internet radio station, a live show) plays in the audio bar, like a podcast. The bar shows on your plugin’s pages once it has played audio, and the mini player takes over away from them. api.app.audio.live takes the stream:

await api.app.audio.live({
  ref: { ns: 'radio', id: station.stationuuid }, // one of your own refs
  name: 'Classic Vinyl HD',
  art: station.favicon, // http or https, or null
  url: 'https://icecast.walmradio.com:8443/classic', // http or https, MP3 or AAC
})
  • The stream needn’t be one of your declared hosts: the app plays it, as it plays a podcast’s audio.
  • The bar shows the song title when the stream sends one (Icecast and Shoutcast metadata), else its name. It has no scrubber, speed or skip. Stop drops the stream, and Play picks it up from now.
  • The bar’s cover and title, and Back to Playactor in the mini player, open your plugin’s area on its first page (the first one shown, if someone hid a page in Settings › Sidebar).
  • The bar’s cast button plays the stream on a Chromecast, through the Mac, so onLive keeps reporting song titles. The Playactor receiver shows the station’s current song and artist on the TV. If that receiver fails to start, casting retries with Google’s receiver, which may keep showing the station name. While something casts, a stream you play goes to the same device.
  • A stream replaces whatever audio was playing, and stops when a video plays.
  • Throws for another plugin’s ref. Needs the release after 0.1.54.

api.app.audio.onLive tells your plugin when one of its own streams starts and each time it names a different song, while the app runs. Nothing is kept, so a plugin that wants a history writes its own rows. streamSong reads Artist - Title (or Title by Artist - Show on site.com) out of a stream title:

import { streamSong } from '@playactor/plugin'

activate(api) {
  api.onDispose(
    api.app.audio.onLive(event => {
      if (event.kind === 'started') markPlayed(event.ref.id)
      // { kind: 'title', ref, title: 'Miles Davis - So What' }
      else if (streamSong(event.title)) addHeard(event.ref.id, event.title)
    })
  )
}

streamSong('Miles Davis - So What')        // { title: 'So What', artist: 'Miles Davis', isrc: null }
streamSong('Miles Davis – So What (Live)') // an en or em dash too; a second ` - ` stays in the title
streamSong('TSF Jazz')                     // null: no separator, so not a song
streamSong('A Taste Of Honey by Martin Denny - Classic Vinyl on walmradio.com')
// { title: 'A Taste Of Honey', artist: 'Martin Denny', isrc: null }

songQuery is what the app searches catalogs for: the title without what stations add, and the first artist of a joint credit. Use it when your plugin looks a heard song up on its own service:

import { songQuery } from '@playactor/plugin'

songQuery({ artist: 'Eydie Gorme & Los Panchos', title: 'Sabor a Mí (Remasterizado)', isrc: null })
// { artist: 'Eydie Gorme', title: 'Sabor a Mí' }
songQuery({ artist: 'Kraftwerk', title: 'Radio Stars / Uranium', isrc: null })
// unchanged: a slash in a title is part of it
  • started comes for each start: your live, the bar’s Play after a pause, a command. A paused stream sends nothing.
  • title is the stream title as the station sent it. A reconnect can send the same song again after a started.
  • Another plugin’s streams never reach you. The host ends the subscription when your plugin stops, if you haven’t. Needs the release after 0.2.13.

SongList draws songs as the bar draws a station’s song: the album’s cover, the title over its artists and album once matched, then one icon: the bookmark puts the album on the wishlist when the library hasn’t got it, the disc opens it when it has. ⋯ on hover, and right-click on the row, hold the rest: Play, Get album, the artist, and every plugin’s song actions (Spotify’s Add to Spotify). A song with no ISRC is matched by artist and title on MusicBrainz, then on Deezer when MusicBrainz has nothing. One list looks its songs up together, so draw one per group (a day) rather than one per song:

import { SongList } from '@playactor/plugin/ui'

<SongList // lead goes before the cover, meta after the song
  items={heard.flatMap(row => {
    const song = streamSong(row.title) // a SongRef: { title, artist, isrc }
    return song
      ? [{ key: row.id, song, lead: formatTime(row.heardAt), meta: station.name }]
      : []
  })}
/>

Photos and videos from this Mac

A plugin that finds photos and videos on this Mac (Messages’ attachments, a WhatsApp chat, the Photos library) keeps them in the library with api.app.library.add. The host reads each file: a photo is copied into the Photos folder and becomes an image in the Library; a video is copied into the Home movies folder and becomes a home movie. Each goes under <plugin name>/<folder>/, keeping its name, and is titled by its date when that name is a camera’s (IMG_4410.HEIC → 6 Jul 2024, 14:02):

const results = await api.app.library.add(
  picked.map(a => ({
    path: a.path,                                 // absolute or from `~/`, inside your `files.read`; copied, never moved, renamed or deleted
    name: a.name,                                 // `IMG_4410.HEIC`: the copy's name
    when: a.sentAt,                               // Unix ms: its date when the file has none
    origin: { ns: 'imessage', id: a.guid },       // one of your own refs
    // folder: '2024',                            // optional: this file's folder, instead of the add's
  })),
  { folder: chat.name }                           // → Photos/Messages/Mum/IMG_4410.HEIC
)
// the host shows "Adding 3 photos and 1 video", then "Added 3 photos and 1 video"
// or "Added 2 photos · Couldn’t add IMG_1.HEIC, IMG_2.HEIC, IMG_3.HEIC and 4 more"
// → [{ origin, status: 'added', titleId: 'image:<hash>', kind: 'image' }
//    | { origin, status: 'added', titleId: 'home:<hash>', kind: 'home' }
//    | { origin, status: 'failed', problem: 'notAllowed' | 'unreadable' | 'notMedia' | 'notLanded' }]
  • A photo is dated by when its camera says it was taken, a video by when it was recorded (an iPhone’s com.apple.quicktime.creationdate); else by when.
  • Each path is held to the manifest’s files.read, as api.local.files holds it: one outside is notAllowed, and nothing of it is read or copied. The others still land.
  • Bytes the library already holds aren’t copied again while a copy of them is on this Mac: the result is the title they have, so adding a file twice gives one title. When that copy is gone, the add copies it in again under the same title; a video the library holds as a movie keeps its title. A photo deleted from the Library comes back with its notes. A clash of names with different bytes takes (2).
  • The host owns the toast: one while the add runs, counting photos and videos by extension, then what landed by kind and the files that didn’t by name, the first three then how many more. Show nothing of your own; the results are for your marks. A file’s folder puts it somewhere other than the add’s (Photos files each under the year it was taken), so one add is one toast.
  • One result per file, in order. unreadable is a file that couldn’t be read where it is; notMedia one that is neither a photo nor a video (a PDF), or a photo whose pixels can’t be read; notLanded one that couldn’t be copied or imported. It throws for another plugin’s ref.

api.app.library.added is your added files whose title is still in the library, a live query like api.app.downloads.files, for a card’s In library mark. Delete the title and its row leaves:

const { data: added } = useLiveQuery(q => q.from({ a: api.app.library.added }))
const inLibrary = new Set(added.map(a => a.origin.id))   // each row: { id, origin, titleId, addedAt }

api.app.home.add(videos, { folder }) is the same landing for videos alone, taking sentAt for when, with the same toast; its problems are notAllowed, unreadable and notLanded. New plugins call library.add. Both are additive and keep PLUGIN_API at 7; library.add, library.added, a file’s folder, the host’s add toast and home.add’s notAllowed need the release after 0.2.24.

A card for one of those files gets its art from api.app.home.poster(path): a video’s frame 10% in, or for a photo (HEIC, JPEG, PNG, GIF, WebP) a JPEG thumbnail at most 800 px on its longest side, made once and kept until the file changes. It answers the image URL, or null for a file that can’t be read or decoded:

art: { src: (await api.app.home.poster(item.path)) ?? null }

Messages shows a chat’s photos among its videos in one grid: selectable picks what can be added, and a glyph marks the videos:

const isVideo = (item: Attachment) => item.kind === 'video' // outside the component
const addable = (item: Attachment) => item.path !== null     // an attachment in iCloud can't be added

<MediaGrid
  items={items}                                  // videos and photos, newest first
  selectable={addable}                           // one in iCloud opens; ⌘A and ranges skip it
  card={item => ({ ...face(item), glyph: isVideo(item) ? Play : null })}
  …
/>

A card opens its photo or video under its row with MediaPreview in the grid’s detail: the media at left, its title and lines at right, ← → to step and Esc to close. It takes a URL, so a photo from api.local.files.urls and an attachment from convertFileSrc open the same way. media is a video, a photo (with a fallback thumbnail for one the webview can’t decode, and its size when src is a smaller copy), or absent with where it is instead:

detail={opened && {
  key: opened.id,
  content: (
    <MediaPreview
      key={opened.id}                              // each item mounts anew
      media={opened.src ? { kind: 'photo', src: opened.src, fallback: opened.thumb } : { kind: 'absent', label: 'In iCloud' }}
      title={formatTakenAt(opened.at)}
      lines={[opened.name]}                        // muted, under the title
      facts={[formatFileSize(opened.bytes)]}       // after the size or length it measures
      onStep={by => setOpen(items[index + by]?.id ?? opened.id)}
      onClose={() => setOpen(null)}
    />
  ),
}}

api.local

What the manifest’s capabilities let the plugin read on this Mac: a SQLite database another app keeps, the files in a folder, and who a number or email is in Contacts. It’s there only when the manifest declares them; without a declaration api.local doesn’t exist, and a plugin with a native half keeps api.native as it is.

const PHOTOS_DB = '~/Pictures/Photos Library.photoslibrary/database/Photos.sqlite'

const db = await api.local.sqlite(PHOTOS_DB)        // one of capabilities.sqlite.read, typed
const rows = await db.all<AssetRow>(
  'SELECT ZUUID, ZDIRECTORY, ZFILENAME FROM ZASSET WHERE ZKIND = ?1', [0]
)                                                   // every row, by column name
const newest = await db.get<{ at: number }>('SELECT max(ZDATECREATED) AS at FROM ZASSET') // first row, or null

const files = await api.local.files.urls(paths)     // one call for thousands of paths
files.get(path)                                     // a URL to load, or null: nothing on disk there
files.refused                                       // the paths outside every declared folder, which aren't keys
const art = await api.local.files.poster(path)      // a small JPEG of a video (10% in) or photo, for a card; null: nothing there

const people = await api.local.contacts.lookup(handles) // capabilities.contacts: one call for every handle
people.get('+61412345678')                          // { id, name, photoUrl } or null: not in Contacts

await api.local.openAccessSettings('fullDiskAccess') // System Settings › Full Disk Access; whether it opened
  • The database opens read-only and reads the WAL, so rows the other app wrote a moment ago are there. Only reads run: SELECT, WITH and PRAGMA table_info. ATTACH, every other pragma and every write are refused, and a query is one statement.
  • Values are text, numbers and null. A blob column, or an integer past 2^53, fails the query naming the column: leave it out, CAST it AS TEXT, read a blob as hex(column), or divide a huge integer down in the SQL.
  • files.poster makes its JPEG once and keeps it until the file changes; two are made at a time, so a grid can ask for every card at once.
  • contacts.lookup takes handles as a messaging app stores them (+61412345678, mum@example.com) and never lists the address book. Numbers match on their last nine digits, emails ignoring case. id is one person across their numbers and addresses; photoUrl is their picture, or null. macOS asks for Contacts access the first time; refused, every handle is null. Without capabilities.contacts it rejects as refused. Needs the release after 0.2.5, as does a ~/ path in api.app.home.add.
  • A path starts with / or ~/. Symlinks are followed before the check, so a link inside a declared folder pointing out of it is outside. A folder holds what’s under it by whole names: Photos Library.photoslibrary-old isn’t in Photos Library.photoslibrary.
  • Failures reject with a LocalReadError (from @playactor/plugin) whose kind picks the page’s copy:
kind When
denied macOS refused the read. Usually Full Disk Access: offer openAccessSettings('fullDiskAccess').
missing Nothing is at that path.
refused The path isn’t declared, or the SQL does more than read. A mistake in the plugin.
unreadable The read failed: not a database, bad SQL, a blob or a huge integer.

The declaration is held to on every call, which catches honest mistakes and keeps what you approved the thing that runs. It isn’t a sandbox: plugins share the app’s window.

api.faces

Faces in the plugin’s own files, named as home people through the same faces seam the app’s screens use. It’s there only when the manifest declares capabilities.faces, which needs files; without it api.faces doesn’t exist.

import type { FoundFace } from '@playactor/plugin'

const found = await api.faces.found([
  { kind: 'file', path: '~/Pictures/Photos Library.photoslibrary/originals/A/ada.heic' }, // an image
  { kind: 'file', path: video, atMs: 90_000 },                                           // a video, 90 s in
])                                                   // FoundFace[], most on screen first
const review = await api.faces.review(subjects)     // found, by who each is guessed as; the rest clustered
await api.faces.confirm(picked, { person })         // a home person (`p_…`); { newPerson: 'Ada' } makes one
const dismissal = await api.faces.dismiss(picked)   // not offered again…
await api.faces.restore(dismissal)                  // …until this Undo
const faces = await api.faces.ofPerson(person)      // what names them, the plugin's files and the app's clips
  • Each file is scanned once and kept. Asking again re-offers nothing confirmed or dismissed. A file whose bytes changed is scanned again, and what was settled in it stays settled; touching it without changing it scans nothing.
  • A video’s moment is part of the subject: 10 s and 90 s of one video are two, and hiding a face at one doesn’t hide it at the other.
  • Every path is held to files.read the way api.local.files holds it. One path outside them rejects the whole call with a LocalReadError of kind refused, before any file is read; a path with nothing there is missing.
  • confirm, dismiss and restore take only faces from the plugin’s own files: a face of a clip or of another plugin’s file is refused.
  • A confirmed face joins the person’s faces, so it steers the app’s guesses on the tapes too. In ofPerson its from is { kind: 'file', plugin, path, atMs }; there’s nothing to play.

The faces kit draws them as the app does, from @playactor/plugin/ui:

import { FaceReview, FaceTiles, PersonFaces } from '@playactor/plugin/ui'

<FaceTiles faces={found} />           // ✓ the closest home person, the name for a picker, ✕ to hide with an Undo
<FaceReview review={review} />        // a person's clear faces ticked with Confirm N, then the clusters nobody named
<PersonFaces person={person} />       // what names them: their tapes' faces, then each plugin's

FaceTile is one face on its own. ▶ shows only for a clip’s face; a file’s has nothing to play, and an image’s has no moment either.

Actions

Every menu, ⋯ and bar in the app speaks one vocabulary, and a plugin uses the same one. verb (from @playactor/plugin) makes each entry with its label, icon and id; a toggle takes whether it’s on now and says the way back:

import { verb, videoActions } from '@playactor/plugin'

verb.watchLater(saved, toggle)    // "Watch later", or "Remove from Watch later" when saved
verb.watched(watched, mark)       // "Mark watched" / "Mark unwatched"; { audio: true } says played
verb.archive(archived, toggle)    // "Archive", or "Unarchive" when archived
verb.playNext(queue)              // "Play next"
verb.openOn('Twitch', open)       // "Open on Twitch"
verb.copyLink(copy)

A menu is a list of sections, [[play, later], [openOn, copyLink]]: the menu draws a line between two sections that have entries and skips an empty one, so a verb that isn’t offered never leaves a stray line. Delete goes in its own last section. A menu entry can also be a submenu, { type: 'submenu', id, label, icon, menu }, whose menu is sections too and which opens beside the menu on hover, or carry toggle: { on }. A toggle with an icon is a verb (Favorite): its row shows the icon, filled while on unless its glyph already says so (Watch later’s checked clock and Unarchive’s arrow stay outlined), and picking it closes the menu like any row. A toggle without an icon is a pick from a list: a ✓ while on, and picking it keeps the menu open for the next. as: 'switch' draws a switch, icon or not, and keeps the menu open too. YouTube’s channel ⋯ uses a submenu of iconless toggles for Add to group. An entry with endsSelection: true ends a selection after it runs over the picks, whether from the selection row or the picks’ right-click, and even when its run fails. verb already sets it on Download, Remove download, Clear progress and Not interested. Leave it off an entry that keeps the picks for the next action, such as Mark watched or a submenu like Add to collection. Delete doesn’t need it: the deleted picks leave the page, and a selection with no picks left ends. The types are ActionMenu, ActionMenuEntry, ActionMenuItem and ActionMenuSubmenu, from @playactor/plugin/ui.

A surface shows some entries as buttons and holds the whole menu in its ⋯ and right-click. The ⋯ is drawn only when the menu adds something: an entry that isn’t a button, the pin, the Want mark or what a click on the card already does. Each is matched by the entry itself, so build a verb once and use that one entry in both places; the click is matched by its run. A disabled button doesn’t count. A card whose menu is Play and Favorite, with Play its click and Favorite its pin, has no ⋯, and right-click still opens the menu. moreButton: false drops the ⋯ anyway, for a row the page already crowds; a Player takes it too.

videoActions(picks, runs, { playing }) builds streamed videos’ verbs, in the app’s order, over one pick or several: each pick is its facts (later, started, watched, site) and whatever else the runs need. It returns each verb (play, playNext, watchLater, clearProgress, watched, openOn, copyLink), null where it isn’t offered, menu, the whole menu, and what a collection reads (click, Play; bar, Watch later, Download and Mark watched; download, when runs.download is given). Play, Open on and Copy link are one pick’s. Watch later and Watched are toggles over the picks: on for those off it, else off for them all. Play next and Clear progress run over the picks they apply to. A verb whose run you leave out isn’t offered. playNext puts the video first in the plugin’s own queue (YouTube’s Watch later); it shows after Play. playing: true is for the video in the player, which offers neither Play, Play next nor Clear progress. The surface picks its buttons. shelfClear(video.clearProgress) is a button that draws that same Clear progress entry with a ✕ ({ action, icon }), so the ⋯ doesn’t repeat it:

import { shelfClear, videoActions } from '@playactor/plugin'

const video = videoActions(
  [{ later: saved, started, watched, site: 'Internet Archive', id }],
  { play, watchLater: (picks, on) => setSaved(picks, on), clearProgress, watched: setWatched, openOn, copyLink }
)
const face = { ...rest, onOpen: video.play?.run, menu: video.menu, source }
// Continue watching: a ✕ in the corner that clears progress
const shelf = { ...face, buttons: [shelfClear(video.clearProgress)] }

The file verbs are the app’s. A card face or Player that names its source gets the download’s caption and fill on the art and, after a line in its menu, Download, Cancel download while it runs, Show in Finder and Remove download once it’s here, or Retry and Cancel download once it failed, all live wherever the download was started. A live source gets none. A plugin that records why a file was fetched (YouTube marks it kept) before calling api.app.downloads.start gives its own start once: a collection’s builder returns it as download, and every card, shelf and lane of that kind runs it for Download and Retry, so a face in a selecting collection has no onDownload. A Player takes it as onDownload. A face whose download is set, even to null, keeps its own caption.

Host components

Host components, so plugin pages look and behave like the app’s own. They are imports, not members of api. The ones typed by the manifest come from pluginUi(manifest), once, in the plugin’s src/ui.ts:

// src/ui.ts
import { pluginUi } from '@playactor/plugin'
import { manifest } from './manifest'

export const { PageLink, MediaRow, DownloadsShelf, ServiceStatus, toastFailure, crumb } = pluginUi(manifest)

Image, Player and the media kit take no page or service, so they come straight from @playactor/plugin/ui:

import { Image, OpenLinkField, Player } from '@playactor/plugin/ui'
import { MediaRow, PageLink, ServiceStatus, toastFailure } from '../ui'

<PageLink page="episode" params={{ episodeUuid }}>Open</PageLink>
<ServiceStatus service="pocketcasts" />       // health and a Fix link
<Image src={poster} alt={title} />            // served from the disk cache
<MediaRow title="Up next" seeAll={{ page: 'home' }} items={rows} getKey={row => row.id} frame="landscape" card={face} />
<Player source={source} resumeSeconds={30} onProgress={sink} /> // a plugin's own source
<OpenLinkField />                             // Watch › Web's link field, for headerActions

toastFailure('pocketcasts', error, 'Couldn’t load episodes')

For artwork whose content changes at the same URL, pass freshness to Image, or put it on a card or row’s art. Change revision when the broadcast or content changes; maxAgeSeconds also refreshes a long-running broadcast:

art: {
  src: stream.thumbnailUrl,
  freshness: { revision: stream.id, maxAgeSeconds: 86_400 },
}

The host replaces the cached file at that URL when the revision changes or 24 hours elapse, including while the image stays mounted. Existing permanent copies refresh on their first request with a freshness policy. Static artwork without freshness retains the permanent offline cache.

A page PageLink or MediaRow names, its params, and the service ServiceStatus or toastFailure takes are typed by the manifest: a misspelt one doesn’t compile. The components render inside the plugin’s own pages, layout, title tabs and episode panels; toastFailure works from anywhere, an event handler or a query included, and does nothing while the plugin is off.

Player is the app’s mpv player for a web source the plugin hands it ({ ref, url, meta }), with clips, screenshots, captions and the inspector; while it’s on the page, so are the player’s shortcuts and theater mode. Its top row is the host’s, the same as a movie’s: title (else meta.title), then facts on the quiet line after it, then buttons as icon buttons at the right end, the source’s first file verb (Download, a progress ring that cancels, Show in Finder, Retry) beside them, and a ⋯ with menu and the file’s verbs, drawn when that adds to the buttons (moreButton: false drops it). Right-click on the top row opens that whole menu. tabs adds the plugin’s own inspector tabs for the video, before Clips:

<Player
  source={source}
  facts={[<PageLink key="channel" page="channel" params={{ login }}>{name}</PageLink>, timeAgo(publishedAt)]}
  buttons={[video.watchLater]}
  menu={video.menu} // video = videoActions(facts, runs, { playing: true })
  tabs={[{ id: 'similar', label: 'Similar to', count: videos.length, body: <Grid videos={videos} /> }]}
/>

A fact or button that is null or false is skipped. A button’s label is its tooltip; disabled greys it out.

A source that is still resolving is null: the player draws itself opening, a black frame with a spinner, with your title and facts in the top row. Render the player as soon as the page knows what it will play, not after the source arrives. A switch from another video then goes straight from one player to the other: the video that was playing stops instead of going to picture in picture, theater stays on, and no page shows in between. Key the player by the source’s url, or 'opening':

<Player key={source?.url ?? 'opening'} source={source ?? null} title={matchup} />

A Watch › Web video needs neither speed nor onSpeedChange: the host starts it at its channel’s speed and keeps what’s picked. For a plugin’s own source, speed is the speed the video starts at, read once when it loads (1 when omitted); given for a Web video, it overrides the channel’s. onSpeedChange hears a speed the viewer picks from the speed control or the keys, a moment after they stop; never the start speed coming back, and once when they come back from picture in picture with a speed changed there. The YouTube plugin starts a video at the channel’s speed, else its Default speed, and keeps what you pick as the channel’s:

<Player
  source={source}
  speed={channelSpeed ?? Number(preferences.defaultSpeed)}
  onSpeedChange={speed => setChannelSpeed(api, channel, speed)}
/>

feeds are other feeds of the same thing, such as a game’s servers. The host draws a select after the facts, headed by label, and when the playing feed fails or ends, the failure offers Try the next one. A pick calls onPick, which loads it, usually by navigating to its page as an episode pick does; the player remounts for the new source. nextFeed(items, current) from @playactor/plugin is the feed a failure offers, for a plugin’s own fallback:

<Player
  source={source}
  feeds={{
    label: 'Server',
    items: servers, // { id, label }[]
    current: serverId,
    onPick: server => void api.app.navigate(watchTarget(game, server.id)),
  }}
/>

side puts a column right of the video, such as a live stream’s chat. The viewer resizes it by its edge and hides or shows it from a button at the top row’s right end; that choice is kept for every player with a side column. While hidden it stays mounted, so a socket inside it stays open. Theater and fullscreen show the video alone. Pass null to drop the column, as Twitch does while signed out:

const { connected } = useAccount(api.services.twitch.account)
<Player source={source} side={connected ? <Chat api={api} channel={login} /> : null} />

Opening, closing or resizing the column never reloads the video.

switcher adds one button to the player’s controls, labelled label, which opens render() over the bottom of the video. render is called only while it’s open, so a query inside it runs only then. Render a PlayerRail from @playactor/plugin/ui. You give it the items, what each tile shows, which one is playing (current, ringed and scrolled to), optional tabs (groups), and what a pick does; the host draws the tiles and runs the pick. The row is a tile high whether it’s loading, empty or full. captions={false} draws each tile as its art alone, for art that names itself, such as a scorebug; the face’s title still names the tile to screen readers. A pick that returns a promise marks its tile Opening. When the promise resolves, the rail closes. When it rejects, the rail stays open with the failure on that tile: a PickFailure‘s message, or Couldn’t open for anything else. Closing the rail or picking again aborts signal. A rail that throws shares the page’s error boundary, as inspector tabs do. Sports’ Games loads every league’s board with the player, so the rail opens on them, and lists only the leagues with a live game:

import { Player, PlayerRail, PickFailure } from '@playactor/plugin/ui'

<Player
  source={source}
  switcher={{ label: 'Games', render: () => <GameRail api={api} current={game} boards={boards} /> }}
/>

function GameRail({ api, current, boards }) {
  const [league, setLeague] = useState(current.league)
  return (
    <PlayerRail
      captions={false}
      groups={leaguesWithLiveGames(boards, current)}
      group={league}
      onGroup={setLeague}
      items={liveGames(boards[league], current)}
      loading={!boards[league]}
      empty="No live games"
      getKey={game => game.id}
      current={current.id}
      card={game => ({
        // The period and clock sit along the scorebug's foot.
        art: { src: null, still: <Scorebug game={game} /> },
        title: `${game.away} at ${game.home}`,
      })}
      onPick={async (game, { signal }) => {
        const servers = await loadServers(game)
        signal.throwIfAborted()
        if (!servers[0]) throw new PickFailure('No stream for this game')
        api.app.navigate(watchTarget(game, servers[0].id))
      }}
    />
  )
}

A tile’s face takes the card face’s art, title, meta, live, progress, watched and label, plus number (muted before the title, as an episode’s) and dim (greyed out, still pickable).

Mark a live stream’s source live: true. It never resumes or saves progress, and the player shows Record (beside Live) instead of a download. It loads with a rewind buffer on disk and its own reconnects: the bar spans what has been watched, and a dropped stream is opened again from url, so url must be the page that always resolves to the current broadcast. When yt-dlp can read the stream from its start, as with a YouTube live, the host does that on its own: the bar spans the broadcast, up to 12 hours, and a reconnect resumes in place. api.app.player.warm warms that resolve for a live: true source. Set live before the player mounts, since a source loads once; wait for whatever tells you, as the YouTube plugin waits for videos.list on a cold link. The recording is named after meta.title and meta.subtitle:

const source = { ref: { ns: api.id, id: `live:${login}` }, url, live: true, meta: { title: name, subtitle: streamTitle, posterUrl } }

For a direct HLS feed, set source.hls. It bypasses yt-dlp and applies the request context only while that source plays, including reconnects, Record and casting. Casting relays the HLS playlists and media through the Mac, preserving the referrer; a live cast starts at the live edge and does not use the local rewind buffer:

const source = {
  ref: { ns: api.id, id: `game:${game.id}` },
  url: playlistLoaderUrl,
  live: true,
  hls: { referrer: embedOrigin, nonstandardSegments: true },
  meta: { title: game.title },
}

hls.referrer is optional. Enable hls.nonstandardSegments only for a provider whose media segments use non-media extensions; it relaxes FFmpeg’s HLS extension checks for that source. Keep url as a fresh playlist loader rather than an expiring CDN manifest. Direct HLS recordings copy the source audio/video into Matroska without re-encoding.

toastFailure turns not-connected and rejected-credential errors into a link to the plugin’s settings.

Title bar

A page’s title and its controls go in the window’s title bar through PageHeader, from @playactor/plugin/ui. A page renders one, and a layout none. Its children are parts, in any order; the host puts each where its kind goes and in that order:

Part Where Holds
crumbs The bar, before the title Steps back to where the page sits, below the sidebar row: “Minecraft” on a stream’s page. crumb(label, { page, params }) from pluginUi(manifest) makes each
title The bar The page’s name. On a sidebar row’s own page, the row’s name stands for it; under a hero, it joins the bar once the hero scrolls out
PageHeader.Sections A tabs row under the bar, or the page’s tabs The page’s own views as tabs (Games · Standings · Teams), each with an optional count, and a label naming them for a screen reader; end goes at the row’s far end (a link, or the open view’s filters)
PageHeader.Stepper The bar Previous, what’s showing and next (a day, a week); a missing step disables its arrow, and reset goes back to the start
PageHeader.Actions The bar, last The page’s buttons; where the bar is narrow, all but the first go into a ⋯. afterHero waits until the hero has scrolled out
PageHeader.Filters The strip, left Chips, which scroll sideways rather than wrap (a FilterRow from @playactor/ui/filter-chip first folds its unset ones into More); active counts the ones set away from their defaults. MediaToolbar with only filters or facets draws the host’s chips
PageHeader.Search The strip, right of the filters; leading, on the left, when there are none The page’s search field; ⌘F focuses it, and autoFocus does on a search page
PageHeader.Sort The strip, right The sort menu: sort, sortDir, config and onChange, as MediaListPage’s
PageHeader.View The strip, right One View button opening a grid or list toggle and a size slider; icon is the button’s, usually the current layout’s

The bar reads as a path: the host puts the plugin’s area and lit sidebar row first (“Twitch › Browse”), so crumbs hold only what’s deeper. The strip is one row under the bar, drawn only while the page has a part for it. While cards are picked, the bar keeps only the title and the strip only its chips.

A crumb’s target is the same { page, params } a PageLink takes; the host builds its link.

// Sports' league page: its sections in the row under the bar, the day in the bar
import { PageHeader } from '@playactor/plugin/ui'

<PageHeader title={leagueTitle(t, league)}>
  <PageHeader.Sections
    label={t('League view')}
    value={section}
    items={LEAGUE_SECTIONS.map(s => ({ id: s, label: t.label(SECTION_LABELS[s]) }))}
    onSelect={s => api.app.navigate({ page: league, params: { section: s } })}
  />
  <PageHeader.Stepper
    label={weekly ? week?.label : dayLabel(day, language)}
    previous={previous ? () => go(previous) : undefined}
    next={next ? () => go(next) : undefined}
    reset={selection !== undefined ? { label: t('Today'), onSelect: () => go(undefined) } : undefined}
  />
</PageHeader>

// Its Teams section: the same sections, and one search field in the strip
<PageHeader title={leagueTitle(t, league)}>
  <PageHeader.Sections label={t('League view')} value="teams" items={sections} onSelect={select} />
  <PageHeader.Search value={search} onChange={setSearch} placeholder={t('Find team')} />
</PageHeader>

// Twitch's category page: a crumb back to Twitch's home
<PageHeader title={category.name} crumbs={[crumb(t('Twitch'), { page: 'home' })]} />

hero is the page’s own top (a picture, a name, Play), the element a callback ref gave it. While any of it is on screen, the title in the bar is dimmed; once it scrolls out, the title is at full strength and Actions afterHero joins the bar. Without tabs, Sections draw in a row of their own under the bar, and the bar drops its rule. tabs is a PageTabsRow the page puts under its hero, given the same way: Sections draw there instead, held at the top as the page scrolls, and while picking that row is the selection’s.

const [hero, setHero] = useState<HTMLElement | null>(null)

<PageHeader title={chat.name} hero={hero} />
<div ref={setHero} className="flex items-center gap-4 px-6 pb-4">
  <MediaAvatar name={chat.name} src={chat.photo} />
  <div className="text-title font-semibold">{chat.name}</div>
</div>

Anything else above a page’s content, such as a legend or a shelf, is the page’s own body, outside PageHeader. Plugins built for API 6 imported it from @playactor/ui/page-header and passed rows as children and an icon; neither works now.

Lists

A plugin’s cards, grids, rows and selection are the app’s own media kit, from @playactor/plugin/ui. MediaListPage is the page Movies and YouTube’s Watch later and Continue watching use: its title and headerActions in the title bar, and its filter chips, search and sort menu in a row under it, over one grid of MediaCards, or, given row and rowFrame instead of card and frame, a list of MediaRowItems (as Downloads); with rows, sections heads each run of rows in one section while the page sorts by its sort (Downloads’ Failed, Now, Up next and Done). hero takes a hero above the chips (an artist’s photo and name), scrolling with the cards; the title joins the bar once it scrolls out. A page says what each card shows; the host draws it.

import { MediaListPage } from '@playactor/plugin/ui'

<MediaListPage
  title="Saved"
  searchPlaceholder="Search saved"
  items={rows}
  getKey={row => row.id}
  frame="landscape"                             // or 'poster', 'square', 'round'
  filters={filters}
  search={row => [row.title]}
  sorts={sort}
  empty={{ icon: Bookmark, label: 'Nothing saved' }}
  scrollRestorationId="saved"
  actions={saved}
  card={(row, one) => ({
    art: { src: row.thumbnailUrl },
    title: row.title,
    byline: { label: row.channel, onOpen: () => openChannel(row) },
    meta: [row.views, row.ago],
    badge: row.duration,
    progress: row.watchedShare,                   // 0–1; leave it out for a Web video's source
    source: row.source,                           // its download, live, the file's verbs; a Web video's place
    pin: one.favorite,                            // a corner toggle, filled while on
  })}
/>

// Declared once (outside the component, or in a useMemo): the saved rows' verbs over picks.
const saved = kindActions('saved-video', (picks: ReadonlyArray<Row>) => {
  const play = one(picks, row => verb.play(() => playRow(row)))
  const favorite = toggleOver(picks, row => row.starred, verb.favorite, setStarred)
  const remove = { id: 'remove', label: 'Remove', icon: X, destructive: true, run: () => removeAll(picks) }
  return {
    favorite,
    click: play,                                  // the card's click
    menu: menuOf([play, favorite], [remove]),     // its ⋯ and right-click, over the card or the picks
    bar: host => [favorite, host.download, remove], // the lane's buttons while picking
  }
})
  • actions is the kind’s builder over picks, made with kindActions(kind, picks => …) (from @playactor/plugin), and every collection of that kind shares it: a card’s click, its ⋯ and right-click, the lane, ⌘A and Esc all come from it. card(item, one) gets one, the builder over that item alone, and returns the face without menu or onOpen: the card’s menu is one.menu and its click one.click, so the ⋯ never repeats the click. Collections of one kind share picks; picking one of another kind starts a new selection.
  • The builder returns menu (the ⋯ and right-click), and may return click (the entry whose run is the card’s click; without it, the face’s onOpen), bar(host) (the lane’s buttons, given the host’s Download, Mark watched and Add to collection over the picks) and download (its own start for Download and Retry over the picks, as YouTube keeps a downloaded video). one, over, toggleOver and menuOf (from @playactor/plugin) build verbs over picks: one pick’s, the picks it applies to, a toggle over them all, and the sections. Name each verb on the result as well, for the card’s pin, mark and buttons.
  • While picking, the row under the title bar becomes the selection’s: × to end it, how many are picked, Select all while some aren’t, the first four of bar’s buttons that apply (else of menu) and a ⋯; it stays at the top as the page scrolls, and the title bar doesn’t change. List the verbs people run on many first. A button is an item (red when destructive) or a submenu, which opens its menu below it. The ⋯ holds menu and the host’s verbs, and shows when it adds to the four buttons. A right-click on a picked card opens it too, over every pick, and on another card, that card’s menu and Select.
  • A list whose verbs make sense only one at a time says selects={false}: nothing picks, and card(item) carries its own menu and onOpen. A collection’s bar ((actions, host) => buttons) puts this surface’s own buttons in the lane.
  • A pin and Want are toggle items (verb.favorite(on, run), verb.watchlist(on, run)), so they must carry toggle, and the pin its icon: the pin sits in the corner, filled while on; Want goes in the card’s one top-left mark, { kind: 'want', want }, a small ribbon on the art’s top edge. The same slot says what’s yours isn’t on this Mac instead, { kind: 'away' }: a cloud dot. Where yours and the rest mix, owned: true puts a grey check at the right end of the meta line. watched fills the progress bar; a progress under way shows instead. buttons are icons in the card’s corner on hover.
  • A filter is { id, label, test }; filters sharing a group are one choice. A sort is the sort menu’s config, an ascending compare per key, and the key it starts on.
  • A face without a source can draw its own download: { state, percent }. progress and a download’s percent are 0–1 and clamp; one that isn’t a number draws nothing. A download greys the art, fills it with colour as it arrives, and says how far under the title.
  • A ⌘- or ⇧-click or Select in a card’s right-click menu starts picking: a click picks instead of opening, and ⇧-click ranges over the order showing. ⌘A takes every card of the collection you’re in (the one holding focus, else the last one clicked), and × or Esc ends it; one Esc ends one thing, so a menu, a clip’s pending in-point and fullscreen or theater take it first. A page’s collections share one selection, which the route moving ends. Unpicking the last card doesn’t end it. A picked card sits on a tinted plate with a ring round its art, and keeps its top-left mark; a picked row sits on the plate with a check on its art.
  • The app’s own collections can take a held selection that outlives the page (clips gather across screens); its resolve(ids) gives the items for picks no screen shows, so the lane and a right-click reach them too.
  • byline takes a list for several people, as an album’s artists: they join with commas, each opening its own page. A single byline’s picture draws round before its name, as a channel’s avatar.
  • tag ({ label, art, onOpen }) sits at the right end of the byline’s line in a faint filled label, with art as a small poster before it: Twitch puts a stream’s game there with its box art. A long tag truncates before the byline does.
  • A live card sets live: true; its badge is the viewer count.
  • glyph (an icon component) sits on the art’s foot, left, where kinds mix: Messages’ play mark on its videos among the photos.
  • art.absent greys the art of something not here to open, as a Messages video still in iCloud (the release after 0.1.45).

The rest of the kit, from @playactor/plugin/ui:

Component Use
MediaGrid The same virtualized grid without the page, under a header the page gives (a channel’s PageHeader and banner). footer holds loading and empty lines; onEndReached pages. detail ({ key, content }, key a card’s id) opens a full-width block under that card’s row, pushing the rows below down: Messages plays a video or shows a photo there. selectable names the cards that pick when not all do; the rest only open.
MediaToolbar The host’s chips, in a page’s PageHeader.Filters. filters are on/off chips; facets pick one value each from a list ({ id, label, value, options: [{ value, label }], onChange }), with an inline clear once one is set.
MediaTiles A few cards that wrap, inside a page that already scrolls: a title tab, a channel’s clips. current sits one card on the plate. In an inspector tab its cards start smaller, and fill each row as a page’s do. rows={2} shows at most two whole rows, as many columns as the width fits, never a partial last row: a shelf with See all beside it. compact uses the inspector tab’s smaller cells on a page (a category’s box art).
MediaRowTiles Rows in wrapping columns inside a page that already scrolls, selecting as a grid does: Radio’s stations beside its Favorites and Load more. columns is a count, or 'auto' (as many as fit); it takes row(item, one) and actions as MediaRowList does.
MediaRowList A virtualized list of rows (round avatar art, the title’s initials where it has no picture, or with art.faces and no src up to three people’s pictures overlapping, as a Messages group’s; a 16:9 still, a small thumb or poster, or none where every row’s art would be the same, as a recording’s tracks), selecting as a grid does; current is the keyboard’s row. A row’s strip of stills opens on its own, buttons are its text buttons (buttonsStyle: 'icon' draws icons, buttonsShown: true shows them without hover), pin is a toggle beside them, and menu is its ⋯ and right-click. section heads runs of rows. column sets the rows on a title page’s centred column, as a show’s episodes sit; divided draws a hairline between rows.
TitleHero A title page’s top, as a show page’s: title, a meta line, body (four lines), one action, and a backdrop clear at right (blur lays art too small to show sharp behind it all). Put it in a MediaRowList column’s header, with the parts or episodes as rows.
MediaRowItem, MediaCard One row or card on its own.
MediaPreview A photo or video open under its card, in a MediaGrid‘s detail, stepping with ← →: Messages’ attachments and Photos’ library. See Photos and videos from this Mac.
Segmented, from @playactor/ui/segmented 2–5 fixed options: label, value, onChange and options ({ value, label, icon, count, busy }; more draws the count as 40+). With place it says where you are (a panel’s or dialog’s own tabs) and sits on a track; without, it picks what’s showing (a filter, sort or view) and drops the track. iconsOnly shows each option’s icon, its label the name and tooltip. A long or changing list (genres, sites, people) is chips in PageHeader.Filters instead.
MediaAvatar A row’s round art on its own (name, src, faces), in a page’s hero: Messages heads a chat’s page with its group photo, faces or initials.
useHeldSelection, usePicked A selection the page holds and picks into itself (a key that acts on the picks), and what’s picked in it.

A page that shows See all only when some cards were left out measures with useWholeRows and hands MediaTiles what fits:

import { MediaTiles, useWholeRows } from '@playactor/plugin/ui'

const { measure, shown, columns, cut } = useWholeRows(stations, { rows: 2, frame: 'square', compact: true })
{cut && seeAll}
<div ref={measure}>
  <MediaTiles items={shown} columns={columns} compact frame="square" … />
</div>

MediaRow (from pluginUi(manifest)) is a titled row of the same cards, See all on one of the plugin’s pages; it shows the first six and nothing without any. Given the page’s builder, its picks join the page’s grid: YouTube’s Continue shelf and Latest grid share one useYoutubeListActions(), and the shelf’s ✕ is shelfClear(one.clearProgress).

Ordered lists

A list the person drags into their own order (favorites, presets, a queue) stores a position on each row, lowest first. useOrdered reads a collection in that order and keeps it; MediaTiles takes its move as onReorder, and the cards drag:

import { useOrdered } from '@playactor/plugin'
import { MediaTiles } from '@playactor/plugin/ui'

// collections.ts: position: z.number()
const favorites = useOrdered(api.data.collections.favorites)

<MediaTiles items={favorites.rows} getKey={f => f.id} frame="square" card={face} onReorder={favorites.move} />

await favorites.add(position => ({ ...station, position }))       // after the last
await favorites.addFirst(position => ({ ...station, position }))  // before the first: Play next

A press that moves a few pixels picks a card up; a press that doesn’t is a click, and a drop never opens what was dragged. A drop writes the one row it moved, between its new neighbours (onReorder(key, { after }), after null for first); when repeated moves leave no room between two, every row is renumbered once. A list the kit doesn’t draw (chips, a rail) takes Sortable:

import { Sortable } from '@playactor/plugin/ui'

<Sortable items={chips} getKey={c => c.id} getLabel={c => c.label} orientation="mixed" onReorder={chips.move} className="flex flex-wrap gap-1.5">
  {chip => <Chip … />}
</Sortable>

orientation is vertical, horizontal, or mixed for a layout that wraps; getLabel is what a screen reader calls an item while it moves.

Rows that do something on a click of their own (play, expand) drag by a handle instead: grip makes each item’s SortableGrip the only thing that picks it up, and the keyboard lifts it too (Space, then the arrows). list draws a queue as an ol. itemClassName styles each item, and its data-dragging: classes change the lift:

import { Sortable, SortableGrip } from '@playactor/plugin/ui'

<Sortable items={queue} getKey={e => e.id} getLabel={e => e.title} onReorder={queue.move} grip list>
  {episode => (
    <Row lead={<SortableGrip aria-label={`Drag ${episode.title}`}><GripVertical /></SortableGrip>} … />
  )}
</Sortable>

A MediaListPage drags while it sorts by one of its sorts, first to last: give it order. YouTube’s Watch later opens on its Queue sort, and the person can still sort by Added or Title (nothing drags then):

<MediaListPage … sorts={sorts} order={{ sort: 'queue', onReorder: (key, place) => void move(key, place) }} />

A field with another name than position moves with moveTo(list, key, place), which returns the writes to make. Rows stored before they had a position need one once, in the order they showed in. carriedPositions(rows, { key, position, shown }) returns those writes, and a second run returns none:

carriedPositions(rows, {
  key: v => v.id,
  position: v => v.rank,
  shown: v => (v.starredAt == null ? null : -v.starredAt), // newest starred first, as it showed
})

YouTube’s Watch later is the host’s watchlist: its drop is api.app.media.saved(titleId).moveAfter(after).

A For you list from what the person watched: give rankBySeeds each seed’s similar items (a video they played or saved, and what its site lists beside it). Each item shows once, ranked by how many seeds list it, then its best place in a list, then weight. Keys in exclude never show (Adult and Internet Archive pass every video already played or saved):

const forYou = rankBySeeds(seedPages.map(page => page.related), {
  key: video => video.id,
  exclude: played,
  weight: video => video.views,
})

Downloads

A plugin that downloads gives itself a Downloads page and a shelf on its main page; the host lists the plugin’s downloads on this device and draws them:

import { PluginDownloadsPage } from '@playactor/plugin/ui'
import { DownloadsShelf } from '../ui'

pages: { downloads: { component: () => <PluginDownloadsPage open={open} />, icon: Download } }
<DownloadsShelf open={open} seeAll={{ page: 'downloads' }} />   // on the main page; nothing without any

const open = (download: PluginDownload) => api.app.navigate({ page: 'video', params: { id: download.ref.id } })

Both list what’s downloading first, in the order it was asked for, then failed ones, then the files here, newest first. Each card is drawn from what was downloaded (the WebSource its download started with: title, subtitle, poster) and shows Queued, its percent or Failed; its ⋯ has the file’s verbs. The page has Downloading and Failed chips, search, a sort by status, recency, title or size, and a selection whose actions start with Remove download (a file goes to the Trash, with Undo on its message; a running one is stopped, a failed one forgotten).

card(download, one) draws the plugin’s own card instead, from its own row for the video, without menu or onOpen (they’re one’s); returning null falls back to the host’s. actions(picks) returns the plugin’s own verbs (KindActions): its menu follows Remove download, its bar buttons follow it in the lane, and its download is Download and Retry’s start. A download whose record is gone and that the plugin draws no card for isn’t listed.

A web video’s download (the web namespace, which every plugin’s web videos share) is listed only when web(source) claims what was downloaded, so a plugin whose videos are web sources passes a predicate on the URL:

<PluginDownloadsPage web={source => new URL(source.url).hostname === 'archive.org'} open={open} />

YouTube’s Downloads gives its own cards and the same video builder as its other pages, so Retry marks the video kept:

<PluginDownloadsPage
  open={open}
  card={download => { const item = videos.get(videoIdOf(download.ref)); return item ? face(item) : null }}
  actions={picks => youtube(picks.flatMap(d => videos.get(videoIdOf(d.ref)) ?? []))}
/>

The kit’s pieces (the poster grid, the sort menu, the list state, the plate, the progress bar) are not importable: @playactor/ui/media, /media/opened-from, /list, /sort-menu and /virtualized-poster-grid aren’t in the import map, and the app’s lint fails a built-in plugin that imports them.

api.text

api.text<Messages>() is the t that usePluginText returns, for text outside React: a remote section’s load, a search, a service, a failure shown right away. Phrases, values, plurals and context work as they do there, and playactor plugin i18n collects its phrases the same way.

import type { Messages } from './messages.gen'

load: async ({ signal, language }, api) => {
  const t = api.text<Messages>(language)
  const clips = await topClips(api, signal)
  return {
    items: clips.map(clip => ({
      id: clip.id,
      title: clip.title,
      subtitle: [t('Clip'), t('{{count}} views', { count: clip.views }), timeAgo(clip.createdAt, language)].join(' · '),
      send: { page: 'clip', params: { slug: clip.id } },
    })),
    next: null,
  }
}

Given a language, as here, t translates into that one only, so a page’s words agree with its numbers and dates. Without one, t keeps one identity and reads the Mac’s language each time it’s called, so one held by a service follows a language change. A component uses usePluginText instead, which re-renders on the change.

Failures

A failure shown as it happens, such as a toast or a PluginFailure a command throws, can be translated when it’s thrown:

throw new PluginFailure(api.text<Messages>()('No favorite station called {{name}}', { name }))

A failure the host stores and shows later, a download’s or a game’s fetch, carries the English phrase instead. The Downloads page translates it from your catalog each time it’s shown, and so does your own page from a game copy’s error. Translated when thrown, it would stay in that language after a switch:

throw new PluginFailure(phrase('This download is incomplete.').source)

The rest

Member Use
api.id The plugin’s id.
api.log debug, info, warn, error into the app’s log.
api.text<Messages>(language?) The plugin’s catalog outside React. See api.text.
api.state What activate returned. See api and api.state.
api.native The native half’s commands, when the manifest has native. See Native half.
api.local Local reads, when the manifest has capabilities. See api.local.
api.faces Faces in its files, named as home people, when capabilities has faces. See api.faces.
api.onDispose(fn) Runs when the plugin is disabled or the app shuts down.

SDK version

PLUGIN_API (from @playactor/plugin, now 7) is the SDK contract a plugin built outside the app declares as api in its plugin.json. The app skips a plugin built for another one. isPluginDefinition(value) is true only for what the app’s own definePlugin returned.

When something breaks

The app’s log is ~/Library/Logs/actor.play.desktop/Playactor.log. Besides api.log, it gets:

  • a page, tab or panel that throws while rendering, with the plugin, the surface and the component stack. The page shows “Couldn’t load this page”; a tab or panel shows nothing.
  • a page still loading after 10 seconds, and how long it took once it loads.
  • every console.warn and console.error, uncaught errors and unhandled rejections.
  • one line at startup with each plugin’s status (active, failed, gated, off).

Right-click → Inspect Element opens the web inspector, in installed builds too.

Dates, times and numbers

api.formats() returns the host’s Formats for text produced outside React. React views import usePluginFormats from @playactor/plugin (also available from @playactor/plugin/ui). The hook updates with the host language and time format; the locale keeps the system region when it matches that language.

const formats = usePluginFormats()
formats.time(game.startsAt)
formats.date(photo.takenAt, { dateStyle: 'medium' })
formats.number(total)
formats.relative(updatedAt)
formats.bytes(file.size)
formats.duration(durationMs, 'hms')

This additive API keeps PLUGIN_API at 6. Plugins using it must require Playactor 0.2.23 or newer; publish them after that app release ships.

Was this page helpful?