theme

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package theme loads theme packages and resolves the active theme for a request.

Index

Constants

View Source
const DefaultID = "default"

DefaultID is the built-in fallback theme.

View Source
const (
	MaxBlocks = 30
)

Limits of a page composition.

Variables

View Source
var BlockTypes = []BlockType{
	{Type: "hero", Props: []Prop{
		{Name: "title", Type: PropText}, {Name: "subtitle", Type: PropText}, {Name: "background", Type: PropImage},
		{Name: "primaryAction", Type: PropLink}, {Name: "secondaryAction", Type: PropLink},

		{Name: "layout", Type: PropChoice, Options: []string{"split", "centered", "banner"}},

		{Name: "showcase", Type: PropChoice, Options: []string{"latest", "popular", "none"}},
	}},
	{Type: "announcement", Props: []Prop{}},
	{Type: "features", Props: []Prop{}},
	{Type: "stats", Props: []Prop{{Name: "title", Type: PropText}}},
	{Type: "latest-textures", Props: textureListProps()},
	{Type: "popular-textures", Props: textureListProps()},
	{Type: "markdown", Props: []Prop{{Name: "content", Type: PropMarkdown}}},
	{Type: "image", Props: []Prop{{Name: "src", Type: PropImage}, {Name: "alt", Type: PropText}, {Name: "href", Type: PropLink}}},
	{Type: "buttons", Props: []Prop{{Name: "items", Type: PropButtons}}},
	{Type: "launcher-guide", Props: []Prop{}},
}

BlockTypes are the built-in blocks, rendered on the server by the frontend (web/apps/web/src/components/blocks). Plugins declare theirs in phase 2.

View Source
var ColorSchemes = []string{"both", "light", "dark"}

ColorSchemes are the color modes a theme may support (ADR 0043).

View Source
var DocumentedColorTokens = []string{
	"background", "foreground",
	"card", "card-foreground",
	"popover", "popover-foreground",
	"muted", "muted-foreground", "faint-foreground",
	"secondary", "secondary-foreground",
	"accent", "accent-foreground",
	"primary", "primary-foreground",
	"highlight", "highlight-foreground",
	"warning", "warning-foreground",
	"success", "success-foreground",
	"destructive", "destructive-foreground",
	"border", "input", "overlay", "ring",
	"chart-1", "chart-2", "chart-3", "chart-4", "chart-5",
	"sidebar", "sidebar-foreground",
	"sidebar-primary", "sidebar-primary-foreground",
	"sidebar-accent", "sidebar-accent-foreground",
	"sidebar-border", "sidebar-ring",
	"pixel-a", "pixel-b",
	"shadow-popover", "shadow-dialog",
	"radius", "brand-gradient",
}

DocumentedColorTokens are the color, shadow and radius tokens in web/design.md §2.2. Unlisted token names remain allowed for a theme's own CSS.

View Source
var DocumentedFontTokens = []string{"sans", "mono", "display"}

DocumentedFontTokens are the font tokens in web/design.md §3.1.

View Source
var Layouts = map[string][]string{
	"auth":    {"card", "split"},
	"skinlib": {"comfortable", "compact"},
	"user":    {"sidebar", "tabs"},
	"texture": {"split", "stacked"},
}

Layouts are the layout variants a theme may choose (docs/design/05 §6.1 ③, ADR 0043), the default first. Keys not listed here are ignored.

View Source
var OverrideTargets = []string{
	"site.header",
	"site.footer",
	"site.logo",
	"auth.background",
	"home.hero",
	"texture.card",
	"player.card",
}

OverrideTargets are the Level 5 React component override points (docs/design/09 §3.2).

Functions

func AssetURL

func AssetURL(t *Theme, file string) string

AssetURL is the public URL of a theme file; the version or content hash in the path makes it cacheable forever.

func ContrastRatio added in v1.1.0

func ContrastRatio(fg, bg string) (float64, bool)

ContrastRatio returns the WCAG 2.1 contrast ratio between two opaque oklch() or #hex colors.

func CustomCSSURL

func CustomCSSURL(css string) string

CustomCSSURL is where theme.custom_css is served: named by its content, so it can be cached forever and a change reaches every page at once.

func CustomHandler

func CustomHandler(css, js func() string) http.Handler

CustomHandler serves theme.custom_css and theme.custom_js (css and js return the current values) at CustomCSSURL and CustomJSURL. Files of their own, not a <style> or <script> in the page: nothing in them can end the element and inject HTML, and the script runs only where a page loads it with its nonce.

func CustomJSURL

func CustomJSURL(js string) string

CustomJSURL is where theme.custom_js is served, named like CustomCSSURL.

func IsBuiltinID added in v1.1.0

func IsBuiltinID(id string) bool

IsBuiltinID reports whether id is reserved by a built-in embedded theme.

func RegisterPluginBlocks added in v1.1.0

func RegisterPluginBlocks(pluginID string, types []BlockType)

RegisterPluginBlocks registers homepage block definitions contributed by pluginID.

func Scaffold added in v1.1.0

func Scaffold(themesDir, id, extends string) (string, error)

Scaffold creates a new local theme skeleton under <themesDir>/<id>/.

func UnregisterPluginBlocks added in v1.1.0

func UnregisterPluginBlocks(pluginID string)

UnregisterPluginBlocks removes any block types previously registered by pluginID.

func ValidateBlocks

func ValidateBlocks(blocks []Block) error

ValidateBlocks checks a page composition against BlockTypes: known types, known properties of the right kind, and the size limits.

func ValidateHome

func ValidateHome(v any) error

ValidateHome is the validator of the home.blocks setting: null, or blocks that ValidateBlocks accepts.

func ValidateOverrides

func ValidateOverrides(v any) error

ValidateOverrides is the validator of theme.overrides: {"light" | "dark" | "fonts" | "viewer": {token: CSS value}}. Unsafe values were dropped on render before; refusing them on save tells the administrator.

Types

type Block

type Block struct {
	Type  string         `json:"type"`
	Props map[string]any `json:"props,omitempty"`
}

Block is one entry of a page composition (home page in M0).

func LocalizeBlocks

func LocalizeBlocks(blocks []Block, locale string, markdown func(string) string) []Block

LocalizeBlocks prepares blocks for one request: text properties become the text of locale, Markdown ones are rendered by markdown into <name>Html. Pages then only read strings; the admin panel edits the stored values (home.blocks) instead.

type BlockType

type BlockType struct {
	Type  string `json:"type"`
	Props []Prop `json:"props"`
}

BlockType is a kind of block pages are composed of (docs/design/05 §5.4).

func AllBlockTypes added in v1.1.0

func AllBlockTypes() []BlockType

AllBlockTypes returns built-in block definitions followed by active plugin blocks. If a plugin block type collides with an earlier block type name, it is emitted in its qualified "<pluginId>:<type>" form so every block type in the list is unique.

type LocalizedMap added in v1.1.0

type LocalizedMap map[string]string

LocalizedMap is a locale-to-string map that also unmarshals from a plain JSON string.

func (*LocalizedMap) UnmarshalJSON added in v1.1.0

func (m *LocalizedMap) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts either a plain string or a locale map {"zh-CN": "…", "en": "…"}.

type Manifest

type Manifest struct {
	ID          string             `json:"id"`
	Kind        string             `json:"kind"`
	Version     string             `json:"version"`
	Name        LocalizedMap       `json:"name"`
	Description LocalizedMap       `json:"description,omitempty"`
	APIVersion  int                `json:"apiVersion"`
	Extends     string             `json:"extends,omitempty"`
	Screenshot  string             `json:"screenshot,omitempty"`
	Web         string             `json:"web,omitempty"`
	Settings    map[string]Setting `json:"settings,omitempty"`
	Theme       struct {
		ColorScheme string             `json:"colorScheme,omitempty"`
		Tokens      Tokens             `json:"tokens"`
		CSS         string             `json:"css,omitempty"`
		Layout      map[string]string  `json:"layout,omitempty"`
		Home        []Block            `json:"home,omitempty"`
		Overrides   []string           `json:"overrides,omitempty"`
		Settings    map[string]Setting `json:"settings,omitempty"`
	} `json:"theme"`
}

Manifest is the subset of plugin.json a theme uses (docs/design/05 §6.2, ADR 0043).

type Prop

type Prop struct {
	Name    string   `json:"name"`
	Type    PropType `json:"type" enum:"text,markdown,link,image,number,choice,buttons"`
	Min     int      `json:"min,omitempty"`
	Max     int      `json:"max,omitempty"`
	Options []string `json:"options,omitempty"`
}

Prop describes one property of a block type.

type PropType

type PropType string

PropType is the kind of value a block property holds.

const (
	// PropText is a short line: a string, or one per language {"zh-CN": …, "en": …}.
	PropText PropType = "text"
	// PropMarkdown is longer text in Markdown, plain or per language. Pages receive it
	// rendered, as <name>Html.
	PropMarkdown PropType = "markdown"
	// PropLink is a path on this site (/skinlib) or an http(s) URL.
	PropLink PropType = "link"
	// PropImage is an image URL or a path on this site.
	PropImage PropType = "image"
	// PropNumber is an integer from Min to Max.
	PropNumber PropType = "number"
	// PropChoice is one of Options.
	PropChoice PropType = "choice"
	// PropButtons is a list of {"label": text, "href": link}.
	PropButtons PropType = "buttons"
)

type Registry

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

Registry holds every installed theme.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) AssetHandler

func (r *Registry) AssetHandler() http.Handler

AssetHandler serves /themes-assets/{id}/{version-or-hash}/{file...}.

func (*Registry) AssetHandlerWithTrust added in v1.1.0

func (r *Registry) AssetHandlerWithTrust(webTrusted func(themeID string) bool) http.Handler

AssetHandlerWithTrust serves static theme assets, allowing web/*.js|mjs scripts only when the theme is built-in or approved by webTrusted (signed package or superadmin confirmation).

func (*Registry) Get

func (r *Registry) Get(id string) (*Theme, bool)

Get returns a valid installed theme by ID.

func (*Registry) IsBuiltin added in v1.1.0

func (r *Registry) IsBuiltin(id string) bool

IsBuiltin reports whether id is reserved by a built-in theme (including registry-loaded built-ins).

func (*Registry) List

func (r *Registry) List() []*Theme

List returns all themes (including broken local themes) sorted by ID.

func (*Registry) LoadDir

func (r *Registry) LoadDir(root fs.FS, source string) error

LoadDir loads every subdirectory of root that contains a theme plugin.json.

func (*Registry) Put

func (r *Registry) Put(t *Theme)

Put adds or replaces a theme (hot: callers bump the config version afterwards).

func (*Registry) Reload added in v1.1.0

func (r *Registry) Reload()

Reload rescans the local themes directory, keeping built-in themes intact.

func (*Registry) Resolve

func (r *Registry) Resolve(s *settings.Snapshot) ResolvedTheme

Resolve applies the active theme, theme settings, admin token overrides and the home layout.

func (*Registry) ResolveTheme added in v1.1.0

func (r *Registry) ResolveTheme(s *settings.Snapshot, overrideID string, webTrusted func(id string) bool) ResolvedTheme

ResolveTheme resolves either the site's active theme or an explicit override theme ID (used for administrator session previews), gating Level-5 JS overrides behind webTrusted.

func (*Registry) SetLocalDir added in v1.1.0

func (r *Registry) SetLocalDir(dir string, log *slog.Logger)

SetLocalDir configures the local themes directory (<DataDir>/themes) and loads it. Broken local themes are recorded on the registry and logged without stopping startup.

func (*Registry) ValidateActive

func (r *Registry) ValidateActive(v any) error

ValidateActive is the validator for the theme.active setting.

func (*Registry) ValidateSettings added in v1.1.0

func (r *Registry) ValidateSettings(v any) error

ValidateSettings is the validator for the theme.settings setting: {themeId: {settingName: value}}.

func (*Registry) Watch added in v1.1.0

func (r *Registry) Watch(ctx context.Context, onChange func())

Watch monitors the local themes directory in dev mode and invokes onChange after reloading.

type ResolvedTheme

type ResolvedTheme struct {
	ID          string            `json:"id"`
	Version     string            `json:"version"`
	ColorScheme string            `json:"colorScheme"`
	Tokens      Tokens            `json:"tokens"`
	CSS         []string          `json:"css"`
	JS          []string          `json:"js"`
	WebEntry    string            `json:"webEntry,omitempty"`
	Overrides   []string          `json:"overrides,omitempty"`
	Previewing  bool              `json:"previewing,omitempty"`
	PreviewName string            `json:"previewName,omitempty"`
	Layout      map[string]string `json:"layout"`
	Home        []Block           `json:"home"`
	Settings    map[string]string `json:"settings,omitempty"`
}

ResolvedTheme is what the frontend needs to render with the active theme. JS lists the scripts pages load with their CSP nonce (theme.custom_js).

type Setting added in v1.1.0

type Setting struct {
	Type    SettingType       `json:"type" enum:"color,image,choice,text,boolean"`
	Label   map[string]string `json:"label,omitempty"`
	Default any               `json:"default,omitempty"`
	Options []string          `json:"options,omitempty"`
	Token   string            `json:"token,omitempty"`
}

Setting is one setting declared by a theme in plugin.json.

func (*Setting) UnmarshalJSON added in v1.1.0

func (s *Setting) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts label as either a localized object {"zh-CN": "…", "en": "…"} or a plain string.

type SettingType added in v1.1.0

type SettingType string

SettingType is the kind of value a theme setting holds (ADR 0043).

const (
	SettingColor   SettingType = "color"
	SettingImage   SettingType = "image"
	SettingChoice  SettingType = "choice"
	SettingText    SettingType = "text"
	SettingBoolean SettingType = "boolean"
)

type Theme

type Theme struct {
	Manifest
	Source        string   // "builtin" or "local"
	Error         string   // non-empty when a local theme failed to load
	ScreenshotURL string   // resolved AssetURL of Screenshot
	CSSFiles      []string // resolved AssetURLs (parent first when Extends is set)
	WebEntry      string   // resolved AssetURL of Web (e.g. web/index.js)
	WebCSS        string   // resolved AssetURL of optional web/index.css alongside Web
	Overrides     []string // validated Level 5 component override targets
	// contains filtered or unexported fields
}

Theme is a loaded theme package (or a failed local theme when Error != "").

func Check added in v1.1.0

func Check(files fs.FS, base *Registry) (*Theme, []string, error)

Check validates a theme package in files against the loading rules and returns any contrast or completeness warnings (web/design.md §2.4).

type Tokens

type Tokens struct {
	Light  map[string]string `json:"light"`
	Dark   map[string]string `json:"dark"`
	Fonts  map[string]string `json:"fonts,omitempty"`
	Viewer map[string]string `json:"viewer,omitempty"`
}

Tokens are CSS custom property values, keyed by token name without the leading "--".

Jump to

Keyboard shortcuts

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