sdui

package
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0

Documentation

Overview

Package sdui is WittyMediaServer's server-driven UI: the model an administrator writes pages in, the catalogue that describes it, the validator, and the renderer that turns one page into the tree of components one profile's app draws on one device.

A Page is an ordered list of Sections. Each section is a component from the catalogue (Hero, Shelf, Grid, DetailHeader, SeasonList, ...), most of them filled from a data Source ({"type": "recentlyAdded", "library": 3}) that a Resolver answers. Conditions, variants, repeats and a profile's own arrangement decide which sections a request gets, and a device profile (Layout) decides how much of each.

issues := sdui.ValidatePage(&page)          // what is wrong, and how to fix it
doc, err := sdui.Render(page, &sdui.RenderContext{
	Profile: sdui.ProfileFor(sdui.FormTV, "4k"), ProfileKind: "adult",
	Resolver: myResolver,                    // where the items come from
})
patches := sdui.Diff(previous, doc)          // for a client holding an older render

The package is pure Go and standard library only. It knows nothing about HTTP, storage or the media library: the server supplies a Resolver, and the conformance kit (package conformance) supplies one made of canned data.

docs/SDUI.md is the contract and the reference; its reference section is written from Catalog by a test, as is docs/sdui.schema.json from the types.

Versioning

SchemaVersion is the wire version of what a client is sent; it changes only for something a client built for it could not survive. CatalogRevision counts changes to the catalogue within it. Every renderer draws every component of the revision: there is no negotiation and no fallback.

Index

Constants

View Source
const (
	PropString   = "string"   // one line of text
	PropText     = "text"     // text that may hold placeholders ({user}, {library}, ...)
	PropMarkdown = "markdown" // the small Markdown subset (see docs/SDUI.md)
	PropInt      = "int"
	PropBool     = "bool"
	PropEnum     = "enum"     // one of Options
	PropEnumList = "enumList" // an ordered list of Options, none twice
	PropIcon     = "icon"     // one of Icons
	PropRoute    = "route"    // a place in the app: /library/3, /page/family-night
	PropImage    = "image"    // a picture on this server: a path beginning /api/
	PropURL      = "url"      // an http(s) address, opened outside the app
	PropSection  = "section"  // the ID of another section on the page
	PropLibrary  = "library"  // a library's ID, or $library / $each
	PropRef      = "ref"      // the ID of a collection, saved view or title, or a $ variable
	PropScope    = "scope"    // a theme scope
	// The rest are only on components the server makes (Card, Track).
	PropNumber = "number"
	PropObject = "object"
	PropList   = "list"
)

Property types, as an editor needs them to build a form.

View Source
const (
	FormTV      = "tv"
	FormPhone   = "phone"
	FormTablet  = "tablet"
	FormDesktop = "desktop"
	FormWeb     = "web"
	// FormHeadset is a headset (visionOS, Quest): a floating window, gaze and pinch.
	FormHeadset = "headset"
)

Form factors, platforms and the other fixed vocabularies.

View Source
const (
	NavSidebar       = "sidebar"          // a column at the side, labels and icons
	NavRail          = "rail"             // a narrow column of icons, labels under them
	NavRailDrawer    = "railDrawer"       // a rail that opens into a full menu and a library drawer
	NavBottomTabs    = "bottomTabs"       // a tab bar at the bottom (a phone's)
	NavTopTabs       = "topTabs"          // a row of tabs across the top
	NavFloatingGlass = "floatingGlassBar" // a glossy glass bar floating across the top
	NavCableBar      = "cableBar"         // flat blue rows with yellow highlights
	NavBevelBar      = "bevelBar"         // a silver bevelled bar
	NavTeleKeys      = "teleKeys"         // colour-coded keys, as teletext has
	NavCrossbar      = "crossbar"         // a horizontal bar of categories over a vertical list
	NavOrnament      = "ornamentTabs"     // a headset's ornament tabs beside the window
	NavTVTopMenu     = "tvTopMenu"        // a television's menu across the top, shown when focus goes up
	NavTVSideMenu    = "tvSideMenu"       // a television's menu down the side, opened by going left
)

How an app draws its menu.

View Source
const (
	FxNone   = "none"
	FxSubtle = "subtle"
	FxFull   = "full"
)

Levels of a finish effect.

View Source
const (
	ExpLumen      = "lumen"
	ExpClassic    = "classic"
	ExpStage      = "stage"
	ExpCompact    = "compact"
	ExpPaper      = "paper"
	ExpBigPicture = "bigpicture"
)

Experience IDs the code names.

View Source
const (
	ActNavigate = "navigate"
	ActPlay     = "play"
	ActNative   = "native"
	ActExternal = "external"
	ActBack     = "back"
	ActCommand  = "command"
)

Action types.

View Source
const (
	ControlSwitch = "switch" // on or off; the row's Action is what flipping it does
	ControlSelect = "select" // one of Options
	ControlField  = "field"  // a line (or lines) of text, or a number
	ControlSlider = "slider" // a number from Min to Max in steps of Step
)

Control types.

View Source
const (
	ModuleFormat        = "wittymodule-sdui"
	ModuleFormatVersion = 1
)

ModuleFormat and ModuleFormatVersion mark a module's SDUI file.

View Source
const (
	SettingBool   = "bool"   // a switch
	SettingEnum   = "enum"   // one of Options
	SettingInt    = "int"    // a whole number between Min and Max
	SettingString = "string" // a line of text
	SettingSecret = "secret" // a password or key: never shown again once saved
	SettingInfo   = "info"   // a line of text to read, with no value
)

Kinds of setting.

View Source
const (
	SettingScopeServer  = "server"  // one value for the server; only administrators change it
	SettingScopeProfile = "profile" // each profile its own
)

Where a setting's value is kept.

View Source
const (
	// MaxTopShelfSections and MaxTopShelfItems bound what is sent: the
	// extension is killed if it takes long, and nobody scrolls far there.
	MaxTopShelfSections = 4
	MaxTopShelfItems    = 10
)
View Source
const (
	// MaxPageBytes bounds one page as JSON.
	MaxPageBytes = 256 << 10
	// MaxSections bounds the sections of one page, nested ones and every
	// variant's included.
	MaxSections = 200
	// MaxDepth bounds nesting: a top-level section is depth 1.
	MaxDepth = 6
	// MaxChildren bounds the sections directly inside one container, and the
	// top-level sections of a page or variant.
	MaxChildren = 60
	// MaxVariants bounds a page's variants.
	MaxVariants = 8
	// MaxNavItems bounds the navigation.
	MaxNavItems = 40
	// MaxPages bounds the pages of one configuration.
	MaxPages = 200
	// MaxIDLength bounds a page's or section's ID; MaxNodeIDLength a rendered
	// node's, which is a section's ID and an item's joined.
	MaxIDLength     = 64
	MaxNodeIDLength = 128
	// MaxPersonalBytes bounds what one profile stores about one page.
	MaxPersonalBytes = 8 << 10
)

Limits on what is authored, so one edit can't make a page no small device can hold.

View Source
const BooksNone = "~none"

BooksNone, as a books source's series or author, is the books with none: the last row of a repeat over a library's series or authors.

View Source
const CatalogRevision = 8

CatalogRevision counts changes to the catalogue within one SchemaVersion. Every renderer draws every component of the current revision: there is no negotiation and no fallback. 5 added cast and crew: the Credits component, the credits and filmography sources, people in search, the person page. 6 added the Design 2 components and looks. 7 changed what the person card style shows (its badges: a friend's presence, a seat), so a renderer that copied the card-style table needs the new one; it also brought a source's person items, and the WittyPlay commands with their params. 8 changed what the person card style does: a presence badge is drawn as a dot by the style's badgeTones, and a person card with no action takes no focus unless its list says focusable (the card-style table, conformance/card-style-table.json, has both); it also brought, all additive, what WittyPlay Online and the server's own pages need: Shelf focusGrow and detail, an item's actions (the detail panel's buttons), item action, trailing and control, the shell regions statusBar and systemDock with a page's regions field, navigate actions shown as a layer, confirm on a command, the controls a list row can carry (switch, select, field, slider) with the Form component, the commands a button, notice or row can run, command params of type bool and ints, the sources versions, listsFor, newList, devices, year, activity and notices, custom pages opened about something (item, name, of), the routes of the pages the server serves for every app, the always-present key legend Dock on a television and a headset, and the settings slots route.

The rule: a change to what an existing component or card style shows or does bumps the revision. Only new components, card styles, sources, commands and optional properties are additive and stay in the revision they came in.

View Source
const MaxDocumentBytes = 2 << 20 // 2 MiB

MaxDocumentBytes is the largest encoded document Unmarshal accepts.

View Source
const MaxModuleBytes = 1 << 20

MaxModuleBytes bounds a module's SDUI file.

View Source
const ModuleFile = "sdui.json"

ModuleFile is the name of a module's SDUI file, beside module.json in a release.

View Source
const PresentLayer = "layer"

PresentLayer is Action.As for a page shown over the screen.

View Source
const SchemaVersion = 1

SchemaVersion is the wire version of what a client is sent (Document, NavDocument, TopShelf). See docs/SDUI.md, "Versioning".

Variables

View Source
var (
	// FormFactors are the kinds of device a page is fitted to.
	FormFactors = []string{FormTV, FormPhone, FormTablet, FormDesktop, FormWeb, FormHeadset}
	// Platforms are the apps a condition can name.
	Platforms = []string{"web", "tvos", "ios", "android", "androidtv", "desktop", "visionos", "quest"}
	// ProfileKinds are the kinds of profile.
	ProfileKinds = []string{"adult", "kids", "guest"}
	// LibraryKinds are the kinds of library a page or repeat can name.
	LibraryKinds = []string{"movies", "discs", "shows", "anime", "videos", "shorts", "channels", "musicvideos", "commercials", "music", "audiobooks", "podcasts", "radio", "books", "photos", "games"}
	// MediaKinds are the kinds of title a detail page can match.
	MediaKinds = []string{"movie", "show", "episode", "video", "disc", "album", "artist", "track", "book", "audiobook", "podcast", "game", "photo", "collection", "person"}
	// SpacingSteps are the abstract distances a layout component may use; a
	// device profile says how many points each is.
	SpacingSteps = []string{"none", "xs", "s", "m", "l", "xl"}
	// CardSizes are the three sizes of a card.
	CardSizes = []string{"s", "m", "l"}
	// Densities are how tightly a page is packed.
	Densities = []string{"compact", "comfortable", "spacious"}
	// PersonalKinds are what a profile may change about a page.
	PersonalKinds = []string{"reorder", "hide", "pin", "density", "cardSize", "defaultTab"}
	// CanFeatures are what a "can" condition may ask about.
	CanFeatures = []string{"games", "recordings", "downloads", "sharing", "comments", "syncplay", "remoteControl", "remote", "editProfile", "editLayout", "liveTv"}
	// Flags are what a "flag" condition may ask about.
	Flags = []string{"setupIncomplete", "scanning", "librariesEmpty", "hasQuery", "screenTimeUp"}
	// NativeScreens are the screens every app draws itself and SDUI only
	// links to. Settings is one of them on purpose: it is never an SDUI page.
	NativeScreens = []string{"settings", "guide", "profiles", "downloads", "remote", "nowPlaying", "pair", "collections", "player", "livePlayer", "reader", "game", "download", "share", "playOn", "watchParty"}
	// NativeViews are parts of a page an app may draw itself (NativeView).
	NativeViews = []string{"guide", "photoTimeline", "photoMap", "coverFlow"}
	// RepeatKinds are what a section can be repeated over.
	RepeatKinds = []string{"libraries", "pinnedViews", "collections", "bookSeries", "bookAuthors", "personParts"}
	// CreditGroups are the parts of a title's credits, in the order a page lists them: the
	// cast, the guest stars, then each crew department. The keys are the API's
	// (GET /items/{id}/credits).
	CreditGroups = opts(creditGroupSpecs...)

	// PersonParts are what a person did, as their page groups their titles: acting, then the
	// departments.
	PersonParts = opts(personPartSpecs...)

	// Weekdays as a condition names them, Sunday first as time.Weekday counts.
	Weekdays = []string{"sun", "mon", "tue", "wed", "thu", "fri", "sat"}
	// Placements are where a navigation entry can sit.
	Placements = []string{"primary", "more", "end", "hidden"}
)
View Source
var ColorTokenNames = []string{
	"accent", "accentFg", "accentHover", "accentLine", "accentSoft", "accentText", "bg", "bg2", "bg3", "bg4",
	"border", "borderStrong", "brandAccent", "controlLine", "danger", "dangerSoft", "fg", "fg2", "fg3", "focus",
	"hover", "ok", "okSoft", "onImage", "overlay", "pressed", "scrim", "warn", "warnSoft",
}

ColorTokenNames are the colour tokens of every theme (the names in themes/*/theme.json "colors"); a test holds them to internal/themes.

View Source
var ErrNotFound = errors.New("sdui: not found")

ErrNotFound is what a Resolver answers when the page's subject (the library, the title) isn't there or isn't this profile's to see, and what Render answers when a page can't be shown because of it.

View Source
var ErrTooLarge = errors.New("sdui: document exceeds 2 MiB")

ErrTooLarge is returned by Unmarshal when the input exceeds MaxDocumentBytes.

View Source
var ErrVersion = errors.New("sdui: unsupported schema version")

ErrVersion is returned (wrapped) by Unmarshal when the document's version is not SchemaVersion.

View Source
var Experiences = loadExperiences()

Experiences are the looks, in the order they are offered: experiences/*.json.

View Source
var Glyphs = []string{"a", "b", "x", "y"}

Glyphs are the keys an ItemAction may carry.

View Source
var Icons = []string{
	"home", "library", "movie", "show", "tv", "live", "guide", "record", "music", "album", "artist", "mic", "radio",
	"podcast", "book", "audiobook", "comic", "photo", "video", "disc", "game", "collection", "list", "folder",
	"search", "settings", "user", "users", "kids", "star", "heart", "clock", "history", "calendar", "sparkles",
	"fire", "shuffle", "play", "download", "share", "globe", "info", "warning", "check", "plus", "grid", "filter",
	"sort", "plug", "chart", "devices", "more",
}

Icons is the fixed icon set: a name every renderer has a glyph for.

View Source
var ItemKinds = []string{"movie", "episode", "show", "season", "video", "disc", "album", "artist", "track", "book", "audiobook", "podcast", "game", "photo", "channel", "recording", "collection", "library", "genre", "view", "person"}

ItemKinds are the kinds of item a data source may give.

View Source
var MapFields = []string{"title", "subtitle", "overview", "tagline", "year", "studio", "contentRating", "artist", "showTitle", "count", "number", "runtime", "genres"}

MapFields are the item fields a source's "map" may put into a card's title, subtitle or synopsis.

View Source
var MapProps = []string{"title", "subtitle", "synopsis"}

MapProps are the card props a source's "map" may set.

View Source
var ModulePageKinds = []string{"custom", "library", "detail", "livetv", "music", "photos", "books", "games"}

ModulePageKinds are the kinds of page a module may add. Home, search, the libraries and collections pages stay the server's; a module adds to Home with an insert.

NavStyles are every way an app draws its menu.

View Source
var Regions = []Region{
	{ID: "brand", Label: "Server name", Positions: []string{"start", "center", "top"}},
	{ID: "nav", Label: "Menu", Positions: []string{"start", "end", "top", "bottom"}, Locked: true},
	{ID: "search", Label: "Search", Positions: []string{"nav", "top", "floating"}},
	{ID: "profile", Label: "You", Positions: []string{"nav", "top"}, Locked: true},
	{ID: "clock", Label: "Clock", Positions: []string{"top", "dock"}},
	{ID: "dock", Label: "Dock", Positions: []string{"top", "bottom", "side"}},
	{ID: "legend", Label: "Key legend"},
	{ID: "hero", Label: "Spotlight", Styles: []string{"billboard", "banner", "carousel", "row"}},

	{ID: "statusBar", Label: "Status bar", Positions: []string{"top"}, Off: true},
	{ID: "systemDock", Label: "System dock", Positions: []string{"bottom", "side"}, Off: true},
}

Regions are the regions of the shell, in the order an editor lists them.

SettingKinds are the kinds of setting row.

View Source
var SettingsSlots = map[string]bool{"you.games": false, "people.profile": true}

SettingsSlots are the places a module's settings page may declare, and whether each is for administrators only.

View Source
var StatusKinds = []string{"profile", "server", "text"}

Status item kinds: "profile" (the profile's name, with Text as the line under it), "server" (the server's name, drawn from the brand) and "text" (Text alone).

Functions

func AsError

func AsError(issues []Issue) error

AsError wraps the errors among issues, nil when there are none.

func Breakpoint

func Breakpoint(width int) string

Breakpoint names the window class for a width in points.

func Canonical

func Canonical(doc Document) ([]byte, error)

Canonical returns the canonical JSON encoding of doc: object keys sorted, no insignificant whitespace, Meta.GeneratedAt and Meta.ETag omitted. Two documents with equal Canonical bytes are the same screen.

func CardSubtitle

func CardSubtitle(style string, it *Item) string

func CardTitle

func CardTitle(style string, it *Item) string

CardTitle and CardSubtitle are what a card of a style shows for an item before any "map": the binding rules, one place.

  • episode: "<episode>. <title>", and the running time under it;
  • progress: an episode shows its show's name with "S<s> E<e> · <title>" under it; anything else its own title and subtitle;
  • every other style: the item's title and subtitle.

func CatalogueMarkdown

func CatalogueMarkdown() string

CatalogueMarkdown writes the reference part of docs/SDUI.md from the catalogue: every component, card style, data source, condition, page kind, route and device profile. A test keeps the document equal to this, so the reference can't say something the code doesn't.

func CheckSetting

func CheckSetting(r *SettingRow, val any) error

CheckSetting checks one value for a setting row.

func ChooseExperience

func ChooseExperience(required, personal, server string, allowed []string, formFactor string) string

ChooseExperience picks the experience for a request: what is required of the profile, then the profile's choice for the device, then the administrator's for the form factor, then the default; a choice the administrator doesn't allow, or that isn't a layout, is passed over.

func DefaultExperience

func DefaultExperience(formFactor string) string

DefaultExperience is the experience a form factor has when nobody chose one: Lumen.

func ETag

func ETag(doc Document) string

ETag returns a weak entity tag for doc derived from Canonical: W/"sha256-<first 32 hex digits>". It is stable across renders that produce the same screen.

func Evaluate

func Evaluate(c *Condition, ctx *RenderContext) bool

Evaluate reports whether c holds for ctx. A nil or zero condition holds. Every set field must hold; All, Any and Not combine nested conditions. {"not": {}} never holds.

func ExperienceIDs

func ExperienceIDs() []string

ExperienceIDs are the experiences' IDs.

func Focusable

func Focusable(n *Node, inHero bool) bool

Focusable reports whether a person can act on a rendered node, so that it takes a place in the focus order: a card, a tab, a track, a search box, a filter bar, a hero with something in it, a title header with buttons, and anything else that has an action. A Card inside a Hero doesn't: the Hero is one stop and moves between its own titles.

func FormatRuntime

func FormatRuntime(sec float64) string

FormatRuntime writes a length in seconds the way cards and facts show it: "45 sec", "42 min", "2 hr", "1 hr 58 min". Minutes are rounded to the nearest. Zero and negative lengths are "".

func HasErrors

func HasErrors(issues []Issue) bool

HasErrors reports whether any issue is an error.

func JSONSchema

func JSONSchema() []byte

JSONSchema returns docs/sdui.schema.json: a JSON Schema (2020-12) for everything the SDUI routes send and accept, written from the Go types so it can't drift from them, with the catalogue's vocabularies beside it. A test keeps the file in the repository equal to this.

The schema is deliberately open: no object forbids extra properties and a node's type is any string. That is the forward-compatibility rule in machine-readable form: a client built today must accept a page from a newer server.

func LibraryIcon

func LibraryIcon(kind string) string

LibraryIcon is the icon of a kind of library.

func Marshal

func Marshal(doc Document) ([]byte, error)

Marshal encodes doc as compact JSON. It does not validate.

func MarshalIndent

func MarshalIndent(doc Document) ([]byte, error)

MarshalIndent encodes doc as indented JSON for humans and golden files.

func ModuleJSONSchema

func ModuleJSONSchema() []byte

ModuleJSONSchema returns docs/sdui-module.schema.json: a JSON Schema (2020-12) of a module's sdui.json (docs/SDUI-MODULES.md), written from ModuleUI. Unlike the rendered documents, a module's file is read strictly: every object here is closed, so an editor flags a misspelt property as the server would refuse it.

func ModuleOf

func ModuleOf(name string) string

ModuleOf is the module a namespaced name belongs to: "wittyplay" for wittyplay.ConsoleShelf or wittyplay.recent, "" for a name of the catalogue.

func Remaining

func Remaining(it *Item) string

Remaining is the "42 min left" of a progress card, "" when it isn't known.

func Truncate

func Truncate(s string, limit int) string

Truncate cuts s to at most limit characters: at the last space within 20 characters of the limit when there is one, trailing spaces and punctuation removed, an ellipsis added. Text within the limit is returned unchanged. Every renderer that shortens text itself (a lazily loaded page it formats) uses the same rule, which the conformance kit checks.

func ValidID

func ValidID(s string) bool

ValidID reports whether s can be a page's or section's ID.

func ValidModuleID

func ValidModuleID(s string) bool

ValidModuleID reports whether s can be a module's ID.

func ValidRoute

func ValidRoute(s string) bool

ValidRoute reports whether s is a place in the app: a path on this server beginning with exactly one slash, with nothing that could lead elsewhere.

func ValidURL

func ValidURL(s string) bool

ValidURL reports whether s is an http or https address.

Types

type Action

type Action struct {
	// Type is navigate, play, native, external, back or command.
	Type string `json:"type"`
	// To is a route in the app (navigate) or a native screen (native).
	To string `json:"to,omitempty"`
	// Item is the ID of the title to play (play) or act on (command).
	Item string `json:"item,omitempty"`
	// URL is a web address (external).
	URL string `json:"url,omitempty"`
	// Op is the command: see Commands.
	Op string `json:"op,omitempty"`
	// Params are extra, per type: {"resume": true} for play.
	Params map[string]any `json:"params,omitempty"`
	// As says how a navigate action's page is shown: "layer" over the current screen (a sheet, a
	// quick menu) instead of replacing it, which a client that has no layers does as a page.
	// Left out: the page replaces the screen.
	As string `json:"as,omitempty"`
	// Confirm is a question the client asks before it carries a command out ("Delete this memory?"),
	// with the command's own label as the confirming button and Cancel beside it. Left out: no question.
	Confirm string `json:"confirm,omitempty"`
}

Action is what a client does when a node is activated.

type Budget

type Budget struct {
	// MaxSections is the most sections a page has; the rest are left out and
	// Layout.Truncated set.
	MaxSections int `json:"maxSections"`
	// EagerSections is how many data sections arrive with their items. The
	// ones after are "deferred": the client asks for their items as they
	// near the screen.
	EagerSections int `json:"eagerSections"`
	// ShelfItems, GridItems and ListItems are the most items a section's
	// first page holds; PageSize the size of each page after.
	ShelfItems int `json:"shelfItems"`
	GridItems  int `json:"gridItems"`
	ListItems  int `json:"listItems"`
	PageSize   int `json:"pageSize"`
	// HeroItems is the most titles a Hero rotates through.
	HeroItems int `json:"heroItems"`
	// Repeats is the most copies a repeated section makes.
	Repeats int `json:"repeats"`
}

Budget is how much of a page one device is sent at once.

type CardMetrics

type CardMetrics struct {
	Shape  string         `json:"shape"`
	Aspect string         `json:"aspect,omitempty"`
	Width  map[string]int `json:"width"`
	// Columns is how many of the medium card a Grid has on a device whose
	// grids don't follow the window (a television); 0 elsewhere.
	Columns int `json:"columns,omitempty"`
}

CardMetrics is how big one card style is on a device, in points. Width is by card size (s, m, l); the height of the picture follows from Aspect.

type CardStyleSpec

type CardStyleSpec struct {
	Style       string `json:"style"`
	Label       string `json:"label"`
	Description string `json:"description"`
	// Shape is the basic shape every renderer knows: poster, landscape,
	// square, circle or chip. A renderer that doesn't know Style draws Shape.
	Shape  string `json:"shape"`
	Aspect string `json:"aspect"`
	// Image is the order in which an item's pictures are tried.
	Image []string `json:"image,omitempty"`
	// Shows lists the card props the style displays, in reading order; it is
	// also the order of the accessibility label.
	Shows []string `json:"shows"`
	// TitleLines and SubtitleLines are the most lines each may take before
	// it is cut with an ellipsis.
	TitleLines    int `json:"titleLines"`
	SubtitleLines int `json:"subtitleLines"`
	// Kinds are the item kinds the style is the natural one for.
	Kinds []string `json:"kinds,omitempty"`
	// BadgeTones say how a badge's text is drawn on the style, by the badge's text: for a person
	// card a presence dot on the avatar (Playing and Online ok, Away warn, Offline muted). A
	// renderer draws what the table says, the same on every app.
	BadgeTones map[string]string `json:"badgeTones,omitempty"`
	// Tokens are the theme tokens it is drawn with (tokens.go).
	Tokens *TokenRoles `json:"tokens,omitempty"`
}

CardStyleSpec describes one way a Card is drawn.

func CardStyle

func CardStyle(s string) (*CardStyleSpec, bool)

CardStyle returns the spec of a card style.

type Catalogue

type Catalogue struct {
	SchemaVersion int                `json:"schemaVersion"`
	Revision      int                `json:"revision"`
	Components    []ComponentSpec    `json:"components"`
	CardStyles    []CardStyleSpec    `json:"cardStyles"`
	Sources       []SourceSpec       `json:"sources"`
	Conditions    []ConditionSpec    `json:"conditions"`
	PageKinds     []PageKindSpec     `json:"pageKinds"`
	Routes        []RouteSpec        `json:"routes"`
	Commands      []CommandSpec      `json:"commands"`
	NativeScreens []NativeScreenSpec `json:"nativeScreens"`
	NativeViews   []EnumOption       `json:"nativeViews"`
	// TVThemes are the WittyTV looks as data, Remote the WittyRemote's keys and which stay
	// dimmed for each kind of disc, and Music the mini player, visualizer and karaoke controls
	// (data/*.json): every client draws them from these tables.
	TVThemes      json.RawMessage `json:"tvThemes"`
	Remote        json.RawMessage `json:"remote"`
	Music         json.RawMessage `json:"music"`
	Icons         []string        `json:"icons"`
	Placeholders  []EnumOption    `json:"placeholders"`
	Repeats       []EnumOption    `json:"repeats"`
	FormFactors   []string        `json:"formFactors"`
	Platforms     []string        `json:"platforms"`
	ProfileKinds  []string        `json:"profileKinds"`
	LibraryKinds  []string        `json:"libraryKinds"`
	MediaKinds    []string        `json:"mediaKinds"`
	PersonalKinds []EnumOption    `json:"personalKinds"`
	Placements    []EnumOption    `json:"placements"`
	Spacing       []string        `json:"spacing"`
	Limits        map[string]int  `json:"limits"`
	// Profiles are the device profiles, so an editor can preview a page's
	// budgets and a renderer can lay out a lazily loaded page of cards.
	Profiles map[string]*Layout `json:"profiles"`
	// Theme is the vocabulary of the components' tokens (tokens.go).
	Theme *ThemeRoles `json:"theme,omitempty"`
	// Experiences are the looks: the menu's style on each form factor and what each
	// changes about pages.
	Experiences []Experience `json:"experiences"`
	// NavStyles are the ways an app draws its menu.
	NavStyles []string `json:"navStyles"`
}

Catalogue is everything an editor or a renderer needs to know about the schema, as data: GET /api/v1/sdui/catalog answers it.

func Catalog

func Catalog() *Catalogue

Catalog returns the catalogue. It is shared: don't change it.

func CatalogWith

func CatalogWith(s *ModuleSet) *Catalogue

CatalogWith is the catalogue with the modules' components, sources and views added, as an editor needs it. With an empty set it is Catalog() itself.

type CommandParam

type CommandParam struct {
	Name     string `json:"name"`
	Type     string `json:"type"` // string, int, bool, ints (a list of numbers) or object (a JSON object)
	Label    string `json:"label"`
	Required bool   `json:"required,omitempty"`
}

CommandParam is one value a command takes besides the action's item.

type CommandSpec

type CommandSpec struct {
	Op          string `json:"op"`
	Label       string `json:"label"`
	Description string `json:"description"`
	// Method and Path are the request that carries it out; {item} is the
	// action's item, as it is ("5", "show-5"): URL-escaped in Path, and in Body
	// always inside a JSON string, escaped as one, so the body is JSON for any ID.
	Method string `json:"method"`
	Path   string `json:"path"`
	Body   string `json:"body,omitempty"`
	// Params are the values besides {item} the command needs, from the action's params, by
	// name. A client puts each one in place of {name} the way {item} goes: URL-escaped in
	// Path; in Body inside a JSON string, escaped as one, except that for an int parameter the
	// string and its quotes are replaced by the number. A parameter that wasn't given is an
	// empty string (an int one is required, so it is always given). Body stays JSON whatever
	// the values.
	Params []CommandParam `json:"params,omitempty"`
	// Module is the module whose pages and items may carry this command besides the server's own
	// pages; empty: only the server's pages. A module's item may carry a command only when it is the
	// module's (Module, or an op beginning with its ID and a dot), so a module can't ask a client to
	// sign a device out. Disc settings, for one, are a module page whose rows run disc.choose.
	Module string `json:"module,omitempty"`
}

CommandSpec describes one thing a "command" action can ask for.

type ComponentSpec

type ComponentSpec struct {
	Type        string `json:"type"`
	Label       string `json:"label"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
	// Category groups the editor's palette: media, detail, navigation, text,
	// layout, structure.
	Category string `json:"category"`
	// Since is the catalogue revision the component appeared in.
	Since int `json:"since"`
	// Authored is false for components only the server makes (Page, Card,
	// Track): they aren't in an editor's palette.
	Authored bool `json:"authored"`
	// Data is "none", "optional" or "required": whether the component takes
	// a data source. Accepts lists the kinds of source it takes; empty: any.
	Data    string   `json:"data"`
	Accepts []string `json:"accepts,omitempty"`
	// Container components hold other sections; Children lists which types,
	// empty meaning any authored component.
	Container bool     `json:"container"`
	Children  []string `json:"children,omitempty"`
	// Focus is "none", "item" (the node takes focus itself), "group" (its
	// children take focus and it is their group) or "stop" (it is one stop in
	// the page's focus order and moves focus among its own parts).
	Focus string `json:"focus"`
	// FormFactors lists where the component is shown; empty means everywhere.
	FormFactors []string   `json:"formFactors,omitempty"`
	Props       []PropSpec `json:"props,omitempty"`
	// Renders says in words how each form factor draws it.
	Renders map[string]string `json:"renders,omitempty"`
	// States says what is drawn while loading, when empty and on an error.
	States map[string]string `json:"states,omitempty"`
	// A11y says how the accessibility role and label are derived.
	A11y string `json:"a11y,omitempty"`
	// Example is a section using the component.
	Example json.RawMessage `json:"example,omitempty"`
	// Module is the module a component comes from (docs/SDUI-MODULES.md):
	// the server expands it into the catalogue component Expands, so no
	// client is ever sent it. PageKinds are the kinds of page it may be used
	// on; empty: any.
	Module    string   `json:"module,omitempty"`
	Expands   string   `json:"expands,omitempty"`
	PageKinds []string `json:"pageKinds,omitempty"`
	// Tokens are the theme tokens it is drawn with (tokens.go).
	Tokens *TokenRoles `json:"tokens,omitempty"`
}

ComponentSpec describes one component.

func Component

func Component(t string) (*ComponentSpec, bool)

Component returns the spec of a component type.

type Condition

type Condition struct {
	All []Condition `json:"all,omitempty"`
	Any []Condition `json:"any,omitempty"`
	Not *Condition  `json:"not,omitempty"`
	// FormFactor: the device is one of these (tv, phone, tablet, desktop, web).
	FormFactor []string `json:"formFactor,omitempty"`
	// Platform: the app is one of these (web, tvos, ios, android, androidtv, desktop).
	Platform []string `json:"platform,omitempty"`
	// ProfileKind: the profile is one of these (adult, kids, guest).
	ProfileKind []string `json:"profileKind,omitempty"`
	// Admin: the profile is (true) or isn't (false) an administrator.
	Admin *bool `json:"admin,omitempty"`
	// Feature: the server has this feature (/capabilities features).
	Feature string `json:"feature,omitempty"`
	// Module: this module is installed and on.
	Module string `json:"module,omitempty"`
	// Can: the profile may use this (games, recordings, downloads, sharing,
	// comments, syncplay, remoteControl, remote, liveTv, editLayout): its
	// parental feature switches.
	Can string `json:"can,omitempty"`
	// HasLibrary: the profile can open at least one library of this kind.
	HasLibrary string `json:"hasLibrary,omitempty"`
	// LibraryKind: the page's own library is of this kind (library pages).
	LibraryKind string `json:"libraryKind,omitempty"`
	// Capability: the client said it has this (capabilities=hdr,touch).
	Capability string `json:"capability,omitempty"`
	// Flag: something the server knows is so: setupIncomplete, scanning,
	// librariesEmpty, hasQuery, screenTimeUp.
	Flag string `json:"flag,omitempty"`
	// MinWidth and MaxWidth bound the window's width in points, inclusive.
	// They pass when the client didn't say how wide it is.
	MinWidth int `json:"minWidth,omitempty"`
	MaxWidth int `json:"maxWidth,omitempty"`
	// TimeFrom and TimeTo bound the time of day on the server, "HH:MM",
	// from inclusive and to exclusive; a range may pass midnight.
	TimeFrom string `json:"timeFrom,omitempty"`
	TimeTo   string `json:"timeTo,omitempty"`
	// Weekday: today is one of these (mon, tue, wed, thu, fri, sat, sun).
	Weekday []string `json:"weekday,omitempty"`
	// Locale: the client's language is this or a kind of it (en matches en-GB).
	Locale string `json:"locale,omitempty"`
}

Condition says when a section, variant or navigation entry is shown. Every field that is set must hold; All, Any and Not combine conditions. The zero Condition always holds.

type ConditionSpec

type ConditionSpec struct {
	Field string `json:"field"`
	PropSpec
}

ConditionSpec describes one field of Condition.

type Control

type Control struct {
	Type string `json:"type"`
	// Name is the control's name inside a Form: the key its value goes under in the Form's command.
	Name string `json:"name,omitempty"`
	// Value is a bool (switch), a string (select, field) or a number (slider).
	Value any `json:"value,omitempty"`
	// Options are a select's choices.
	Options []EnumOption `json:"options,omitempty"`
	// Min, Max, Step and Unit are a slider's; Unit is a suffix ("%", " min").
	Min  float64 `json:"min,omitempty"`
	Max  float64 `json:"max,omitempty"`
	Step float64 `json:"step,omitempty"`
	Unit string  `json:"unit,omitempty"`
	// Placeholder, MaxLength, Multiline and Input (text, number, url, search) are a field's.
	Placeholder string `json:"placeholder,omitempty"`
	MaxLength   int    `json:"maxLength,omitempty"`
	Multiline   bool   `json:"multiline,omitempty"`
	Input       string `json:"input,omitempty"`
	// Disabled draws it dimmed and leaves it out of focus; Why says why, in a line under it.
	Disabled bool   `json:"disabled,omitempty"`
	Why      string `json:"why,omitempty"`
}

Control is a control drawn in a list row, so a page can hold settings-like rows: Settings itself stays hand-built, but a page the server serves (the profile's games privacy, a smart playlist's rules) is made of these. A switch says its state in Value (a bool) and its row's Action is what flipping it does: the server has already put the new value in the action's params, so a client never works out the opposite. A select, field or slider carries the Action to run with the chosen value added to its params as "value"; inside a Form the control has no Action of its own and the Form's is run with every named control's value (see the Form component).

type DemoResolver

type DemoResolver struct{}

DemoResolver answers every source with a few generated sample items and no pictures, so a page can be drawn before any library exists: the first-run chooser draws every experience with the client's own renderer from it (GET /sdui/preview). It touches no library and holds no real title.

func (DemoResolver) Each

func (DemoResolver) Each(over string, kinds []string, limit int) ([]Each, error)

Each lists four sample libraries.

func (DemoResolver) Facets

func (DemoResolver) Facets(string, []string) ([]Facet, error)

func (DemoResolver) Items

Items makes up to req.Limit samples of the kind the source yields.

func (DemoResolver) Seasons

func (DemoResolver) Seasons(string) ([]Item, error)

Seasons and Facets have nothing.

func (DemoResolver) Subject

func (DemoResolver) Subject() (*Item, error)

Subject has nothing: there is no detail page in a preview.

type DockEntry

type DockEntry struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Icon  string `json:"icon"`
	// Route is the place it opens; As "layer" shows that page over the screen.
	Route string `json:"route"`
	As    string `json:"as,omitempty"`
	// Current marks the button a page belongs under when no button opens it (a store under
	// Settings): it is labelled as the current one, as the button whose route is the page is.
	Current bool `json:"current,omitempty"`
}

DockEntry is one destination of the system dock: a round button, the current one labelled.

type DockMetrics

type DockMetrics struct {
	Placement string `json:"placement"`
	Height    int    `json:"height"`
	// HintSize is the key legend's text size in points.
	HintSize int `json:"hintSize"`
}

DockMetrics place the Dock: "bottom" is a bar Height points tall across the bottom of the screen, outside the page's scroll; "sheet" is no bar, the controls opening from an Options button as a sheet.

type Document

type Document struct {
	// Version is SchemaVersion.
	Version int `json:"version"`
	// Catalog is the catalogue revision the tree was written for: the
	// client's own when it is older than the server's.
	Catalog int `json:"catalog"`
	// Page says which page this is.
	Page PageInfo `json:"page"`
	// Layout is the device profile the page was fitted to.
	Layout *Layout `json:"layout,omitempty"`
	// Theme is the page's theme scope and the colours it overrides.
	Theme *ThemeScope `json:"theme,omitempty"`
	// Root is the tree. Its type is Page.
	Root Node `json:"root"`
	// Personal says what the profile may change about this page and what it
	// has changed, so an app can offer "Customise" without knowing the page.
	Personal *PersonalInfo `json:"personal,omitempty"`
	// Regions is what the page puts into the shell's regions (Page.Regions), with the regions it
	// turns on in Shell.
	Regions *PageRegions `json:"regions,omitempty"`
	// ScreenTime is present when the profile's screen time is over: nothing
	// in the page offers to play, and this says why and until when.
	ScreenTime *ScreenTime `json:"screenTime,omitempty"`
	Meta       Meta        `json:"meta,omitzero"`
}

Document is one page rendered for one profile on one device.

func Apply

func Apply(doc Document, patches []Patch) (Document, error)

Apply returns a copy of doc with patches applied in order. It fails on a malformed path, an unknown node ID, an out-of-range index or an operation missing its payload; doc is never modified.

func Render

func Render(page Page, ctx *RenderContext) (Document, error)

Render draws page for ctx. It chooses the variant, drops the sections whose conditions don't hold, makes the copies of repeated sections, applies the profile's own arrangement, asks the Resolver for each section's items within the device's budget, and stamps focus and the ETag.

The page should have passed ValidatePage; Render never panics on one that hasn't, but leaves out what it can't make sense of.

func Unmarshal

func Unmarshal(data []byte) (Document, error)

Unmarshal decodes a document strictly: unknown fields are rejected, input larger than MaxDocumentBytes is rejected with ErrTooLarge, trailing data is rejected, and the version must equal SchemaVersion (ErrVersion). It does not run Validate; callers that accept documents from users should.

type Each

type Each struct {
	// Key replaces $each in the section's source and ends the copy's ID.
	Key string
	// Label replaces {each} in its title.
	Label string
	// Kind is the library's kind, for Repeat.Kinds.
	Kind string
	// ID ends the copy's ID in place of Key, when Key is text (a series' name) that two
	// copies could share once cut to what an ID may hold. "" uses Key.
	ID string
}

Each is one thing a section is repeated over.

type Effects

type Effects struct {
	Glass   string `json:"glass"`
	Gloss   string `json:"gloss"`
	Glow    string `json:"glow"`
	Texture string `json:"texture"`
	Bevel   string `json:"bevel"`
}

Effects are the finish an experience puts on surfaces and controls: each none, subtle or full. Renderers draw the recipes in the theme's finish tokens at that level, and lower a level on modest hardware and with reduced transparency.

type EnumOption

type EnumOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

EnumOption is one choice of a property or facet.

func ExperienceOptions

func ExperienceOptions(p *ExperiencePolicy) []EnumOption

ExperienceOptions are the layouts a profile may choose from under a policy, as choices.

type Experience

type Experience struct {
	ID          string  `json:"id"`
	Order       int     `json:"order"`
	Name        string  `json:"name"`
	Tagline     string  `json:"tagline"`
	Description string  `json:"description"`
	Icon        string  `json:"icon"`
	Preview     Preview `json:"preview"`
	// Nav is how the menu is drawn on each form factor; NavExpand is how a rail opens:
	// "drawer" (a library drawer beside it), "" (a plain menu).
	Nav       map[string]string `json:"nav"`
	NavExpand string            `json:"navExpand,omitempty"`
	// Overlay: the menu is drawn over the top of the page, transparent until the
	// page scrolls, where it is drawn across the top.
	Overlay bool `json:"overlay,omitempty"`
	// Pages are the changes the server makes to every page for this experience.
	Pages PageStyle `json:"pages"`
	// Theme is the theme it wears unless one is required or chosen; TVTheme the WittyTV
	// look it suggests (themes/tokens.json tvThemes).
	Theme   string          `json:"theme"`
	TVTheme string          `json:"tvTheme"`
	Effects Effects         `json:"effects"`
	Shape   ExperienceShape `json:"shape"`
	// Type is the type set: system, humanist, rounded, mono or serif.
	Type    string           `json:"type"`
	Density string           `json:"density"`
	Motion  ExperienceMotion `json:"motion"`
	Home    ExperienceHome   `json:"home"`
	// Placements are the shell's regions as the experience has them; the administrator's
	// and the profile's placements are laid over them (Placements).
	Placements map[string]Placement `json:"placements,omitempty"`
	// Wire is the layout as a picker draws it on each form factor (wire.go): worked out from the
	// rest of the experience, never written in its file.
	Wire map[string]Wire `json:"wire"`
}

Experience describes one look.

func ExperienceByID

func ExperienceByID(id string) *Experience

ExperienceByID is an experience, nil for an ID that isn't one.

type ExperienceChoice

type ExperienceChoice struct {
	Current string `json:"current"`
	// Chosen is the profile's own choice for the device, "" when it follows the server.
	Chosen  string       `json:"chosen,omitempty"`
	Options []EnumOption `json:"options"`
	URL     string       `json:"url"`
	// Required says an administrator requires the experience: who, when and for whom. The
	// person can't choose another; Options is then empty.
	Required *RequiredPart `json:"required,omitempty"`
}

ExperienceChoice is what a profile may choose for its layout on a device.

type ExperienceHome

type ExperienceHome struct {
	Hero string `json:"hero"`
	Rows string `json:"rows"`
}

ExperienceHome is what an experience's Home starts with: the spotlight's style and the arrangement of rows.

type ExperienceMotion

type ExperienceMotion struct {
	Focus     string `json:"focus"`
	Screen    string `json:"screen"`
	Overshoot bool   `json:"overshoot,omitempty"`
}

ExperienceMotion is how focus and screens move: focus ring, ring-lift, fill or glow; screens fade, slide or cut. Overshoot adds a small settle (never on modest hardware).

type ExperiencePolicy

type ExperiencePolicy struct {
	// Default is the layout each form factor has unless a profile chose another; a form
	// factor left out has DefaultExperience.
	Default map[string]string `json:"default,omitempty"`
	// Placements are the administrator's changes to an experience's regions, for everyone:
	// by experience, then region.
	Placements map[string]RegionPlacements `json:"placements,omitempty"`
	// Allowed are the layouts profiles may choose; empty: every one.
	Allowed []string `json:"allowed,omitempty"`
	// Required is a look (an experience, a theme or both) the administrator requires of
	// everyone, of kids profiles or of named profiles (look.go).
	Required *RequiredPolicy `json:"required,omitempty"`
	// ProfileThemes lets profiles import themes of their own.
	ProfileThemes bool `json:"profileThemes,omitempty"`
}

ExperiencePolicy is the administrator's choice of layouts for the server: the layout each form factor starts with, and the layouts profiles may choose from.

type ExperienceShape

type ExperienceShape struct {
	// RadiusMultiple multiplies the theme's radius.
	RadiusMultiple float64 `json:"radiusMultiple"`
	// CardSet names the card styles it prefers: poster, plate, landscape, tile, block, list,
	// row or carousel.
	CardSet string `json:"cardSet"`
}

ExperienceShape is the corner and card set an experience wears.

type Facet

type Facet struct {
	ID      string       `json:"id"`
	Label   string       `json:"label"`
	Options []EnumOption `json:"options"`
}

Facet is one thing a FilterBar can filter or sort by, with its choices.

type Focus

type Focus struct {
	// Order is the node's place in reading order, from 1, without gaps.
	Order int `json:"order"`
	// Group is the ID of the row, grid or bar the node is in. A client treats
	// a group as one focus section and remembers where focus was in it.
	Group string `json:"group,omitempty"`
	// Default marks the one node focus starts on.
	Default bool `json:"default,omitempty"`
}

Focus places a node in the focus order of a device driven by a remote or a keyboard. Render stamps it on every node a person can act on.

type ImageRef

type ImageRef struct {
	URL    string `json:"url"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
	Aspect string `json:"aspect"`
}

ImageRef is a picture and the size to show it at, in pixels.

type Insets

type Insets struct {
	Top    int `json:"top"`
	Right  int `json:"right"`
	Bottom int `json:"bottom"`
	Left   int `json:"left"`
}

Insets are distances from each edge of the screen, in points.

type Issue

type Issue struct {
	// Path locates it: /sections/2/props/cardStyle.
	Path string `json:"path"`
	// Severity is "error" (it can't be saved) or "warning" (it can, but
	// probably isn't what was meant).
	Severity string `json:"severity"`
	Message  string `json:"message"`
	// Fix suggests what to do about it.
	Fix string `json:"fix,omitempty"`
}

Issue is one thing wrong with something authored: where, what, and how to put it right, in words an administrator can act on.

func ValidateExperiencePolicy

func ValidateExperiencePolicy(p *ExperiencePolicy) []Issue

ValidateExperiencePolicy checks the administrator's layouts.

func ValidateModuleUI

func ValidateModuleUI(ui *ModuleUI, module string, checks ModuleChecks) []Issue

ValidateModuleUI checks one module's SDUI file on its own: the names are the module's, everything is from the catalogue or the module itself, and every page, insert, preset and component validates. A module may use only its own components and sources, never another module's, so it works wherever it is installed.

func ValidateNavigation

func ValidateNavigation(n *Navigation, pageExists func(id string) bool) []Issue

ValidateNavigation checks the navigation. pageExists says whether a page ID is one the configuration or the built-in pages have.

func ValidatePage

func ValidatePage(p *Page) []Issue

ValidatePage checks a page against the catalogue and answers everything wrong with it: errors, which keep it from being saved, and warnings.

func ValidatePageWith

func ValidatePageWith(p *Page, ui *ModuleSet) []Issue

ValidatePageWith checks a page that may use the components, sources and views of the modules in ui. A section of a module that isn't in use is a warning, not an error: it is left out until the module is back.

func ValidatePersonal

func ValidatePersonal(p *Personal) []Issue

ValidatePersonal checks what a profile sent about its own arrangement.

func ValidateRequired

func ValidateRequired(p *RequiredPolicy) []Issue

ValidateRequired checks the requirements' experiences.

func (Issue) String

func (i Issue) String() string

type Item

type Item struct {
	// ID is unique among the items of one source, and stable.
	ID string `json:"id"`
	// Kind is movie, episode, show, season, video, disc, album, artist, track,
	// book, audiobook, podcast, game, photo, channel, recording, collection,
	// library, genre, view or person.
	Kind     string `json:"kind"`
	Title    string `json:"title"`
	Subtitle string `json:"subtitle,omitempty"`
	Overview string `json:"overview,omitempty"`
	Tagline  string `json:"tagline,omitempty"`
	Year     int    `json:"year,omitempty"`
	// Rating is the community score out of 10; ContentRating the certificate.
	Rating        float64  `json:"rating,omitempty"`
	ContentRating string   `json:"contentRating,omitempty"`
	RuntimeSec    float64  `json:"runtimeSec,omitempty"`
	Genres        []string `json:"genres,omitempty"`
	Studio        string   `json:"studio,omitempty"`
	// Progress is how far through it the profile is, 0 to 1; Watched that it
	// finished; Unwatched how many episodes of a show are left.
	Progress  float64 `json:"progress,omitempty"`
	Watched   bool    `json:"watched,omitempty"`
	Unwatched int     `json:"unwatched,omitempty"`
	// InWatchLater: the title is on the profile's Watch later list.
	InWatchLater bool `json:"inWatchLater,omitempty"`
	// ResumeSec is where Play picks up, 0 to start over.
	ResumeSec float64 `json:"resumeSec,omitempty"`
	// Season and Episode number an episode; ShowTitle names its show.
	Season    int    `json:"season,omitempty"`
	Episode   int    `json:"episode,omitempty"`
	ShowTitle string `json:"showTitle,omitempty"`
	ShowID    string `json:"showId,omitempty"`
	// Artist and Track are a song's; Count is how many things an album,
	// artist, library, collection or season holds.
	Artist string `json:"artist,omitempty"`
	Track  int    `json:"track,omitempty"`
	Count  int    `json:"count,omitempty"`
	// Channel and Programme open WittyTV's More info (GET /api/tv/{key}/programme) from a
	// recording: its channel's key and "<key>@<start>". Empty when the profile may not watch it.
	Channel   string `json:"channel,omitempty"`
	Programme string `json:"programme,omitempty"`
	// Number is a channel's number. Now and Next are what is on it.
	Number string     `json:"number,omitempty"`
	Now    *Programme `json:"now,omitempty"`
	Next   *Programme `json:"next,omitempty"`
	// Images are addresses on this server by kind: poster (2/3), backdrop
	// (16/9), square (1/1), logo. Render adds the width to ask for.
	Images map[string]string `json:"images,omitempty"`
	// Route is the item's place in the app; PlayID what to play, when it can
	// be played from a card.
	Route  string `json:"route,omitempty"`
	PlayID string `json:"playId,omitempty"`
	// Badges are short labels: 4K, HDR, NEW, LIVE.
	Badges []string `json:"badges,omitempty"`
	// Icon is one of Icons, for items without pictures (libraries, genres).
	Icon string `json:"icon,omitempty"`
	// Scope is the theme scope the item belongs to (wittytv for a channel).
	Scope string `json:"scope,omitempty"`
	// Can lists what DetailHeader may offer for the item: play, download,
	// share, watchLater, watched, playOn, watchParty.
	Can []string `json:"can,omitempty"`
	// NextID is the item Play should start for a show: its next episode.
	NextID string `json:"nextId,omitempty"`
	// Console is a game's console as people call it (SNES, Mega Drive): a games row can be narrowed by it.
	Console string `json:"console,omitempty"`
	// Titles are a game's other names, each only when known: in its own script (native), its
	// English release's (english) and the title as listed (romanized). A game card carries them
	// as its "titles" prop, so an app can show the one its profile prefers.
	Titles *Titles `json:"titles,omitempty"`
	// Group is the part of a title's credits a person card is in: cast, guests, or a crew
	// department (CreditGroups). The card's subtitle is the part played or the job.
	Group string `json:"group,omitempty"`
	// Born, Died and KnownFor are a person's, as their page's facts say them: "3 February
	// 1970, Lisbon", "2021", "Acting".
	Born     string `json:"born,omitempty"`
	Died     string `json:"died,omitempty"`
	KnownFor string `json:"knownFor,omitempty"`
	// Action is what activating the item's row does instead of opening Route or playing PlayID: a
	// command (sign a device out, add a title to a list). Trailing is the text at the row's end
	// ("2 hours ago", "22 GB"). Control draws a switch, a choice, a field or a slider in the row:
	// see Control. All three are drawn by List rows (docs/SDUI.md, "Forms and controls").
	Action   *Action  `json:"action,omitempty"`
	Trailing string   `json:"trailing,omitempty"`
	Control  *Control `json:"control,omitempty"`
	// Actions are the buttons a Shelf's detail panel shows for the item while it has focus (Resume,
	// Play online, Options), first the A action. An item with none has its route as its A action.
	Actions []ItemAction `json:"actions,omitempty"`
	// Link is what a QR code stands for: a route of the app (/games?join=CODE) or an https address. Only
	// the QR component reads it.
	Link string `json:"link,omitempty"`
}

Item is one thing a data source found, in the one shape every card style reads. A source fills what it knows; a card style shows what it has room for (see CardStyles).

type ItemAction

type ItemAction struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Glyph is the key the button is drawn with: a, b, x or y, the shared pad map (A selects, B goes
	// back, X and Y are the secondary and options keys).
	Glyph  string  `json:"glyph,omitempty"`
	Action *Action `json:"action"`
}

ItemAction is one button of an item's detail panel.

type Layout

type Layout struct {
	// FormFactor is tv, phone, tablet, desktop or web; Class tells devices of
	// one form factor apart ("hd" and "4k" for tv).
	FormFactor string `json:"formFactor"`
	Class      string `json:"class,omitempty"`
	// Canvas is the screen in points when the form factor fixes it (tv:
	// 1920×1080).
	Canvas Viewport `json:"canvas,omitzero"`
	Scale  int      `json:"scale"`
	// Breakpoint is compact (under 600 points wide), medium (under 840),
	// expanded (under 1200) or large, from the window's width when the
	// client sent it, else the form factor's usual.
	Breakpoint string `json:"breakpoint"`
	// SafeArea is the margin content keeps inside. Zero where the system
	// reports its own.
	SafeArea Insets `json:"safeArea"`
	// FocusEngine is true where focus is the only pointer (tv).
	FocusEngine bool `json:"focusEngine"`
	// Density is compact, comfortable or spacious.
	Density string `json:"density"`
	// Spacing is each spacing step in points; Text each text role's size.
	Spacing map[string]int `json:"spacing"`
	Text    map[string]int `json:"text"`
	// Cards is the size of each card style; Hero the size of a Hero.
	Cards map[string]CardMetrics `json:"cards"`
	Hero  Viewport               `json:"hero"`
	// Peek is how much of the next card (or slide) shows at the trailing edge of a row
	// or spotlight that scrolls, as a fraction of its width: 0 where the pointer has
	// arrows or the edge is already clear (revision 3).
	Peek float64 `json:"peek"`
	// Dock is where a Dock goes and how tall it is (revision 3).
	Dock DockMetrics `json:"dock"`
	// ImageWidths are the widths pictures are asked for at: a card asks for
	// the smallest that is at least its width times Scale.
	ImageWidths []int      `json:"imageWidths"`
	Budget      Budget     `json:"budget"`
	TextLimits  TextLimits `json:"textLimits"`
	// ExternalLinks says whether the device can open a web page.
	ExternalLinks bool `json:"externalLinks"`
	// ReducedMotion is true when the client said the person asked for it.
	ReducedMotion bool `json:"reducedMotion,omitempty"`
	// Truncated is set when sections were left out to fit MaxSections.
	Truncated bool `json:"truncated,omitempty"`
	// Shell is the experience the page was made for and how the app's frame is
	// drawn with it: see Experiences.
	Shell *Shell `json:"shell,omitempty"`
}

Layout is a device profile: what a page has to fit, and the numbers a renderer lays out with. Render fits a page to it and sends it along as Document.Layout.

Sizes are in points: what the platform calls points, dp or CSS pixels. Scale is how many picture pixels a point is, used only to choose pictures.

func ProfileFor

func ProfileFor(formFactor, class string) *Layout

ProfileFor is the device profile for a form factor and class. An unknown form factor gets the web profile; an unknown television class the HD one, the smaller of the two.

func (*Layout) BackdropWidth

func (l *Layout) BackdropWidth(points int) int

BackdropWidth is the picture width for a backdrop that spans a window this wide in points: at most twice the width, whatever the device's scale. A backdrop sits behind text, under a scrim, so a phone's third pixel per point is never worth its bytes.

func (*Layout) ContentWidth

func (l *Layout) ContentWidth() int

ContentWidth is the width a page's sections have to themselves, in points: the canvas (or the breakpoint's usual window when the client didn't say) less the side margins: the safe area on a television, the m spacing elsewhere.

func (*Layout) GridColumns

func (l *Layout) GridColumns(style, size string) int

GridColumns is how many columns a Grid of cards this wide has: the television's fixed count, or as many as fit the window, at least two (three for cards under 130 points). The rule a renderer applies when its window changes size:

columns = max(minimum, floor((content + gap) / (card + gap)))

where content is ContentWidth and gap the s plus the xs spacing on compact windows, the m spacing otherwise.

func (*Layout) ImageWidth

func (l *Layout) ImageWidth(points int) int

ImageWidth is the picture width a card of this width in points asks for: the smallest bucket that covers it at the device's scale, or the largest.

func (*Layout) Placeholders

func (l *Layout) Placeholders(cardWidth int) int

Placeholders is how many grey placeholder cards a row of cards this wide shows while it loads: as many as are at least partly on screen, and no more than the row's first page.

func (*Layout) SideMargin

func (l *Layout) SideMargin() int

SideMargin is the margin at each side of a page's content, in points: the safe area's left inset on a television, the m spacing on every other form factor (16 points on a phone, a tablet, a desktop and the web).

func (*Layout) WindowWidth

func (l *Layout) WindowWidth() int

WindowWidth is the window's width in points: the canvas the client sent (a television's fixed one), else the breakpoint's usual window. A picture that spans the window, such as a title's backdrop, is chosen for this width.

func (*Layout) WithDensity

func (l *Layout) WithDensity(d string) *Layout

WithDensity returns the profile at another density: compact tightens the spacing by a quarter and spacious loosens it by a quarter. Card sizes are the profile's own choice per section, not the density's.

func (*Layout) WithViewport

func (l *Layout) WithViewport(v Viewport) *Layout

WithViewport returns the profile for a window of this size: the breakpoint follows the width. A television's canvas is fixed and is left alone.

type Match

type Match struct {
	// Library is one library's ID.
	Library int64 `json:"library,omitempty"`
	// LibraryKind is a kind of library: movies, shows, anime, music, ...
	LibraryKind string `json:"libraryKind,omitempty"`
	// MediaKind is a kind of title on a detail page: movie, show, episode,
	// album, book, game, collection, ...
	MediaKind string `json:"mediaKind,omitempty"`
}

Match narrows a page. Zero fields match anything.

type Meta

type Meta struct {
	// GeneratedAt and ETag are stamped by Render and left out of the ETag.
	GeneratedAt time.Time `json:"generatedAt,omitzero"`
	ETag        string    `json:"etag,omitempty"`
	// Source is "builtin", "config" or "draft".
	Source string `json:"source,omitempty"`
	// ConfigRevision is the revision of the configuration rendered.
	ConfigRevision int64 `json:"configRevision,omitempty"`
	// TTLSeconds suggests how long to show the page before asking again.
	TTLSeconds int `json:"ttlSeconds,omitempty"`
}

Meta is information about a rendered document that isn't part of the page.

type ModuleChecks

type ModuleChecks struct {
	// ColorToken reports whether a name is a colour token themes have; Color
	// whether a value is a colour. nil: not checked.
	ColorToken func(string) bool
	Color      func(string) bool
}

ModuleChecks are the server's own checks a module's file is held to that this package can't make: the theme engine's colour tokens.

type ModuleComponent

type ModuleComponent struct {
	// Type is "<module>.<Name>": wittyplay.ConsoleShelf.
	Type        string     `json:"type"`
	Label       string     `json:"label"`
	Description string     `json:"description,omitempty"`
	Icon        string     `json:"icon,omitempty"`
	Props       []PropSpec `json:"props,omitempty"`
	// PageKinds are the kinds of page it may be used on; empty: any.
	PageKinds []string `json:"pageKinds,omitempty"`
	Section   Section  `json:"section"`
}

ModuleComponent is a named section with properties of its own. Its Section is a template: a value written "{{name}}" becomes the property's value, and "{{name}}" inside text is replaced by it.

type ModuleInsert

type ModuleInsert struct {
	// Page is the built-in page's ID: home, music, games, ...
	Page string `json:"page"`
	// After or Before name a section of that page; neither: at the end.
	After   string  `json:"after,omitempty"`
	Before  string  `json:"before,omitempty"`
	Section Section `json:"section"`
}

ModuleInsert puts a section into a built-in page.

type ModulePreset

type ModulePreset struct {
	ID          string  `json:"id"`
	Label       string  `json:"label"`
	Description string  `json:"description,omitempty"`
	Section     Section `json:"section"`
}

ModulePreset is a section for the editor's gallery.

type ModuleSet

type ModuleSet struct {
	// contains filtered or unexported fields
}

ModuleSet is the SDUI of every module in use, indexed. A nil *ModuleSet is an empty one. It is shared and never changed once made.

func NewModuleSet

func NewModuleSet(uis []ModuleUI) *ModuleSet

NewModuleSet indexes modules' SDUI. Files should have passed ValidateModuleUI; a name two files claim goes to the first.

func (*ModuleSet) Command added in v0.5.2

func (s *ModuleSet) Command(op string) (CommandSpec, bool)

Command is a command of the server's own or of a module in the set.

func (*ModuleSet) Component

func (s *ModuleSet) Component(t string) *ModuleComponent

Component is a module's component, nil when no module in the set has it.

func (*ModuleSet) ExpandPage

func (s *ModuleSet) ExpandPage(p Page) Page

ExpandPage replaces every module component on a page with the sections it stands for. Sections of a component no module in the set has stay as they are; Render leaves them out.

func (*ModuleSet) Modules

func (s *ModuleSet) Modules() []ModuleUI

Modules are the files in the set, by module ID.

func (*ModuleSet) Navigation

func (s *ModuleSet) Navigation() []NavItem

Navigation are the modules' entries, by module.

func (*ModuleSet) Page

func (s *ModuleSet) Page(id string) (Page, bool)

Page is a module's page by ID: a copy.

func (*ModuleSet) PageModule

func (s *ModuleSet) PageModule(id string) string

PageModule is the module a page of the set comes from, "" for none.

func (*ModuleSet) Pages

func (s *ModuleSet) Pages() []Page

Pages are every module's pages, copies, by module and then in each file's order.

func (*ModuleSet) Presets

func (s *ModuleSet) Presets() []Preset

Presets are the modules' section presets, as the editor's gallery lists them.

func (*ModuleSet) Scopes

func (s *ModuleSet) Scopes() map[string]map[string]string

Scopes are the modules' colours by scope.

func (*ModuleSet) Source

func (s *ModuleSet) Source(t string) *SourceSpec

Source is a module's data source, nil when no module in the set answers it.

func (*ModuleSet) TopShelfSources

func (s *ModuleSet) TopShelfSources() []SourceSpec

TopShelfSources are the sources the modules offer for Top Shelf, by module and then in each file's order.

func (*ModuleSet) View

func (s *ModuleSet) View(id string) bool

View reports whether a module in the set has the view.

func (*ModuleSet) WithInserts

func (s *ModuleSet) WithInserts(p Page) Page

WithInserts is a built-in page with the modules' sections put into it. Sections whose IDs are already on the page are left out.

type ModuleSource

type ModuleSource struct {
	SourceSpec
}

ModuleSource is a data source a module answers: the catalogue's description of a source, with Type "<module>.<name>".

type ModuleTheme

type ModuleTheme struct {
	Scope  string            `json:"scope"`
	Label  string            `json:"label,omitempty"`
	Tokens map[string]string `json:"tokens,omitempty"`
}

ModuleTheme is a module's theme scope: its ID, a name to show in the theme editor, and the colours the module would like, which an administrator's own overrides for the scope replace token by token.

type ModuleUI

type ModuleUI struct {
	// Schema may name the JSON Schema an editor checks the file with
	// (docs/sdui-module.schema.json); the server ignores it.
	Schema string `json:"$schema,omitempty"`
	// Format is ModuleFormat, FormatVersion ModuleFormatVersion.
	Format        string `json:"format"`
	FormatVersion int    `json:"formatVersion"`
	// Module is the module's ID, the same as its manifest's.
	Module string `json:"module"`
	// Catalog is the catalogue revision the module was written against. A
	// server refuses a file newer than its own catalogue.
	Catalog int `json:"catalog"`
	// Theme is the module's theme scope. Required.
	Theme ModuleTheme `json:"theme"`
	// Pages are whole pages the module adds: its own (kind custom, opened at
	// /page/{id}), or a page for a kind of library or title (a games library
	// page, the detail page of a game), or the page of a kind the module is
	// about (games, photos, books, music, livetv).
	Pages []Page `json:"pages,omitempty"`
	// Inserts put one of the module's sections into a built-in page, such as a
	// row on Home. An administrator's own page is never changed by a module.
	Inserts []ModuleInsert `json:"inserts,omitempty"`
	// Presets are sections offered in the page editor's gallery.
	Presets []ModulePreset `json:"presets,omitempty"`
	// Components are the module's named sections: a section of catalogue
	// components with properties of its own, offered in the editor's palette
	// and expanded by the server, so no app needs to know them.
	Components []ModuleComponent `json:"components,omitempty"`
	// Sources are the data sources the module answers, through its helper.
	Sources []ModuleSource `json:"sources,omitempty"`
	// Views are views of the module's own that an app may draw in a
	// NativeView (the module's web bundle, for one); every other app draws the
	// NativeView's sections instead.
	Views []ModuleView `json:"views,omitempty"`
	// Commands are the module's own commands, which its pages and items run: each named
	// <module>.<name>, carried out by a request to the module's own routes
	// (/api/modules/<module>/…). The server lists them in its catalogue, beside its own, so every
	// client runs them as it runs the server's.
	Commands []CommandSpec `json:"commands,omitempty"`
	// Navigation entries the module adds to the main menu.
	Navigation []NavItem `json:"navigation,omitempty"`
	// Settings describe the module's settings, which every app's own Settings
	// draws in its own style under Settings, Modules. They are never SDUI pages.
	Settings []SettingsPage `json:"settings,omitempty"`
}

ModuleUI is one module's SDUI file.

func ParseModuleUI

func ParseModuleUI(b []byte) (*ModuleUI, error)

ParseModuleUI reads a module's SDUI file strictly: unknown fields, trailing data and a file over MaxModuleBytes are refused. It doesn't check the content; ValidateModuleUI does.

type ModuleView

type ModuleView struct {
	// ID is "<module>.<name>"; it is what a NativeView's view prop names and
	// what an app that can draw it sends in views=.
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	// Platforms that can draw it, as a hint for the editor; empty: unknown.
	Platforms []string `json:"platforms,omitempty"`
}

ModuleView is a view of the module's own for a NativeView.

type NativeScreenSpec

type NativeScreenSpec struct {
	Screen      string `json:"screen"`
	Label       string `json:"label"`
	Description string `json:"description"`
	Route       string `json:"route"`
	Icon        string `json:"icon"`
	// Menu: a navigation entry may open it (type native). Screens that need a
	// title or a channel are opened by actions only.
	Menu bool `json:"menu,omitempty"`
}

NativeScreenSpec describes a screen every app draws itself.

type NavDocument struct {
	Version int `json:"version"`
	// FormFactor is the device the placements were chosen for.
	FormFactor string `json:"formFactor"`
	// Items are in order. A client puts "primary" entries in its bar (the
	// tab bar of a phone, the top menu of a television, the sidebar of the
	// web app), "more" entries behind More or in the sidebar's lower group,
	// and "end" entries at the bar's far end.
	Items []NavEntry `json:"items"`
	// Personal is what the profile may change about the menu and what it has
	// changed: every entry it could have, in its order, hidden ones included,
	// so an app can offer "Arrange the menu" without knowing the navigation.
	// Settings is listed like the rest and is never marked hidden. Left out
	// for a profile that may not rearrange.
	Personal *PersonalInfo `json:"personal,omitempty"`
	// Shell is how the app draws its frame with the experience in force: the menu's
	// style on this device, and whether it lies over the page.
	Shell *Shell `json:"shell,omitempty"`
	// Experiences are the experiences this profile may choose from on this device, the
	// one in force marked, for an app's "Layout" setting. Left out for a profile kept
	// from rearranging.
	Experiences *ExperienceChoice `json:"experiences,omitempty"`
	ETag        string            `json:"etag,omitempty"`
}

NavDocument is the main menu rendered for one profile on one device.

func RenderNavigation

func RenderNavigation(nav Navigation, pages func(id string) (Page, bool), libs []NavLibrary, ctx *RenderContext) NavDocument

RenderNavigation makes the main menu for ctx: entries whose conditions don't hold are left out, "libraries" becomes one entry per library, pages take their own title and icon, and the profile's own order and hidden entries are applied (ctx.Personal). Settings is always there: when the navigation as authored lacks it, it is added at the end.

pages looks a page up by ID; an entry for a page that isn't there is left out.

type NavDrawer struct {
	Title string `json:"title"`
	Icon  string `json:"icon"`
	// Count is how many titles the library holds, 0 when not known.
	Count int       `json:"count,omitempty"`
	Views []NavView `json:"views"`
}

NavDrawer is a library's drawer.

type NavEntry struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Icon  string `json:"icon"`
	// Kind is "page" (an SDUI page: ask for Page with Params) or "native" (a
	// screen the app draws itself, named by Screen).
	Kind   string            `json:"kind"`
	Page   string            `json:"page,omitempty"`
	Params map[string]string `json:"params,omitempty"`
	Screen string            `json:"screen,omitempty"`
	// Route is the entry's place in the app.
	Route     string `json:"route"`
	Placement string `json:"placement"`
	// Drawer is the second column a library opens beside the rail (experiences with
	// navExpand "drawer", shell.drawer points wide): headed by the library's name, its icon
	// and its item count, listing its views. Back closes the drawer, then the rail.
	Drawer *NavDrawer `json:"drawer,omitempty"`
}

NavEntry is one rendered entry of the main menu.

type NavItem struct {
	ID string `json:"id"`
	// Label and Icon may be left out for a page (its title and icon are used)
	// and for the libraries (each library's name and its kind's icon).
	Label string `json:"label,omitempty"`
	Icon  string `json:"icon,omitempty"`
	// Type is "page" (Page names it), "libraries" (one entry per library the
	// profile can open), "library" (Library is its ID), "native" (Screen is a
	// screen the app draws itself: settings, guide, profiles, downloads,
	// remote) or "route" (Route is a place in the app).
	Type    string `json:"type"`
	Page    string `json:"page,omitempty"`
	Library int64  `json:"library,omitempty"`
	Screen  string `json:"screen,omitempty"`
	Route   string `json:"route,omitempty"`
	// When must hold for the entry to be shown. The settings entry has none.
	When *Condition `json:"when,omitempty"`
	// Placement says where the entry sits on each form factor: "primary" (the
	// bar itself), "more" (behind More or in the sidebar's lower group), "end"
	// (pinned to the far end) or "hidden". A form factor left out is primary.
	Placement map[string]string `json:"placement,omitempty"`
}

NavItem is one entry of the main menu.

type NavLibrary struct {
	ID    int64
	Name  string
	Kind  string
	Count int
}

NavLibrary is a library the profile can open, for the "libraries" entry.

type NavView struct {
	ID     string            `json:"id"`
	Label  string            `json:"label"`
	Icon   string            `json:"icon"`
	Params map[string]string `json:"params,omitempty"`
	Route  string            `json:"route"`
}

NavView is one view of a library, opened as the library's page with Params.

type Navigation struct {
	Items []NavItem `json:"items"`
}

Navigation is the app's main menu as authored: the tab bar of a phone, the sidebar of the web app, the top menu of a television.

func DecodeNavigation

func DecodeNavigation(data []byte) (Navigation, error)

DecodeNavigation decodes an authored navigation strictly.

func StockNavigation

func StockNavigation() Navigation

StockNavigation is the built-in main menu: Home, Search, Live TV and the libraries, with the app's own profile screen and Settings at the end. On a phone the bar holds Home, Search and Live TV and the libraries sit behind More; a television has a Libraries entry in place of one per library.

type Node

type Node struct {
	// Type is the component: see the catalogue. A client draws a type it
	// doesn't know as a plain column of its children.
	Type string `json:"type"`
	// ID is unique in the document and stable between renders: patches name
	// nodes by it.
	ID string `json:"id"`
	// Props are the component's properties, resolved.
	Props map[string]any `json:"props,omitempty"`
	// Children are in display order.
	Children []Node `json:"children,omitempty"`
	// Action is what activating the node does.
	Action *Action `json:"action,omitempty"`
	// Focus is the node's place in the focus order.
	Focus *Focus `json:"focus,omitempty"`
	// State is "" (ready), "deferred" (ask props.more.url for the items when
	// the node nears the screen), "empty" or "error".
	State string `json:"state,omitempty"`
	// Scope is the theme scope of the node and everything in it, and Tokens
	// the colours that scope overrides.
	Scope  string            `json:"scope,omitempty"`
	Tokens map[string]string `json:"tokens,omitempty"`
}

Node is one component in a rendered tree.

type Page

type Page struct {
	// ID names the page: lower-case letters, digits, - and _. A page with the
	// ID of a built-in page replaces it.
	ID string `json:"id"`
	// Kind says what the page is for, which decides when the app opens it and
	// what its sources may refer to ($library on a library page, $item on a
	// detail page). See PageKinds.
	Kind string `json:"kind"`
	// Title is shown in the page's heading and the window title. It may hold
	// placeholders ({library}, {title}, {query}, {user}).
	Title string `json:"title"`
	// Icon is one of Icons, for a navigation entry made from the page.
	Icon string `json:"icon,omitempty"`
	// Description is for whoever edits the page; clients never see it.
	Description string `json:"description,omitempty"`
	// Match narrows a library or detail page to one library, one kind of
	// library or one kind of media. The most specific match wins.
	Match *Match `json:"match,omitempty"`
	// Scope is the theme scope the page belongs to: a module id (wittymusic)
	// or another name with colours under theme.modules. The whole page takes
	// that scope's colour overrides.
	Scope string `json:"scope,omitempty"`
	// Sections are the page, top to bottom.
	Sections []Section `json:"sections"`
	// Variants replace Sections for the first variant whose condition holds:
	// a kids home, a television home.
	Variants []Variant `json:"variants,omitempty"`
	// Personal says what a profile may change about the page for itself. nil:
	// everything in PersonalKinds.
	Personal *PersonalPolicy `json:"personal,omitempty"`
	// TTLSeconds suggests how long a client may show the page before asking
	// again. 0: the default for the page's kind.
	TTLSeconds int `json:"ttlSeconds,omitempty"`
	// Slot puts a module's page into a place of the hand-built Settings, as a settings page can (SettingsPage.Slot):
	// "you.games" or "people.profile" (administrators only, opened about one profile: the route carries
	// ?item=<its id>, which the page's sources read as $item). Only a module's page may have one.
	Slot string `json:"slot,omitempty"`
	// Regions are what the page puts into the shell's own regions while it, or its theme scope, is
	// showing: the status bar's items and the system dock's actions (docs/SDUI.md, "Shell regions").
	Regions *PageRegions `json:"regions,omitempty"`
}

Page is one page of the app as it is authored: an ordered list of sections, each a component from the catalogue, most of them filled from a data source. A page is rendered for one profile on one device into a Document.

func ClonePage

func ClonePage(p Page) Page

ClonePage deep-copies a page.

func DecodePage

func DecodePage(data []byte) (Page, error)

DecodePage decodes one authored page strictly: unknown fields, trailing data and input over MaxPageBytes are refused. It does not validate.

func SelectPage

func SelectPage(pages []Page, kind string, library int64, libraryKind, mediaKind string) (Page, bool)

SelectPage picks the page for a request from every page of a kind: the one matching the library's ID, else its kind, else the media kind, else the page with no match at all. Among equals the one named first wins, so a configured page (listed before the built-in ones) beats a built-in page.

func StockPage

func StockPage(id string) (Page, bool)

StockPage returns one built-in page by ID.

func StockPages

func StockPages() []Page

StockPages returns the built-in pages, in the order an editor lists them. The result is a copy.

type PageInfo

type PageInfo struct {
	ID    string `json:"id"`
	Kind  string `json:"kind"`
	Title string `json:"title"`
	Icon  string `json:"icon,omitempty"`
	// Route is the page's place in the app: what a deep link to it holds.
	Route string `json:"route,omitempty"`
	// Variant is the ID of the variant used, if one was.
	Variant string `json:"variant,omitempty"`
	// Params are what the page was opened with (library, item, q, ...).
	Params map[string]string `json:"params,omitempty"`
}

PageInfo identifies a rendered page.

type PageKindSpec

type PageKindSpec struct {
	Kind        string `json:"kind"`
	Label       string `json:"label"`
	Description string `json:"description"`
	// Route is the page's place in the app, and Params the query parameters
	// GET /sdui/pages/{kind} takes for it.
	Route  string   `json:"route"`
	Params []string `json:"params,omitempty"`
	// Variables are the $names a source on such a page may use.
	Variables []string `json:"variables,omitempty"`
	// Match lists the Match fields that narrow such a page.
	Match []string `json:"match,omitempty"`
}

PageKindSpec describes a kind of page.

type PageRegions

type PageRegions struct {
	// StatusBar is what the status bar shows besides what the client knows (the clock, the
	// controllers' batteries): the profile's name and a line, the server's name.
	StatusBar []StatusItem `json:"statusBar,omitempty"`
	// SystemDock is the round dock of the screen's destinations.
	SystemDock []DockEntry `json:"systemDock,omitempty"`
}

PageRegions is a page's contribution to the shell: the content of the regions that take any. A page that supplies one turns that region on for as long as the page shows, unless the profile's own placements hide it.

func (*PageRegions) StatusItems

func (p *PageRegions) StatusItems() []StatusItem

StatusItems are the status bar's items, in order.

type PageStyle

type PageStyle struct {
	// GridsAsRows draws grids as rows of cards (a television's way of browsing), except a
	// grid a filter bar drives.
	GridsAsRows bool `json:"gridsAsRows,omitempty"`
	// RowsAsLists draws rows and grids as lists, a line per title.
	RowsAsLists bool `json:"rowsAsLists,omitempty"`
	// Hero is the spotlight's style: "" as authored, billboard, banner, "carousel" (a
	// centred carousel of posters) or "row" (a row of large cards).
	Hero string `json:"hero,omitempty"`
	// CardSize is the size of cards whose section doesn't say: s, m or l; "" as authored.
	CardSize string `json:"cardSize,omitempty"`
	// CardStyle is the style of the cards of films, shows and episodes where a section
	// leaves it to its source: landscape, plate, tile or block; "" as the source has it.
	CardStyle string `json:"cardStyle,omitempty"`
	// SectionStyle is how a section's heading is drawn where it says nothing: band
	// (a coloured header row) or underline; "" plain.
	SectionStyle string `json:"sectionStyle,omitempty"`
	// SeeAllCard makes See all the last card of a row where a section leaves it to the experience.
	SeeAllCard bool `json:"seeAllCard,omitempty"`
	// Crossbar turns Home into a CrossBar of the page's rows; Widgets into a grid of widgets.
	Crossbar bool `json:"crossbar,omitempty"`
	Widgets  bool `json:"widgets,omitempty"`
	// Density is the page's spacing where the profile chose none; "" the device's.
	Density string `json:"density,omitempty"`
}

PageStyle is what an experience changes about pages. Renderers needn't know it: the server has made the changes in the document. It is in the catalogue for editors.

type Patch

type Patch struct {
	Op PatchOp `json:"op"`
	// Path is the target location.
	Path string `json:"path"`
	// Node is the payload for add and node-level replace.
	Node *Node `json:"node,omitempty"`
	// Value is the payload for document-level replace.
	Value any `json:"value,omitempty"`
	// From is the source node ("#id") for move.
	From string `json:"from,omitempty"`
}

Patch is one step in transforming a document into another. Paths are ID based: "#<id>" names a node, "#<id>/children/<n>" a position among its children, and "/root", "/page", "/layout", "/theme", "/personal", "/catalog" and "/meta" the document-level fields.

func Diff

func Diff(old, new Document) []Patch

Diff computes the patches that turn old into new. Children are matched by ID; a node whose own fields (type, props, action, focus, state, scope) changed yields a replace, a new ID an add, a missing ID a remove, and a change of order a move. Meta.GeneratedAt and Meta.ETag are ignored. Diff is deterministic.

type PatchOp

type PatchOp string

PatchOp is the kind of a Patch.

const (
	// PatchAdd inserts Node at Path ("#parent/children/i").
	PatchAdd PatchOp = "add"
	// PatchRemove deletes the node at Path ("#id").
	PatchRemove PatchOp = "remove"
	// PatchReplace replaces the node at Path ("#id") with Node — all fields
	// except Children, which are patched separately — or, for document-level
	// paths ("/page", "/layout", "/theme", "/personal", "/screenTime", "/catalog", "/meta",
	// "/root"), sets Value (or Node for "/root"); a null Value clears the field.
	PatchReplace PatchOp = "replace"
	// PatchMove moves the node From ("#id") to Path ("#parent/children/i").
	PatchMove PatchOp = "move"
)

Patch operations.

type Personal

type Personal struct {
	// Order is the profile's order of the page's top-level sections, by ID.
	// Sections it doesn't name keep their place after the ones it does.
	Order []string `json:"order,omitempty"`
	// Hidden sections aren't shown. Pinned ones come first, in Pinned's order.
	Hidden []string `json:"hidden,omitempty"`
	Pinned []string `json:"pinned,omitempty"`
	// Density is compact, comfortable or spacious; "" follows the device.
	Density string `json:"density,omitempty"`
	// CardSize is s, m or l for a section, by ID.
	CardSize map[string]string `json:"cardSize,omitempty"`
	// DefaultTab is the tab a Tabs section opens on, by the Tabs section's ID.
	DefaultTab map[string]string `json:"defaultTab,omitempty"`
}

Personal is what one profile changed about one page for itself.

func (*Personal) IsZero

func (p *Personal) IsZero() bool

IsZero reports whether the profile changed nothing.

type PersonalInfo

type PersonalInfo struct {
	// Editable is false when the profile may not change layouts at all.
	Editable bool `json:"editable"`
	// Allow lists what may be changed (PersonalKinds).
	Allow []string `json:"allow,omitempty"`
	// Sections are the page's top-level sections in the profile's order,
	// hidden ones included, so they can be shown again.
	Sections []PersonalSection `json:"sections,omitempty"`
	// Density is the profile's choice, "" when it made none.
	Density string `json:"density,omitempty"`
	// URL is where the arrangement is read and written.
	URL string `json:"url,omitempty"`
}

PersonalInfo is the profile's own arrangement of a page.

type PersonalPolicy

type PersonalPolicy struct {
	Allow []string `json:"allow"`
}

PersonalPolicy lists what profiles may change: any of PersonalKinds. An empty list means nothing.

type PersonalSection

type PersonalSection struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Hidden bool   `json:"hidden,omitempty"`
	Pinned bool   `json:"pinned,omitempty"`
	Locked bool   `json:"locked,omitempty"`
	// Empty: there is nothing to show in it now, so it isn't on the page.
	Empty bool `json:"empty,omitempty"`
}

PersonalSection is one row of a "Customise" list.

type Placement

type Placement struct {
	Position string `json:"position,omitempty"`
	Visible  *bool  `json:"visible,omitempty"`
	// Style is the hero's: billboard, banner, carousel or row.
	Style string `json:"style,omitempty"`
}

Placement is where one region of the shell is, and whether it is shown.

type Preset

type Preset struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
	// Kind is "page" or "section".
	Kind string `json:"kind"`
	// PageKind is the kind of page a page preset makes, or the kinds a
	// section preset suits (empty: any).
	PageKinds []string `json:"pageKinds,omitempty"`
	Page      *Page    `json:"page,omitempty"`
	Section   *Section `json:"section,omitempty"`
	// Module is the module that offers the preset; "" for the server's own.
	Module string `json:"module,omitempty"`
}

Preset is something ready-made an administrator applies in one step and then changes: a whole page, or one section to drop into a page.

func PresetByID

func PresetByID(id string) (Preset, bool)

PresetByID returns one preset.

func Presets

func Presets() []Preset

Presets returns the gallery of page and section presets. Shared: don't change it.

type Preview

type Preview struct {
	BG      string `json:"bg"`
	Surface string `json:"surface"`
	Accent  string `json:"accent"`
}

Preview is the swatch the chooser draws.

type Programme

type Programme struct {
	Title string `json:"title"`
	// Start and End are Unix seconds.
	Start int64 `json:"start,omitempty"`
	End   int64 `json:"end,omitempty"`
}

Programme is something on a channel.

type PropSpec

type PropSpec struct {
	Name  string `json:"name"`
	Type  string `json:"type"`
	Label string `json:"label"`
	Help  string `json:"help,omitempty"`
	// Default is what a renderer and the server assume when it is left out.
	Default  any  `json:"default,omitempty"`
	Required bool `json:"required,omitempty"`
	// Options are the choices of an enum or enumList.
	Options []EnumOption `json:"options,omitempty"`
	// Min and Max bound an int; MaxLength a string.
	Min       *int `json:"min,omitempty"`
	Max       *int `json:"max,omitempty"`
	MaxLength int  `json:"maxLength,omitempty"`
	// FormFactors lists where the property has an effect; empty means all.
	FormFactors []string `json:"formFactors,omitempty"`
	// Since is the catalogue revision the property appeared in.
	Since int `json:"since"`
}

PropSpec describes one property of a component or parameter of a source, with everything an editor needs to offer it and a validator to check it.

type Region

type Region struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Positions are where it may be; empty: it has none to choose, only to show or hide.
	Positions []string `json:"positions,omitempty"`
	// Locked regions can't be hidden: the way to Settings, to You and out of a screen.
	Locked bool `json:"locked,omitempty"`
	// Styles are the choices of a region with a style (the hero's).
	Styles []string `json:"styles,omitempty"`
	// Off regions are hidden until an experience, a module's page or a placement turns them on.
	Off bool `json:"off,omitempty"`
}

Region describes one region of the shell.

func RegionByID

func RegionByID(id string) *Region

RegionByID is a region, nil for an ID that isn't one.

type RegionPlacements

type RegionPlacements map[string]Placement

RegionPlacements is a set of placements by region.

func MergePlacements

func MergePlacements(layers ...RegionPlacements) RegionPlacements

MergePlacements lays each set over the one before: a region's position, visibility and style set later replace those set earlier. The result has every region.

func (RegionPlacements) Validate

func (p RegionPlacements) Validate(path string) []Issue

Validate checks placements: known regions, positions the region has, locked regions shown.

type RenderContext

type RenderContext struct {
	// Platform is web, tvos, ios, android, androidtv or desktop.
	Platform string
	// ProfileKind is adult, kids or guest; Admin whether it administers.
	ProfileKind string
	Admin       bool
	// UserName and ServerName fill {user} and {server}.
	UserName, ServerName string
	// Features are the server's; Modules those installed and on; Cannot the
	// parental feature switches that are off for the profile; LibraryKinds
	// the kinds of library it can open; Capabilities what the client has.
	Features, Modules, Cannot, LibraryKinds, Capabilities []string
	// Flags are things the server knows: see Flags.
	Flags map[string]bool
	// Viewport is the window in points, zero when unknown. Locale is a
	// language tag. Now is the server's clock; the zero value means now.
	Viewport Viewport
	Locale   string
	Now      time.Time
	// Profile is the device profile. nil is the web profile.
	Profile *Layout
	// NativeViews are the views the client has for NativeView.
	NativeViews []string
	// Vars are what the page was opened with: library, libraryKind,
	// libraryName, item, show, season, collection, artist, album, query.
	Vars map[string]string
	// Params are the page's filter, sort and tab parameters.
	Params map[string]string
	// Scopes are the theme scopes' colour overrides: scope → token → colour.
	Scopes map[string]map[string]string
	// Personal is the profile's own arrangement of the page; CanPersonalise
	// whether it may have one.
	Personal       *Personal
	CanPersonalise bool
	// ScreenTime, when the profile's time is over, is sent with the document.
	ScreenTime *ScreenTime
	// Resolver answers the page's data sources, the modules' included.
	Resolver Resolver
	// UI are the modules in use: their components are expanded before the
	// page is drawn, and their sources are asked like any other. nil: none.
	UI *ModuleSet
	// Experience is the look the page is drawn for (ExperienceByID): its changes to
	// pages are made here, and its shell is sent in document.layout.shell. nil: none,
	// the page as written.
	Experience *Experience
	// Placements are the administrator's and the profile's changes to the experience's
	// regions, laid over them in shell.placements.
	Placements RegionPlacements
	// BasePath is where the SDUI routes are: "/api/v1/sdui".
	BasePath string
	// Source and ConfigRevision are stamped into Meta.
	Source         string
	ConfigRevision int64
}

RenderContext is who a page is rendered for, on what, with what.

type Repeat

type Repeat struct {
	// Over is "libraries", "pinnedViews", "collections", or the series or authors of
	// the page's books library: "bookSeries", "bookAuthors"; or the parts of a person's work on
	// their page: "personParts".
	Over string `json:"over"`
	// Kinds keeps only libraries of these kinds (Over "libraries").
	Kinds []string `json:"kinds,omitempty"`
	// Limit is the most copies made; 0 is the device's limit.
	Limit int `json:"limit,omitempty"`
}

Repeat makes a section once per thing.

type RequiredPart

type RequiredPart struct {
	Value string    `json:"value"`
	By    string    `json:"by,omitempty"`
	At    time.Time `json:"at,omitzero"`
	Scope string    `json:"scope"`
}

RequiredPart is one required value as a client is told it: the value, who required it and when, and for whom (profile, kids or everyone).

type RequiredPolicy

type RequiredPolicy struct {
	Everyone *Requirement           `json:"everyone,omitempty"`
	Kids     *Requirement           `json:"kids,omitempty"`
	Profiles map[string]Requirement `json:"profiles,omitempty"`
}

RequiredPolicy is what is required of whom: of everyone, of every kids profile, and of named profiles (by profile ID). The most specific wins, part by part: a profile's own requirement over the kids' over everyone's.

func (*RequiredPolicy) RequiredThemes

func (p *RequiredPolicy) RequiredThemes() []string

RequiredThemes lists every theme a policy requires, for the server to check against what is installed.

func (*RequiredPolicy) Resolve

func (p *RequiredPolicy) Resolve(profileID string, kids bool) (experience, theme *RequiredPart)

Resolve is the required experience and theme of a profile, nil for a part nobody requires.

type Requirement

type Requirement struct {
	Experience string `json:"experience,omitempty"`
	Theme      string `json:"theme,omitempty"`
	// By is the administrator who set it, At when.
	By string    `json:"by,omitempty"`
	At time.Time `json:"at,omitzero"`
}

Requirement is a look an administrator requires: an experience, a theme or both. A part left empty is not required.

type Resolver

type Resolver interface {
	// Items answers a data source: up to req.Limit items from req.Offset.
	Items(req SourceRequest) (SourceResult, error)
	// Each lists what a section is repeated over.
	Each(over string, kinds []string, limit int) ([]Each, error)
	// Subject is the title a detail page is about. ErrNotFound when there is
	// none or the profile may not see it.
	Subject() (*Item, error)
	// Seasons lists a show's seasons as items (Kind season, Season, Title,
	// Count, Unwatched).
	Seasons(show string) ([]Item, error)
	// Facets gives the choices of each named filter for a library.
	Facets(library string, fields []string) ([]Facet, error)
}

Resolver is where a page's data comes from. The server's own resolver reads the library with the profile's limits applied; the conformance kit's answers from canned data. A resolver belongs to one request.

type RouteSpec

type RouteSpec struct {
	Pattern string            `json:"pattern"`
	Page    string            `json:"page,omitempty"`
	Params  map[string]string `json:"params,omitempty"`
	Native  string            `json:"native,omitempty"`
}

RouteSpec maps a route in the app to what shows it: an SDUI page (Page, with Params taken from the route) or a screen the app draws itself (Native).

type ScreenTime

type ScreenTime struct {
	// Reason is the rule that ended it; Message says so in words to show.
	Reason  string `json:"reason,omitempty"`
	Message string `json:"message"`
	// NextAt is when there is time again, Unix seconds; 0 when not known.
	NextAt int64 `json:"nextAt,omitempty"`
}

ScreenTime says a profile's time for playing is over.

type Section

type Section struct {
	// ID is unique on the page (across variants too): it is how a profile's
	// own order refers to the section and how a client asks for more of it.
	ID string `json:"id"`
	// Component is a type from the catalogue: Shelf, Hero, Grid, ...
	Component string `json:"component"`
	// Props are the component's properties, as the catalogue describes them.
	Props map[string]any `json:"props,omitempty"`
	// Source says where the component's items come from.
	Source Source `json:"source,omitempty"`
	// When must hold for the section to be shown.
	When *Condition `json:"when,omitempty"`
	// Repeat makes one copy of the section for each library, pinned view or
	// collection, with $each standing for it in Source and {each} in titles.
	Repeat *Repeat `json:"repeat,omitempty"`
	// Scope is a theme scope for this section alone (see Page.Scope).
	Scope string `json:"scope,omitempty"`
	// Locked keeps profiles from hiding or moving the section.
	Locked bool `json:"locked,omitempty"`
	// Children are the sections inside a layout component (Stack, Split, Tab).
	Children []Section `json:"children,omitempty"`
}

Section is one component on a page.

type SectionItems

type SectionItems struct {
	Version int `json:"version"`
	// Section is the node the items belong to.
	Section string `json:"section"`
	// State is "" or "empty": a deferred section that turned out to have
	// nothing in it, which the client then takes off the page.
	State string `json:"state,omitempty"`
	// Props are the section's own props as they are now (title, total,
	// seeAll, seasons), for a section that arrived deferred.
	Props map[string]any `json:"props,omitempty"`
	// Items are the cards to add after the ones the client has; with
	// Replace, in place of them (another season).
	Items   []Node `json:"items"`
	Replace bool   `json:"replace,omitempty"`
	// Next is where the page after this one is; "" when this is the last.
	Next string `json:"next,omitempty"`
}

SectionItems is a page of one section's items: what a client gets from a section's props.more.url, and from a season's url.

func RenderSection

func RenderSection(page Page, nodeID string, offset int, season string, ctx *RenderContext) (SectionItems, error)

RenderSection answers one page of a section's items. nodeID is the ID the section had in the rendered page (for a copy of a repeated section, the section's ID, "-" and the key); offset is the cursor; season chooses a SeasonList's season.

type SettingRow

type SettingRow struct {
	// Key names the value: lower-case first letter, then letters, digits, . _ -.
	Key   string `json:"key"`
	Kind  string `json:"kind"`
	Label string `json:"label"`
	Help  string `json:"help,omitempty"`
	// Scope is server (the default) or profile.
	Scope   string       `json:"scope,omitempty"`
	Default any          `json:"default,omitempty"`
	Options []EnumOption `json:"options,omitempty"`
	Min     *int         `json:"min,omitempty"`
	Max     *int         `json:"max,omitempty"`
	// Unit follows a number: "MB", "seconds".
	Unit      string `json:"unit,omitempty"`
	MaxLength int    `json:"maxLength,omitempty"`
}

SettingRow is one setting.

type SettingsGroup

type SettingsGroup struct {
	Title  string       `json:"title,omitempty"`
	Footer string       `json:"footer,omitempty"`
	Rows   []SettingRow `json:"rows"`
}

SettingsGroup is a titled group of rows.

type SettingsPage

type SettingsPage struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Icon  string `json:"icon,omitempty"`
	// Admin pages are shown only to administrators.
	Admin bool `json:"admin,omitempty"`
	// Slot puts the page into a place of the hand-built Settings besides Settings, Modules: "you.games"
	// (You, Games) or "people.profile" (Settings, People, a profile; administrators only, so the page
	// must be Admin). The server lists the pages of a slot at GET /sdui/slots/{slot}, and every app's
	// Settings draws them in its own style with the generic settings-page renderer.
	Slot   string          `json:"slot,omitempty"`
	Groups []SettingsGroup `json:"groups"`
}

SettingsPage is one page of a module's settings, as every app's own Settings draws it: a title, and groups of rows.

type Shell

type Shell struct {
	Experience string `json:"experience"`
	Nav        string `json:"nav"`
	Overlay    bool   `json:"overlay,omitempty"`
	// Size is the menu's breadth in points: a sidebar's or rail's width, a bar's
	// height (a phone's tab bar without the system's own inset). A renderer lays its
	// frame out with it, so the page keeps the same room on every app.
	Size int `json:"size"`
	// Open is how wide a menu is while it is open (a television's side menu with focus, a
	// rail's full menu); 0 where it doesn't open. Drawer is the width of a rail's library
	// drawer beside it; 0 for none.
	Open   int `json:"open,omitempty"`
	Drawer int `json:"drawer,omitempty"`
	// Placements are where every region of the shell is: the experience's, with the
	// administrator's and the profile's laid over it.
	Placements RegionPlacements `json:"placements,omitempty"`
}

Shell is the experience a document was made for, as an app draws its frame: which one, how the menu is drawn on this device, and whether it lies over the page.

func ShellFor

func ShellFor(id, formFactor string) *Shell

ShellFor is the shell a layout makes on a form factor.

type Source

type Source map[string]any

Source is a data source and its parameters, written flat: {"type": "recentlyAdded", "library": 3, "limit": 20}. The catalogue lists every type and its parameters. A string parameter beginning with $ stands for something the page was opened with ($library, $item, $show, $query) or for the thing a repeated section is repeated over ($each).

func (Source) Bool

func (s Source) Bool(k string) bool

func (Source) Int

func (s Source) Int(k string) int

func (Source) Str

func (s Source) Str(k string) string

Str, Int and Bool read a parameter, with "" , 0 and false for one that isn't there or isn't of that type.

func (Source) Type

func (s Source) Type() string

Type is the source's type, "" when the section has no source.

type SourceRequest

type SourceRequest struct {
	// Source is the source with every $variable replaced.
	Source Source
	// Filter holds the page's filter and sort parameters, for a filterable
	// source.
	Filter map[string]string
	// Offset and Limit page the answer.
	Offset, Limit int
}

SourceRequest is one question to a Resolver.

type SourceResult

type SourceResult struct {
	Items []Item
	// More says there are items after these; Total how many there are in
	// all, -1 when that isn't known.
	More  bool
	Total int
	// Reason says why these were chosen, in a line ("Because you watch Sci-Fi"): a row whose subtitle
	// is "{reason}" shows it under its heading.
	Reason string
	// Selected is the season an "episodes" source chose when none was named.
	Selected string
}

SourceResult is a Resolver's answer.

type SourceSpec

type SourceSpec struct {
	Type        string `json:"type"`
	Label       string `json:"label"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
	// Category groups the editor's list: personal, library, discover, live,
	// music, context, structure.
	Category string     `json:"category"`
	Params   []PropSpec `json:"params,omitempty"`
	// Yields are the item kinds it gives; CardStyle the style "auto" means.
	Yields    []string `json:"yields"`
	CardStyle string   `json:"cardStyle"`
	// PageKinds lists the kinds of page it can be used on; empty means any.
	PageKinds []string `json:"pageKinds,omitempty"`
	// Paged sources give more through a section's cursor URL.
	Paged bool `json:"paged"`
	// SeeAll is the route "See all" opens, with {param} placeholders; "" when
	// the source has no page of its own.
	SeeAll string `json:"seeAll,omitempty"`
	// Title is a good default title for a section using it.
	Title   string          `json:"title,omitempty"`
	Since   int             `json:"since"`
	Example json.RawMessage `json:"example,omitempty"`
	// Module is the module that answers the source; "" for the server.
	Module string `json:"module,omitempty"`
	// TopShelf: a module's source that its module offers for tvOS Top Shelf, as a row of
	// its own (GET /sdui/topshelf). The server's own rows there are fixed.
	TopShelf bool `json:"topShelf,omitempty"`
}

SourceSpec describes one data source.

func SourceType

func SourceType(t string) (*SourceSpec, bool)

SourceType returns the spec of a data source type.

type StatusItem

type StatusItem struct {
	ID   string `json:"id"`
	Kind string `json:"kind"`
	Text string `json:"text,omitempty"`
}

StatusItem is one thing in the status bar.

type TextLimits

type TextLimits struct {
	Title    int `json:"title"`
	Subtitle int `json:"subtitle"`
	Synopsis int `json:"synopsis"`
	Overview int `json:"overview"`
}

TextLimits are the most characters the server sends for each kind of text on a device. Longer text is cut at a word with an ellipsis (see Truncate).

type ThemeRoles

type ThemeRoles struct {
	// ColorRoles are the coloured parts a component can have.
	ColorRoles []EnumOption `json:"colorRoles"`
	// ColorTokens are the colour tokens a role may name: GET /api/v1/theme tokens.
	ColorTokens []string `json:"colorTokens"`
	// ShapeTokens are the names in GET /api/v1/theme shape.
	ShapeTokens []EnumOption `json:"shapeTokens"`
	// TypeRoles say the family (display or body: GET /api/v1/theme type) and weight
	// (a name in type.weights) of each text role; the size is layout.text[role].
	TypeRoles map[string]TypeRole `json:"typeRoles"`
}

ThemeRoles is the vocabulary of TokenRoles, in the catalogue as "theme".

type ThemeScope

type ThemeScope struct {
	Scope  string            `json:"scope"`
	Tokens map[string]string `json:"tokens,omitempty"`
}

ThemeScope is a theme scope and its colour overrides: token → colour.

type Titles

type Titles struct {
	Native    string `json:"native,omitempty"`
	English   string `json:"english,omitempty"`
	Romanized string `json:"romanized,omitempty"`
}

Titles are a game's names, each only when known.

type TokenRoles

type TokenRoles struct {
	// Colors maps each coloured part (a ColorRoles name: background, text, accent, ...)
	// to the colour token drawn there (bg, fg, accent, ...: the names in GET
	// /api/v1/theme tokens). A node's scope tokens override the colours, never the roles.
	Colors map[string]string `json:"colors"`
	// Type maps each piece of text to its text role: its size is layout.text[role] and
	// its family and weight are ThemeRoles.TypeRoles[role].
	Type map[string]string `json:"type,omitempty"`
	// Shape maps each rounded part to a shape token: a name in GET /api/v1/theme shape
	// (card, button, field, chip, badge, image, ...), whose value is its corner radius in
	// points; focusWidth and focusOffset are the focus ring's.
	Shape map[string]string `json:"shape,omitempty"`
}

TokenRoles are the theme tokens a component or card style is drawn with.

type TopShelf

type TopShelf struct {
	// Version is SchemaVersion.
	Version int `json:"version"`
	// Style is "sectioned".
	Style    string            `json:"style"`
	Sections []TopShelfSection `json:"sections"`
	// ExpiresInSec is how long the extension may show this before asking again.
	ExpiresInSec int `json:"expiresInSec"`
}

TopShelf is the content for a tvOS Top Shelf extension, in the "sectioned" style (TVTopShelfSectionedContent).

func NewTopShelf

func NewTopShelf(rows []TopShelfRow, l *Layout, ttl int) TopShelf

NewTopShelf builds Top Shelf content from rows of items, cut to the limits, each picture asked for at the size tvOS wants for its shape: square for music, wide for a title part-way through, poster for the rest. Items without a route are left out: there'd be nowhere to go. Rows that end up empty are left out too.

type TopShelfItem

type TopShelfItem struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	// Shape is poster (2:3), wide (16:9) or square (1:1): the three tvOS has.
	Shape string `json:"shape"`
	// Image is the picture at the size tvOS shows that shape.
	Image *ImageRef `json:"image,omitempty"`
	// Progress is 0..1 for something partly played, shown as a bar.
	Progress     float64 `json:"progress,omitempty"`
	DisplayRoute string  `json:"displayRoute"`
	PlayRoute    string  `json:"playRoute,omitempty"`
}

TopShelfItem is one picture. tvOS opens the app with DisplayRoute when it is selected and PlayRoute when Play is pressed on it; both are routes in the app (the same ones Navigate actions use), which the app wraps in its own URL scheme.

type TopShelfRow

type TopShelfRow struct {
	Title string
	Items []Item
}

TopShelfRow is one row of items for NewTopShelf.

type TopShelfSection

type TopShelfSection struct {
	Title string         `json:"title"`
	Items []TopShelfItem `json:"items"`
}

TopShelfSection is one titled row.

type TypeRole

type TypeRole struct {
	Family string `json:"family"`
	Weight string `json:"weight"`
}

TypeRole is how one text role is set.

type ValidationError

type ValidationError struct {
	Issues []Issue
}

ValidationError carries every error found.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Variant

type Variant struct {
	ID       string     `json:"id"`
	Label    string     `json:"label,omitempty"`
	When     *Condition `json:"when"`
	Sections []Section  `json:"sections"`
}

Variant is another list of sections for the same page, used when its condition holds. Variants are tried in order; the first that holds wins.

type Viewport

type Viewport struct {
	Width  int `json:"width"`
	Height int `json:"height"`
}

Viewport is the size of the client's window in points.

type Wire

type Wire struct {
	// Nav is where the menu is: top, side, rail, bottom or none (a crossbar's categories are
	// part of the page). Open: it is drawn open all the time (a sidebar). Style is how its
	// entries are drawn: pill, gloss, under, cable, bevel, tele or crossbar.
	Nav   string `json:"nav"`
	Open  bool   `json:"open,omitempty"`
	Style string `json:"style"`
	// Home is the shape of Home: hero (a billboard), banner, carousel, cross (a crossbar),
	// tiles, widgets or list.
	Home string `json:"home"`
	// Cards are the card style of films and shows: poster, landscape, plate, block or logo.
	Cards string `json:"cards"`
	// Dock: a dock of keys (Look, Sort, Filter ...) is drawn, as on a television or in a headset.
	Dock bool `json:"dock,omitempty"`
	// Brand is where the server's name sits: left of a top bar, at the top of a side menu or
	// tab bar, or in the centre (a crossbar's).
	Brand string `json:"brand"`
	// Finish is the surface: flat, gloss, bevel, glass or crt.
	Finish string `json:"finish"`
}

Wire is a look's layout as a picker draws it: a few words for each part of the screen, so a person sees the layout they are choosing and not only its colours. It is worked out from the experience's own data (its menu on the form factor, its page changes, its effects), so there is one source of truth, and it is what the design canvas's wire thumbnails draw.

func WireFor

func WireFor(e *Experience, formFactor string) Wire

WireFor is the experience as a picker draws it on a form factor.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL