Docs/Ecosystem/Sight: Typed Go Admin Panels

Sight: Typed Go Admin Panels

Build typed Go admin panels with Sight v0.3.0: form sections, rich text editing, Quiver job controls, RBAC, soft deletes, impersonation, and plugins.

github.com/fletchhq/sight

sightpkg.go.devsight/richtextpkg.go.devsight/quiversightpkg.go.dev

Updated 2026-12-06 fletch docs show sight/sight 13 min read

On this page

Sight builds typed Go admin panels and back-office dashboards from Go resource definitions. You get resource indexes, detail pages, forms, rich text editing, uploads, queued actions, job controls, and dashboard metrics without hand-writing CRUD templates.

Introduction

Hand-rolling back-office views in every application leads to repetitive templates, inconsistent permission checks, and missing audit logs. Sight removes that boilerplate by turning typed Go resource declarations into server-rendered Crest and Live screens.

Every request and Live event passes through six layers of rbac authorization, and every write is written to an audit trail. Sight builds pure Go with CGO_ENABLED=0, ships pre-compiled *_crest.go views with zero Node build steps, and never imports root github.com/fletchhq/fletch.

Installation

Install Sight v0.3.0 with go get:

go get github.com/fletchhq/sight@v0.3.0

Companion packages such as sight/richtext, sight/richtext/editor, sight/quiversight, and sight/ui live inside the github.com/fletchhq/sight module. You do not need separate go get calls to use them, and root sight does not import richtext or quiversight unless your app does.

To scaffold resources and custom pages in a Fletch app, use the CLI generators:

fletch make resource Product --module catalog --table products
fletch make admin-page Reports
fletch make admin-page Timeline --record orders

Panels and mounting

Create a panel with sight.New(id, opts...), register your resources, and mount it on a Fletch app or any net/http mux. Both sight.WithPolicy and sight.WithSubject are required.

panel := sight.New("admin",
	sight.WithBrand(sight.Brand{Name: "Meridian Supply"}),
	sight.WithPolicy(policy),           // *rbac.Policy, required
	sight.WithSubject(subjectForUser),  // func(ctx, userID) (rbac.Subject, error), required
	sight.WithTxAudit(sight.SQLAudit),  // audit rows commit inside the write transaction
)
if err := panel.Register(ProductResource(), OrderResource(repo)); err != nil {
	return err
}
if err := fletch.MountAdmin(app, panel); err != nil { // serves /admin
	return err
}

fletch.MountAdmin(app, panels...) wires panels through structural interfaces (AdminHost and AdminPanel), keeping root fletch free of a sight dependency. It hands each panel the app's Nock database, audit recorder, authenticator, and Alpine bundle unless the panel sets its own, validates every panel before mounting anything, and registers each panel's Live handlers so App.EvictLiveBinding ends sessions on logout and graceful shutdown closes them cleanly.

To mount multiple panels under one app, give each panel a distinct prefix with sight.WithPath("/partners").

Dedicated admin host

If you want a panel at the root of its own hostname, set sight.WithPath("/") and mount it with fletch.MountAdminHost:

panel := sight.New("admin",
	sight.WithPath("/"),
	sight.WithPolicy(policy),
	sight.WithSubject(subjectForUser),
)
if err := panel.Register(ProductResource()); err != nil {
	return err
}
if err := fletch.MountAdminHost(app, "admin.example.com", panel); err != nil {
	return err
}

fletch.MountAdmin refuses a root ("/") panel so it cannot shadow your app's routes. With fletch.MountAdminHost, Fletch routes that hostname to the panel while keeping infrastructure paths (/healthz, /assets, /_fletch) reachable.

Resources, repositories, and soft deletes

Resources read and write records through a Repository[T, ID]. For Nock-backed tables, sight.NockRepo[T](table, idCol, ...) handles queries, search, sorting, filters, pagination, and writes.

Every repository must declare its tenant boundary with sight.Scope(fn) or opt out explicitly with sight.Unscoped() (missing both triggers diagnostic W0708). Add sight.Version(col) to enable optimistic locking on concurrent edits.

Soft deletes

Soft-delete UI support is opt-in per resource. Configure sight.SoftDelete(col) on your NockRepo (or implement SoftDeletable[T, ID]) and pass sight.WithSoftDeletes() on the resource:

repo := sight.NockRepo[Product](ProductsTable, ProductID,
	sight.Scope(scopeByTenant),
	sight.Version(ProductVersion),
	sight.SoftDelete(ProductDeletedAt),
)

When soft deletes are enabled:

  • The list view adds a Trashed filter (Active by default, plus With trashed and Only trashed).
  • The standard Delete action performs a soft delete instead of removing the row.
  • Search, relation pickers, detail views, edit forms, CSV exports, and relation lookups stay active-only.
  • Trashed records expose row and bulk Restore (<kind>:restore) and Force delete (<kind>:force_delete) actions, both recorded through WithTxAudit.

Form sections, aside layout, and fields

You may group form and detail fields into titled .section-card blocks using res.Sections(...) and sight.Section[T](title, fields...). Because Go cannot infer T from a variadic interface slice, pass the explicit type parameter [T] on sight.Section.

res.Sections(
	sight.Section[Product]("Basics", name.Span(2), sku, category).
		Help("Core identity fields shown in search and exports."),
	sight.Section[Product]("Content",
		description,
		sight.Text[Product]("change_note", nil).Col(ProductChangeNote).WriteOnly(),
	).Columns(1),
	sight.Section[Product]("Files",
		specSheet,
		coverImage,
		sight.Images("gallery",
			sight.Get(func(p *Product) []string { return list(p.Gallery) }),
			sight.Upload{Prefix: "products/gallery", MaxBytes: 2 << 20, MaxFiles: 6},
		).ColJSON(ProductGallery),
	),
	sight.Section[Product]("Record",
		status,
		owner.ReadOnly(),
		externalURL.ReadOnly().HideWhenEmpty(),
	).Aside(),
)
stockQty.Action(restockAction())

Section layout rules:

  • Columns: Sections default to 2 columns. Call .Columns(1) or .Columns(2); any other value fails registration.
  • Help text: .Help(text) renders under the section title on create and edit forms (capped at 65ch) and is omitted on detail pages.
  • Aside rail: .Aside() places a section in a sticky 320px right column on desktop (stacking below on narrow screens) using compact label/value rows. On create forms (/new), read-only fields are hidden, so an aside containing only read-only fields does not render until the record exists.
  • Backward compatibility: Existing flat Fields(...) declarations keep working. Any field not assigned to a section renders first in a default "Details" section. Form container width is capped (1000px without an aside, 1180px with an aside).

Field modifiers and inline actions

Each field builder exposes modifiers for width, visibility, and actions:

Modifier Behavior
.Span(n) Spans 1 or 2 columns inside a 2-column section. Textarea, Markdown, JSON, KeyValue, Files, and Images default to Span(2); all others default to Span(1).
.ReadOnly() Renders as a plain display value (text, badge, or file link) instead of a disabled input box. Empty values display a muted dash unless .HideWhenEmpty() is set.
.HideWhenEmpty() Omits empty values on detail pages and on read-only fields in forms.
.WriteOnly() Form-only input that allows a nil getter, starts empty, and is never read back. Non-empty submissions arrive in Changes and write to Col if set; empty submissions are skipped.
.Action(act) Attaches one FieldAction (any non-bulk sight.Action[...]) beside the field value on both detail pages and edit forms.
.Sensitive() Marks private fields; pair with .Can(...) so unauthorized subjects never receive the value (caught by W0704).
.AuditValues() Records before and after values for this field in the audit log.

When you attach field.Action(act), Sight registers act as a row action automatically. On edit forms, the action dialog runs outside the main <form>, refreshes the record while preserving unsaved edits, and updates the record version to avoid optimistic-lock conflicts. If a field is hidden by Can or HideWhenEmpty, its action falls back to the page header so operators never lose access to it.

Uploads and built-in Markdown preview

Sight supports single-file (sight.File, sight.Image) and multi-file (sight.Files, sight.Images, backed by []string) uploads using sight.Upload{Prefix, MaxBytes, MaxFiles} (MaxFiles defaults to 10).

  • On single-file edit fields, an uploaded file replaces the drop zone with a file card or thumbnail and a Remove button. Removing it restores the drop zone.
  • On multi-file fields, thumbnails render inside a unified drop zone with per-item Remove buttons and an add slot.

Markdown fields include a pure-Go, XSS-sanitizing Markdown preview renderer out of the box with zero setup. Pass sight.WithMarkdown(fn) only when you need custom Markdown rendering. Single-record BelongsTo fields render the selected value with Clear and change controls over a @alpinejs/csp-safe search popover, and boolean checkboxes render inline at the same weight as surrounding inputs.

Rich text editing and custom widgets

Sight separates rich text rendering, the browser editor, and the widget extension seam so public pages never pull in admin or JavaScript dependencies.

  • github.com/fletchhq/sight/richtext contains zero JavaScript and does not import sight. Import it directly in public Crest views.
  • github.com/fletchhq/sight/richtext/editor embeds prebuilt JS, CSS, and icons for CGO_ENABLED=0 builds with zero Node required.
  • Root sight imports neither package.

Defining a shared renderer

Configure one *richtext.Renderer in either richtext.Markdown mode (stores GFM text; canonicalizes on edit, preserves untouched text, rejects Underline) or richtext.HTML mode (stores canonical classless sanitized semantic HTML). Classes are never stored in your database; WithClasses injects them at render time and passes the same map to the editor via ClientConfig().

var PostBody = richtext.MustNew(richtext.Markdown,
	richtext.WithClasses(richtext.Classes{
		richtext.H2:         "mt-8 text-2xl font-semibold",
		richtext.P:          "my-4 leading-7",
		richtext.Blockquote: "border-l-2 pl-4 italic",
		richtext.A:          "underline underline-offset-2",
	}),
	richtext.WithAlign(richtext.Align{
		Left:   "text-left",
		Center: "text-center",
		Right:  "text-right",
	}),
	richtext.WithLinks(richtext.Links{
		SiteHosts: []string{"example.com"},
		External:  richtext.ExternalLinks{Target: "_blank", Rel: "noopener noreferrer"},
	}),
	richtext.WithImages(richtext.Images{
		Hosts: []string{"cdn.example.com"},
		Lazy:  true,
	}),
	richtext.WithHeadings(2, 3, 4),
	richtext.WithHeadingIDs("sec-"),
)

Every document passes through Goldmark GFM, a bluemonday allowlist, x/net/html normalization with class/attribute injection, and a final invariant check. No <style> tags or inline style="..." attributes are emitted, keeping output compatible with StrictCSP() (style-src 'self').

Renderer methods:

  • r.Render(ctx, src) (crest.Component, error) renders directly inside Crest templates (and matches sight.WithMarkdown).
  • r.RenderString(src) returns sanitized HTML as a string.
  • r.Clean(src) normalizes and sanitizes input before persistence.
  • r.Text(src) extracts plain text for search indexing or excerpts.
  • r.Mode() and r.ClientConfig() expose the mode and editor config.

Oversized or pathological inputs return sentinel errors richtext.ErrTooLarge (default richtext.DefaultMaxBytes = 1 MiB, configurable with WithMaxBytes), richtext.ErrTooDeep, or richtext.ErrTooComplex. You may also limit enabled features with WithFeatures(...), allow raw HTML with WithRawHTML(), or run a post-pass with WithTransform(fn).

Attaching the editor widget

Attach editor.New(r, opts...) to any string field with .Widget(...), then render the stored body on your public site with the exact same *richtext.Renderer:

body := sight.Textarea[Post]("body", sight.Get(func(p *Post) string { return p.Body })).
	Col(PostBodyCol).
	Widget(editor.New(PostBody,
		editor.Standard,
		editor.WithSource(),
		editor.Height(editor.Large),
		editor.InlineImages(sight.Upload{Prefix: "posts/media", MaxBytes: 4 << 20}, "/media/"),
	))
comp, err := PostBody.Render(r.Context(), post.Body)
if err != nil {
	return err
}
// Pass comp into your Crest template and render {props.Body}.

Editor options include toolbar presets (editor.Full, editor.Standard, editor.Compact), custom toolbar groups via editor.Toolbar(editor.G(...)) (including editor.Undo and editor.Redo), editor.WithSource(), editor.WithoutBaseStyles(), and editor.Height(editor.Small|Medium|Large|Auto).

Inline image uploads via editor.InlineImages(u, mediaBase) reuse Sight's signed-token upload flow, magic-byte sniffing, and save-transaction ledger commit. Only JPEG, PNG, WebP, and GIF images are accepted (never SVG). mediaBase must be relative or match a host in Images.Hosts. Orphaned uploads are reclaimed by SweepUploads, and removed images are kept unless you opt in with editor.DeleteRemovedImages().

Custom widgets (sight.Widget)

To build your own string-backed field widget without modifying Sight, implement sight.Widget (WidgetKind, Assets, Input, Clean, Display, Text) and attach it to any string field with field.Widget(w).

  • Return static scripts, stylesheets, or icon sprites from Assets() as sight.Asset{Base, Ext, ContentType, Body, Kind} (AssetScript, AssetStyle, AssetSprite); Sight serves them content-hashed under strict CSP.
  • Opt into interactive Live callbacks with sight.WidgetEvents (Event(ctx, h WidgetHost, op, data)), signed uploads with sight.WidgetUploads (WidgetUpload, UploadKeys, ReleaseRemoved), or extra CSP sources with sight.WidgetCSP (CSPSources).

Quiver job controls (sight/quiversight)

Package github.com/fletchhq/sight/quiversight is a first-party Sight plugin (plugin ID "quiver") that lets operators inspect and manage a Quiver queue from inside Sight. It adds zero external dependencies to go.mod.

Install the plugin and mount its stylesheet on your app mux:

q := quiver.New(driver)
panel := sight.New("admin",
	sight.WithPolicy(policy),
	sight.WithSubject(subjectForUser),
	sight.WithPlugins(quiversight.Plugin(q.(quiver.Manager))),
)
mux.Handle(quiversight.StylesheetPath, quiversight.StylesheetHandler())

Surfaces added by QuiverSight

Surface Behavior
Dashboard KPIs Running Jobs, Pending Jobs, Failed Jobs, and Completed Jobs .Snapshot() metrics linked to the jobs page (disable with WithoutDashboard()).
pages/quiver-jobs Stored jobs newest first, state lenses (All, Running, Pending, Failed, Completed, Cancelled) with live counts, Queue and Kind filters, row actions (Retry, Cancel, Delete), and Purge.
pages/quiver-job?id= Full job metadata, timestamps, duration, tags, meta, HTML-escaped pretty JSON payload (capped at 64 KB), full error trace, and row actions.
pages/quiver-queues Queue counts by state, active/paused status with Pause and Resume toggles, plus registered schedules with spec, kind, next run time, and Run now.

If the queue is nil or uses a driver that does not implement quiver.AdminDriver (such as quiver/sqs, which returns quiver.ErrNotManaged), QuiverSight renders a clear notice instead of 500 errors and shows a dash on dashboard KPIs.

Options and audit actions

Option Default
WithGroup(label) "Jobs"
WithViewPermission(perm) quiver:view (DefaultViewPermission); "" allows any panel user
WithManagePermission(perm) quiver:manage (DefaultManagePermission); "" allows any viewer
WithLimit(n) 100 (DefaultLimit)
WithStylesheetPath(path) "/_quiver/quiversight.css" (StylesheetPath)
WithPanelPath(path) "/admin"
WithoutDashboard() Dashboard widgets enabled
WithAudit(rec) Panel audit trail via sight.AuditEvent

Every mutation, denial, and failure is CSRF-checked, RBAC-enforced on both render and event execution, and audited under one of seven constants: ActionRetry ("quiver.job.retry"), ActionCancel ("quiver.job.cancel"), ActionDelete ("quiver.job.delete"), ActionPurge ("quiver.jobs.purge"), ActionPause ("quiver.queue.pause"), ActionResume ("quiver.queue.resume"), and ActionRunNow ("quiver.schedule.run").

Plugins, custom pages, and sight/ui

Bundle resources, custom pages, dashboard widgets, sidebar groups, and a same-origin stylesheet into a reusable sight.Plugin:

type Reports struct{}

func (Reports) PluginID() string { return "reports" }

func (Reports) Install(in *sight.Installer) error {
	in.Nav(sight.Group("Reports", "file-text"))
	in.Dashboard(sight.ValueMetric("revenue", "Revenue", revenue).Can("report:revenue"))
	in.Stylesheet("/static/reports.css")
	return in.Register(
		sight.CustomPage("weekly", "Weekly", newWeekly, sight.InGroup("Reports"), sight.Can("report:view")),
	)
}

Install plugins with sight.WithPlugins(...) or panel.Use(...) before serving. Plugin IDs must match ^[a-z][a-z0-9-]*$. Installs are atomic: if Install returns an error or panics, Sight rolls back every resource, page, widget, nav group, and stylesheet the plugin registered.

Installer exposes no panel services (no DB, queue, or audit recorder), and plugins receive no extra privileges. All plugin permissions appear in panel.Permissions(), and panel.Plugins() / panel.InspectJSON() report installed plugin IDs.

For standalone custom pages (sight.CustomPage) and per-record pages (sight.RecordPage, which requires Can or triggers W0709), Sight provides context helpers (CurrentRecord, CurrentID, Actor, Notify, Require) and exports its Crest UI primitives in github.com/fletchhq/sight/ui:

Card, Table, Button, Field, Badge, Dialog, Toast, Pagination, EmptyState, Stat, Widget, Chart, Sparkline, and Progress.

Use Metric.Snapshot() when building dashboard KPIs that report a current count rather than a period-over-period delta.

Access control, audit logging, and impersonation

Every HTTP request and Live event passes through six authorization layers:

Layer Check
Panel <id>:access
Resource <kind>:list, view, create, update, delete
Row Policy RegisterResource check against the loaded record
Field Can (omitted from DOM and payloads) and CanEdit
Action <kind>:<key> and .When(...)
Data scope NockRepo Scope or custom repository filter

Edit-form Live events (change, preview, save) re-read the row through the repository's scope and re-run row policy before mutating anything. Unauthenticated page requests redirect to WithLoginURL; non-page requests return 401. Submitting a field the subject cannot edit is refused and audited.

Transactional audit logging

Creates, updates, deletes, exports, actions, and denials write an audit.Record (admin.<kind>.<verb>). With sight.WithTxAudit(sight.SQLAudit), the audit row commits inside the write transaction targeting fletch_audit_log; if auditing fails, the write rolls back. Custom plugins and handlers can write to the active panel trail via sight.AuditEvent. Marking a panel or action RequireTxAudit without WithTxAudit is caught by W0707.

Impersonation

When an operator impersonates another user, Sight renders a high-contrast banner on every panel page naming both users. Audit records keep the impersonated user as Actor and record impersonator_id in Metadata automatically.

Pass sight.WithImpersonation(im) to enable the banner's Exit impersonation button:

panel := sight.New("admin",
	sight.WithPolicy(policy),
	sight.WithSubject(subjectForUser),
	sight.WithImpersonation(impersonator),
)
  • Clicking Exit impersonation submits a CSRF-protected POST to <path>/_impersonation/exit (or /_impersonation/exit on a root panel), ends the impersonation, and redirects back to the panel. Exiting does not require <id>:access.
  • If the impersonated user lacks panel access, Sight renders a 403 page with the exit banner intact instead of a bare error.
  • Use panel.ImpersonationExitPath() if your main app layout renders its own exit button, and start impersonations from your own action or handler with im.Start.

Panel state, theming, and tooling

Panels store saved views, column preferences, action runs, and the upload ledger in a StateStore (sight.WithState). By default Sight uses sight.NockState backed by WithDB, falling back to sight.MemoryState() (single process) when no database is configured.

Include sight.Tables (admin_saved_views, admin_column_prefs, admin_runs, admin_uploads) in your Nock schema so fletch db generate manages them in normal migrations. Sight never runs DDL at runtime. Verify custom stores with sighttest.StateStoreSuite and verify tenant isolation across subjects with sighttest.LeakScan.

Styling uses --admin-* CSS custom properties with light-dark() so light and dark themes follow the OS automatically with a per-user toggle. No markup emits inline style attributes, and Alpine runs as @alpinejs/csp under strict CSP.

Inspect panels and verify diagnostics from the CLI:

fletch ax inspect admin --json
fletch check --json

fletch check enforces Sight diagnostics W0700 through W0709 (missing scopes, unguarded sensitive fields, missing WithTxAudit, and missing Can on record pages).

Reference: Panel options

Option Purpose
WithPath(path) URL prefix for the panel (defaults to /<id>)
WithBrand(sight.Brand{...}) Display name and brand styling
WithPolicy(*rbac.Policy) Required RBAC policy checked on every request and Live event
WithSubject(fn) Required func(ctx, userID) (rbac.Subject, error) resolver
WithDB(db) Nock database for repositories and default NockState
WithAuth(a) Authenticator for standalone panels or overrides
WithAudit(rec) Audit recorder for standalone panels or overrides
WithTxAudit(sight.SQLAudit) Writes audit records inside the database write transaction
WithState(store) Storage for saved views, column toggles, runs, and uploads
WithMarkdown(fn) Overrides the built-in sanitizing Markdown renderer
WithLoginURL(url) Redirect target for unauthenticated page requests
WithCSRFSecret / WithCSRFToken CSRF configuration for standalone panels
WithLiveOptions(opts...) Extra Live options (cannot weaken auth, CSRF, or transport)
WithDashboard(widgets...) Dashboard metrics and widgets
WithNav(groups...) Sidebar navigation groups and ordering
WithPlugins(ps...) Installs sight.Plugin bundles at panel creation
WithImpersonation(im) Wires the impersonation exit button and endpoint
WithClock(clk) Clock override for deterministic tests