admin

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 52 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package admin builds back-office panels from typed Go definitions: an index, a detail view, and create and edit forms for each resource, served as Crest + Live pages under a strict CSP.

A panel is defined with New, given resources with Register, and served with fletch.MountAdmin, Mount, or Routes. Resources read and write through a NockRepo or any Repository; every request and Live event is checked against the panel's rbac policy, and every write is audited. See docs/admin.md.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound means the row is missing or outside the caller's scope.
	// errors.Is also matches nock.ErrNotFound against it.
	ErrNotFound error = notFoundError{}
	// ErrConflict means the row changed after the form loaded it.
	ErrConflict = errors.New("admin: the record was changed by someone else")
)
View Source
var (
	// Today is the current day.
	Today = RangeDef{Key: "today", Label: "Today", Compare: "yesterday", /* contains filtered or unexported fields */}
	// MonthToDate is the current month through today.
	MonthToDate = RangeDef{Key: "mtd", Label: "MTD", Compare: "the previous period", /* contains filtered or unexported fields */}
	// QuarterToDate is the current quarter through today.
	QuarterToDate = RangeDef{Key: "qtd", Label: "QTD", Compare: "the previous period", /* contains filtered or unexported fields */}
	// YearToDate is the current year through today.
	YearToDate = RangeDef{Key: "ytd", Label: "YTD", Compare: "the previous period", /* contains filtered or unexported fields */}
)
View Source
var ErrNoTx = errors.New("admin: the panel has no transaction runner (WithDB or WithTx)")

ErrNoTx is returned by Tx when the panel has neither WithDB nor WithTx.

View Source
var Tables = []*schema.TableDef{
	schema.Table("admin_saved_views",
		schema.Col("id").Text().PrimaryKey(),
		schema.Col("panel").Text().NotNull(),
		schema.Col("resource").Text().NotNull(),
		schema.Col("subject").Text().NotNull(),
		schema.Col("name").Text().NotNull(),
		schema.Col("query").Text().NotNull().Default("''"),
		schema.Col("columns").Text().NotNull().Default("'[]'"),
		schema.Col("shared").Bool().NotNull().Default("false"),
		schema.Col("created_at").Timestamptz().NotNull(),
	).Index("panel", "resource", "subject"),
	schema.Table("admin_column_prefs",
		schema.Col("panel").Text().NotNull(),
		schema.Col("resource").Text().NotNull(),
		schema.Col("subject").Text().NotNull(),
		schema.Col("columns").Text().NotNull(),
	).Unique("panel", "resource", "subject"),
	schema.Table("admin_runs",
		schema.Col("id").Text().PrimaryKey(),
		schema.Col("panel").Text().NotNull(),
		schema.Col("resource").Text().NotNull().Default("''"),
		schema.Col("action").Text().NotNull(),
		schema.Col("subject").Text().NotNull().Default("''"),
		schema.Col("state").Text().NotNull(),
		schema.Col("done").BigInt().NotNull().Default("0"),
		schema.Col("total").BigInt().NotNull().Default("0"),
		schema.Col("note").Text().NotNull().Default("''"),
		schema.Col("result").Text().NotNull().Default("''"),
		schema.Col("error").Text().NotNull().Default("''"),
		schema.Col("created_at").Timestamptz().NotNull(),
		schema.Col("updated_at").Timestamptz().NotNull(),
	).Index("panel", "state"),
	schema.Table("admin_uploads",
		schema.Col("key").Text().PrimaryKey(),
		schema.Col("panel").Text().NotNull(),
		schema.Col("resource").Text().NotNull(),
		schema.Col("field").Text().NotNull(),
		schema.Col("subject").Text().NotNull(),
		schema.Col("content_type").Text().NotNull().Default("''"),
		schema.Col("size").BigInt().NotNull().Default("0"),
		schema.Col("committed").Bool().NotNull().Default("false"),
		schema.Col("swept").Bool().NotNull().Default("false"),
		schema.Col("created_at").Timestamptz().NotNull(),
	).Index("committed", "created_at"),
}

Tables are the tables NockState uses. Add them to the app's database/schema.go so its migrations create them; the panel never runs DDL itself.

Functions

func Actor

func Actor(ctx context.Context) string

Actor returns the ID of the subject acting in ctx.

func Audit

func Audit(ctx context.Context, action, resource string, meta map[string]any) error

Audit records an event for custom pages and hooks; inside a write or Tx it joins the transaction when the panel has WithTxAudit.

func CSPSources

func CSPSources(p *Panel) map[string][]string

CSPSources returns the sources a panel needs beyond 'self', by CSP directive: the bucket origin of presigned uploads under connect-src, and the image service's origin under img-src. Add them to the app's secure.Config.CSP when the app, not the panel, sends the policy.

func Change

func Change[V any](c Changes, name string) (v V, set bool, null bool)

Change returns the new value of field name. set is false when the field did not change; null is true when it changed to NULL.

func CountOf

func CountOf(q *nock.SelectQuery, at nock.Col[time.Time]) func(ctx context.Context, r Range) (ValueResult, error)

CountOf counts the rows of q whose at falls in the range, and in the range before it. q must select at's column, as nock.Select() (every column) does:

admin.CountOf(nock.Select().From(Orders).Where(Orders.Status.Neq("void")), Orders.PlacedAt)

func CurrentID

func CurrentID(c *live.Ctx) string

CurrentID returns the raw ID of the record page being mounted, or "".

func CurrentRecord

func CurrentRecord[T any, ID comparable](c *live.Ctx, r *Resource[T, ID]) (*T, error)

CurrentRecord loads the record of the record page being mounted, through the resource's repository and scope, and checks the subject may view it. It fails with a not-found status outside a record page of r.

func CurrentTx

func CurrentTx(ctx context.Context) any

CurrentTx returns the transaction of the write or action running in ctx, or nil.

func DateRange

func DateRange(ctx context.Context, v FilterValue) (from, to time.Time)

DateRange returns the bounds of a date range filter in the panel's time zone: from is the start of the first day and to the start of the day after the last, so rows match when from <= t < to. A zero bound is open.

func Exec

func Exec(ctx context.Context) nock.Executor

Exec returns the executor repositories should use: the current transaction when it is a nock executor, else the panel's WithDB database. It is nil outside a panel request or without either.

func FieldError

func FieldError(name, msg string) error

FieldError returns an error that marks one field invalid.

func FormatCount

func FormatCount(v int64) string

FormatCount shows an integer with thousands separators.

func FormatMoney

func FormatMoney(code string) func(int64) string

FormatMoney shows minor units of currency code, as in "$1,234.50".

func FormatPercentBP

func FormatPercentBP(v int64) string

FormatPercentBP shows basis points as a percentage: 1234 is "12.34%".

func ImageAuthorizer

func ImageAuthorizer(next images.Authorizer) images.Authorizer

ImageAuthorizer lets the image service render the thumbnails of a panel's Image fields. The panel serves each thumbnail from its own route, after the subject's view check on the record, and grants that one key for that one request; other Stored refs go to next, or are refused when next is nil. Pass it to images.WithAuthorizer.

func Mount

func Mount(mux *http.ServeMux, panels ...*Panel) error

Mount serves standalone panels on mux: each under its Path, plus the Live and Alpine scripts they load, registered once however many panels share them. It reports every panel's configuration error, and two panels on one path, before it registers anything.

func NavOrder(n int) interface {
	NavOption
	ResourceOption
	PageOption
}

NavOrder sorts sidebar groups and items; lower comes first.

func Notify

func Notify(c *live.Ctx, tone Tone, msg string) error

Notify shows a toast in the user's view.

func Progress

func Progress(ctx context.Context, done, total int, note string)

Progress reports how far the current admin run is: done of total, with a note such as the partner being paid. It sets the numbers rather than adding to them, so a redelivered job reports the same. It is a no-op outside an admin run and is throttled to one update per 250ms or 1%.

func Require

func Require(ctx context.Context, perm rbac.Permission) error

Require checks perm for the subject of a panel request, for custom code such as action inputs.

func RunMeta

func RunMeta(run RunInfo) []quiver.EnqueueOption

RunMeta returns the enqueue options that attach a job to an admin run, for services that enqueue inside their own transaction with quiver.EnqueueTx.

func SQLAudit

func SQLAudit(tx any) audit.Recorder

SQLAudit returns a recorder that writes to the fletch_audit_log table of audit/postgres through tx, which must be a nock executor such as the *nock.Transaction of a panel write. Pass it to WithTxAudit.

func StrictCSP

func StrictCSP() secure.Config

StrictCSP is the policy standalone panels send: no inline script without the request nonce, and no inline style at all.

func SumOf

func SumOf(q *nock.SelectQuery, value nock.Col[int64], at nock.Col[time.Time]) func(ctx context.Context, r Range) (ValueResult, error)

SumOf sums value over the rows of q whose at falls in the range, and in the range before it. q must select both columns.

func SweepUploads

func SweepUploads(ctx context.Context, p *Panel, olderThan time.Duration) (int, error)

SweepUploads deletes files uploaded through the panel but never saved, begun more than olderThan ago, and the files saves replaced, and returns how many it deleted. Only uploads it claims from the ledger are deleted, so a save that commits an upload first keeps it; a failed delete is retried by the next sweep. Run it periodically, such as from a daily quiver.Every job.

func TrendOf

func TrendOf(q *nock.SelectQuery, at nock.Col[time.Time], value nock.Col[int64], b Bucket) func(ctx context.Context, r Range) ([]Point, error)

TrendOf is one point per bucket of the range: the sum of value over the rows of q whose at falls in it, or their count when value is the zero Col. Postgres groups in SQL with date_trunc in the panel's time zone; SQLite, whose dates are text, groups the range's rows in Go.

func Tx

func Tx(ctx context.Context, fn func(ctx context.Context, tx any) error) error

Tx runs fn in the panel's transaction, or in the current one when ctx is already inside a write; Audit calls with the returned ctx join it.

func ValueOf

func ValueOf[V any](vals Values, name string) (V, bool)

ValueOf returns the current value of field name. ok is false when the field is unknown, NULL, or of another type.

func WatchRun

func WatchRun(c *live.Ctx, id string, fn func(c *live.Ctx, ev RunEvent) error) error

WatchRun calls fn on the session's goroutine with each change of run id, through the panel's broker. Without a broker it returns an error; poll the panel's StateStore instead.

func WidgetOf

func WidgetOf(ctx context.Context, m *Metric, rangeKey string) ui.WidgetData

WidgetOf computes m for a custom page, as the subject of ctx, over the metric's range keyed rangeKey or its default. A metric the subject may not see comes back with an error and no data.

Types

type ActionBuilder

type ActionBuilder[T any, ID comparable, In any] struct {
	// contains filtered or unexported fields
}

ActionBuilder defines an action. Its permission defaults to "<kind>:<key>"; When narrows the rows it applies to. Every run is authorized against each row and audited as admin.<kind>.<key>.

func Action

func Action[T any, ID comparable, In any](key, label string) *ActionBuilder[T, ID, In]

Action starts an action definition. It is a row action unless Bulk or Both says otherwise.

func (*ActionBuilder[T, ID, In]) Both

func (a *ActionBuilder[T, ID, In]) Both() *ActionBuilder[T, ID, In]

Both offers the action on one record and on a selection.

func (*ActionBuilder[T, ID, In]) Bulk

func (a *ActionBuilder[T, ID, In]) Bulk() *ActionBuilder[T, ID, In]

Bulk offers the action on the rows selected in the index.

func (*ActionBuilder[T, ID, In]) Can

func (a *ActionBuilder[T, ID, In]) Can(perm rbac.Permission) *ActionBuilder[T, ID, In]

Can overrides the permission the action needs.

func (*ActionBuilder[T, ID, In]) Confirm

func (a *ActionBuilder[T, ID, In]) Confirm(title string, body ...string) *ActionBuilder[T, ID, In]

Confirm asks for confirmation with a title and an optional body before running.

func (*ActionBuilder[T, ID, In]) Destructive

func (a *ActionBuilder[T, ID, In]) Destructive() *ActionBuilder[T, ID, In]

Destructive styles the action as dangerous.

func (*ActionBuilder[T, ID, In]) Form

func (a *ActionBuilder[T, ID, In]) Form(inputs ...*Input[In]) *ActionBuilder[T, ID, In]

Form sets the typed inputs of the action's dialog.

func (*ActionBuilder[T, ID, In]) JobKind

func (a *ActionBuilder[T, ID, In]) JobKind(kind string) *ActionBuilder[T, ID, In]

JobKind declares the kind of the job Queue returns. A run whose job has another kind fails before it is enqueued, and fletch check (W0702) verifies the app handles the kind.

func (*ActionBuilder[T, ID, In]) Queue

func (a *ActionBuilder[T, ID, In]) Queue(fn func(ctx context.Context, ids []ID, in In, run RunInfo) (quiver.JobArgs, error)) *ActionBuilder[T, ID, In]

Queue makes the action asynchronous: fn returns the job to enqueue. The job carries the run, so admin.Progress inside it updates the user's run tray, and its outcome becomes a toast.

func (*ActionBuilder[T, ID, In]) Row

func (a *ActionBuilder[T, ID, In]) Row() *ActionBuilder[T, ID, In]

Row offers the action on one record at a time. It is the default.

func (*ActionBuilder[T, ID, In]) Run

func (a *ActionBuilder[T, ID, In]) Run(fn func(ctx context.Context, rows []*T, in In, run RunInfo) (Result, error)) *ActionBuilder[T, ID, In]

Run sets what a synchronous action does.

func (*ActionBuilder[T, ID, In]) Timeout

func (a *ActionBuilder[T, ID, In]) Timeout(d time.Duration) *ActionBuilder[T, ID, In]

Timeout bounds a synchronous run; default 10s.

func (*ActionBuilder[T, ID, In]) Transactional

func (a *ActionBuilder[T, ID, In]) Transactional() *ActionBuilder[T, ID, In]

Transactional runs the action in the panel's transaction, so its writes, a queued job where the queue supports it, and its audit event commit together.

func (*ActionBuilder[T, ID, In]) Validate

func (a *ActionBuilder[T, ID, In]) Validate(fn func(ctx context.Context, rows []*T, in *In) error) *ActionBuilder[T, ID, In]

Validate checks the input against the target rows before the action runs; return FieldError to mark an input.

func (*ActionBuilder[T, ID, In]) When

func (a *ActionBuilder[T, ID, In]) When(fn func(ctx context.Context, row *T) bool) *ActionBuilder[T, ID, In]

When offers the action only for rows where fn is true; it is checked again when the action runs.

type ActionDef

type ActionDef[T any, ID comparable] interface {
	// contains filtered or unexported methods
}

ActionDef is a row or bulk action of a resource over T keyed by ID. Build one with Action.

type BadgeValue

type BadgeValue struct {
	Text string
	Tone Tone
}

BadgeValue is the count or label a NavBadge shows beside a sidebar item.

type Brand

type Brand struct {
	Name string
	// Logo renders in the sidebar header; LogoURL is the alternative.
	LogoURL string
	Favicon string
	// HomeURL is where the brand links; default the panel's dashboard.
	HomeURL string
}

Brand is the identity a panel shows: the app's, never Fletch's.

type Bucket

type Bucket string

Bucket is the width of one trend point.

const (
	Day   Bucket = "day"
	Week  Bucket = "week"
	Month Bucket = "month"
)

The trend bucket widths.

type CanOption

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

CanOption limits a lens or a relation to subjects with a permission.

func Can

func Can(perm rbac.Permission) CanOption

Can limits a lens to subjects with perm.

type Changes

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

Changes is the validated set of fields a form changed and the caller may edit. Fields the user left alone are absent, so an update never rewrites a column nobody touched.

func (*Changes) Assign

func (c *Changes) Assign(as ...nock.Assignment)

Assign adds assignments that are not form fields, such as a tenant column set in a BeforeWrite hook.

func (Changes) Assignments

func (c Changes) Assignments() []nock.Assignment

Assignments returns a nock assignment for each changed field bound with Col or ColJSON, then those added with Assign.

func (Changes) Has

func (c Changes) Has(name string) bool

Has reports whether name changed.

func (Changes) Len

func (c Changes) Len() int

Len is the number of changed fields.

func (Changes) Names

func (c Changes) Names() []string

Names lists the changed fields in form order.

type Column

type Column[T any] struct {
	Label   string
	Cell    func(*T) string
	Link    func(*T) string
	Numeric bool
}

Column is one column of a TableWidget. Link makes the cell a link.

type Density

type Density string

Density sets row and control heights.

const (
	Comfortable Density = "comfortable"
	Compact     Density = "compact"
)

The row and control densities.

type Field

type Field[T, V any] struct {
	// contains filtered or unexported fields
}

Field is one typed field of a resource over rows of type T with values of type V. Its modifiers return the field, so definitions chain.

func Badge

func Badge[T any](name string, fn func(*T) (string, Tone)) *Field[T, string]

Badge is a computed, read-only badge.

func BelongsTo

func BelongsTo[T any, R any, RID comparable](name string, get Getter[T, RID], target *Resource[R, RID]) *Field[T, RID]

BelongsTo is a reference to a row of target. Forms pick it with a search box that runs as the current subject, so target's list permission and scope apply; without list on target the field is read-only. A saved value must be a row the subject can see.

func Boolean

func Boolean[T any](name string, get Getter[T, bool]) *Field[T, bool]

Boolean is a checkbox field.

func Date

func Date[T any](name string, get Getter[T, time.Time]) *Field[T, time.Time]

Date is a calendar date. It is stored and shown without a time zone.

func DateTime

func DateTime[T any](name string, get Getter[T, time.Time]) *Field[T, time.Time]

DateTime is an instant, stored in UTC and shown in the panel's zone.

func File

func File[T any](name string, get Getter[T, string], u Upload) *Field[T, string]

File is a stored file, kept by its storage key.

func Image

func Image[T any](name string, get Getter[T, string], u Upload) *Field[T, string]

Image is a stored image, kept by its storage key, shown as a thumbnail.

func JSON

func JSON[T any](name string, get Getter[T, []byte]) *Field[T, []byte]

JSON is a JSON document field.

func KeyValue

func KeyValue[T any](name string, get Getter[T, []byte]) *Field[T, []byte]

KeyValue is a JSON object of string values, edited as rows.

func Markdown

func Markdown[T any](name string, get Getter[T, string]) *Field[T, string]

Markdown is a string field shown through the panel's WithMarkdown renderer, or as escaped text without one.

func Money

func Money[T any](name string, get Getter[T, int64], currency string) *Field[T, int64]

Money is an amount in integer minor units (cents for USD) of the ISO 4217 currency code. Input is parsed exactly; there are no floats.

func MultiSelect

func MultiSelect[T any](name string, get Getter[T, []string], opts ...Option) *Field[T, []string]

MultiSelect is a list of option values, usually stored with ColJSON.

func Number

func Number[T any, N Numeric](name string, get Getter[T, N]) *Field[T, N]

Number is an integer or float field.

func Select

func Select[T any](name string, get Getter[T, string], opts ...Option) *Field[T, string]

Select is a string field with a fixed or computed list of options.

func Status

func Status[T any](name string, get Getter[T, string], opts ...Option) *Field[T, string]

Status is a Select shown as a toned badge. It is read-only on forms unless Editable.

func Tags

func Tags[T any](name string, get Getter[T, []string]) *Field[T, []string]

Tags is a free-form list of strings, usually stored with ColJSON.

func Text

func Text[T any](name string, get Getter[T, string]) *Field[T, string]

Text is a single-line string field.

func Textarea

func Textarea[T any](name string, get Getter[T, string]) *Field[T, string]

Textarea is a multi-line string field.

func Toggle

func Toggle[T any](name string, get Getter[T, bool]) *Field[T, bool]

Toggle is a switch field.

func (*Field[T, V]) AuditValues

func (f *Field[T, V]) AuditValues() *Field[T, V]

AuditValues records the before and after values in audit metadata.

func (*Field[T, V]) Can

func (f *Field[T, V]) Can(perm rbac.Permission) *Field[T, V]

Can hides the field from subjects without perm everywhere: pages, Live frames, exports, search, form submissions, and audit metadata.

func (*Field[T, V]) CanEdit

func (f *Field[T, V]) CanEdit(perm rbac.Permission) *Field[T, V]

CanEdit makes the field read-only for subjects without perm.

func (*Field[T, V]) Col

func (f *Field[T, V]) Col(c nock.Col[V]) *Field[T, V]

Col binds the field to a column: sorting, searching, and writes use it.

func (*Field[T, V]) ColJSON

func (f *Field[T, V]) ColJSON(c nock.Col[[]byte]) *Field[T, V]

ColJSON binds a list or object field to a column that stores JSON.

func (*Field[T, V]) CreateOnly

func (f *Field[T, V]) CreateOnly() *Field[T, V]

CreateOnly makes the field editable on the create form only.

func (*Field[T, V]) CurrencyFrom

func (f *Field[T, V]) CurrencyFrom(fn func(*T) string) *Field[T, V]

CurrencyFrom reads a Money field's ISO 4217 code from the row.

func (*Field[T, V]) DefaultFunc

func (f *Field[T, V]) DefaultFunc(fn func(ctx context.Context, vals Values) V) *Field[T, V]

DefaultFunc computes the field's initial value on the create form from the form's current values.

func (*Field[T, V]) DependsOn

func (f *Field[T, V]) DependsOn(names ...string) *Field[T, V]

DependsOn re-evaluates this field's VisibleWhen, OptionsFunc, DefaultFunc, and ReadOnlyWhen on the server when the named fields change.

func (*Field[T, V]) Editable

func (f *Field[T, V]) Editable() *Field[T, V]

Editable lets a Status field be changed on forms.

func (*Field[T, V]) Email

func (f *Field[T, V]) Email() *Field[T, V]

Email requires the value to be an email address.

func (*Field[T, V]) ExceptOnForms

func (f *Field[T, V]) ExceptOnForms() *Field[T, V]

ExceptOnForms leaves the field off the create and edit forms.

func (*Field[T, V]) Format

func (f *Field[T, V]) Format(fn func(V) string) *Field[T, V]

Format replaces the display text of a value.

func (*Field[T, V]) Help

func (f *Field[T, V]) Help(s string) *Field[T, V]

Help sets the hint shown under the input.

func (*Field[T, V]) HideFromDetail

func (f *Field[T, V]) HideFromDetail() *Field[T, V]

HideFromDetail leaves the field out of the detail page.

func (*Field[T, V]) HideFromIndex

func (f *Field[T, V]) HideFromIndex() *Field[T, V]

HideFromIndex leaves the field out of the index table.

func (*Field[T, V]) Label

func (f *Field[T, V]) Label(s string) *Field[T, V]

Label sets the field's display label.

func (f *Field[T, V]) Link(fn func(row *T) string) *Field[T, V]

Link makes the displayed value a link to fn(row).

func (*Field[T, V]) Max

func (f *Field[T, V]) Max(v V) *Field[T, V]

Max sets the largest allowed value: minor units for Money.

func (*Field[T, V]) MaxLen

func (f *Field[T, V]) MaxLen(n int) *Field[T, V]

MaxLen sets the longest allowed text length.

func (*Field[T, V]) Min

func (f *Field[T, V]) Min(v V) *Field[T, V]

Min sets the smallest allowed value: minor units for Money.

func (*Field[T, V]) MinLen

func (f *Field[T, V]) MinLen(n int) *Field[T, V]

MinLen sets the shortest allowed text length.

func (*Field[T, V]) Nullable

func (f *Field[T, V]) Nullable() *Field[T, V]

Nullable stores empty input as NULL.

func (*Field[T, V]) OnlyOnDetail

func (f *Field[T, V]) OnlyOnDetail() *Field[T, V]

OnlyOnDetail shows the field on the detail page only.

func (*Field[T, V]) OnlyOnForms

func (f *Field[T, V]) OnlyOnForms() *Field[T, V]

OnlyOnForms shows the field on the create and edit forms only.

func (*Field[T, V]) OnlyOnIndex

func (f *Field[T, V]) OnlyOnIndex() *Field[T, V]

OnlyOnIndex shows the field on the index table only.

func (*Field[T, V]) OptionsFunc

func (f *Field[T, V]) OptionsFunc(fn func(ctx context.Context, vals Values) ([]Option, error)) *Field[T, V]

OptionsFunc computes the field's options from the form's current values.

func (*Field[T, V]) Pattern

func (f *Field[T, V]) Pattern(re string) *Field[T, V]

Pattern requires text values to match the regular expression re.

func (*Field[T, V]) Placeholder

func (f *Field[T, V]) Placeholder(s string) *Field[T, V]

Placeholder sets the input's placeholder text.

func (*Field[T, V]) ReadOnly

func (f *Field[T, V]) ReadOnly() *Field[T, V]

ReadOnly shows the field on forms without letting anyone change it.

func (*Field[T, V]) ReadOnlyWhen

func (f *Field[T, V]) ReadOnlyWhen(fn func(ctx context.Context, row *T) bool) *Field[T, V]

ReadOnlyWhen makes the field read-only for rows where fn is true.

func (*Field[T, V]) Required

func (f *Field[T, V]) Required() *Field[T, V]

Required rejects an empty value.

func (*Field[T, V]) Rows

func (f *Field[T, V]) Rows(n int) *Field[T, V]

Rows sets the height of a Textarea or Markdown input.

func (*Field[T, V]) Searchable

func (f *Field[T, V]) Searchable() *Field[T, V]

Searchable includes the field in the index search.

func (*Field[T, V]) Sensitive

func (f *Field[T, V]) Sensitive() *Field[T, V]

Sensitive keeps the value out of audit metadata, exports, and search.

func (*Field[T, V]) Sortable

func (f *Field[T, V]) Sortable() *Field[T, V]

Sortable lets the index table sort by this field.

func (*Field[T, V]) Step

func (f *Field[T, V]) Step(s string) *Field[T, V]

Step sets the input step of a Number field.

func (*Field[T, V]) Suffix

func (f *Field[T, V]) Suffix(s string) *Field[T, V]

Suffix is shown after a Number value, such as a unit.

func (*Field[T, V]) URL

func (f *Field[T, V]) URL() *Field[T, V]

URL requires the value to be a URL.

func (*Field[T, V]) Unique

func (f *Field[T, V]) Unique() *Field[T, V]

Unique shows a unique-constraint violation as an error on this field.

func (*Field[T, V]) Validate

func (f *Field[T, V]) Validate(fn func(ctx context.Context, v V, vals Values) error) *Field[T, V]

Validate adds a check that runs after the built-in ones.

func (*Field[T, V]) VisibleWhen

func (f *Field[T, V]) VisibleWhen(fn func(ctx context.Context, vals Values) bool) *Field[T, V]

VisibleWhen shows the field on forms only while fn returns true for the form's current values.

type FieldDef

type FieldDef[T any] interface {
	// contains filtered or unexported methods
}

FieldDef is a field of a resource over rows of type T. Build one with a kind constructor such as Text or Money.

type FieldErrors

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

FieldErrors maps field names to messages. Validation and repository errors of this type are shown beside their fields.

func (*FieldErrors) Add

func (e *FieldErrors) Add(name, msg string)

Add records msg for name, keeping the first message per field.

func (*FieldErrors) Error

func (e *FieldErrors) Error() string

func (*FieldErrors) Fields

func (e *FieldErrors) Fields() map[string]string

Fields returns a copy of the messages by field name.

func (*FieldErrors) Get

func (e *FieldErrors) Get(name string) string

Get returns the message for name, or "".

func (*FieldErrors) Len

func (e *FieldErrors) Len() int

Len is the number of invalid fields.

type Filter

type Filter interface {
	// contains filtered or unexported methods
}

Filter narrows an index. All active filters AND together. Build one with FilterIn, FilterBool, FilterDateRange, FilterDateRangeOn, FilterNumberRange, FilterBelongsTo, FilterSelect, or FilterCustom.

func FilterBelongsTo

func FilterBelongsTo[RID comparable, R any](col nock.Col[RID], label string, target *Resource[R, RID]) Filter

FilterBelongsTo filters col to rows of target, picked with a search box that runs as the current subject.

func FilterBool

func FilterBool(col nock.Col[bool], label string) Filter

FilterBool filters col to true or false.

func FilterCustom

func FilterCustom(key, label string, input FilterInput, fn func(ctx context.Context, v FilterValue) (nock.Expr, error)) Filter

FilterCustom compiles its own condition from the submitted value. input picks the control; a select input offers no choices, so use text, bool, daterange, or numberrange.

func FilterDateRange

func FilterDateRange(key, label string) Filter

FilterDateRange is a date range filter that custom repositories read from ListQuery.Filters with DateRange.

func FilterDateRangeOn

func FilterDateRangeOn(col nock.Col[time.Time], label string) Filter

FilterDateRangeOn filters a time column to the chosen dates, inclusive, in the panel's time zone.

func FilterIn

func FilterIn[V comparable](col nock.Col[V], label string, opts ...Option) Filter

FilterIn filters col to the chosen options; several choices are an IN.

func FilterNumberRange

func FilterNumberRange[N Numeric](col nock.Col[N], label string) Filter

FilterNumberRange filters col to an inclusive range; either end may be open.

type FilterInput

type FilterInput string

FilterInput is the control a custom filter shows.

const (
	FilterInputText   FilterInput = "text"
	FilterInputSelect FilterInput = "select"
	FilterInputBool   FilterInput = "bool"
	FilterInputDates  FilterInput = "daterange"
	FilterInputNumber FilterInput = "numberrange"
)

The controls a custom filter can show.

type FilterValue

type FilterValue struct {
	Key, Op string
	Values  []string
}

FilterValue is one active filter of a ListQuery.

type Getter

type Getter[T, V any] func(*T) (V, bool)

Getter reads a field's value from a row; ok=false means NULL.

func Get

func Get[T, V any](fn func(*T) V) Getter[T, V]

Get wraps a getter for a NOT NULL value.

func GetNull

func GetNull[T, V any](fn func(*T) *V) Getter[T, V]

GetNull wraps a getter for a nullable value; nil is NULL.

type Host

type Host = interface {
	NockDB() nock.DB
	AuditRecorder() audit.Recorder
	Authenticator() auth.Authenticator
	AlpineBundle() *alpine.Bundle
	Queue() quiver.Queue
	Store() storage.Store
	ImageService() images.Service
	Broker() pubsub.Broker
}

Host is what a framework hands a panel when it mounts it. fletch.AdminHost is the same interface literal, so the two types are identical while neither module imports the other.

type Input

type Input[In any] struct {
	// contains filtered or unexported fields
}

Input is one typed input of an action's dialog. Its pointer accessor both reads and writes the field of the input struct In, with no reflection.

func InBelongsTo

func InBelongsTo[In any, R any, RID comparable](name string, ptr func(*In) *RID, target *Resource[R, RID]) *Input[In]

InBelongsTo picks a row of target with a search box. The search and the chosen row are checked as the current subject, under target's scope.

func InDate

func InDate[In any](name string, ptr func(*In) *time.Time) *Input[In]

InDate is a date input in the panel's time zone.

func InMoney

func InMoney[In any](name string, ptr func(*In) *int64, currency string) *Input[In]

InMoney is an amount in minor units of currency, entered as a decimal.

func InNumber

func InNumber[In any, N Numeric](name string, ptr func(*In) *N) *Input[In]

InNumber is a whole or decimal number input.

func InSelect

func InSelect[In any](name string, ptr func(*In) *string, opts ...Option) *Input[In]

InSelect picks one of opts.

func InText

func InText[In any](name string, ptr func(*In) *string) *Input[In]

InText is a single-line text input.

func InTextarea

func InTextarea[In any](name string, ptr func(*In) *string) *Input[In]

InTextarea is a multi-line text input.

func InToggle

func InToggle[In any](name string, ptr func(*In) *bool) *Input[In]

InToggle is an on/off switch.

func (*Input[In]) AuditValue

func (in *Input[In]) AuditValue() *Input[In]

AuditValue records the input's value in the action's audit event; other inputs are recorded by name only.

func (*Input[In]) Default

func (in *Input[In]) Default(raw string) *Input[In]

Default is the input's initial value, as it would be typed.

func (*Input[In]) Help

func (in *Input[In]) Help(s string) *Input[In]

Help sets the hint shown under the input.

func (*Input[In]) Label

func (in *Input[In]) Label(s string) *Input[In]

Label sets the input's display label.

func (*Input[In]) Max

func (in *Input[In]) Max(v float64) *Input[In]

Max is the largest allowed number: minor units for InMoney.

func (*Input[In]) MaxLen

func (in *Input[In]) MaxLen(n int) *Input[In]

MaxLen sets the longest allowed text length.

func (*Input[In]) Min

func (in *Input[In]) Min(v float64) *Input[In]

Min is the smallest allowed number: minor units for InMoney.

func (*Input[In]) Required

func (in *Input[In]) Required() *Input[In]

Required rejects an empty value.

func (*Input[In]) Validate

func (in *Input[In]) Validate(fn func(ctx context.Context, x *In) error) *Input[In]

Validate adds a check on the decoded input.

type LensDef

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

LensDef is a named preset of an index: conditions, filter values, a sort, and columns, shown as a tab above the table.

func Lens

func Lens(key, label string, parts ...LensPart) LensDef

Lens defines a preset of the index, such as "Low stock".

type LensPart

type LensPart interface {
	// contains filtered or unexported methods
}

LensPart configures a lens.

func Columns

func Columns(names ...string) LensPart

Columns shows only these fields while the lens is on.

func FilterPreset

func FilterPreset(key string, values ...string) LensPart

FilterPreset sets a filter's value while the lens is on, as if the user had chosen values.

func SortBy

func SortBy(spec string) LensPart

SortBy sorts the lens by a Sortable field; a leading "-" sorts descending.

func Where

func Where(exprs ...nock.Expr) LensPart

Where adds conditions to a lens. They need a NockRepo.

type ListQuery

type ListQuery struct {
	Search string
	// Sort keys are always names of Sortable fields.
	Sort    []SortKey
	Filters []FilterValue
	// Where holds conditions the panel compiled from column-bound fields,
	// such as the search over Searchable columns. NockRepo applies them.
	Where         []nock.Expr
	Lens          string
	Parent        *ParentRef
	Page, PerPage int
	// contains filtered or unexported fields
}

ListQuery is an index request after the panel allow-listed and clamped it.

func (ListQuery) Offset

func (q ListQuery) Offset() int

Offset is the number of rows before the requested page.

type Metric

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

Metric is a dashboard widget. Build one with ValueMetric, TrendMetric, PartitionMetric, or TableWidget and place it with WithDashboard, Resource.Cards, or WidgetOf on a custom page.

func PartitionMetric

func PartitionMetric(key, label string, fn func(ctx context.Context, r Range) ([]Slice, error)) *Metric

PartitionMetric shows how a total splits: a donut for up to six slices, a stacked bar for more, with the smallest beyond eight as "Other".

func TableWidget

func TableWidget[T any](key, label string, fn func(ctx context.Context) ([]T, error), cols ...Column[T]) *Metric

TableWidget is a short table of rows, such as the latest orders.

func TrendMetric

func TrendMetric(key, label string, fn func(ctx context.Context, r Range) ([]Point, error)) *Metric

TrendMetric is a line or bar chart of points over a range.

func ValueMetric

func ValueMetric(key, label string, fn func(ctx context.Context, r Range) (ValueResult, error)) *Metric

ValueMetric is a figure with its change from the previous range.

func (*Metric) Bars

func (m *Metric) Bars() *Metric

Bars draws a trend as bars.

func (*Metric) Bucket

func (m *Metric) Bucket(b Bucket) *Metric

Bucket sets the width of a trend's points. Default Day.

func (*Metric) Can

func (m *Metric) Can(perm rbac.Permission) *Metric

Can shows the widget only to subjects with perm.

func (*Metric) Donut

func (m *Metric) Donut() *Metric

Donut draws a partition as a donut whatever its size.

func (*Metric) Format

func (m *Metric) Format(fn func(int64) string) *Metric

Format shows values with fn, such as FormatMoney("USD"). Default FormatCount.

func (*Metric) Help

func (m *Metric) Help(s string) *Metric

Help is a short note under the title.

func (*Metric) Key

func (m *Metric) Key() string

Key returns the metric's key.

func (*Metric) Line

func (m *Metric) Line() *Metric

Line draws a trend as a line. It is the default.

func (m *Metric) Link(url string, label ...string) *Metric

Link adds a link to the widget's header, such as a lens of the index.

func (*Metric) LowerIsBetter

func (m *Metric) LowerIsBetter() *Metric

LowerIsBetter shows a falling value as good news.

func (*Metric) Ranges

func (m *Metric) Ranges(defs ...RangeDef) *Metric

Ranges sets the periods the metric offers; the first is its default.

func (*Metric) Refresh

func (m *Metric) Refresh(d time.Duration) *Metric

Refresh is how long a result is reused for the same range and roles. Default one minute; 0 computes it on every view.

func (*Metric) Stacked

func (m *Metric) Stacked() *Metric

Stacked draws a partition as a stacked bar whatever its size.

func (*Metric) Width

func (m *Metric) Width(n int) *Metric

Width is how many of the dashboard's four columns the widget spans.

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

NavGroup is a labeled sidebar section that resources join with InGroup.

func Group

func Group(label, icon string, opts ...NavOption) NavGroup

Group declares a sidebar section. Resources whose InGroup names no declared group get a section of their own after the declared ones.

type NavItemOption interface {
	ResourceOption
	PageOption
}

NavItemOption configures how a resource or a custom page appears in the sidebar.

func Hidden

func Hidden() NavItemOption

Hidden leaves a resource or a page out of the sidebar; it stays reachable by URL.

func Icon

func Icon(name string) NavItemOption

Icon names the sidebar icon: package, receipt, users, shopping-cart, tag, folder, file-text, box, settings, inbox, layout-dashboard, or a symbol added with WithIcons.

func InGroup

func InGroup(label string) NavItemOption

InGroup puts a resource or a page in the sidebar group with this label.

func NavBadge(fn func(ctx context.Context) (BadgeValue, error)) NavItemOption

NavBadge computes a sidebar badge on each page render, within a 250ms budget. Results are cached per resource and role set for 30s.

type NavOption interface {
	// contains filtered or unexported methods
}

NavOption configures a NavGroup.

type NockOption

type NockOption interface {
	// contains filtered or unexported methods
}

NockOption configures a NockRepository.

func AfterWrite

func AfterWrite[ID comparable](fn func(ctx context.Context, tx any, id ID, ch Changes) error) NockOption

AfterWrite runs inside the write's transaction after Create and Update, for side effects that must commit with it, such as quiver.EnqueueTx.

func BaseQuery

func BaseQuery(fn func(ctx context.Context) *nock.SelectQuery) NockOption

BaseQuery sets the base query, for joins or computed columns. It must select the primary key. Default: SELECT * FROM table.

func BeforeWrite

func BeforeWrite[ID comparable](fn func(ctx context.Context, tx any, id *ID, ch *Changes) error) NockOption

BeforeWrite runs inside the write's transaction before Create (id nil) and Update, and may add assignments to ch.

func Scope

func Scope(fn func(ctx context.Context) (nock.Expr, error)) NockOption

Scope adds a condition to every List, Find, Update, and Delete, such as a tenant filter. An error denies the call.

func SoftDelete

func SoftDelete(col nock.Col[time.Time]) NockOption

SoftDelete makes Delete set col to the current time, and List and Find skip rows where it is set.

func Unscoped

func Unscoped() NockOption

Unscoped marks a repository that deliberately lists every row, such as one on an internal panel. It changes nothing at run time; it tells fletch check (W0708) that the missing Scope is intended.

func Version

func Version(col nock.Col[time.Time]) NockOption

Version enables optimistic locking on col: an update applies only if the row still has the value the form loaded, and sets it to the current time. Otherwise it fails with ErrConflict.

type NockRepository

type NockRepository[T any, ID comparable] struct {
	// contains filtered or unexported fields
}

NockRepository is a Repository and Writer over one Nock table. Rows scan through nock.All, so a generated ScanRow keeps the path reflection-free.

func NockRepo

func NockRepo[T any, ID comparable](table nock.TableRef, pk nock.Col[ID], opts ...NockOption) *NockRepository[T, ID]

NockRepo returns a repository over table with primary key pk.

func (*NockRepository[T, ID]) Create

func (r *NockRepository[T, ID]) Create(ctx context.Context, ch Changes) (ID, error)

Create inserts a row from ch and returns its ID.

func (*NockRepository[T, ID]) Delete

func (r *NockRepository[T, ID]) Delete(ctx context.Context, id ID) error

Delete deletes the row with id.

func (*NockRepository[T, ID]) Find

func (r *NockRepository[T, ID]) Find(ctx context.Context, id ID) (T, error)

Find returns the row with id, or ErrNotFound when it is missing or out of scope.

func (*NockRepository[T, ID]) List

func (r *NockRepository[T, ID]) List(ctx context.Context, q ListQuery) (Page[T], error)

List returns the page of rows that q selects.

func (*NockRepository[T, ID]) Update

func (r *NockRepository[T, ID]) Update(ctx context.Context, id ID, ch Changes) error

Update applies ch to the row with id.

type Numeric

type Numeric interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}

Numeric constrains the value types of Number fields.

type Option

type Option struct {
	Value, Label string
	// contains filtered or unexported fields
}

Option is one choice of a Select, MultiSelect, or Status field.

func Opt

func Opt(value, label string) Option

Opt returns an option with a stored value and a display label.

func (Option) Disabled

func (o Option) Disabled() Option

Disabled keeps the option visible but not selectable.

func (Option) Tone

func (o Option) Tone(t Tone) Option

Tone sets the badge color of the option.

type OptionItem

type OptionItem struct {
	ID       string
	Title    string
	Subtitle string
}

OptionItem is one row of an Optioner answer.

type Optioner

type Optioner interface {
	Options(ctx context.Context, term string, limit int) ([]OptionItem, error)
}

Optioner is implemented by repositories that answer picker and search lookups more cheaply than List.

type Page

type Page[T any] struct {
	Items []T
	nock.PageMeta
}

Page is one page of rows.

func NewPage

func NewPage[T any](items []T, q ListQuery, total int64) Page[T]

NewPage builds the page q asked for from its rows and the total row count.

type PageDef

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

PageDef is a custom page registered on a panel with Register. It is served at /<panel>/pages/<slug>.

func CustomPage

func CustomPage(slug, title string, newView func() live.Component, opts ...PageOption) *PageDef

CustomPage defines a page of the app's own Live component, rendered inside the panel's shell with its navigation, breadcrumbs, theme, palette, and toasts. Without Can, anyone with the panel's access permission may open it.

type PageOption

type PageOption interface {
	// contains filtered or unexported methods
}

PageOption configures a custom page: InGroup, Icon, NavOrder, NavBadge, Hidden, and Can.

type Panel

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

Panel is one admin panel: its own path, access permission, navigation, resources, brand, and Live endpoints.

func New

func New(id string, opts ...PanelOption) *Panel

New defines a panel. It does no I/O; Register and mounting report every configuration error.

func (*Panel) Adopt

func (p *Panel) Adopt(h Host) error

Adopt fills services the panel was not given from h and checks the panel's configuration. fletch.MountAdmin calls it.

func (*Panel) DashboardEvent

func (p *Panel) DashboardEvent(c *live.Ctx, v *views.DashboardPage, name string, payload json.RawMessage) error

DashboardEvent handles a Live event from the dashboard page.

func (*Panel) DetailEvent

func (p *Panel) DetailEvent(c *live.Ctx, v *views.DetailPage, name string, payload json.RawMessage) error

DetailEvent handles a Live event from a resource's detail page.

func (*Panel) FormEvent

func (p *Panel) FormEvent(c *live.Ctx, v *views.FormPage, name string, payload json.RawMessage) error

FormEvent handles a Live event from the create or edit form.

func (*Panel) Handler

func (p *Panel) Handler() http.Handler

Handler serves the panel under Path. It panics when the panel is misconfigured; Adopt reports the same errors as a value.

func (*Panel) ID

func (p *Panel) ID() string

ID returns the panel id.

func (*Panel) IndexEvent

func (p *Panel) IndexEvent(c *live.Ctx, v *views.IndexPage, name string, payload json.RawMessage) error

IndexEvent handles a Live event from a resource's index page.

func (*Panel) InspectJSON

func (p *Panel) InspectJSON() ([]byte, error)

InspectJSON describes the panel as registered: its resources with their fields, filters, lenses, relations, actions, and record pages; custom pages; dashboard widgets; permissions; routes; and the W07xx diagnostics it finds in its own definition. fletch.MountAdmin reads it for `fletch ax inspect admin` and fletch check.

func (*Panel) LiveHandlers

func (p *Panel) LiveHandlers() []*live.Handler

LiveHandlers returns the panel's Live handlers once it serves, so a host can close their sessions on logout and shutdown. fletch.MountAdmin adds them to the app's set.

func (*Panel) Mount

func (p *Panel) Mount(r *router.Router)

Mount serves the panel and its scripts on a Fletch router.

func (*Panel) MountDashboard

func (p *Panel) MountDashboard(c *live.Ctx, v *views.DashboardPage) error

MountDashboard is the dashboard page's Live mount hook, called by the panel's views.

func (*Panel) MountDetail

func (p *Panel) MountDetail(c *live.Ctx, v *views.DetailPage) error

MountDetail is the detail page's Live mount hook, called by the panel's views.

func (*Panel) MountForm

func (p *Panel) MountForm(c *live.Ctx, v *views.FormPage) error

MountForm is the create and edit form's Live mount hook, called by the panel's views.

func (*Panel) MountIndex

func (p *Panel) MountIndex(c *live.Ctx, v *views.IndexPage) error

MountIndex and the other Live backend methods are called by the views; they are not part of the admin API.

func (*Panel) MountPalette

func (p *Panel) MountPalette(c *live.Ctx, v *views.Palette) error

MountPalette is the command palette's Live mount hook, called by the panel's views.

func (*Panel) PaletteEvent

func (p *Panel) PaletteEvent(c *live.Ctx, v *views.Palette, name string, payload json.RawMessage) error

PaletteEvent handles a Live event from the command palette.

func (*Panel) Path

func (p *Panel) Path() string

Path returns the mount prefix, such as /admin.

func (*Panel) Permissions

func (p *Panel) Permissions() []rbac.Permission

Permissions lists every permission the panel checks, sorted, so apps can seed roles.

func (*Panel) Register

func (p *Panel) Register(items ...Registrable) error

Register adds resources. It returns every definition error at once.

func (*Panel) Routes

func (p *Panel) Routes() []Route

Routes returns the panel's routes plus the Alpine and Live client scripts it loads, for a standalone http.ServeMux. For several panels on one mux use Mount, which registers the shared scripts once.

func (*Panel) RunMiddleware

func (p *Panel) RunMiddleware() quiver.Middleware

RunMiddleware tracks the jobs of queued actions and of Enqueue: it marks the run running, lets Progress report, heartbeats the run, and records whether the job succeeded, will be retried, or failed. The panel adds it to its WithQueue queue; add it yourself to queues of worker processes that do not serve the panel.

func (*Panel) State

func (p *Panel) State() StateStore

State returns the panel's StateStore; nil until Handler, Mount, or fletch.MountAdmin has built the panel.

type PanelOption

type PanelOption func(*Panel)

PanelOption configures a Panel.

func WithAccess

func WithAccess(perm rbac.Permission) PanelOption

WithAccess sets the permission needed to use the panel at all. Default "<id>:access".

func WithAlpine

func WithAlpine(b *alpine.Bundle) PanelOption

WithAlpine serves pages with this Alpine bundle's CSP build.

func WithAudit

func WithAudit(r audit.Recorder) PanelOption

WithAudit records events after commit.

func WithAuth

func WithAuth(a auth.Authenticator) PanelOption

WithAuth identifies callers. Under fletch.MountAdmin it defaults to the app's authenticator.

func WithBrand

func WithBrand(b Brand) PanelOption

WithBrand sets the panel's name, logo, favicon, and home link.

func WithBroker

func WithBroker(b pubsub.Broker) PanelOption

WithBroker publishes queued-run progress on b, so every node's views see it. With no broker, or a memory broker on several nodes, views poll the StateStore instead. Default from the host.

func WithBulkLimit

func WithBulkLimit(n int) PanelOption

WithBulkLimit caps the rows of one synchronous bulk action; bigger sets need a queued action. Default 500.

func WithCSRFSecret

func WithCSRFSecret(secret []byte) PanelOption

WithCSRFSecret installs auth.CSRF inside a standalone panel.

func WithCSRFToken

func WithCSRFToken(fn func(*http.Request) string) PanelOption

WithCSRFToken tells the panel the request's CSRF token, for apps with their own CSRF middleware. Default auth.CSRFTokenFromRequest.

func WithClock

func WithClock(now func() time.Time) PanelOption

WithClock sets the clock dashboard ranges resolve against, for tests and screenshots. Default time.Now.

func WithDB

func WithDB(db nock.DB) PanelOption

WithDB is the database NockRepo resources use and the default transaction runner.

func WithDashboard

func WithDashboard(ms ...*Metric) PanelOption

WithDashboard places widgets on the panel's overview, in order.

func WithExportLimit

func WithExportLimit(n int) PanelOption

WithExportLimit caps the rows of one CSV export. Default 100000.

func WithIcons

func WithIcons(fsys fs.FS) PanelOption

WithIcons adds SVG <symbol> elements (id="i-<name>") to the icon sprite from every .svg file in fsys.

func WithImages

func WithImages(s images.Service) PanelOption

WithImages renders Image thumbnails through s. Without it, thumbnails are the stored image, served by the panel after a view check.

func WithLiveOptions

func WithLiveOptions(opts ...live.Option) PanelOption

WithLiveOptions passes options to every Live handler of the panel.

func WithLoginURL

func WithLoginURL(url string) PanelOption

WithLoginURL redirects unauthenticated page requests to url?next=<path>; other requests get 401.

func WithMarkdown

func WithMarkdown(fn func(ctx context.Context, src string) (crest.Component, error)) PanelOption

WithMarkdown renders Markdown fields. The renderer must sanitize its output; without one, Markdown shows as escaped text.

func WithMoneyFormat

func WithMoneyFormat(fn func(minor int64, code string) string) PanelOption

WithMoneyFormat replaces the en-US money display.

func WithNav

func WithNav(groups ...NavGroup) PanelOption

WithNav declares sidebar groups and their order.

func WithPath

func WithPath(prefix string) PanelOption

WithPath sets the mount prefix, such as /partners. Default "/" + id.

func WithPolicy

func WithPolicy(pol *rbac.Policy) PanelOption

WithPolicy sets the rbac policy every check runs through. Required.

func WithQueue

func WithQueue(q quiver.Queue) PanelOption

WithQueue runs queued actions and Enqueue on q. The panel adds RunMiddleware to q when it starts serving. Default from the host.

func WithSecureHeaders

func WithSecureHeaders(on bool) PanelOption

WithSecureHeaders turns the panel's own strict security headers and CSP on or off. Default on for standalone panels; fletch.MountAdmin leaves headers to the app.

func WithState

func WithState(s StateStore) PanelOption

WithState sets where the panel keeps saved views, column choices, action runs, and uploads. Default NockState over WithDB's database (add Tables to its schema), else MemoryState.

func WithStorage

func WithStorage(s storage.Store) PanelOption

WithStorage keeps File and Image uploads in s. Default from the host.

func WithSubject

func WithSubject(fn func(ctx context.Context, userID string) (rbac.Subject, error)) PanelOption

WithSubject maps an authenticated user to roles and attributes. Required.

func WithSubjectTTL

func WithSubjectTTL(d time.Duration) PanelOption

WithSubjectTTL sets how long a resolved subject is reused; Live events re-resolve after it. Default 30s.

func WithTheme

func WithTheme(t Theme) PanelOption

WithTheme overrides the panel's design tokens and color scheme.

func WithTimeZone

func WithTimeZone(loc *time.Location) PanelOption

WithTimeZone sets the zone dates are shown and entered in. Default UTC.

func WithTx

func WithTx(fn func(ctx context.Context, fn func(ctx context.Context, tx any) error) error) PanelOption

WithTx sets a custom transaction runner, such as pgx.BeginFunc.

func WithTxAudit

func WithTxAudit(fn func(tx any) audit.Recorder) PanelOption

WithTxAudit records events inside the write's transaction, so a write and its audit event commit or roll back together.

func WithUploadKey

func WithUploadKey(key []byte) PanelOption

WithUploadKey signs upload tokens. Nodes behind one load balancer need the same key; the default is random per process.

type ParentRef

type ParentRef struct {
	Relation string
	ID       any
}

ParentRef names the parent row of a relation manager.

type Pivot

type Pivot[ID, RID comparable] struct {
	Table   nock.TableRef
	Parent  nock.Col[ID]
	Related nock.Col[RID]
}

Pivot is the join table of a BelongsToMany relation.

type Point

type Point struct {
	At    time.Time
	Value int64
}

Point is one value of a trend, at the start of its bucket.

type Range

type Range struct {
	From, To time.Time
	Key      string
}

Range is the period a metric is computed over: [From, To) in the panel's time zone. Key names the RangeDef it came from, such as "30d".

func (Range) Previous

func (r Range) Previous() Range

Previous is the range of the same length that ends where r starts.

type RangeDef

type RangeDef struct {
	Key, Label string
	// Compare describes the previous range, as in "compared to previous 30 days".
	Compare string
	// contains filtered or unexported fields
}

RangeDef is a period a dashboard offers, resolved against the clock and the panel's time zone each time a metric runs.

func Days

func Days(n int) RangeDef

Days is the last n days, today included.

func (RangeDef) Resolve

func (d RangeDef) Resolve(now time.Time) Range

Resolve returns the range at now, in now's location.

type RecordPageDef

type RecordPageDef[T any, ID comparable] struct {
	// contains filtered or unexported fields
}

RecordPageDef is a custom page about one record of a resource, added with Resource.Pages and served at /<panel>/<resource>/<id>/<slug>.

func RecordPage

func RecordPage[T any, ID comparable](slug, title string, newView func() live.Component, opts ...PageOption) *RecordPageDef[T, ID]

RecordPage defines a page about one record, such as an order's fulfillment screen. Opening it needs the resource's view permission on that record, plus Can when set. The view reads its record with CurrentRecord.

type Registrable

type Registrable interface {
	// contains filtered or unexported methods
}

Registrable is something a Panel can register: a resource or a custom page.

type RelationDef

type RelationDef[ID comparable] struct {
	// contains filtered or unexported fields
}

RelationDef is a relation manager on the detail view of a resource keyed by ID. Build one with HasMany, HasManyVia, or BelongsToMany.

func BelongsToMany

func BelongsToMany[ID comparable, R any, RID comparable](name string, target *Resource[R, RID], pivot Pivot[ID, RID]) *RelationDef[ID]

BelongsToMany lists the rows of target joined to the parent through pivot. Attach and Detach insert and delete pivot rows in the panel's transaction, audited as admin.<kind>.attach and .detach, and need update on the parent. target needs a NockRepo.

func HasMany

func HasMany[ID comparable, C any, CID comparable](name string, child *Resource[C, CID], fk nock.Col[ID]) *RelationDef[ID]

HasMany lists the rows of child whose fk column holds the parent's ID. child needs a NockRepo; use HasManyVia for other repositories. Create opens child's form with fk set to the parent and locked.

func HasManyVia

func HasManyVia[ID comparable, C any, CID comparable](name string, child *Resource[C, CID]) *RelationDef[ID]

HasManyVia lists rows of child through child's own repository, which reads the parent from ListQuery.Parent.

func (*RelationDef[ID]) Can

func (r *RelationDef[ID]) Can(perm rbac.Permission) *RelationDef[ID]

Can shows the relation only to subjects with perm.

func (*RelationDef[ID]) Columns

func (r *RelationDef[ID]) Columns(names ...string) *RelationDef[ID]

Columns picks the child fields the manager shows. Default: the child's index columns.

func (*RelationDef[ID]) Inline

func (r *RelationDef[ID]) Inline() *RelationDef[ID]

Inline shows the manager on the parent's edit view too.

func (*RelationDef[ID]) Label

func (r *RelationDef[ID]) Label(s string) *RelationDef[ID]

Label sets the tab label. Default: the name.

func (*RelationDef[ID]) PerPage

func (r *RelationDef[ID]) PerPage(n int) *RelationDef[ID]

PerPage sets the manager's page size. Default 10.

type Repository

type Repository[T any, ID comparable] interface {
	List(ctx context.Context, q ListQuery) (Page[T], error)
	// Find returns ErrNotFound when the row is missing or out of scope.
	Find(ctx context.Context, id ID) (T, error)
}

Repository is what a resource reads through. Writes, streaming, and option lookup are optional: a repository that does not implement Writer makes its resource read-only.

type Resource

type Resource[T any, ID comparable] struct {
	// contains filtered or unexported fields
}

Resource is a typed admin resource over rows of type T keyed by ID.

func NewResource

func NewResource[T any, ID comparable](slug string, repo Repository[T, ID], opts ...ResourceOption) *Resource[T, ID]

NewResource defines a resource served at /<panel>/<slug>.

func (*Resource[T, ID]) Actions

func (r *Resource[T, ID]) Actions(as ...ActionDef[T, ID]) *Resource[T, ID]

Actions adds row and bulk actions.

func (*Resource[T, ID]) Cards

func (r *Resource[T, ID]) Cards(ms ...*Metric) *Resource[T, ID]

Cards places widgets above the resource's index.

func (*Resource[T, ID]) Fields

func (r *Resource[T, ID]) Fields(fs ...FieldDef[T]) *Resource[T, ID]

Fields sets the resource's fields, in display order.

func (*Resource[T, ID]) Filters

func (r *Resource[T, ID]) Filters(fs ...Filter) *Resource[T, ID]

Filters adds the filters of the index's filter bar.

func (*Resource[T, ID]) Key

func (r *Resource[T, ID]) Key(fn func(*T) ID) *Resource[T, ID]

Key reads the row's ID. Required.

func (*Resource[T, ID]) Lenses

func (r *Resource[T, ID]) Lenses(ls ...LensDef) *Resource[T, ID]

Lenses adds presets shown as tabs above the index.

func (*Resource[T, ID]) Pages

func (r *Resource[T, ID]) Pages(ps ...*RecordPageDef[T, ID]) *Resource[T, ID]

Pages adds record pages, linked from the record's detail view.

func (*Resource[T, ID]) Relations

func (r *Resource[T, ID]) Relations(rs ...*RelationDef[ID]) *Resource[T, ID]

Relations adds relation managers to the detail view.

func (*Resource[T, ID]) Subtitle

func (r *Resource[T, ID]) Subtitle(fn func(*T) string) *Resource[T, ID]

Subtitle is shown under the title on the detail view.

func (*Resource[T, ID]) Title

func (r *Resource[T, ID]) Title(fn func(*T) string) *Resource[T, ID]

Title is the row's display name. Required.

type ResourceOption

type ResourceOption interface {
	// contains filtered or unexported methods
}

ResourceOption configures a resource.

func DefaultSort

func DefaultSort(key string, desc bool) ResourceOption

DefaultSort orders the index by a Sortable field when the URL names none.

func GlobalSearch

func GlobalSearch(n int) ResourceOption

GlobalSearch lists up to n matching rows of the resource in the panel's Cmd+K palette, n from 1 to 20. The search runs as the subject, through the resource's repository and scope, over its Searchable fields that the subject may see and that are not Sensitive (or through its Optioner).

func IDCodec

func IDCodec(parse func(string) (any, error), format func(any) string) ResourceOption

IDCodec parses and formats IDs of a type other than string, int, int32, and int64.

func Kind

func Kind(kind string) ResourceOption

Kind sets the rbac kind, the part before the colon in "product:update". Default: the slug without a trailing s.

func Labels

func Labels(singular, plural string) ResourceOption

Labels sets the singular and plural names, such as "Product", "Products".

func PerPage

func PerPage(n int, choices ...int) ResourceOption

PerPage sets the default page size and the choices offered.

func RequireTxAudit

func RequireTxAudit() ResourceOption

RequireTxAudit refuses to register the resource on a panel without WithTxAudit, so its writes and their audit events commit together.

type Result

type Result interface {
	// contains filtered or unexported methods
}

Result is what an action returns to the user.

func Redirect

func Redirect(url string) Result

Redirect sends the user to a same-origin path after the action.

func Refresh

func Refresh() Result

Refresh reloads the current view after the action.

func Toast

func Toast(msg string) Result

Toast shows msg after the action.

func Toastf

func Toastf(format string, args ...any) Result

Toastf is Toast with fmt.Sprintf.

type Route

type Route struct {
	Prefix  string
	Handler http.Handler
}

Route is a prefix and its handler, for mounting a panel on any mux.

type RunEvent

type RunEvent struct {
	ID     string   `json:"id"`
	State  RunState `json:"state"`
	Done   int      `json:"done"`
	Total  int      `json:"total"`
	Note   string   `json:"note,omitempty"`
	Result string   `json:"result,omitempty"`
	Error  string   `json:"error,omitempty"`
}

RunEvent is a change of an action run, published on the topic "admin.run.<id>" of the panel's broker.

type RunInfo

type RunInfo struct {
	ID string
}

RunInfo identifies one run of an action. ID is minted when the dialog opens, so a double submit finds the first run; pass it to services as an idempotency key.

func Enqueue

func Enqueue[A quiver.JobArgs](ctx context.Context, label string, args A, opts ...quiver.EnqueueOption) (RunInfo, error)

Enqueue starts a run named label for a custom page and enqueues args for it. Watch it with WatchRun.

func RunFrom

func RunFrom(ctx context.Context) (RunInfo, bool)

RunFrom returns the admin run a job is working on, when it carries one.

type RunProgress

type RunProgress struct {
	Done, Total int
	Note        string
}

RunProgress is how far a run is. It is set, never added to, so a redelivered job reports the same numbers.

type RunRecord

type RunRecord struct {
	ID       string
	Panel    string
	Resource string
	Action   string
	Subject  string
	State    RunState
	RunProgress
	// Result is the outcome shown to the user, such as a toast.
	Result    string
	Error     string
	CreatedAt time.Time
	UpdatedAt time.Time
}

RunRecord is one action run.

type RunState

type RunState string

RunState is where an action run is.

const (
	RunQueued    RunState = "queued"
	RunRunning   RunState = "running"
	RunRetrying  RunState = "retrying"
	RunSucceeded RunState = "succeeded"
	RunFailed    RunState = "failed"
)

The states of an action run.

type RunUpdate

type RunUpdate struct {
	State    RunState
	Progress *RunProgress
	Result   string
	Error    string
}

RunUpdate changes a run. Zero fields leave the run as it is.

type SavedView

type SavedView struct {
	ID       string
	Panel    string
	Resource string
	// Subject is the owner.
	Subject string
	Name    string
	// Query is the index URL query, such as "q=bolt&sort=-price_cents".
	Query   string
	Columns []string
	// Shared shows the view to everyone in the panel.
	Shared    bool
	CreatedAt time.Time
}

SavedView is an index query a user saved under a name.

type SelectFilter

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

SelectFilter is a key-only select filter for custom repositories.

func FilterSelect

func FilterSelect(key, label string, opts ...Option) *SelectFilter

FilterSelect is a select filter that custom repositories read from ListQuery.Filters. Values are checked against opts.

func (*SelectFilter) Multiple

func (f *SelectFilter) Multiple() *SelectFilter

Multiple lets the filter take several values, an IN.

type Slice

type Slice struct {
	Label string
	Value int64
	Tone  Tone
}

Slice is one part of a partition. Tone colors it; without one it takes the next series color.

type SortKey

type SortKey struct {
	Key  string
	Desc bool
}

SortKey is one key of a multi-column sort.

type StateStore

type StateStore interface {
	// SavedViews lists subject's views of resource plus the views others
	// shared with the panel, sorted by name.
	SavedViews(ctx context.Context, panel, resource, subject string) ([]SavedView, error)
	// SaveView creates or replaces the view with v.ID.
	SaveView(ctx context.Context, v SavedView) error
	// DeleteView deletes a view; ErrNotFound when there is none.
	DeleteView(ctx context.Context, id string) error
	// Columns returns subject's visible columns of resource, or nil when
	// they never chose.
	Columns(ctx context.Context, panel, resource, subject string) ([]string, error)
	SetColumns(ctx context.Context, panel, resource, subject string, cols []string) error
	// BeginRun records r and returns it with true, or returns the run
	// already recorded under r.ID with false, so a double submit gets the
	// first run.
	BeginRun(ctx context.Context, r RunRecord) (RunRecord, bool, error)
	// UpdateRun applies u and moves UpdatedAt, even when u is empty, which
	// makes it the heartbeat. ErrNotFound when there is no such run.
	UpdateRun(ctx context.Context, id string, u RunUpdate) error
	// Run returns a run; ErrNotFound when there is none.
	Run(ctx context.Context, id string) (RunRecord, error)
	Uploads() UploadLedger
}

StateStore keeps what a panel remembers between requests: saved views, column choices, action runs, and the upload ledger. MemoryState is the default without WithDB; NockState keeps it in the tables of Tables.

func MemoryState

func MemoryState() StateStore

MemoryState returns a StateStore in process memory: one process only, lost on restart.

func NockState

func NockState(db nock.DB) StateStore

NockState returns a StateStore over the tables of Tables in db. Inside a panel write it joins the write's transaction.

type Streamer

type Streamer[T any] interface {
	Each(ctx context.Context, q ListQuery, fn func(*T) error) error
}

Streamer is implemented by repositories that can stream every row of a query, for exports.

type Theme

type Theme struct {
	// Accent and AccentDark (#rgb or #rrggbb) set --admin-accent in light
	// and dark mode; the on-accent text color is derived from each.
	Accent, AccentDark string
	Mode               ThemeMode
	// Tokens overrides any --admin-* custom property.
	Tokens map[string]string
	// Stylesheets are extra same-origin stylesheets loaded after admin.css.
	Stylesheets []string
	Density     Density
}

Theme overrides the panel's design tokens. Everything is written to a hashed theme.css, so pages carry no inline style attribute.

type ThemeMode

type ThemeMode string

ThemeMode is the default color scheme. Users can switch; their choice is kept in localStorage under admin.<panel id>.theme.

const (
	ThemeSystem ThemeMode = "system"
	ThemeLight  ThemeMode = "light"
	ThemeDark   ThemeMode = "dark"
)

The color schemes a panel can default to.

type Tone

type Tone string

Tone colors badges, statuses, and option chips.

const (
	Neutral Tone = "neutral"
	Info    Tone = "info"
	Success Tone = "success"
	Warning Tone = "warning"
	Danger  Tone = "danger"
)

The tones a badge or chip can have.

type Upload

type Upload struct {
	Prefix string
	// MaxBytes is the largest accepted file. Required.
	MaxBytes int64
	// Accept is the MIME allow-list, checked against the file's bytes, not
	// the browser's claim. Image defaults to JPEG, PNG, WebP, and GIF.
	Accept     []string
	Visibility storage.Visibility
	// Preset is the images preset of thumbnails (Image only).
	Preset string
}

Upload configures a File or Image field. Keys are minted by the server as <Prefix>/<yyyy>/<mm>/<random>.<ext>; the browser never names one.

type UploadLedger

type UploadLedger interface {
	// Begin records an uncommitted upload. A key already recorded is an
	// error.
	Begin(ctx context.Context, u UploadRecord) error
	// Get returns an upload; ErrNotFound when there is none or it is
	// claimed.
	Get(ctx context.Context, key string) (UploadRecord, error)
	// Commit marks an upload as saved; ErrNotFound when there is none or it
	// is claimed.
	Commit(ctx context.Context, key string) error
	// Release claims a saved upload whose record no longer uses it, for
	// deletion; ErrNotFound when there is none.
	Release(ctx context.Context, key string) error
	// Sweep claims the uncommitted uploads begun before t and returns them,
	// with every claim not yet forgotten, for the caller to delete from
	// storage.
	Sweep(ctx context.Context, before time.Time) ([]UploadRecord, error)
	// Forget removes a claimed upload once its object is deleted.
	Forget(ctx context.Context, key string) error
}

UploadLedger tracks uploads from the moment a key is minted until a save commits it, so abandoned objects can be swept. A store that joins the panel's transaction, as NockState does, commits an upload together with the record that uses it.

Commit and Sweep race for an uncommitted upload and exactly one wins: a committed upload is never claimed, and a claimed one cannot be committed. A claimed upload reads as gone until Forget.

type UploadRecord

type UploadRecord struct {
	Key         string
	Panel       string
	Resource    string
	Field       string
	Subject     string
	ContentType string
	Size        int64
	Committed   bool
	CreatedAt   time.Time
}

UploadRecord is one upload in the ledger.

type ValueResult

type ValueResult struct{ Current, Previous int64 }

ValueResult is a figure for a range and the range before it. Values are integers: cents, counts, or basis points.

type Values

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

Values is the in-progress state of a form, for DependsOn callbacks.

type Writer

type Writer[T any, ID comparable] interface {
	Create(ctx context.Context, ch Changes) (ID, error)
	Update(ctx context.Context, id ID, ch Changes) error
	Delete(ctx context.Context, id ID) error
}

Writer is implemented by repositories whose rows the panel may create, update, and delete.

Directories

Path Synopsis
Package admintest drives admin panels in tests: a header-based authenticator, a fixed subject table for switching roles, an HTTP client that handles CSRF, and a Live client for index and form events over the SSE+POST transport admin panels serve.
Package admintest drives admin panels in tests: a header-based authenticator, a fixed subject table for switching roles, an HTTP client that handles CSRF, and a Live client for index and form events over the SSE+POST transport admin panels serve.
internal
assets
Package assets embeds the admin's stylesheet, script, and icon sprite and serves them under content-hashed names.
Package assets embeds the admin's stylesheet, script, and icon sprite and serves them under content-hashed names.
views
Package views holds the admin's Crest templates and the plain data they render.
Package views holds the admin's Crest templates and the plain data they render.
Package ui holds the Crest components admin views are made of, for custom admin pages.
Package ui holds the Crest components admin views are made of, for custom admin pages.

Jump to

Keyboard shortcuts

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