Documentation
¶
Overview ¶
DOM-id helpers for the re-render seam: a host's widget block lives inside a stable wrapper element so a bind/unbind can target it for an in-place HTMX swap; the picker fragment loads into a separate slot inside that wrapper.
Package widgetbindings — embedded SQL migrations so the binding table is created from the compiled binary regardless of the runtime working dir (same pattern as the other plugins; ADR-030).
The binding HTTP surface: the only Echo-aware code in the widgetbindings plugin; the Service stays Echo-free. Handlers are thin: collect inputs, call the Service, render the generic picker fragment (or signal a reload after a mutation).
SECURITY: the host's campaign always comes from the route's campaign context, never the request body; the Service re-checks the instance is in-campaign (no DB FK to lean on). host_type/widget_type are validated against the app-code namespace (registry + IsValidHostType), never a DB enum.
Package widgetbindings is the foundation for the widget-binding framework: a generic, host-agnostic mapping of host (entity / entity-type / dashboard) ↔ widget-type ↔ data-instance.
Widget types register their behavior in the Registry; the Service resolves, for a given host, which data-instance a widget renders, following a precedence chain (host's own binding → entity-type template → default).
The binding table is polymorphic and FK-free on both host_id and instance_id (ADR-038), so it can live in a plugin without tripping the core-before-plugin migration-ordering rule. Referential integrity is therefore the app layer's job, enforced by per-plugin delete hooks, an always-on render-time orphan guard, and a periodic campaign integrity sweep.
The dynamic widget-type registry. Widget types register their behavior here declaratively instead of being hardcoded into each block's renderer. The registry is the app-code guard for the widget_type namespace (a registered slug == a valid widget_type value), so a new widget type plugs in by registering, with no schema change.
Hand-written SQL for widget_bindings.
SECURITY: campaignID is pushed down to every signature so an unscoped read is unrepresentable — there is no method that reads a binding without a campaign filter. MariaDB has no row-level-security backstop, so this repository + the service are the only line of defense against cross-campaign access.
The binding UI routes. Campaign-scoped; all writes are Scribe+. Generic across widget types (the handler validates host_type/widget_type against the registry). No addon gate — the affordance only appears on already-rendered, addon-gated widget blocks.
The binding service: the precedence resolver plus the integrity mitigation kit.
FK-free polymorphism (see package doc, ADR-038) means integrity is enforced here by two mechanisms:
- per-plugin DELETE HOOK → OnInstanceDeleted (owning plugins call it)
- always-on RENDER-TIME GUARD → Resolve validates each candidate via WidgetType.InstanceExists, skips dead ones and deletes them
Sweep is a third, campaign-wide cleanup, but nothing calls it in production (Chronicle has no job runner), so it is not part of the integrity story.
Index ¶
- Constants
- Variables
- func BlockHostID(widgetType, hostID string) string
- func DeclareInlineSizeHost(widgetType string)
- func IsValidHostType(ht string) bool
- func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, ...)
- type BlockRenderContext
- type CreateInput
- type Handler
- type HostRef
- type InstanceRef
- type Registry
- type Repository
- type Resolution
- type Service
- type WidgetBinding
- type WidgetType
Constants ¶
const ( HostTypeEntity = "entity" // a single entity instance hosts the widget HostTypeEntityType = "entity_type" // an entity-type template (inherited by its entities) HostTypeDashboard = "dashboard" // a campaign dashboard surface (host_id e.g. "<campaignID>:player") )
Host types. These are PERSISTED polymorphic discriminators — an immutable, append-only namespace. Renaming one orphans every stored binding, so they are validated in app code (not a DB enum) and only ever added to.
const ( SourceOwn = "own" // the host's own binding SourceEntityType = "entity_type" // inherited from the entity's type template SourceDefault = "default" // the widget type's default (today's behavior) SourceNone = "none" // nothing resolved (no binding, no default) )
Resolution source layers — which rung of the precedence chain won. Returned alongside the instance id so the cascade is inspectable, not a black box (precedent refinement #2).
Variables ¶
var ( ErrUnknownWidgetType = errors.New("widgetbindings: unknown widget type") ErrInvalidHostType = errors.New("widgetbindings: invalid host type") ErrCampaignMismatch = errors.New("widgetbindings: host campaign mismatch") // ErrInstanceNotInCampaign is the security stop: a bind whose instance // doesn't exist in the host's campaign (cross-campaign or bogus). ErrInstanceNotInCampaign = errors.New("widgetbindings: instance not found in campaign") )
Sentinel errors.
var ErrNotImplemented = errors.New("widgetbindings: not implemented in this wave")
ErrNotImplemented is returned by P1 stubs (ListInstances/CreateInstance) that P4 (the create-or-pick UI) fills in.
var MigrationsFS embed.FS
MigrationsFS contains the embedded SQL migration files for the widget-binding plugin.
Functions ¶
func BlockHostID ¶
BlockHostID is the stable DOM id of a host's widget block — the swap target a binding mutation replaces (outerHTML), so the block re-renders in place with no full reload. The id is derived from the widget type + host id, which is unique per rendered block (one widget type per host).
func DeclareInlineSizeHost ¶
func DeclareInlineSizeHost(widgetType string)
DeclareInlineSizeHost marks a widget type whose block sizes itself with CSS container queries, so its BlockHost wrapper becomes a measured inline-size container. Called from the widget type's constructor at registration.
A block that declares this takes on style + inline-size containment for its whole subtree — see inlineSizeHosts for what was and was not measured.
func IsValidHostType ¶
IsValidHostType reports whether ht is a known host-type discriminator.
func RegisterRoutes ¶
func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterRoutes mounts the binding picker + bind/create/unbind endpoints under the campaign group. Picker is Scribe+ (the create-or-pick affordance is a Scribe action); mutations are Scribe+. CSRF is enforced by the global middleware (boot.js attaches the token to HTMX requests).
Types ¶
type BlockRenderContext ¶
type BlockRenderContext struct {
CC *campaigns.CampaignContext
HostID string // the entity id (host)
UserID string // viewing user (player-visibility filtering)
CSRFToken string
Role int // the viewer's effective role (campaigns.Role as int)
Resolution Resolution
}
BlockRenderContext is the seam that lets the binding handler re-render a widget's entity block without importing the widget plugin: widget plugins depend on widgetbindings, so widgetbindings delegates rendering back through the registry via WidgetType.RenderBlock. The Resolution is pre-computed by the caller, so RenderBlock is a pure "render this resolved instance".
type CreateInput ¶
CreateInput is the generic payload for WidgetType.CreateInstance. The binding HTTP handler collects form fields into it (so the handler stays widget-type-agnostic) and each WidgetType type-asserts it and reads what it needs; Raw carries any extra fields a type wants without changing this boundary.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler serves the create-or-pick binding UI + bind/create/unbind mutations.
func NewHandler ¶
NewHandler builds the binding handler over the service + widget-type registry.
func (*Handler) BindAPI ¶
BindAPI binds a host to an existing instance (Scribe+): POST /campaigns/:id/bindings {host_type, host_id, widget_type, instance_id}
func (*Handler) CreateBindAPI ¶
CreateBindAPI creates a new instance then binds it (Scribe+): POST /campaigns/:id/bindings/create {host_type, host_id, widget_type, name, ...}
type HostRef ¶
type HostRef struct {
CampaignID string
Type string // one of HostType*
ID string // entity id / entity-type id / dashboard key
EntityTypeID string // entity hosts only; "" otherwise
}
HostRef identifies the thing a widget is rendered on, for resolution. It is plain strings so this foundation plugin imports no other plugin.
EntityTypeID enables the inheritance path: for an `entity` host it carries the entity's type id so Resolve can fall back to the entity-type's template binding. Empty when not applicable.
type InstanceRef ¶
type InstanceRef struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon,omitempty"`
Color string `json:"color,omitempty"`
}
InstanceRef is a lightweight instance summary for the picker.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds the registered widget types. Safe for concurrent reads after startup (writes happen during app wiring).
func (*Registry) Get ¶
func (r *Registry) Get(slug string) (WidgetType, bool)
Get returns the widget type for a slug.
func (*Registry) IsValidWidgetType ¶
IsValidWidgetType reports whether slug names a registered widget type. This is the app-code namespace guard (no DB enum).
func (*Registry) Register ¶
func (r *Registry) Register(wt WidgetType)
Register adds (or replaces) a widget type by its slug.
type Repository ¶
type Repository interface {
// Upsert creates or updates the binding for (campaign, host, widget_type).
// One binding per host per widget type (calendar is singleton-per-host).
Upsert(ctx context.Context, b *WidgetBinding) error
// GetForHost returns the binding for an exact host + widget type, or nil.
GetForHost(ctx context.Context, campaignID, hostType, hostID, widgetType string) (*WidgetBinding, error)
// DeleteForHostWidget removes a host's binding for a widget type (no-op if absent).
DeleteForHostWidget(ctx context.Context, campaignID, hostType, hostID, widgetType string) error
// ListByCampaign returns all bindings in a campaign (the integrity sweep input).
ListByCampaign(ctx context.Context, campaignID string) ([]WidgetBinding, error)
// ListForInstance returns bindings pointing at a specific instance (the
// delete-hook input when that instance is deleted).
ListForInstance(ctx context.Context, campaignID, widgetType, instanceID string) ([]WidgetBinding, error)
// DeleteByID removes one binding (campaign-scoped).
DeleteByID(ctx context.Context, campaignID, id string) error
}
Repository is the persistence boundary for widget bindings. Every method is campaign-scoped by signature.
func NewRepository ¶
func NewRepository(db *sql.DB) Repository
NewRepository creates a MariaDB-backed binding repository.
type Resolution ¶
Resolution is the outcome of Resolve: the winning instance id + which layer it came from (+ the widget type, for convenience).
func (Resolution) Resolved ¶
func (r Resolution) Resolved() bool
Resolved reports whether resolution produced a usable instance.
type Service ¶
type Service interface {
// Bind upserts a host's binding to an instance, after validating the
// instance belongs to the host's campaign (security). host.CampaignID is
// authoritative.
Bind(ctx context.Context, host HostRef, widgetType, instanceID string) error
// Unbind removes a host's binding for a widget type.
Unbind(ctx context.Context, host HostRef, widgetType string) error
// Resolve runs the precedence chain (own → entity-type template → default)
// with a render-time orphan guard, returning the winning instance + source.
Resolve(ctx context.Context, host HostRef, widgetType string) (Resolution, error)
// OnInstanceDeleted is the per-plugin delete hook: owning plugins call it
// when an instance is deleted so its bindings are removed promptly. Returns
// the number of bindings cleaned.
OnInstanceDeleted(ctx context.Context, campaignID, widgetType, instanceID string) (int, error)
// Sweep removes bindings whose instance no longer validates, campaign-wide.
// It has no production caller: Chronicle has no job runner to run it from,
// so integrity rests on OnInstanceDeleted and Resolve's render-time guard.
// Returns the number swept.
Sweep(ctx context.Context, campaignID string) (int, error)
}
Service is the binding API consumed by widget blocks + (P4) the assign UI.
func NewService ¶
func NewService(repo Repository, registry *Registry) Service
NewService builds the binding service over a repository + widget-type registry.
type WidgetBinding ¶
type WidgetBinding struct {
ID string `json:"id"`
CampaignID string `json:"campaign_id"`
HostType string `json:"host_type"`
HostID string `json:"host_id"`
WidgetType string `json:"widget_type"`
InstanceID string `json:"instance_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
WidgetBinding is one host ↔ widget-type ↔ instance row. host_id and instance_id are polymorphic strings with NO foreign keys (see package doc).
type WidgetType ¶
type WidgetType interface {
// Slug is the persisted widget_type discriminator (e.g. "calendar").
Slug() string
// InstanceExists reports whether instanceID is a real instance of this
// widget type that belongs to campaignID. It is BOTH the orphan guard and
// the campaign-scope security check (the instance fetch is the #1 leakage
// vector) — it must return false for a missing OR cross-campaign instance.
InstanceExists(ctx context.Context, campaignID, instanceID string) (bool, error)
// DefaultInstance returns the unbound default instance for a host — i.e.
// today's behavior (calendar → the campaign's default calendar). ok=false
// when there is no default. MUST equal pre-framework behavior so unbound
// hosts render identically (zero churn for #411–#420).
DefaultInstance(ctx context.Context, host HostRef) (instanceID string, ok bool, err error)
// ListInstances powers the P4 picker (campaign's instances of this type).
ListInstances(ctx context.Context, campaignID string, role int) ([]InstanceRef, error)
// CreateInstance powers the P4 "create new" flow.
CreateInstance(ctx context.Context, campaignID string, input any) (instanceID string, err error)
// RenderBlock re-renders this widget's entity block for the resolved
// host, letting a bind/unbind return a swappable fragment instead of
// forcing a full page reload. Wrap the output in BlockHost so the
// rendered fragment carries the stable swap-target id.
RenderBlock(ctx context.Context, rc BlockRenderContext) templ.Component
}
WidgetType declares one widget type's behavior to the framework. Owning plugins implement it and register an instance at startup; the binding Service drives resolution through it without importing the plugin.