Documentation
¶
Overview ¶
Package sight 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. A Plugin adds a whole feature to a panel. See docs/sight.md and docs/plugins.md.
Index ¶
- Variables
- func Actor(ctx context.Context) string
- func Audit(ctx context.Context, action, resource string, meta map[string]any) error
- func AuditEvent(ctx context.Context, ev audit.Event) error
- func CSPSources(p *Panel) map[string][]string
- func Change[V any](c Changes, name string) (v V, set bool, null bool)
- func CountOf(q *nock.SelectQuery, at nock.Col[time.Time]) func(ctx context.Context, r Range) (ValueResult, error)
- func CurrentID(c *live.Ctx) string
- func CurrentRecord[T any, ID comparable](c *live.Ctx, r *Resource[T, ID]) (*T, error)
- func CurrentTx(ctx context.Context) any
- func DateRange(ctx context.Context, v FilterValue) (from, to time.Time)
- func Exec(ctx context.Context) nock.Executor
- func FieldError(name, msg string) error
- func FormatCount(v int64) string
- func FormatMoney(code string) func(int64) string
- func FormatPercentBP(v int64) string
- func ImageAuthorizer(next images.Authorizer) images.Authorizer
- func ImpersonationAudit(rec audit.Recorder) func(ctx context.Context, e auth.ImpersonationEvent) error
- func Mount(mux *http.ServeMux, panels ...*Panel) error
- func NavOrder(n int) interface{ ... }
- func Notify(c *live.Ctx, tone Tone, msg string) error
- func Progress(ctx context.Context, done, total int, note string)
- func Require(ctx context.Context, perm rbac.Permission) error
- func RunMeta(run RunInfo) []quiver.EnqueueOption
- func SQLAudit(tx any) audit.Recorder
- func StrictCSP() secure.Config
- func SumOf(q *nock.SelectQuery, value nock.Col[int64], at nock.Col[time.Time]) func(ctx context.Context, r Range) (ValueResult, error)
- func SweepUploads(ctx context.Context, p *Panel, olderThan time.Duration) (int, error)
- func TrendOf(q *nock.SelectQuery, at nock.Col[time.Time], value nock.Col[int64], b Bucket) func(ctx context.Context, r Range) ([]Point, error)
- func Tx(ctx context.Context, fn func(ctx context.Context, tx any) error) error
- func ValueOf[V any](vals Values, name string) (V, bool)
- func WatchRun(c *live.Ctx, id string, fn func(c *live.Ctx, ev RunEvent) error) error
- func WidgetOf(ctx context.Context, m *Metric, rangeKey string) ui.WidgetData
- type ActionBuilder
- func (a *ActionBuilder[T, ID, In]) Both() *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Bulk() *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Can(perm rbac.Permission) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Confirm(title string, body ...string) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Destructive() *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Form(inputs ...*Input[In]) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) JobKind(kind string) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Queue(...) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Row() *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Run(fn func(ctx context.Context, rows []*T, in In, run RunInfo) (Result, error)) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Timeout(d time.Duration) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Transactional() *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) Validate(fn func(ctx context.Context, rows []*T, in *In) error) *ActionBuilder[T, ID, In]
- func (a *ActionBuilder[T, ID, In]) When(fn func(ctx context.Context, row *T) bool) *ActionBuilder[T, ID, In]
- type ActionDef
- type Asset
- type AssetKind
- type BadgeValue
- type Brand
- type Bucket
- type CanOption
- type Changes
- type Column
- type Density
- type Field
- func Badge[T any](name string, fn func(*T) (string, Tone)) *Field[T, string]
- func BelongsTo[T any, R any, RID comparable](name string, get Getter[T, RID], target *Resource[R, RID]) *Field[T, RID]
- func Boolean[T any](name string, get Getter[T, bool]) *Field[T, bool]
- func Date[T any](name string, get Getter[T, time.Time]) *Field[T, time.Time]
- func DateTime[T any](name string, get Getter[T, time.Time]) *Field[T, time.Time]
- func File[T any](name string, get Getter[T, string], u Upload) *Field[T, string]
- func Files[T any](name string, get Getter[T, []string], u Upload) *Field[T, []string]
- func Image[T any](name string, get Getter[T, string], u Upload) *Field[T, string]
- func Images[T any](name string, get Getter[T, []string], u Upload) *Field[T, []string]
- func JSON[T any](name string, get Getter[T, []byte]) *Field[T, []byte]
- func KeyValue[T any](name string, get Getter[T, []byte]) *Field[T, []byte]
- func Markdown[T any](name string, get Getter[T, string]) *Field[T, string]
- func Money[T any](name string, get Getter[T, int64], currency string) *Field[T, int64]
- func MultiSelect[T any](name string, get Getter[T, []string], opts ...Option) *Field[T, []string]
- func Number[T any, N Numeric](name string, get Getter[T, N]) *Field[T, N]
- func Select[T any](name string, get Getter[T, string], opts ...Option) *Field[T, string]
- func Status[T any](name string, get Getter[T, string], opts ...Option) *Field[T, string]
- func Tags[T any](name string, get Getter[T, []string]) *Field[T, []string]
- func Text[T any](name string, get Getter[T, string]) *Field[T, string]
- func Textarea[T any](name string, get Getter[T, string]) *Field[T, string]
- func Toggle[T any](name string, get Getter[T, bool]) *Field[T, bool]
- func (f *Field[T, V]) Action(a FieldAction) *Field[T, V]
- func (f *Field[T, V]) AuditValues() *Field[T, V]
- func (f *Field[T, V]) Can(perm rbac.Permission) *Field[T, V]
- func (f *Field[T, V]) CanEdit(perm rbac.Permission) *Field[T, V]
- func (f *Field[T, V]) Col(c nock.Col[V]) *Field[T, V]
- func (f *Field[T, V]) ColJSON(c nock.Col[[]byte]) *Field[T, V]
- func (f *Field[T, V]) CreateOnly() *Field[T, V]
- func (f *Field[T, V]) CurrencyFrom(fn func(*T) string) *Field[T, V]
- func (f *Field[T, V]) DefaultFunc(fn func(ctx context.Context, vals Values) V) *Field[T, V]
- func (f *Field[T, V]) DependsOn(names ...string) *Field[T, V]
- func (f *Field[T, V]) Editable() *Field[T, V]
- func (f *Field[T, V]) Email() *Field[T, V]
- func (f *Field[T, V]) ExceptOnForms() *Field[T, V]
- func (f *Field[T, V]) Format(fn func(V) string) *Field[T, V]
- func (f *Field[T, V]) Help(s string) *Field[T, V]
- func (f *Field[T, V]) HideFromDetail() *Field[T, V]
- func (f *Field[T, V]) HideFromIndex() *Field[T, V]
- func (f *Field[T, V]) HideWhenEmpty() *Field[T, V]
- func (f *Field[T, V]) Label(s string) *Field[T, V]
- func (f *Field[T, V]) Link(fn func(row *T) string) *Field[T, V]
- func (f *Field[T, V]) Max(v V) *Field[T, V]
- func (f *Field[T, V]) MaxLen(n int) *Field[T, V]
- func (f *Field[T, V]) Min(v V) *Field[T, V]
- func (f *Field[T, V]) MinLen(n int) *Field[T, V]
- func (f *Field[T, V]) Nullable() *Field[T, V]
- func (f *Field[T, V]) OnlyOnDetail() *Field[T, V]
- func (f *Field[T, V]) OnlyOnForms() *Field[T, V]
- func (f *Field[T, V]) OnlyOnIndex() *Field[T, V]
- func (f *Field[T, V]) OptionsFunc(fn func(ctx context.Context, vals Values) ([]Option, error)) *Field[T, V]
- func (f *Field[T, V]) Pattern(re string) *Field[T, V]
- func (f *Field[T, V]) Placeholder(s string) *Field[T, V]
- func (f *Field[T, V]) ReadOnly() *Field[T, V]
- func (f *Field[T, V]) ReadOnlyWhen(fn func(ctx context.Context, row *T) bool) *Field[T, V]
- func (f *Field[T, V]) Required() *Field[T, V]
- func (f *Field[T, V]) Rows(n int) *Field[T, V]
- func (f *Field[T, V]) Searchable() *Field[T, V]
- func (f *Field[T, V]) Sensitive() *Field[T, V]
- func (f *Field[T, V]) Sortable() *Field[T, V]
- func (f *Field[T, V]) Span(n int) *Field[T, V]
- func (f *Field[T, V]) Step(s string) *Field[T, V]
- func (f *Field[T, V]) Suffix(s string) *Field[T, V]
- func (f *Field[T, V]) URL() *Field[T, V]
- func (f *Field[T, V]) Unique() *Field[T, V]
- func (f *Field[T, V]) Validate(fn func(ctx context.Context, v V, vals Values) error) *Field[T, V]
- func (f *Field[T, V]) VisibleWhen(fn func(ctx context.Context, vals Values) bool) *Field[T, V]
- func (f *Field[T, V]) Widget(w Widget) *Field[T, V]
- func (f *Field[T, V]) WriteOnly() *Field[T, V]
- type FieldAction
- type FieldDef
- type FieldErrors
- type Filter
- func FilterBelongsTo[RID comparable, R any](col nock.Col[RID], label string, target *Resource[R, RID]) Filter
- func FilterBool(col nock.Col[bool], label string) Filter
- func FilterCustom(key, label string, input FilterInput, ...) Filter
- func FilterDateRange(key, label string) Filter
- func FilterDateRangeOn(col nock.Col[time.Time], label string) Filter
- func FilterIn[V comparable](col nock.Col[V], label string, opts ...Option) Filter
- func FilterNumberRange[N Numeric](col nock.Col[N], label string) Filter
- type FilterInput
- type FilterValue
- type Getter
- type Host
- type Input
- func InBelongsTo[In any, R any, RID comparable](name string, ptr func(*In) *RID, target *Resource[R, RID]) *Input[In]
- func InDate[In any](name string, ptr func(*In) *time.Time) *Input[In]
- func InMoney[In any](name string, ptr func(*In) *int64, currency string) *Input[In]
- func InNumber[In any, N Numeric](name string, ptr func(*In) *N) *Input[In]
- func InSelect[In any](name string, ptr func(*In) *string, opts ...Option) *Input[In]
- func InText[In any](name string, ptr func(*In) *string) *Input[In]
- func InTextarea[In any](name string, ptr func(*In) *string) *Input[In]
- func InToggle[In any](name string, ptr func(*In) *bool) *Input[In]
- func (in *Input[In]) AuditValue() *Input[In]
- func (in *Input[In]) Default(raw string) *Input[In]
- func (in *Input[In]) Help(s string) *Input[In]
- func (in *Input[In]) Label(s string) *Input[In]
- func (in *Input[In]) Max(v float64) *Input[In]
- func (in *Input[In]) MaxLen(n int) *Input[In]
- func (in *Input[In]) Min(v float64) *Input[In]
- func (in *Input[In]) Required() *Input[In]
- func (in *Input[In]) Validate(fn func(ctx context.Context, x *In) error) *Input[In]
- type Installer
- type LensDef
- type LensPart
- type ListQuery
- type Metric
- func PartitionMetric(key, label string, fn func(ctx context.Context, r Range) ([]Slice, error)) *Metric
- func TableWidget[T any](key, label string, fn func(ctx context.Context) ([]T, error), ...) *Metric
- func TrendMetric(key, label string, fn func(ctx context.Context, r Range) ([]Point, error)) *Metric
- func ValueMetric(key, label string, fn func(ctx context.Context, r Range) (ValueResult, error)) *Metric
- func (m *Metric) Bars() *Metric
- func (m *Metric) Bucket(b Bucket) *Metric
- func (m *Metric) Can(perm rbac.Permission) *Metric
- func (m *Metric) Donut() *Metric
- func (m *Metric) Format(fn func(int64) string) *Metric
- func (m *Metric) Help(s string) *Metric
- func (m *Metric) Key() string
- func (m *Metric) Line() *Metric
- func (m *Metric) Link(url string, label ...string) *Metric
- func (m *Metric) LowerIsBetter() *Metric
- func (m *Metric) Ranges(defs ...RangeDef) *Metric
- func (m *Metric) Refresh(d time.Duration) *Metric
- func (m *Metric) Snapshot() *Metric
- func (m *Metric) Stacked() *Metric
- func (m *Metric) Width(n int) *Metric
- type NavGroup
- type NavItemOption
- type NavOption
- type NockOption
- func AfterWrite[ID comparable](fn func(ctx context.Context, tx any, id ID, ch Changes) error) NockOption
- func BaseQuery(fn func(ctx context.Context) *nock.SelectQuery) NockOption
- func BeforeWrite[ID comparable](fn func(ctx context.Context, tx any, id *ID, ch *Changes) error) NockOption
- func Scope(fn func(ctx context.Context) (nock.Expr, error)) NockOption
- func SoftDelete(col nock.Col[time.Time]) NockOption
- func Unscoped() NockOption
- func Version(col nock.Col[time.Time]) NockOption
- type NockRepository
- func (r *NockRepository[T, ID]) Create(ctx context.Context, ch Changes) (ID, error)
- func (r *NockRepository[T, ID]) Delete(ctx context.Context, id ID) error
- func (r *NockRepository[T, ID]) Find(ctx context.Context, id ID) (T, error)
- func (r *NockRepository[T, ID]) FindTrashed(ctx context.Context, id ID) (T, error)
- func (r *NockRepository[T, ID]) ForceDelete(ctx context.Context, id ID) error
- func (r *NockRepository[T, ID]) List(ctx context.Context, q ListQuery) (Page[T], error)
- func (r *NockRepository[T, ID]) Restore(ctx context.Context, id ID) error
- func (r *NockRepository[T, ID]) Trashed(ctx context.Context, ids []ID) (map[ID]bool, error)
- func (r *NockRepository[T, ID]) Update(ctx context.Context, id ID, ch Changes) error
- type Numeric
- type Option
- type OptionItem
- type Optioner
- type Page
- type PageDef
- type PageOption
- type Panel
- func (p *Panel) Adopt(h Host) error
- func (p *Panel) DashboardEvent(c *live.Ctx, v *views.DashboardPage, name string, payload json.RawMessage) error
- func (p *Panel) DetailEvent(c *live.Ctx, v *views.DetailPage, name string, payload json.RawMessage) error
- func (p *Panel) FormEvent(c *live.Ctx, v *views.FormPage, name string, payload json.RawMessage) error
- func (p *Panel) Handler() http.Handler
- func (p *Panel) ID() string
- func (p *Panel) ImpersonationExitPath() string
- func (p *Panel) IndexEvent(c *live.Ctx, v *views.IndexPage, name string, payload json.RawMessage) error
- func (p *Panel) InspectJSON() ([]byte, error)
- func (p *Panel) LiveHandlers() []*live.Handler
- func (p *Panel) Mount(r *router.Router)
- func (p *Panel) MountDashboard(c *live.Ctx, v *views.DashboardPage) error
- func (p *Panel) MountDetail(c *live.Ctx, v *views.DetailPage) error
- func (p *Panel) MountForm(c *live.Ctx, v *views.FormPage) error
- func (p *Panel) MountIndex(c *live.Ctx, v *views.IndexPage) error
- func (p *Panel) MountPalette(c *live.Ctx, v *views.Palette) error
- func (p *Panel) MountPrefixes() []string
- func (p *Panel) PaletteEvent(c *live.Ctx, v *views.Palette, name string, payload json.RawMessage) error
- func (p *Panel) Path() string
- func (p *Panel) Permissions() []rbac.Permission
- func (p *Panel) Plugins() []string
- func (p *Panel) Register(items ...Registrable) error
- func (p *Panel) Routes() []Route
- func (p *Panel) RunMiddleware() quiver.Middleware
- func (p *Panel) State() StateStore
- func (p *Panel) Use(ps ...Plugin) error
- type PanelOption
- func WithAccess(perm rbac.Permission) PanelOption
- func WithAlpine(b *alpine.Bundle) PanelOption
- func WithAudit(r audit.Recorder) PanelOption
- func WithAuth(a auth.Authenticator) PanelOption
- func WithBrand(b Brand) PanelOption
- func WithBroker(b pubsub.Broker) PanelOption
- func WithBulkLimit(n int) PanelOption
- func WithCSRFSecret(secret []byte) PanelOption
- func WithCSRFToken(fn func(*http.Request) string) PanelOption
- func WithClock(now func() time.Time) PanelOption
- func WithDB(db nock.DB) PanelOption
- func WithDashboard(ms ...*Metric) PanelOption
- func WithExportLimit(n int) PanelOption
- func WithIcons(fsys fs.FS) PanelOption
- func WithImages(s images.Service) PanelOption
- func WithImpersonation(im *auth.Impersonation) PanelOption
- func WithLiveOptions(opts ...live.Option) PanelOption
- func WithLoginURL(url string) PanelOption
- func WithMarkdown(fn func(ctx context.Context, src string) (crest.Component, error)) PanelOption
- func WithMoneyFormat(fn func(minor int64, code string) string) PanelOption
- func WithNav(groups ...NavGroup) PanelOption
- func WithPath(prefix string) PanelOption
- func WithPlugins(ps ...Plugin) PanelOption
- func WithPolicy(pol *rbac.Policy) PanelOption
- func WithQueue(q quiver.Queue) PanelOption
- func WithSecureHeaders(on bool) PanelOption
- func WithState(s StateStore) PanelOption
- func WithStorage(s storage.Store) PanelOption
- func WithSubject(fn func(ctx context.Context, userID string) (rbac.Subject, error)) PanelOption
- func WithSubjectTTL(d time.Duration) PanelOption
- func WithTheme(t Theme) PanelOption
- func WithTimeZone(loc *time.Location) PanelOption
- func WithTx(fn func(ctx context.Context, fn func(ctx context.Context, tx any) error) error) PanelOption
- func WithTxAudit(fn func(tx any) audit.Recorder) PanelOption
- func WithUploadKey(key []byte) PanelOption
- type ParentRef
- type Pivot
- type Plugin
- type Point
- type Range
- type RangeDef
- type RecordPageDef
- type Registrable
- type RelationDef
- func BelongsToMany[ID comparable, R any, RID comparable](name string, target *Resource[R, RID], pivot Pivot[ID, RID]) *RelationDef[ID]
- func HasMany[ID comparable, C any, CID comparable](name string, child *Resource[C, CID], fk nock.Col[ID]) *RelationDef[ID]
- func HasManyVia[ID comparable, C any, CID comparable](name string, child *Resource[C, CID]) *RelationDef[ID]
- func (r *RelationDef[ID]) Can(perm rbac.Permission) *RelationDef[ID]
- func (r *RelationDef[ID]) Columns(names ...string) *RelationDef[ID]
- func (r *RelationDef[ID]) Inline() *RelationDef[ID]
- func (r *RelationDef[ID]) Label(s string) *RelationDef[ID]
- func (r *RelationDef[ID]) PerPage(n int) *RelationDef[ID]
- type Repository
- type Resource
- func (r *Resource[T, ID]) Actions(as ...ActionDef[T, ID]) *Resource[T, ID]
- func (r *Resource[T, ID]) Cards(ms ...*Metric) *Resource[T, ID]
- func (r *Resource[T, ID]) Fields(fs ...FieldDef[T]) *Resource[T, ID]
- func (r *Resource[T, ID]) Filters(fs ...Filter) *Resource[T, ID]
- func (r *Resource[T, ID]) Key(fn func(*T) ID) *Resource[T, ID]
- func (r *Resource[T, ID]) Lenses(ls ...LensDef) *Resource[T, ID]
- func (r *Resource[T, ID]) Pages(ps ...*RecordPageDef[T, ID]) *Resource[T, ID]
- func (r *Resource[T, ID]) Relations(rs ...*RelationDef[ID]) *Resource[T, ID]
- func (r *Resource[T, ID]) Sections(ss ...*SectionDef[T]) *Resource[T, ID]
- func (r *Resource[T, ID]) Subtitle(fn func(*T) string) *Resource[T, ID]
- func (r *Resource[T, ID]) Title(fn func(*T) string) *Resource[T, ID]
- type ResourceOption
- func DefaultSort(key string, desc bool) ResourceOption
- func GlobalSearch(n int) ResourceOption
- func IDCodec(parse func(string) (any, error), format func(any) string) ResourceOption
- func Kind(kind string) ResourceOption
- func Labels(singular, plural string) ResourceOption
- func PerPage(n int, choices ...int) ResourceOption
- func RequireTxAudit() ResourceOption
- func WithSoftDeletes() ResourceOption
- type Result
- type Route
- type RunEvent
- type RunInfo
- type RunProgress
- type RunRecord
- type RunState
- type RunUpdate
- type SavedView
- type SectionDef
- type SelectFilter
- type Slice
- type SoftDeletable
- type SortKey
- type StateStore
- type Streamer
- type Theme
- type ThemeMode
- type Tone
- type Upload
- type UploadLedger
- type UploadRecord
- type UploadTicket
- type ValueResult
- type Values
- type Widget
- type WidgetCSP
- type WidgetEvents
- type WidgetHost
- type WidgetInput
- type WidgetUploads
- type Writer
Constants ¶
This section is empty.
Variables ¶
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("sight: the record was changed by someone else") )
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 */} )
var ErrNoTx = errors.New("sight: the panel has no transaction runner (WithDB or WithTx)")
ErrNoTx is returned by Tx when the panel has neither WithDB nor WithTx.
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 Audit ¶
Audit records an event for custom pages and hooks; inside a write or Tx it joins the transaction when the panel has WithTxAudit.
func AuditEvent ¶ added in v0.3.0
AuditEvent records ev with its own Outcome, for plugins and custom pages that report failures and denials too. Inside a write or Tx it joins the transaction when the panel has WithTxAudit. Outside one it goes to the panel's recorder, or, on a panel with only WithTxAudit, in a transaction of its own. Actor, request ID, and IP come from ctx when ev leaves them empty.
func CSPSources ¶
CSPSources returns the sources a panel needs beyond 'self', by CSP directive: the bucket origin of presigned uploads under connect-src, the image service's origin under img-src, and what field widgets ask for (see WidgetCSP). Add them to the app's secure.Config.CSP when the app, not the panel, sends the policy.
func Change ¶
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:
sight.CountOf(nock.Select().From(Orders).Where(Orders.Status.Neq("void")), Orders.PlacedAt)
func CurrentRecord ¶
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 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 ¶
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 ¶
FieldError returns an error that marks one field invalid.
func FormatCount ¶
FormatCount shows an integer with thousands separators.
func FormatMoney ¶
FormatMoney shows minor units of currency code, as in "$1,234.50".
func FormatPercentBP ¶
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 ImpersonationAudit ¶
func ImpersonationAudit(rec audit.Recorder) func(ctx context.Context, e auth.ImpersonationEvent) error
ImpersonationAudit adapts rec to auth.NewImpersonation's record func. Each event's Actor is the real user, Resource is "user/<target>", and Metadata holds target, reason, and, for a denial, error.
func Mount ¶
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 ¶
func NavOrder(n int) interface { NavOption ResourceOption PageOption }
NavOrder sorts sidebar groups and items; lower comes first.
func Progress ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ValueOf returns the current value of field name. ok is false when the field is unknown, NULL, or of another type.
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 sight.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 Asset ¶ added in v0.2.0
Asset is one file a widget needs on every admin page. The panel serves it as Base.<hash>.Ext; identical assets of several fields are served once.
type BadgeValue ¶
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.
Logo crest.Component
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 CanOption ¶
type CanOption struct {
// contains filtered or unexported fields
}
CanOption limits a lens or a relation to subjects with a permission.
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.
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 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 File ¶
File is a stored file, kept by its storage key. Once it has one, the form shows the file with Open and Remove instead of the drop zone.
func Files ¶ added in v0.2.0
Files is a list of stored files, kept as their storage keys, usually with ColJSON. The form shows them inside one drop zone that takes more until Upload.MaxFiles.
func Markdown ¶
Markdown is a string field rendered on the detail page and in the editor's Preview tab by the panel's Markdown renderer (see WithMarkdown).
func Money ¶
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 ¶
MultiSelect is a list of option values, usually stored with ColJSON.
func (*Field[T, V]) Action ¶ added in v0.2.0
func (f *Field[T, V]) Action(a FieldAction) *Field[T, V]
Action shows the row action a beside the field's value on the detail page, instead of in the page's action bar. a must be an Action of the field's resource; it is added to the resource's actions if Actions does not list it. A field carries one action.
func (*Field[T, V]) AuditValues ¶
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]) CreateOnly ¶
CreateOnly makes the field editable on the create form only.
func (*Field[T, V]) CurrencyFrom ¶
CurrencyFrom reads a Money field's ISO 4217 code from the row.
func (*Field[T, V]) DefaultFunc ¶
DefaultFunc computes the field's initial value on the create form from the form's current values.
func (*Field[T, V]) DependsOn ¶
DependsOn re-evaluates this field's VisibleWhen, OptionsFunc, DefaultFunc, and ReadOnlyWhen on the server when the named fields change.
func (*Field[T, V]) ExceptOnForms ¶
ExceptOnForms leaves the field off the create and edit forms.
func (*Field[T, V]) HideFromDetail ¶
HideFromDetail leaves the field out of the detail page.
func (*Field[T, V]) HideFromIndex ¶
HideFromIndex leaves the field out of the index table.
func (*Field[T, V]) HideWhenEmpty ¶ added in v0.2.0
HideWhenEmpty leaves the field out of the detail page, and off forms where it is read-only, while it has no value, instead of showing a dash.
func (*Field[T, V]) OnlyOnDetail ¶
OnlyOnDetail shows the field on the detail page only.
func (*Field[T, V]) OnlyOnForms ¶
OnlyOnForms shows the field on the create and edit forms only.
func (*Field[T, V]) OnlyOnIndex ¶
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]) Placeholder ¶
Placeholder sets the input's placeholder text.
func (*Field[T, V]) ReadOnlyWhen ¶
ReadOnlyWhen makes the field read-only for rows where fn is true.
func (*Field[T, V]) Searchable ¶
Searchable includes the field in the index search.
func (*Field[T, V]) Sensitive ¶
Sensitive keeps the value out of audit metadata, exports, and search.
func (*Field[T, V]) Span ¶ added in v0.2.0
Span sets how many columns of a two-column section the field takes on forms and the detail page: 1 or 2. By default Textarea, Markdown, JSON, KeyValue, Files, and Images take both and the rest take one.
func (*Field[T, V]) VisibleWhen ¶
VisibleWhen shows the field on forms only while fn returns true for the form's current values.
func (*Field[T, V]) Widget ¶ added in v0.2.0
Widget replaces the field's input and display with w. Only string fields take one.
func (*Field[T, V]) WriteOnly ¶ added in v0.2.0
WriteOnly makes the field an input of the create and edit forms that is never read back: it needs no getter, starts empty, and is left off the index and detail page. A submitted value reaches the repository in Changes (see Change and BeforeWrite); an empty one is left out. With Col, it is also written to the column.
type FieldAction ¶ added in v0.2.0
type FieldAction interface {
// contains filtered or unexported methods
}
FieldAction is a row action a field can carry beside its value. Every Action builder is one.
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 "".
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 ¶
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 ¶
FilterDateRange is a date range filter that custom repositories read from ListQuery.Filters with DateRange.
func FilterDateRangeOn ¶
FilterDateRangeOn filters a time column to the chosen dates, inclusive, in the panel's time zone.
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 ¶
FilterValue is one active filter of a ListQuery.
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 InTextarea ¶
InTextarea is a multi-line text input.
func (*Input[In]) AuditValue ¶
AuditValue records the input's value in the action's audit event; other inputs are recorded by name only.
type Installer ¶
type Installer struct {
// contains filtered or unexported fields
}
Installer is what a Plugin receives in Install. It declares definitions only: it exposes none of the panel's services (database, audit, queue, storage), and everything it registers is checked by the panel's policy like anything else, so a plugin gains no privileges.
func (*Installer) Dashboard ¶
Dashboard places widgets on the panel's overview, after those already there.
func (*Installer) Register ¶
func (in *Installer) Register(items ...Registrable) error
Register adds resources and custom pages, as Panel.Register does.
func (*Installer) Stylesheet ¶
Stylesheet loads href after the panel's own stylesheets. href must be a same-origin absolute path such as /static/plugin.css; the panel does not serve it.
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.
type LensPart ¶
type LensPart interface {
// contains filtered or unexported methods
}
LensPart configures a lens.
func FilterPreset ¶
FilterPreset sets a filter's value while the lens is on, as if the user had chosen values.
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
// Trash picks live rows (the zero value), trashed rows too, or only
// trashed rows, from the Trashed filter of a resource with
// WithSoftDeletes. A SoftDeletable repository applies it in List.
Trash nock.TrashScope
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.
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 ¶
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) Can ¶
func (m *Metric) Can(perm rbac.Permission) *Metric
Can shows the widget only to subjects with perm.
func (*Metric) Format ¶
Format shows values with fn, such as FormatMoney("USD"). Default FormatCount.
func (*Metric) LowerIsBetter ¶
LowerIsBetter shows a falling value as good news.
func (*Metric) Refresh ¶
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) Snapshot ¶ added in v0.3.0
Snapshot marks a value metric as a figure of now, such as a queue's pending jobs, that no range changes: it shows the current value with no comparison to the previous range.
type NavGroup ¶
type NavGroup struct {
// contains filtered or unexported fields
}
NavGroup is a labeled sidebar section that resources join with InGroup.
type NavItemOption ¶
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 ¶
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 ¶
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 ¶
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. List shows them when its ListQuery asks with Trash, and the repository is SoftDeletable: FindTrashed, Restore, and ForceDelete reach trashed rows. Pair it with the resource's WithSoftDeletes for the Trashed filter and the Restore and Force delete actions.
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.
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]) FindTrashed ¶
func (r *NockRepository[T, ID]) FindTrashed(ctx context.Context, id ID) (T, error)
FindTrashed returns the trashed row with id, or ErrNotFound when it is missing, live, or out of scope.
func (*NockRepository[T, ID]) ForceDelete ¶
func (r *NockRepository[T, ID]) ForceDelete(ctx context.Context, id ID) error
ForceDelete deletes the row with id for good, trashed or not.
func (*NockRepository[T, ID]) Restore ¶
func (r *NockRepository[T, ID]) Restore(ctx context.Context, id ID) error
Restore clears the SoftDelete column of the trashed 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.
type OptionItem ¶
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 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 ¶
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 ¶
Handler serves the panel under Path. It panics when the panel is misconfigured; Adopt reports the same errors as a value.
func (*Panel) ImpersonationExitPath ¶
ImpersonationExitPath is where WithImpersonation serves the exit, such as /admin/_impersonation/exit, for an app layout's own exit button. It is "" without WithImpersonation.
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 ¶
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 ¶
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) MountDashboard ¶
MountDashboard is the dashboard page's Live mount hook, called by the panel's views.
func (*Panel) MountDetail ¶
MountDetail is the detail page's Live mount hook, called by the panel's views.
func (*Panel) MountForm ¶
MountForm is the create and edit form's Live mount hook, called by the panel's views.
func (*Panel) MountIndex ¶
MountIndex and the other Live backend methods are called by the views; they are not part of the admin API.
func (*Panel) MountPalette ¶
MountPalette is the command palette's Live mount hook, called by the panel's views.
func (*Panel) MountPrefixes ¶
MountPrefixes lists the path prefixes the panel answers under: Path for a panel below the root; for a root panel, "/" (the overview, matched exactly) and one prefix per subtree: /_assets, /_search, /_upload, /pages, and /<slug> for each resource. A host router mounts these in place of a catch-all, so the host's other paths, such as /healthz, reach the app. It is complete once the panel is registered.
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) 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 ¶
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 WithImpersonation ¶
func WithImpersonation(im *auth.Impersonation) PanelOption
WithImpersonation serves POST <Path>/_impersonation/exit, which ends the caller's impersonation with im.Stop, and puts its button in the banner every panel page shows while an admin impersonates a user. The exit needs the CSRF token but not the panel permission, since the impersonated user often lacks it. Start impersonations from your own action or handler with im.Start; ImpersonationAudit records them.
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 ¶
WithMarkdown replaces the renderer of Markdown fields on detail pages and in the editor's preview. The renderer must sanitize its output. The default is a pure-Go CommonMark core renderer that escapes raw HTML and allows only http, https, mailto, tel, and relative URLs; nil shows Markdown 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. "/" serves the panel at the root of a host of its own, under fletch.MountAdminHost; fletch.MountAdmin refuses it, since the panel would cover the app's routes.
func WithPlugins ¶
func WithPlugins(ps ...Plugin) PanelOption
WithPlugins installs ps at the end of New, in order. Their errors are reported with the panel's other definition errors.
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 ¶
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 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 Plugin ¶
type Plugin interface {
// PluginID names the plugin, [a-z][a-z0-9-]*, unique per panel.
PluginID() string
// Install declares the plugin's definitions through in. It does no I/O.
Install(in *Installer) error
}
Plugin adds a coherent feature to a panel: resources, pages, dashboard widgets, and nav groups, under one ID.
type Range ¶
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".
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.
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]) 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]) Sections ¶ added in v0.2.0
func (r *Resource[T, ID]) Sections(ss ...*SectionDef[T]) *Resource[T, ID]
Sections adds fields in titled groups, after any added with Fields. The fields join the resource as Fields would add them, in order, so the index shows them too. Fields that are in no section are shown first, in a section titled Details.
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 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.
func WithSoftDeletes ¶
func WithSoftDeletes() ResourceOption
WithSoftDeletes turns on the trash for a resource whose repository is SoftDeletable, such as a NockRepo with SoftDelete: the index gets a Trashed filter (live rows by default, With trashed, Only trashed); Delete moves a row to the trash; and the Restore and Force delete row and bulk actions, which need "<kind>:restore" and "<kind>:force_delete" and are audited like other actions, inside the panel's transaction when it has one, work on trashed rows only. Every other read, such as search, pickers, relation managers, and the detail and edit views, sees live rows only.
type Result ¶
type Result interface {
// contains filtered or unexported methods
}
Result is what an action returns to the user.
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.
type RunProgress ¶
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 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.
CreatedAt time.Time
}
SavedView is an index query a user saved under a name.
type SectionDef ¶ added in v0.2.0
type SectionDef[T any] struct { // contains filtered or unexported fields }
SectionDef is a titled group of a resource's fields: a card on the create and edit forms and on the detail page. Build one with Section and add it with Resource.Sections.
func Section ¶ added in v0.2.0
func Section[T any](title string, fields ...FieldDef[T]) *SectionDef[T]
Section groups fields under title. It has two columns unless Columns says otherwise; Field.Span sets a field's width within it.
sight.Section[Partner]("Payout", bankLast4, w9).Help("Where payouts go.")
func (*SectionDef[T]) Aside ¶ added in v0.2.0
func (s *SectionDef[T]) Aside() *SectionDef[T]
Aside moves the section into a narrow column beside the others, sticky as the page scrolls, on forms and the detail page. Its read-only values show as compact label and value rows; it has one column.
func (*SectionDef[T]) Columns ¶ added in v0.2.0
func (s *SectionDef[T]) Columns(n int) *SectionDef[T]
Columns sets the section's columns: 1 or 2. Default 2.
func (*SectionDef[T]) Help ¶ added in v0.2.0
func (s *SectionDef[T]) Help(text string) *SectionDef[T]
Help sets the guidance shown under the section's title on forms; the detail page shows the title only.
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 ¶
Slice is one part of a partition. Tone colors it; without one it takes the next series color.
type SoftDeletable ¶
type SoftDeletable[T any, ID comparable] interface { // FindTrashed returns the trashed row with id, or ErrNotFound when it is // missing, not trashed, or out of scope. FindTrashed(ctx context.Context, id ID) (T, error) // Trashed reports which of ids are trashed rows in scope. Trashed(ctx context.Context, ids []ID) (map[ID]bool, error) // Restore takes the trashed row with id out of the trash, or returns // ErrNotFound. Restore(ctx context.Context, id ID) error // ForceDelete removes the row with id for good, trashed or not, or // returns ErrNotFound. ForceDelete(ctx context.Context, id ID) error }
SoftDeletable is implemented by repositories whose Delete moves a row to the trash instead of removing it. List, Find, and every other read keep trashed rows out unless the ListQuery asks for them with Trash. A resource with WithSoftDeletes uses it for its Trashed filter and its Restore and Force delete actions.
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 ¶
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.
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
// MaxFiles caps how many files a Files or Images field holds. Default 10.
MaxFiles int
}
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 UploadTicket ¶ added in v0.2.0
type UploadTicket struct {
Token string `json:"token"`
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
UploadTicket tells the browser where to send a file and the token that finishes the upload.
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 Widget ¶ added in v0.2.0
type Widget interface {
// WidgetKind names the widget, matching [a-z][a-z0-9-]*.
WidgetKind() string
// Assets are served by the panel under content-hashed names: scripts
// load after the admin script, styles after the admin stylesheet, and
// sprite symbols join the icon sprite.
Assets() []Asset
// Input renders the form control.
Input(ctx context.Context, in WidgetInput) crest.Component
// Clean runs on save before validation and returns the value to store.
// An error becomes the field's error.
Clean(ctx context.Context, raw string) (string, error)
// Display renders a stored value on the detail page.
Display(ctx context.Context, v string) (crest.Component, error)
// Text is the visible text of v: index cells, Required, and MaxLen
// use it.
Text(v string) string
}
Widget replaces the input and the display of a string field, such as a rich text editor. Attach one with Field.Widget. Values stay plain strings: the widget cleans what the form submits and renders what the row holds.
A widget may also implement WidgetEvents, WidgetUploads, and WidgetCSP. One with an Err() error method reports its own definition errors through it, and Register returns them.
type WidgetCSP ¶ added in v0.2.0
WidgetCSP is a widget that needs sources beyond 'self', by CSP directive. CSPSources and a standalone panel's own policy include them.
type WidgetEvents ¶ added in v0.2.0
type WidgetEvents interface {
Event(ctx context.Context, h WidgetHost, op string, data json.RawMessage) (any, error)
}
WidgetEvents is a widget that answers its own browser events, sent as the form event widget.call with {field, op, seq, data}. The panel runs Event only while the subject may edit the field on that form. The result, or the message of a FieldErrors error, returns to the browser as the admin:widget client event; any other error fails the event.
type WidgetHost ¶ added in v0.2.0
type WidgetHost interface {
BeginUpload(ctx context.Context, contentType string, size int64) (UploadTicket, error)
// FinishUpload checks the uploaded object as File fields do and
// returns its storage key.
FinishUpload(ctx context.Context, token string) (key string, err error)
}
WidgetHost is what a widget event may do: upload files under the widget's own Upload, for the current subject, field, and form.
type WidgetInput ¶ added in v0.2.0
type WidgetInput struct {
Name, ID, Value, Placeholder, LabelID, DescribedBy string
ReadOnly, Required, Invalid bool
MaxLen, Rows int
}
WidgetInput is what a widget renders a form control from. LabelID names the field's label and DescribedBy its help and error, for aria attributes.
type WidgetUploads ¶ added in v0.2.0
type WidgetUploads interface {
// WidgetUpload is the configuration of the widget's uploads; ok false
// means it takes none.
WidgetUpload() (u Upload, ok bool)
// UploadKeys lists the storage keys v references.
UploadKeys(v string) []string
// ReleaseRemoved reports whether a save deletes the uploads of this
// field the new value no longer references.
ReleaseRemoved() bool
}
WidgetUploads is a widget whose values reference uploaded files. A save commits the uploads a value newly references, as it does for File fields; SweepUploads deletes the rest.
Source Files
¶
- access.go
- action.go
- brand.go
- cachekey.go
- csp.go
- detail.go
- doc.go
- env.go
- export.go
- field.go
- field_widget.go
- filter.go
- form.go
- handlers.go
- impersonation.go
- index.go
- input.go
- inspect.go
- kinds.go
- lens.go
- live.go
- money.go
- nav.go
- nockmetrics.go
- nockrepo.go
- page.go
- panel.go
- plugin.go
- relation.go
- relmanager.go
- repo.go
- resource.go
- runs.go
- schema.go
- search.go
- section.go
- softdelete.go
- state.go
- svg.go
- tx.go
- upload.go
- widget.go
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |
|
markdown
Package markdown is the panel's default Markdown renderer: the CommonMark core of headings, paragraphs, emphasis, code, links, images, lists, blockquotes, and thematic breaks.
|
Package markdown is the panel's default Markdown renderer: the CommonMark core of headings, paragraphs, emphasis, code, links, images, lists, blockquotes, and thematic breaks. |
|
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 quiversight manages a Quiver job queue from a Sight admin panel: job counts on the dashboard, a jobs inspector with state, queue, and kind filters and a detail view, and a page of queues and schedules.
|
Package quiversight manages a Quiver job queue from a Sight admin panel: job counts on the dashboard, a jobs inspector with state, queue, and kind filters and a detail view, and a page of queues and schedules. |
|
Package richtext renders, cleans, and measures rich text for Sight fields and public pages.
|
Package richtext renders, cleans, and measures rich text for Sight fields and public pages. |
|
editor
Package editor is the WYSIWYG rich text widget for Sight string fields.
|
Package editor is the WYSIWYG rich text widget for Sight string fields. |
|
Package sighttest 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 sighttest 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 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. |