npcs

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0 modules, 0 packages

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

Documentation

Overview

handler.go provides HTTP endpoints for the NPC gallery. Thin handlers that bind request parameters, call the NPC service, and render templ components or JSON responses.

Package npcs provides a gallery/hub view for revealed NPCs in a campaign. NPCs are character-type entities that the DM has made visible to players ("revealed"). This plugin is a view layer on top of the entities system — it does not own any database tables.

repository.go provides data access for the NPC gallery. Queries the existing entities + entity_types tables — no separate NPC table is needed because NPCs are just character entities filtered by visibility.

SECURITY: this repository applies NO visibility predicate of its own — a hand-rolled `role < 2 AND is_private = false` check here would miss visibility='custom' entities. The service layer narrows the ID list through the entities plugin's canonical FilterViewableEntityIDs (via EntityVisibilityFilter in service.go); see service.go's visibleNPCIDs for the policy this repository deliberately does not implement.

routes.go registers NPC gallery endpoints on the Echo router. The gallery page is readable by Players; the reveal toggle is the owner's and Co-DMs'.

service.go contains business logic for the NPC gallery. Resolves the campaign's character entity type and delegates listing to the repository.

Index

Constants

View Source
const NPCPageSize = 60

NPCPageSize is the page size of the Characters page NPC list; the "Show more" button loads one more page of this size.

Variables

This section is empty.

Functions

func ParseNPCSectionQuery

func ParseNPCSectionQuery(q, tag, page string, allowedTags []NPCTagInfo) (search, tagSlug string, pageNum int)

ParseNPCSectionQuery normalises the section endpoint's raw query values. tag is only honoured when it is one of allowedTags (the options this viewer is offered), so a hand-typed slug can't probe for GM-only tags.

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterRoutes sets up NPC gallery routes on the Echo instance. Public-capable routes use AllowPublicCampaignAccess so public campaigns show NPCs to unauthenticated visitors. All routes are gated behind the "npcs" addon — campaign owners can enable/disable via the Plugin Hub.

Types

type EntityTypeFinder

type EntityTypeFinder interface {
	FindCharacterTypeIDs(ctx context.Context, campaignID string) ([]int, error)
}

EntityTypeFinder resolves which of a campaign's entity types hold NPCs and monsters. Implemented by an adapter over entities.EntityService (injected to avoid circular imports). An empty result means the campaign has none.

type EntityVisibilityFilter

type EntityVisibilityFilter interface {
	FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
}

EntityVisibilityFilter resolves which of a set of entity IDs a viewer (role + userID) may see, applying the entities plugin's own canonical visibility policy (default is_private, custom per-subject grants, tag grants). Wraps entities.EntityService.FilterViewableEntityIDs — the SAME method sessions and the relations widget use — so the NPC gallery never hand-rolls its own copy of that predicate: a `role < 2 AND is_private = false` check would miss a visibility='custom' NPC.

type Handler

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

Handler serves NPC gallery endpoints.

func NewHandler

func NewHandler(svc NPCService) *Handler

NewHandler creates a new NPC gallery handler.

func (*Handler) CountAPI

func (h *Handler) CountAPI(c *echo.Context) error

CountAPI returns the NPC count as JSON at GET /campaigns/:id/npcs/count. Used by the sidebar badge and layout blocks.

func (*Handler) GalleryBlock

func (h *Handler) GalleryBlock(ctx context.Context, campaignID string, role int, userID string, limit int) ([]NPCCard, error)

GalleryBlock fetches NPC cards for embedding in entity page layout blocks. Returns a compact card list limited by the block config.

func (*Handler) Index

func (h *Handler) Index(c *echo.Context) error

Index used to render the standalone NPC gallery; that page folded into the unified entities Characters page (NPCs/Monsters section). The route now redirects so existing links/bookmarks keep working.

func (*Handler) NPCSection

func (h *Handler) NPCSection(ctx context.Context, cc *campaigns.CampaignContext, userID, csrfToken, featureTag string) templ.Component

NPCSection renders the NPCs/Monsters section embedded in the Characters page: a featured portrait row (entities bearing featureTag) above the full role-aware list. It satisfies entities.NPCSectionProvider (injected there), so the core entities plugin never imports this addon. Role matches CountAPI's cc.VisibilityRole(), which promotes a DM-granted co-DM to Owner, so a co-DM sees dm_only/custom-restricted NPCs here too, same as an Owner.

func (*Handler) SectionFragment

func (h *Handler) SectionFragment(c *echo.Context) error

SectionFragment handles GET /campaigns/:id/npcs/section?q=&tag=&page=, the HTMX endpoint behind the search box, tag filter and "Show more". Page 1 returns the whole list part; later pages return just the next cards plus an out-of-band footer so the client appends them. Direct (non-HTMX) hits go back to the Characters page.

func (*Handler) SetVisibilityToggler

func (h *Handler) SetVisibilityToggler(vt VisibilityToggler)

SetVisibilityToggler injects the entity visibility toggler.

func (*Handler) ToggleReveal

func (h *Handler) ToggleReveal(c *echo.Context) error

ToggleReveal handles POST /campaigns/:id/npcs/:eid/reveal. Toggles an NPC's is_private flag. Only the owner and Co-DMs reveal or hide NPCs: a Scribe sees what players see, so a hidden NPC is not theirs to know.

type NPCCard

type NPCCard struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Slug      string         `json:"slug"`
	ImagePath *string        `json:"image_path,omitempty"`
	TypeLabel *string        `json:"type_label,omitempty"` // Freeform subtype (e.g., "Innkeeper", "Guard").
	TypeName  string         `json:"type_name"`
	TypeIcon  string         `json:"type_icon"`
	TypeColor string         `json:"type_color"`
	Fields    map[string]any `json:"fields_data"`
	IsPrivate bool           `json:"is_private"`
	Tags      []NPCTagInfo   `json:"tags,omitempty"`
}

NPCCard is a lightweight view model for the NPC gallery grid. Fields are sourced from the entities table with joined entity_type info.

func (*NPCCard) FieldString

func (c *NPCCard) FieldString(key string) string

FieldString returns a string field value from the NPC's fields_data, or empty string if the key is missing or not a string.

type NPCListOptions

type NPCListOptions struct {
	Page    int    // 1-indexed page number.
	PerPage int    // Items per page (default 24).
	Sort    string // "name" (default), "updated", "created".
	Search  string // Optional name search (prefix match).
	Tag     string // Optional tag slug filter.

	// IncludeDmOnlyTags lets GM-only tags decorate cards. Off by default so a
	// player-facing list can never carry a dm_only tag name.
	IncludeDmOnlyTags bool
}

NPCListOptions controls filtering and pagination for the NPC gallery.

func DefaultNPCListOptions

func DefaultNPCListOptions() NPCListOptions

DefaultNPCListOptions returns sensible defaults for the NPC gallery.

func (NPCListOptions) Offset

func (o NPCListOptions) Offset() int

Offset returns the SQL offset for the current page.

func (NPCListOptions) OrderByClause

func (o NPCListOptions) OrderByClause() string

OrderByClause returns a safe SQL ORDER BY clause based on the Sort field.

type NPCListView

type NPCListView struct {
	Cards  []NPCCard
	Pager  NPCPager
	Search string
	Tag    string
	// Tags are the filter options (tags present on NPCs the viewer can see).
	Tags []NPCTagInfo
}

NPCListView is everything the NPC list part renders: one page of cards plus the filter state, so the fragment endpoint and the initial section share it.

func (NPCListView) Filtered

func (v NPCListView) Filtered() bool

Filtered reports whether a search or tag narrows the list.

type NPCPager

type NPCPager struct {
	Shown    int
	Total    int
	HasMore  bool
	NextPage int
	// NextCount is how many cards the next click adds (the last page is short).
	NextCount int
}

NPCPager is the "Showing X of N" state of the cumulative NPC list: pages 1..Page have been loaded, so Shown is everything up to the end of Page.

func NewNPCPager

func NewNPCPager(page, perPage, total int) NPCPager

NewNPCPager derives the pager from the requested page and the filtered total. Total comes from the visibility-narrowed set, so the footer never discloses hidden NPCs.

type NPCRepository

type NPCRepository interface {
	// ListRevealedIDs returns ALL unclaimed character entity IDs matching the
	// campaign + any of the character types + optional search/tag filters (excluding templates), in
	// the gallery's sort order, with NO visibility restriction and NO
	// pagination applied. The service layer narrows this list to what the
	// viewer may see (via the canonical entities visibility policy) BEFORE
	// paginating, so the visible list and its count are always derived from
	// the exact same filtered ID set and can never disagree.
	ListRevealedIDs(ctx context.Context, campaignID string, characterTypeIDs []int, opts NPCListOptions) ([]string, error)

	// GetNPCCardsByIDs returns full NPC card data for exactly the given IDs
	// (in that order), scoped to campaignID. Used to fetch one page's worth of
	// cards after the service has already narrowed and paginated the ID list.
	GetNPCCardsByIDs(ctx context.Context, campaignID string, ids []string) ([]NPCCard, error)
}

NPCRepository defines the data access contract for NPC gallery queries.

func NewNPCRepository

func NewNPCRepository(db *sql.DB) NPCRepository

NewNPCRepository creates a new NPC repository backed by the given database.

type NPCService

type NPCService interface {
	// ListNPCs returns revealed character entities for the NPC gallery.
	ListNPCs(ctx context.Context, campaignID string, role int, userID string, opts NPCListOptions) ([]NPCCard, int, error)

	// CountNPCs returns the number of visible NPCs for badge/nav display.
	CountNPCs(ctx context.Context, campaignID string, role int, userID string) (int, error)

	// ListTags returns the distinct tags on the NPCs this viewer can see, for
	// the list's tag filter. Derived from the visibility-narrowed set so a tag
	// that only sits on hidden NPCs is never offered.
	ListTags(ctx context.Context, campaignID string, role int, userID string, includeDmOnly bool) ([]NPCTagInfo, error)

	// SetTagLister injects the batch tag fetcher; without it cards carry no tags
	// and the tag filter is empty.
	SetTagLister(tl TagLister)
}

NPCService handles business logic for the NPC gallery.

func NewNPCService

func NewNPCService(repo NPCRepository, typeFinder EntityTypeFinder, entityVisibility EntityVisibilityFilter) NPCService

NewNPCService creates a new NPC service. entityVisibility is the canonical visibility gate (see EntityVisibilityFilter) — required so a Player/ anonymous viewer's list can never fall back to "everything visible" by construction; see visibleNPCIDs's fail-closed branch.

type NPCTagInfo

type NPCTagInfo struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Slug  string `json:"slug"`
	Color string `json:"color"`
}

NPCTagInfo holds tag display info for NPC cards.

type TagInfo

type TagInfo struct {
	ID    int
	Name  string
	Slug  string
	Color string
}

TagInfo holds tag display data returned by TagLister.

type TagLister

type TagLister interface {
	// includeDmOnly is false for player-facing lists so GM-only tags never decorate or filter them.
	ListTagsForEntities(ctx context.Context, entityIDs []string, includeDmOnly bool) (map[string][]TagInfo, error)
}

TagLister fetches tags for a set of entity IDs in batch. Implemented by tags.TagService — injected to decorate NPC cards with tags.

type VisibilityToggler

type VisibilityToggler interface {
	TogglePrivate(ctx context.Context, entityID, campaignID string) (newPrivate bool, err error)
}

VisibilityToggler toggles an entity's is_private flag and returns the new state, scoped to the caller's campaign. Injected from the entities plugin to avoid circular imports. campaignID is the authorization boundary: the entity must belong to it or the toggle fails with NotFound (SEC-IDOR-1).

Jump to

Keyboard shortcuts

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