entities

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: 48 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

block_registry.go provides a self-registering system for entity page block types. Plugins register their block metadata and renderers at startup so that validation, rendering, and the template-editor palette are all driven by a single source of truth.

block_registry_core.go registers the core block types that are always available (no addon requirement). Template blocks wrap the templ components defined in show.templ. Dashboard blocks have nil renderers (rendered by the Go dashboard handler, not the block registry).

Package entities contains the entity favorites model and repository. Favorites are per-user, per-campaign bookmarks shown in the sidebar drill panel for quick entity access.

genre_presets.go defines entity type presets for different campaign genres. When a campaign is created with a genre selection, the corresponding preset types are seeded instead of (or in addition to) the standard defaults.

Package entities helpers provide utility functions used by entity templates.

Package entities manages worldbuilding entities — the core content objects in Chronicle. Every object (characters, locations, items, organizations, etc.) is an entity with a configurable type. Entity types define what custom fields appear in the profile sidebar.

This is a CORE plugin — always enabled, cannot be disabled.

page_pins.go — the pages on a campaign home's Pinned Pages widget: the ones the Director pins for everyone (page_pins) and each member's own, which are the pages they starred (entity_favorites).

permissions_api.go — wire-contract helpers for the entity permissions endpoints.

wrapPermissionError preserves typed *AppError sub-errors (e.g. a NotFound from UpdateVisibility) so they reach the wire as a structured status instead of a generic 500. respondPermissionsError emits the shared { error, message, category } shape also used by the foundry_vtt API; Category is derived from AppError.Type so callers don't retrofit every apperror constructor.

Package entities contains the saved filter model and repository. Saved filters are per-user, per-campaign tag filter presets shown in the sidebar drill panel for quick tag combo switching.

show_renderer_registry.go — slug-keyed extension point for entity-show rendering. Layered above BlockRegistry: when an entity's entity_type slug has a registered renderer, that renderer owns the page contents; otherwise layout-block dispatch runs unchanged.

Audience: system package authors (Draw Steel, D&D 5.5e, etc.) who want to render character / monster / item entities with system-specific layout the generic block system can't express. See docs/system-package-rendering.md for the external-facing contract.

Package entities contains the sidebar node model and repository for pure organizational folders in the sidebar tree. Sidebar nodes have no page content — they exist solely for hierarchical grouping.

Index

Constants

View Source
const (
	PictureHeading  = "heading" // a page's or a home's big title
	PictureLines    = "lines"   // text: grey lines of prose
	PictureQuote    = "quote"   // text read out, set off by an edge
	PictureImage    = "image"   // a picture, a cover, a sky
	PictureCard     = "card"    // one featured page or person: picture over words
	PictureFacts    = "facts"   // labels with their values
	PictureSheet    = "sheet"   // a character sheet's boxed scores
	PictureLinks    = "links"   // a list of linked pages
	PictureGrid     = "grid"    // cards on a grid
	PictureFeed     = "feed"    // posts or notes, one under another
	PictureTree     = "tree"    // a family tree
	PictureGraph    = "graph"   // pages joined by their links
	PictureMap      = "map"     // a map with a pin
	PictureCalendar = "month"   // a month of days
	PictureTimeline = "track"   // a track with marks along it
	PictureTable    = "table"   // rows and columns
	PictureCounter  = "counter" // a number, a clock or a count
	PictureSteps    = "steps"   // a checklist of steps
	PictureTags     = "tags"    // chips
	PictureDivider  = "divider" // a rule across the page
	PictureSearch   = "search"  // a search field
)

The kinds of small drawing the Customizer's widget list shows beside each widget's name (BlockMeta.Picture). Each is a wireframe of what a widget puts on a page, drawn by static/js/widgets/widget_pictures.js; the set stays small so the list reads as one family of pictures, and every core widget maps to the one that fits it. A package widget declares none and gets PictureLines.

View Source
const (
	EraDiffSame    = "same"
	EraDiffChanged = "changed"
	EraDiffAdded   = "added"
	EraDiffRemoved = "removed"
)

Era diff block kinds.

View Source
const (
	// MaxFamilyEdits bounds one save. A sitting adds a few relatives; a body of
	// hundreds is a mistake or an attack, and each edit is several writes.
	MaxFamilyEdits = 40
	// MaxFamilyNewPages bounds the pages one save may create.
	MaxFamilyNewPages = 10
	// FamilyPickerMax is how many pages the picker ever returns. The Director
	// narrows by typing; there is no unbounded list.
	FamilyPickerMax = 20
)
View Source
const (
	FamilyEdgeParent  = "parent"
	FamilyEdgePartner = "partner"
	FamilyOpAdd       = "add"
	FamilyOpRemove    = "remove"
)

Edge names and operations on the wire.

View Source
const (
	// MaxFamilyGenerations is how many generations the walk follows each way
	// from the page (ancestors up, descendants down). It is read one further
	// to learn whether the family goes on, which is what the block says.
	MaxFamilyGenerations = 4
	// MaxFamilyPeople bounds how many relatives one page carries, so a house
	// of hundreds cannot turn one page view into a wall of data. Nearer
	// relatives are kept first.
	MaxFamilyPeople = 60
)
View Source
const (
	FamilyKindBirth    = "birth"
	FamilyKindAdopted  = "adopted"
	FamilyKindGuardian = "guardian"
)

Relation kinds on a parent link. The wire values are used by the script.

View Source
const (
	FieldTypeLink = "link"
	FieldTypeRule = "rule"
)

Two field types read more than their stored value: a link field stores a page id and shows that page's name, and a rule field shows what its homebrew rule gives unless someone typed a value by hand.

View Source
const (
	FieldSwitchSwitched  = "switched"
	FieldSwitchDismissed = "dismissed"
	FieldSwitchBack      = "back"
)

Field switch states, one row per answered category. No row: not answered.

View Source
const (
	HeroLooksTabID   = "hero-creator"
	HeroLooksSection = "herolooks"
)

HeroLooksTabID is the Customize tab's id (served at /customize/x/hero-creator) and HeroLooksSection the draft section its changes live in; the section's owner is internal/app/customize_herolooks.go.

View Source
const (
	SearchScopeNamed   = "named"
	SearchScopeMention = "mention"
)

The Search page's two groups; see ListOptions.SearchScope.

View Source
const (
	BlockSubPages       = "children"
	BlockPosts          = "posts"
	BlockWritingPrompts = "writing_prompts"
	BlockBacklinks      = "backlinks"
	BlockSystemPanels   = "system_panels"
	BlockCharacterItems = "character_items"
)

Block types for the pieces above.

View Source
const (
	// VersionCreated is the state a page was created with.
	VersionCreated = "created"
	// VersionEdit is a save from the editor, the edit form or a sync client.
	// Saves by the same person close together share one row (see
	// versionCoalesceWindow), so typing with autosave doesn't flood history.
	VersionEdit = "edit"
	// VersionRestore is the state a restore from history saved.
	VersionRestore = "restore"
	// VersionSync is a save by a sync client (Foundry) or an import, shown
	// as "Sync or import" rather than under the key owner's name.
	VersionSync = "sync"
	// VersionBaseline is the state a page had before history was kept: the
	// first save of a page created before this feature records it, so that
	// save can be undone too. Who wrote it is unknown.
	VersionBaseline = "baseline"
)

Version kinds. A page's history is a list of saved states of its title and text, newest first; the kind says what produced each one.

View Source
const (
	// HeroChoiceStateNotOffered marks an entry the campaign's rules keep from
	// this player, shown in a practice plan so they can still try it.
	HeroChoiceStateNotOffered = "not_offered"

	// PracticeAskWaiting and PracticeAskDeclined are the two answers an ask
	// can be in; an empty status means the maker has not asked.
	PracticeAskWaiting  = "waiting"
	PracticeAskDeclined = "declined"
)

Words the creator and the pages use for a practice pick the rules keep from the player.

View Source
const (
	// PresetCategoryPlayerCharacter marks an entity type as the player-claimable
	// "Player Character" sub-type via its system preset category.
	PresetCategoryPlayerCharacter = "player_character"
	// SlugPlayerCharacter is the conventional slug for a Player Characters
	// sub-type created by name ("Player Character" → "player-character").
	SlugPlayerCharacter = "player-character"
	// AddonPlayerCharacterClaiming is the addon slug that must be enabled for
	// a campaign before player-character sub-types can be created.
	AddonPlayerCharacterClaiming = "player-character-claiming"
	// DefaultCharacterTypeSlug is the slug of the default "Characters" category
	// seeded into every campaign (see repository.go defaultEntityTypes). The
	// premade "Player Character" sub-type nests under it.
	DefaultCharacterTypeSlug = "character"
)

Player Character Claiming constants.

View Source
const (
	OrderAZ   = "az"
	OrderHand = "hand"
	OrderNew  = "new"
)

The orders a sidebar container can keep its rows in. OrderAZ is the default and is never stored.

View Source
const (
	OrderContainerCategory = "category"
	OrderContainerFolder   = "folder"
	OrderContainerPage     = "page"
)

The kinds of container that hold rows in the sidebar tree.

View Source
const (
	StandingPartyWire = "party"
	StandingPartyKey  = ""
)

StandingPartyWire is the subject key the API and the block use for the whole party. Storage keeps it as the empty string (StandingPartyKey) so it can sit in the same unique key as a character's page id.

View Source
const (
	StandingLevelMin     = 0
	StandingLevelMax     = 4
	StandingLevelDefault = 2
)

The five steps of a standing, lowest first. The level a standing stores is an index into this list.

View Source
const (
	StandingUp   = "up"
	StandingDown = "down"
	StandingNone = "none"
)

Reason directions: what a reason did to the word.

View Source
const (
	// StandingReasonMax is the longest reason text, in characters.
	StandingReasonMax = 90
	// StandingWhenMax is the longest "when" label, in characters.
	StandingWhenMax = 30
	// MaxStandingReasons is how many reasons one standing keeps; adding past it
	// asks the Director to remove some first.
	MaxStandingReasons = 300
)

Bounds that keep a page's standing a small thing. They are why the block can read everything for a page in a few queries instead of paging.

View Source
const (
	// VisStateEveryone — public: visible to everyone, including anonymous /
	// logged-out visitors on a public campaign (default mode, not private).
	VisStateEveryone = "everyone"
	// VisStateDMOnly — visible only to Scribe+ (default mode, is_private).
	VisStateDMOnly = "dm_only"
	// VisStateCustom — specific entity_permissions grants (custom mode).
	VisStateCustom = "custom"
)

Effective-visibility base states. These name the entity's *configured* visibility before any tag widening, matching the shipped 3-state badge.

View Source
const AddonNPCs = "npcs"

AddonNPCs is the addon slug that gates the NPCs/Monsters section.

View Source
const CastTagSlug = "cast"

CastTagSlug is the conventional tag a GM applies to an NPC to feature it in the portrait row of the Characters page's NPC section, so curation needs no new column.

View Source
const ContentsBlockType = "contents"

ContentsBlockType is the layout block type for the Contents block.

View Source
const ContentsWidgetName = "page-contents"

ContentsWidgetName is the data-widget the block mounts so boot.js loads its script on sight (ADR-063).

View Source
const DefaultTrashRetentionDays = 30

DefaultTrashRetentionDays is used when the site setting is unset.

View Source
const FamilyTreeBlockType = "family_tree"

FamilyTreeBlockType is the block's type key in saved layouts: an append-only namespace value, never rename.

View Source
const FamilyTreeWidgetName = "family-tree"

FamilyTreeWidgetName is the data-widget the block mounts so boot.js loads its script on sight (ADR-063).

View Source
const FieldTypeCalendarDate = "calendar_date"

FieldTypeCalendarDate is a date on the campaign's calendar ("Died on"). Its value is "year-month-day" (month by number), optionally followed by "|" and, per countdown in order, the index of the length this page uses: "1043-3-22|1". Keeping the picks in the value keeps them under the field's own Director-only flag.

View Source
const FieldTypeClimate = "climate"

FieldTypeClimate is a place's climate, one of the calendar's climates by id. A page with none takes its nearest parent's, so a region's towns share its weather; a page with no climate above it keeps the calendar's world climate and shows no climate line at all, so a campaign that never sets one sees nothing new. The page that holds the climate is the place's region: the calendar keeps weather per region.

View Source
const HeroChoiceStateAskFirst = "ask_first"

HeroChoiceStateAskFirst marks a HeroChoice the player may pick only with a Director's yes.

View Source
const HeroLevelKey = "level"

HeroLevelKey is the field that holds a hero's level in the game systems that have one. A system without it never opens a level window.

View Source
const HeroReopenMaxDays = campaigns.HeroChangeMaxDays

HeroReopenMaxDays bounds how long a Director may reopen one hero.

View Source
const MainLayoutKey = "main"

MainLayoutKey is the key that names a category's main layout wherever a key is expected; a page with no choice wears it.

View Source
const MaxAliasLength = 200

MaxAliasLength is the maximum character length for an alias.

View Source
const MaxAliasesPerEntity = 10

MaxAliasesPerEntity is the maximum number of aliases allowed per entity.

View Source
const (
	// MaxPageLayouts is how many named layouts a category keeps besides its
	// main one.
	MaxPageLayouts = 8
)
View Source
const MaxPracticeHeroes = 3

MaxPracticeHeroes is how many practice heroes one player keeps in one campaign.

View Source
const MaxSharedPins = 12

MaxSharedPins caps how many pages the Director can pin for everyone: the widget is a short list to start from, not a second page index.

View Source
const MaxVersionsPerPage = 100

MaxVersionsPerPage caps how many versions a page keeps; the oldest go first.

View Source
const MinAliasLength = 2

MinAliasLength is the minimum character length for an alias.

View Source
const PluginSlug = "entities"

PluginSlug is the entities plugin's registry key. Used to mount the plugin's embedded static assets at /static/plugins/entities/.

View Source
const PresetCategoryAdventures = "adventures"

PresetCategoryAdventures marks the Adventures category. Anything carrying it is invisible to a viewer below Scribe, in every read path.

View Source
const PresetCategoryItem = "item"

PresetCategoryItem is the preset category of a game system's item types.

View Source
const SlugAdventures = "adventures"

SlugAdventures is the slug the seeded category gets.

View Source
const StandingBlockType = "standing"

StandingBlockType is the block's type in the block registry.

View Source
const StandingPluginSlug = "entity_standing"

StandingPluginSlug names the Standing block's tables in the plugin migration bookkeeping and the health registry. It is not "entities" on purpose: a failed standing migration must leave only the Standing block out, never mark the page system itself degraded.

View Source
const TokenFieldKey = "token_image"

TokenFieldKey is the field a page keeps its token picture in, as a media id: a game system declares it on its creature type, the hover card shows it on the corner of the page picture, and the Foundry module uses it as the creature's token.

Variables

View Source
var ErrPracticeChanged = errors.New("practice hero changed since it was read")

ErrPracticeChanged says the practice hero is no longer the one the caller looked at: its maker changed it, or asked again, after the page was drawn.

View Source
var MigrationsFS embed.FS

MigrationsFS contains the embedded SQL migration files for the Standing block's tables (the entities plugin owns entity pages, so it owns them), created from the compiled binary regardless of the working directory.

PictureKinds is every drawing widget_pictures.js knows.

View Source
var StaticAssetsFS embed.FS

StaticAssetsFS contains the entities plugin's static assets (JS/CSS), served by Echo at /static/plugins/entities/ once registered in the App's plugin registry.

View Source
var TrashRetentionChoices = []int{30, 60, 90, 180, 365}

Trash retention choices, in days, offered by the admin setting.

Functions

func BlockConfigInt

func BlockConfigInt(config map[string]any, key string, defaultVal int) int

BlockConfigInt extracts an integer value from a block config map. Returns defaultVal if the key is missing or not a number.

func BlockConfigLimit

func BlockConfigLimit(config map[string]any, key string, defaultLimit int) int

BlockConfigLimit extracts a numeric limit from a block config map. Returns defaultLimit if the key is missing or not a positive number.

func BlockConfigString

func BlockConfigString(config map[string]any, key string) string

BlockConfigString extracts a string value from a block config map. Returns empty string if the key is missing or not a string.

func CanEditIdentity

func CanEditIdentity(role campaigns.Role, entity *Entity, userID string) bool

CanEditIdentity reports whether the viewer may edit the identity fields and rename the page: any Scribe or above, or the claimed owner.

func CanEditOwnPage

func CanEditOwnPage(role campaigns.Role, entity *Entity, userID string) bool

CanEditOwnPage reports whether the viewer may write the page's description and change its picture: any Scribe or above, or the player who claimed it. The player shapes their own hero; the Director keeps the numbers, the GM-only parts and who can see the page.

func CategoryHomeBlockTypes

func CategoryHomeBlockTypes() []string

CategoryHomeBlockTypes are the widgets a category's home can hold: the ones the Customizer's editor offers, in its order. A caller that saves a home offers no others, so what it writes is what the editor could have placed.

func CharacterSurfaceSchemaJSON

func CharacterSurfaceSchemaJSON(entity *Entity, entityType *EntityType, campaignID, csrfToken string, canEdit, canSeeGM, isOwner bool, pictureEndpoint string) string

CharacterSurfaceSchemaJSON builds the dynamic-surface mount schema (with the entity's real data seeded) that the character_surface block embeds. Returns "{}" on marshal failure so the block degrades to an empty surface rather than breaking the page. json.Marshal HTML-escapes the output, so it is safe to embed inside a <script type="application/json"> tag.

canSeeGM gates the GM-only field filter: when false (a player viewing the sheet), fields the system marks gm_only are omitted from the seed so their values never reach the browser. isOwner gates the owner-only field filter the same way for fields the system marks owner_only (e.g. backstory) — visible to canSeeGM callers and the entity's own claimed owner, omitted for every other viewer. Server is the authority.

pictureEndpoint is the image API the portrait saves to, or "" when the viewer may not change the picture.

func CheckClaimedOwnerPatch

func CheckClaimedOwnerPatch(entity *Entity, userID, campaignID string, patch map[string]any, typeFields []FieldDefinition, plan *HeroPlan) error

CheckClaimedOwnerPatch is authorizeFieldsWrite for a sheet change that does not come through the fields route: one a player's AI asked for and the player applied. It always judges the writer as a Player, whatever their role, and takes the hero builder plan that player is shown, so the AI can change exactly what the player could change by hand and no more.

func CheckDateSettings

func CheckDateSettings(f *FieldDefinition) error

CheckDateSettings checks a calendar date field's countdowns before the category is saved.

func ClaimedOwnerPatchHeld

func ClaimedOwnerPatchHeld(entity *Entity, userID, campaignID string, patch map[string]any, typeFields []FieldDefinition, plan *HeroPlan) (held map[string]string, err error)

ClaimedOwnerPatchHeld is CheckClaimedOwnerPatch key by key: it returns why each key may not be written, so a player's AI change can keep the rest. err is set when the writer may not change the character at all.

func ClearStaleStepOptions

func ClearStaleStepOptions(entity *Entity, patch map[string]any)

ClearStaleStepOptions adds a clear of what a hero bought from a step's entry when the patch changes that step and says nothing of the options: traits bought from the old ancestry don't belong to the new one. It works on any writer's patch, and needs no plan.

func CountLineChanges

func CountLineChanges(older, newer string) (added, removed int)

CountLineChanges returns how many lines newer adds and removes compared with older; a changed line counts as one of each.

func CreatureTypeIDs

func CreatureTypeIDs(types []EntityType) []int

CreatureTypeIDs is the enabled creature types and their enabled sub-types, the pages a game system's creature panels go on. Unlike the NPC list it is not a choice: a type is a creature type by what it is.

func CustomizeTabFactory

func CustomizeTabFactory() func(*campaigns.CampaignContext) campaigns.CustomizeTab

CustomizeTabFactory contributes the "Hero creator" tab to the Customize page (campaigns.Handler.RegisterCustomizeTab): the creator as players see it, in which the owner presses a card to change its border. The campaigns plugin only hosts the tab; the choices wait in the draft's "herolooks" section and are saved by the section's own Apply.

func DaysLeft

func DaysLeft(deletedAt time.Time, retentionDays int, now time.Time) int

DaysLeft is how many whole days, rounded up, a Trash item has left.

func DefaultCategoryHomeLayout

func DefaultCategoryHomeLayout() *campaigns.DashboardLayout

DefaultCategoryHomeLayout is the home the editor starts a category from while it has none of its own.

func EraDiffCount

func EraDiffCount(d []EraDiffBlock) int

EraDiffCount is how many blocks a diff changes, adds or removes.

func FilterGMOnlyFields

func FilterGMOnlyFields(fieldsData map[string]any, defs []FieldDefinition, canSeeGM bool) map[string]any

FilterGMOnlyFields returns fieldsData with GM-only field VALUES removed when the caller may not see GM content (canSeeGM == false). GM/owner sessions and Foundry Bearer callers (canSeeGM == true) get the map back unchanged.

It never mutates the input map: when something must be stripped it returns a fresh copy, so the caller's scanned model / DB-backed map stays intact. Otherwise the original map is returned as-is (zero allocation).

"GM-only" is declared per field via FieldDefinition.GMOnly, populated from a system manifest's gm_only annotation — core stays system-agnostic and strips whatever the installed manifest marked.

func FilterOwnerOnlyFields

func FilterOwnerOnlyFields(fieldsData map[string]any, defs []FieldDefinition, canSeeGM, isOwner bool) map[string]any

FilterOwnerOnlyFields returns fieldsData with owner-only field VALUES removed when the caller can neither see GM content nor owns the entity (canSeeGM == false && isOwner == false). Mirrors FilterGMOnlyFields's contract: never mutates the input map, and returns it unchanged when there is nothing to strip.

"Owner-only" is declared per field via FieldDefinition.OwnerOnly. Unlike GMOnly, an owner-only field's value IS shown to the entity's own claimed owner — this is for player-private content (e.g. backstory), not a GM-exclusive secret.

func FilterRestrictedFields

func FilterRestrictedFields(fieldsData map[string]any, defs []FieldDefinition, canSeeGM, isOwner bool) map[string]any

FilterRestrictedFields composes FilterGMOnlyFields and FilterOwnerOnlyFields — the single call every egress path should use, so the two restriction tiers can't be applied out of order or have one forgotten at a call site.

func HTMLToPlainLines

func HTMLToPlainLines(src string) string

HTMLToPlainLines flattens page HTML to text, one paragraph, heading or list item per line, so history can say "+2 lines" and show changed words.

func HeroBuyList

func HeroBuyList(c HeroChoice) (names []string, costs map[string]float64, budget float64, ok bool)

HeroBuyList is what an entry lets a hero buy: the names on its list (in their own spelling), each one's cost and the points to spend. ok is false when the entry has nothing to buy.

func HeroFieldWarnings

func HeroFieldWarnings(plan *HeroPlan, fields map[string]any, written []string) []string

HeroFieldWarnings names each written pick-list field of a hero whose value the plan would not accept, with the closest names the plan does list. fields is the hero's sheet as it will stand (a dependent step reads its parent from there, so a subclass is checked against a class the page already had); written is the keys the change sets, the only ones reported. A nil plan or a value that is not text gives no warning.

func HeroLevelRaised

func HeroLevelRaised(e *Entity, patch map[string]any) int

HeroLevelRaised is the level patch gives the hero when that is higher than the stored one; 0 when patch leaves the level alone, keeps it or lowers it.

func HeroOptionsKey

func HeroOptionsKey(step string) string

HeroOptionsKey is the field that keeps what a hero bought from a step's entry ("ancestry" → "ancestry_choices_json").

func IconColumns

func IconColumns() []database.IconColumn

IconColumns lists this plugin's stored icon columns and the default that replaces an unusable value, for the boot-time icon reconciler.

func IntPtr

func IntPtr(n int) *int

IntPtr is a helper for inline *int literals in ConfigFieldMeta.

func IsClaimedOwnerPlayer

func IsClaimedOwnerPlayer(role campaigns.Role, entity *Entity, userID string) bool

IsClaimedOwnerPlayer reports whether the viewer is a campaign member below Scribe who owns this entity. The claim addon's on/off state is irrelevant: an existing claim keeps its meaning if the addon is later switched off.

func IsCreatureType

func IsCreatureType(t EntityType) bool

IsCreatureType is isCreatureType for other plugins, through app.

func IsExtraCategoryBlock

func IsExtraCategoryBlock(blockType string) bool

IsExtraCategoryBlock reports whether blockType was registered through RegisterCategoryBlock. Saving a category layout accepts these in addition to the dashboard block set, so a registered block survives a save.

func IsHeroPage

func IsHeroPage(e *Entity, pcType bool, pickKeys []string) bool

IsHeroPage reports whether a character page is a hero rather than an NPC: a player has it, the owner marked it playable (a hero nobody has claimed yet), it is of the player character sub-type, or it names one of the hero's picks (pickKeys: the game system's class and hero choices, such as ancestry or kit). The Foundry module applies the same test when it decides between a hero and an NPC actor, so both sides agree on who is a hero.

func IsItemType

func IsItemType(t EntityType) bool

IsItemType reports whether a type is one of the Armory's item categories: a game system's item preset, or the Items category every campaign starts with (slug "item"), which no system marks because it was there first.

func IsPlayerCharacterType

func IsPlayerCharacterType(t EntityType) bool

IsPlayerCharacterType reports whether a page type is the player character sub-type.

func MergeFieldPatch

func MergeFieldPatch(current, patch map[string]any) map[string]any

MergeFieldPatch returns a new map: current with patch applied (nil value deletes the key). Neither input is modified. Exported so partial-update callers of Update can merge before it replaces the whole map.

func NormalizeTrashRetention

func NormalizeTrashRetention(days int) int

NormalizeTrashRetention maps any stored value onto an offered choice, falling back to the default, so a bad setting never purges early.

func OwnerIdentityFieldKeys

func OwnerIdentityFieldKeys() []string

OwnerIdentityFieldKeys returns the short free-text keys, sorted, for UI and docs.

func PageHomeBlockTypes

func PageHomeBlockTypes() []string

PageHomeBlockTypes lists the older home blocks that may sit on any page.

func PatchChangesNothing

func PatchChangesNothing(entity *Entity, patch map[string]any) bool

PatchChangesNothing reports whether every key in patch is what the hero already stores, so a caller can skip building the hero plan: Foundry resends the whole mapped set, and most pushes change nothing a plan judges.

func PlanUnlimited

func PlanUnlimited(ctx context.Context) bool

PlanUnlimited reports whether WithUnlimitedPlan was set.

func PlayerPicksHeld

func PlayerPicksHeld(entity *Entity, patch map[string]any, plan *HeroPlan) map[string]string

PlayerPicksHeld judges the hero-choice part of a sheet write made on a claimed player's behalf outside the web door (Foundry pushes a whole mapped field set under the GM's key). It returns why each pick may not be stored; an empty map means every key may go through.

Only the keys the web door judges as picks are looked at: a builder step, what a step's entry lets the hero buy, and the identity texts (which a rule turns into a pick from the list). Every other key is left to the caller's own rules, because Foundry legitimately writes mapped numbers such as stamina that the web door would refuse a player. A value sent back unchanged is never held: a client resends the whole stored set, and a hero keeps what it already holds. Ask-first picks are held too, since Foundry has no way to record a request and the sheet must never store a pick that is still waiting for a Director.

func ReconcileTemplatePrompts

func ReconcileTemplatePrompts(ctx context.Context, store TemplatePromptStore) (int64, error)

ReconcileTemplatePrompts gives campaigns seeded before template prompts became hints the new built-in templates, whose prompts vanish when written over instead of staying on the page as text. Only a copy still matching the old seed exactly is changed, so an edited template is left alone, and a second run finds nothing. The count is templates changed.

func RegisterCategoryBlock

func RegisterCategoryBlock(blockType string, r CategoryBlockRenderer)

RegisterCategoryBlock adds a category dashboard block owned by another plugin. Registering the same type again replaces it.

func RegisterCategoryBlockWithConfig

func RegisterCategoryBlockWithConfig(blockType string, r ConfiguredCategoryBlockRenderer)

RegisterCategoryBlockWithConfig adds a category dashboard block that reads its settings from the layout it sits in.

func RegisterCategoryLead

func RegisterCategoryLead(typeSlug, blockType string)

RegisterCategoryLead draws blockType (registered through RegisterCategoryBlock) under the heading of every category whose type slug is typeSlug, while that category has no arranged home of its own.

func RegisterContentTemplateRoutes

func RegisterContentTemplateRoutes(e *echo.Echo, h *ContentTemplateHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterContentTemplateRoutes adds content template API routes. Templates are readable by all members (for the create form and editor insert menu) but only manageable by campaign owners.

func RegisterCoreBlocks

func RegisterCoreBlocks(r *BlockRegistry)

RegisterCoreBlocks adds core block types to the registry. Called during NewBlockRegistry or app startup before plugins register their own blocks.

func RegisterEntityListRoutes

func RegisterEntityListRoutes(e *echo.Echo, h *EntityListHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterEntityListRoutes mounts the widget. Like the home it sits on, it is public-capable; what a visitor sees is decided by the visibility filter.

func RegisterLayoutPresetRoutes

func RegisterLayoutPresetRoutes(e *echo.Echo, h *LayoutPresetHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterLayoutPresetRoutes adds layout preset API routes. Presets are readable by all members (for the template editor preset picker) but only manageable by campaign owners.

func RegisterPagePinRoutes

func RegisterPagePinRoutes(e *echo.Echo, h *PagePinHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterPagePinRoutes mounts the pins routes. The widget is public-capable, like the home it sits on; pinning for everyone is the Director's, and taking off your own pin needs a member.

func RegisterPageSafetyRoutes

func RegisterPageSafetyRoutes(e *echo.Echo, h *PageSafetyHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterPageSafetyRoutes mounts History and Trash.

func RegisterRoutes

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

RegisterRoutes sets up all entity-related routes on the given Echo instance. Entity routes are scoped to a campaign and require campaign membership. CRUD permissions: Player can view, Scribe can create/edit, Owner can delete. A Scribe edits only the pages they can see and edit (requirePageWrite). View routes use AllowPublicCampaignAccess so public campaigns are browseable without authentication.

func RegisterStandingRoutes

func RegisterStandingRoutes(e *echo.Echo, h *StandingHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterStandingRoutes mounts the Standing block's routes. Reads need a campaign member (the service narrows them further); writes are the Director's.

func RegisterWorldbuildingPromptRoutes

func RegisterWorldbuildingPromptRoutes(e *echo.Echo, h *WorldbuildingPromptHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)

RegisterWorldbuildingPromptRoutes adds worldbuilding prompt API routes. Prompts are readable by all members (shown on entity pages for Scribe+) but only manageable by campaign owners.

func ReindexSearchText

func ReindexSearchText(ctx context.Context, repo EntityRepository, types EntityTypeRepository, typeID int) (int, error)

ReindexSearchText recomputes search_text the way a save would now write it, so pages written before a rule tightened (GM-only text, mention names, GM-only and owner-only field values) get the same guarantee as new saves. typeID 0 sweeps every candidate page; a typeID redoes one category after its fields change. Only rows whose text changes are written, so a later run finds nothing to do. Returns how many rows it rewrote.

func RenderBlock

func RenderBlock(goCtx context.Context, block TemplateBlock, cc *campaigns.CampaignContext, entity *Entity, entityType *EntityType, csrfToken string) templ.Component

RenderBlock dispatches to the global registry. Called by templ components. Returns an empty component if the block type is unregistered or its addon is disabled. The goCtx is the request context from the templ render call; UserID is extracted from it via layouts.GetUserID so renderers don't need to reach back into request-scoped state themselves.

Singleton enforcement (last-resort guard, layered behind ValidateLayout + the layout editor JS): if a singleton block type has already rendered in this request, subsequent instances are replaced with an inline error message. Catches the edge case where a layout slipped past both upstream guards (direct API write, race between save & validate, etc.) without the page silently breaking via duplicate DOM IDs.

func RenderCharacterItemsBlock

func RenderCharacterItemsBlock(BlockRenderContext) templ.Component

RenderCharacterItemsBlock renders the Items & Money block: the page panel set with SetCharacterPagePanel, when its addon is on.

func RequireFamilyDirector

func RequireFamilyDirector() echo.MiddlewareFunc

RequireFamilyDirector is the route gate for the Family tree's edit routes: the campaign owner or a granted co-Director, not a Scribe. The service checks again on every call.

func ResolveCharacterTypeIDs

func ResolveCharacterTypeIDs(types []EntityType, listed []int, skipPlayerCharacter bool) []int

ResolveCharacterTypeIDs expands a list to the enabled types it shows: each listed type plus every enabled sub-type under it. Sub-types come along because that is how the lists always behaved, and a sub-type such as "Villain" under Character is a character page. skipPlayerCharacter leaves the player-character sub-type out of what a listed parent brings in (the NPC list: claimed characters are the party); a type listed by name is always kept. The result follows the order of types.

func RestrictedFieldKeys

func RestrictedFieldKeys(entity *Entity, et *EntityType, canSeeGM, isOwner bool) map[string]struct{}

RestrictedFieldKeys is restrictedFieldKeys for code outside this plugin that reads a page's fields on a reader's behalf without the handler's served copy, so it can leave out exactly what that copy leaves out.

func SearchTerms

func SearchTerms(query string) []string

SearchTerms are the words a snippet marks: the ones Search matched on. A query of four or more characters is matched word by word (FULLTEXT) and a shorter one, or one with no word in it, as one run (LIKE), so the same split is used here.

func SetCampaignSystemResolver

func SetCampaignSystemResolver(f CampaignSystemResolver)

SetCampaignSystemResolver wires the lookup, once at boot. Without it a check made outside a page render can't tell the systems apart and takes a renderer any system binds.

func SetFoundryLinkChecker

func SetFoundryLinkChecker(f FoundryLinkChecker)

SetFoundryLinkChecker wires the check, once at boot. Without it no campaign reads as linked.

func SetGlobalBlockRegistry

func SetGlobalBlockRegistry(reg *BlockRegistry)

SetGlobalBlockRegistry sets the package-level block registry. Called once during app startup after all plugins have registered.

func SetGlobalEntityShowRendererRegistry

func SetGlobalEntityShowRendererRegistry(r *EntityShowRendererRegistry)

SetGlobalEntityShowRendererRegistry installs (or hot-swaps) the registry that show.templ consults at request time. Called from internal/app/routes.go at boot and from the package-install hook. Atomic — safe to call while requests read.

func ShowedCharacterPanel

func ShowedCharacterPanel(et *EntityType) bool

ShowedCharacterPanel reports whether this type's pages drew the panel on their own before it became a block, so it can be placed where it was.

func Slugify

func Slugify(name string) string

Slugify creates a URL-safe slug from a name. Lowercase, replace non-alphanumeric characters with hyphens, trim leading/trailing hyphens.

func StandingWhyText

func StandingWhyText(total int, newest string) string

StandingWhyText is the quiet line under the word: the newest reason, then how many more there are. total is how many reasons this viewer can see; newest is the newest one's text.

func StandingWord

func StandingWord(level int) string

StandingWord is the word for a level; an out-of-range level reads as Neutral rather than failing a page render.

func SystemDrawsHeroes

func SystemDrawsHeroes(ctx context.Context, et *EntityType) bool

SystemDrawsHeroes reports whether a game system draws a player's character of this category in place of the category's layout. A page wearing a named layout is still drawn from that layout, which a caller outside a page render cannot see.

func ValidPermission

func ValidPermission(p Permission) bool

ValidPermission returns true if p is a recognized permission level.

func ValidSubjectType

func ValidSubjectType(s SubjectType) bool

ValidSubjectType returns true if s is a recognized subject type.

func ValidateLayout

func ValidateLayout(layout EntityTypeLayout, isValidBlock func(string) bool, isSingletonBlock func(string) bool, tileSizes tilegrid.SizesFunc) error

ValidateLayout checks that a layout conforms to structural constraints. The optional isValidBlock callback validates block types; if nil, block type validation is skipped (useful for layout presets where block availability is campaign-dependent). The optional isSingletonBlock callback identifies block types that may only appear once per layout (e.g., map_editor — see BlockMeta.Singleton); if nil, the singleton check is skipped. The optional tileSizes callback reports the sizes a block type can take as a tile (BlockMeta.TileSizes); if nil, a tile section's types and size membership are not checked, only its shape.

Error messages are written for the *user* in the layout editor: concise, no internal IDs, no block-system jargon. The save toast in layout_editor.js surfaces them verbatim, so they're the operator's only feedback when a save fails.

func ViewerSeesType

func ViewerSeesType(et *EntityType, role int) bool

ViewerSeesType reports whether a viewer with the given visibility role may know the category exists: every category except a DM-only one is open to everyone who can view the campaign, and a DM-only one is for the owner and Co-DMs (a member with DM access arrives here as Owner). A Scribe sees what players see.

func WithActor

func WithActor(ctx context.Context, userID string) context.Context

WithActor returns ctx marked with the user whose request is saving a page.

func WithEffectiveVisibility

func WithEffectiveVisibility(ctx context.Context, ev *EffectiveVisibility) context.Context

WithEffectiveVisibility returns a context carrying the entity's glance.

func WithSingletonTracker

func WithSingletonTracker(ctx context.Context) context.Context

WithSingletonTracker returns a child context carrying a fresh singleton-tracking map. The page-level templ (entity show, dashboard) should call this once before iterating blocks so the per-request tracker is in scope. If a page forgets, the tracker simply isn't active — duplicate singletons would render twice and break the IIFE, matching pre-tracker behavior. Server-side ValidateLayout still catches it on save.

func WithSyncActor

func WithSyncActor(ctx context.Context, userID string) context.Context

WithSyncActor is WithActor for a sync client (the API key's user): its saves are listed in history as "Sync or import".

func WithUnlimitedPlan

func WithUnlimitedPlan(ctx context.Context) context.Context

WithUnlimitedPlan reads the hero plan without the player limits. A Scribe makes heroes for the table; the hero is flagged once a player claims it if it breaks a rule.

Types

type AddStandingReasonInput

type AddStandingReasonInput struct {
	CampaignID string
	EntityID   string
	// Subject is "party" or a character's page id.
	Subject   string
	Direction string
	Text      string
	When      string
	DMOnly    bool
	// Level is the word the standing becomes; nil keeps the current word (or
	// Neutral for a subject with none yet).
	Level  *int
	Role   int
	UserID string
}

AddStandingReasonInput is a new reason from the Director.

type AddonChecker

type AddonChecker interface {
	IsEnabledForCampaign(ctx context.Context, campaignID string, addonSlug string) (bool, error)
}

AddonChecker is a narrow interface for checking whether an addon is enabled for a campaign. Satisfied by addons.AddonService.

type BacklinkEntity

type BacklinkEntity struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	TypeName  string `json:"type_name"`
	TypeIcon  string `json:"type_icon"`
	TypeColor string `json:"type_color"`
}

BacklinkEntity is the safe, minimal view of a linking entity exposed by the backlinks API — enough to link to it and render its type icon, never its content. Unlike Entity, this type has no Entry/EntryHTML/FieldsData fields to accidentally serialize, so a new field added to Entity can't leak here.

type BacklinkEntry

type BacklinkEntry struct {
	Entity  BacklinkEntity `json:"entity"`
	Snippet string         `json:"snippet"`
	// DmOnly marks a row a player wouldn't get, for a viewer who sees more
	// than players; player view hides it. Always false for players.
	DmOnly bool `json:"dmOnly,omitempty"`
}

BacklinkEntry pairs a linking entity's safe summary with a text snippet showing the context around the @mention. For viewers below Scribe the snippet is built from GM-secret-stripped HTML (see GetBacklinksWithSnippets).

type BlockMeta

type BlockMeta struct {
	Type         string            `json:"type"`
	Label        string            `json:"label"`
	Icon         string            `json:"icon"` // FontAwesome class (e.g., "fa-heading").
	Description  string            `json:"description"`
	Addon        string            `json:"addon,omitempty"`         // Required addon slug; empty = always available.
	Container    bool              `json:"container,omitempty"`     // True for layout containers (two_column, tabs, etc.).
	WidgetSlug   string            `json:"widget_slug,omitempty"`   // For ext_widget blocks: the extension widget slug.
	Contexts     []string          `json:"contexts,omitempty"`      // Editor contexts: "dashboard", "template", "category". Empty = all.
	ConfigFields []ConfigFieldMeta `json:"config_fields,omitempty"` // Declarative config schema for the editor dialog.
	// Singleton blocks may only appear once per layout. Used by blocks
	// whose render path binds fixed DOM IDs (e.g., map_editor's
	// #map-container, #marker-modal) and would silently misbehave with
	// multiple instances on the same page. Enforcement is layered:
	//   1. Layout-editor JS refuses the second drop (UX guard).
	//   2. ValidateLayout rejects the saved JSON (server defense).
	//   3. RenderBlock renders subsequent instances as a clear error
	//      message (last-resort guard if both layers are bypassed).
	Singleton bool `json:"singleton,omitempty"`
	// Retired blocks still render where a saved layout already has them,
	// but the editor no longer offers them, because another block took
	// their place.
	Retired bool `json:"retired,omitempty"`
	// TileSizes are the "WxH" sizes this type can take in a tile section
	// (internal/tilegrid), on a 4-column grid; the first is its default.
	// Empty means the type cannot be a tile. An extension widget declares
	// them as "tile_sizes" on its manifest widget entry.
	TileSizes []string `json:"tile_sizes,omitempty"`
	// Preset is the config a palette entry places, for a type offered once
	// per saved record (a Homebrew Workshop recipe): the editor tells the
	// entries apart by type and preset. PresetOnly marks the bare type,
	// registered for validation and rendering, which the palette never
	// offers on its own.
	Preset     map[string]string `json:"preset,omitempty"`
	PresetOnly bool              `json:"preset_only,omitempty"`
	// Group names the palette heading an entry goes under; empty lets the
	// editor choose from the type.
	Group string `json:"group,omitempty"`
	// ShowsSheet marks a block that draws a page's own sheet or its fields
	// (the attributes, a character sheet, the game system's panels). A
	// layout without one of them leaves its pages with no sheet.
	ShowsSheet bool `json:"shows_sheet,omitempty"`
	// Picture names the small drawing of what the type puts on a page that
	// the Customizer's widget list shows beside its name: one of
	// PictureKinds. Empty draws PictureLines, as a package widget does.
	Picture string `json:"picture,omitempty"`
	// PageTab, when set, also offers the block as a tab of the panel under a
	// page a game system draws, where no layout can place it.
	PageTab *BlockPageTab `json:"-"`
}

BlockMeta describes a block type for the layout editor UI and validation. Both template (entity page) and dashboard block types are registered here so a single source of truth drives palette, validation, and config dialogs.

type BlockPageTab

type BlockPageTab struct {
	// Label is the tab's name; Count selects the rows the tab counts and Act
	// the piece's own add button, which the panel's action button presses.
	Label, Count, Act string
	// State says what the viewer has on this page: how many rows they can
	// see, and whether they may add one. An error, or neither, means no tab.
	State func(ctx context.Context, rc BlockRenderContext) (rows int, canAdd bool, err error)
}

BlockPageTab describes a block's tab under a system-drawn page. The owning plugin fills it, so the entities plugin never names the block.

type BlockPlacementChecker

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

BlockPlacementChecker implements campaigns.BlockPlacementChecker: it is how a fragment that cannot import this plugin learns whether the owner placed its block on a page the guest may open.

func NewBlockPlacementChecker

func NewBlockPlacementChecker(svc EntityService, layouts PageLayoutService) *BlockPlacementChecker

NewBlockPlacementChecker builds the checker. layouts may be nil.

func (*BlockPlacementChecker) GuestMaySee

func (p *BlockPlacementChecker) GuestMaySee(ctx context.Context, campaignID, blockType, onEntityID, userID string, visibilityRole int) bool

GuestMaySee is true only when every step holds: the page exists in this campaign, the viewer may open it (the check a page view makes, at the same role), and the layout the page actually wears draws blockType for them. A page that is missing, in another campaign or hidden answers the same false, so the route cannot be used to probe for pages. Every error is false.

type BlockRegistry

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

BlockRegistry maps block type names to metadata and renderers. Safe for concurrent reads after startup (writes happen only during init).

func GetGlobalBlockRegistry

func GetGlobalBlockRegistry() *BlockRegistry

GetGlobalBlockRegistry returns the package-level block registry.

func NewBlockRegistry

func NewBlockRegistry() *BlockRegistry

NewBlockRegistry creates an empty registry.

func (*BlockRegistry) HasRenderer

func (r *BlockRegistry) HasRenderer(blockType string) bool

HasRenderer reports whether blockType is registered WITH a non-nil renderer. A registered-but-nil renderer (e.g. calendar_preview, a dashboard-only block whose render lives elsewhere) would otherwise panic on dispatch / render blank — RenderBlock uses this to show a placeholder.

func (*BlockRegistry) IsSingleton

func (r *BlockRegistry) IsSingleton(blockType string) bool

IsSingleton returns true if blockType is registered AND declared as a singleton (max one per layout). Used by ValidateLayout to enforce the max-one rule and by the layout editor JS for UX-side guarding. Unknown types return false — they're caught separately by IsValid.

func (*BlockRegistry) IsValid

func (r *BlockRegistry) IsValid(blockType string) bool

IsValid returns true if blockType is a registered block type.

func (*BlockRegistry) IsValidForContext

func (r *BlockRegistry) IsValidForContext(blockType string, editorCtx string) bool

IsValidForContext returns true if blockType is registered and belongs to the given editor context (or has no context restriction). Pass empty editorCtx to skip the context check.

func (*BlockRegistry) PageTabBlocks

func (r *BlockRegistry) PageTabBlocks() []BlockMeta

PageTabBlocks returns the metadata of blocks that offer a tab under a system-drawn page, in registration order.

func (*BlockRegistry) Register

func (r *BlockRegistry) Register(meta BlockMeta, renderer BlockRenderer)

Register adds a block type to the registry. If a type with the same name already exists it is silently overwritten (allows plugin overrides).

func (*BlockRegistry) Render

Render dispatches to the registered renderer for the block type. Returns nil if the block type is not registered, its renderer is nil, or its addon is disabled.

func (*BlockRegistry) SetAddonChecker

func (r *BlockRegistry) SetAddonChecker(ac blockAddonChecker)

SetAddonChecker sets the addon checker used by Render() to skip blocks whose addon is disabled. Must be called after addon service is initialized.

func (*BlockRegistry) SetRecentPagesLister

func (r *BlockRegistry) SetRecentPagesLister(l campaigns.RecentEntityLister)

SetRecentPagesLister sets the source of the Recent Pages block's pages.

func (*BlockRegistry) SetWidgetLister

func (r *BlockRegistry) SetWidgetLister(wl WidgetBlockLister)

SetWidgetLister sets the source of extension widget metadata used to resolve tile sizes for ext_widget blocks.

func (*BlockRegistry) ShowsSheet

func (r *BlockRegistry) ShowsSheet(blockType string) bool

ShowsSheet reports whether blockType is registered and draws a page's sheet or its fields. Unknown types return false.

func (*BlockRegistry) TileSizesFor

func (r *BlockRegistry) TileSizesFor(ctx context.Context, campaignID, blockType string, config map[string]any) []string

TileSizesFor returns the tile sizes a block of blockType can take in the given campaign, or nil when it cannot be a tile (including a type that is not registered). An ext_widget block's sizes belong to the widget its config names, so they come from that widget's manifest entry; a widget the campaign no longer has therefore has no sizes, and its tile shows the not-available notice instead of failing the page.

func (*BlockRegistry) Types

func (r *BlockRegistry) Types() []BlockMeta

Types returns all registered block metadata in registration order.

func (*BlockRegistry) TypesForCampaign

func (r *BlockRegistry) TypesForCampaign(ctx context.Context, campaignID string, checker blockAddonChecker) []BlockMeta

TypesForCampaign returns block metadata filtered by which addons are enabled for the given campaign. Blocks with no addon requirement are always included.

func (*BlockRegistry) TypesForCampaignAndContext

func (r *BlockRegistry) TypesForCampaignAndContext(ctx context.Context, campaignID string, checker blockAddonChecker, editorCtx string) []BlockMeta

TypesForCampaignAndContext returns block metadata filtered by both addon availability and editor context. Pass an empty editorCtx to skip context filtering (returns all blocks for the campaign, same as TypesForCampaign).

The "category" context is the category dashboard editor: it offers every "dashboard" block plus those that list "category", so blocks only a category page can render (extra category blocks) stay out of the campaign dashboard.

type BlockRenderContext

type BlockRenderContext struct {
	Block      TemplateBlock
	CC         *campaigns.CampaignContext
	Entity     *Entity
	EntityType *EntityType
	CSRFToken  string
	UserID     string
}

BlockRenderContext holds the data available to every block renderer. UserID carries the viewing user's ID (extracted from the request context inside RenderBlock). Empty string when unauthenticated. Renderers that need per-user content filtering (e.g. the map editor's per-player marker visibility) read it directly off this struct instead of calling back into the layouts helpers — which keeps the renderer closure signature uniform across all block types.

type BlockRenderer

type BlockRenderer func(ctx BlockRenderContext) templ.Component

BlockRenderer returns a templ.Component for the given block context.

type BuilderHero

type BuilderHero struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Values holds the hero's text fields, so each blank shows what is
	// already chosen. Hidden carries the keys the viewer may not see or
	// change (fields marked GM-only); their values are left out.
	Values map[string]string `json:"values"`
	Hidden []string          `json:"hidden"`
	// Sheet is true when the game system draws this hero's page as its
	// sheet, so the link can promise one; otherwise it opens the plain page.
	Sheet bool `json:"sheet"`
	// Lock is whether the Director's times let the player change the picks
	// now; nil when the campaign has no times, so the builder says nothing.
	Lock *HeroLock `json:"lock,omitempty"`
}

BuilderHero is one of the viewer's heroes as the builder sees it.

type CalendarSearcher

type CalendarSearcher interface {
	SearchCalendarEvents(ctx context.Context, campaignID, query string, role int) ([]map[string]string, error)
}

CalendarSearcher provides calendar event search results for the quick search popup. Implemented by the calendar plugin and injected via SetCalendarSearcher.

type CampaignSystemResolver

type CampaignSystemResolver func(ctx context.Context, campaignID string) string

CampaignSystemResolver names the game system a campaign runs (its module id), "" for none.

type CastBandEditor

type CastBandEditor struct {
	Kind    CharacterListKind
	Label   string
	Chips   []CastChip
	Options []CastTypeOption
}

CastBandEditor is what the owner's controls on one band render from.

type CastChip

type CastChip struct {
	ID   int
	Name string
}

CastChip is one chosen type on a band.

type CastMember

type CastMember struct {
	Entity    Entity
	OwnerName string
	IsViewer  bool
}

CastMember is one card on the Characters ("Cast") page: an entity plus the display flags the card needs. OwnerName is the resolved display name of a player character's owner (empty for NPCs); IsViewer marks the card as belonging to the viewing user so it can be highlighted and sorted first.

type CastTypeOption

type CastTypeOption struct {
	ID    int
	Name  string
	IsSub bool
	Count int
	// With names the sub-types that come along when this type is added.
	With []string
}

CastTypeOption is one type the owner can still add to a band.

type CastView

type CastView struct {
	Yours       []CastMember
	Party       []CastMember
	ShowPlayers bool
	// IsMember is false for signed-out and non-member viewers of a public
	// campaign; member-only links (claim hint) hide for them.
	IsMember bool
	// ClaimTypeID is the claimable type whose list the empty-party hint links
	// to; 0 means no link.
	ClaimTypeID int
	NPCSection  templ.Component

	// ShowNPCs is true when the npcs addon is on and its section is wired.
	ShowNPCs bool
	// PartyListed and NPCsListed say whether the owner has listed any page
	// type for that band. A band with none is hidden from everyone but the
	// owner, who sees the Add control instead.
	PartyListed bool
	NPCsListed  bool
	// PartyEditor and NPCEditor are the owner's controls; nil for everyone
	// else, so a player's page carries no controls at all.
	PartyEditor *CastBandEditor
	NPCEditor   *CastBandEditor
	// Landed is the type just added, flashed once on its chip.
	Landed int
	// Notice is a one-line confirmation shown as a toast after a change.
	Notice string
	// Alert is a lasting line shown above the page when something needs the
	// reader's action; unlike Notice it does not fade.
	Alert     string
	CSRFToken string
	// CanCreateHero shows the Create hero button: staff always, a player when
	// the owner lets players claim the hero's page type.
	CanCreateHero bool
	// Roster is who plays whom for the Party band's page types, for staff
	// who may reassign; nil hides the control.
	Roster *ClaimRoster
	// Pickable is, for a member with no character of their own, the playable
	// characters nobody has claimed yet that they may see.
	Pickable []Entity
	// Open names the band box rendered open, so a reassign answers with the
	// list still in view.
	Open string
	// Builder is the hero builder for the viewer's own heroes and a new
	// one; nil hides it.
	Builder *HeroBuilderView
	// Practice is the player's Practice shelf; nil for anyone who may not
	// make practice heroes. PracticeDirector is every practice hero of the
	// campaign for the Directors; nil for everyone else, or when none exist.
	Practice         *PracticeShelfView
	PracticeDirector *PracticeDirectorView
	// HeroChanges is the Directors' section that sets when players may
	// change their hero's picks; nil for everyone else.
	HeroChanges *HeroChangesView
	// Tryout is the mount for a try-out kept in the viewer's browser: a
	// visitor's Practice section or a player's offer to keep it. nil otherwise.
	Tryout *TryoutView
}

CastView is the Characters page view-model. The page has addon-gated bands: Yours (the viewer's own characters), the Party (claimed player characters of the types the owner listed, shown when ShowPlayers, i.e. the player-character-claiming addon is on) and the NPCs band (NPCSection, a templ component contributed by the npcs plugin when its addon is on, nil otherwise). The page itself is only served when at least one of the two addons is enabled.

type CategoryBlockRenderer

type CategoryBlockRenderer func(cc *campaigns.CampaignContext, et *EntityType) templ.Component

CategoryBlockRenderer draws one extra block on a category dashboard. It gets the viewer's campaign context and the category, and must decide what the viewer may see itself.

type CharacterHomeMove

type CharacterHomeMove struct {
	FromTypeID int
	FromName   string // the system type's plural name, e.g. "Heroes"
	ToTypeID   int
	ToName     string // "Characters", or whatever the owner renamed it to
	Pages      int    // pages to move, or moved (Trash included)
	NoOp       bool   // nothing to move
}

CharacterHomeMove describes moving a system character type's pages into "Characters": pending (from CharacterHomeCandidate) or done.

type CharacterListKind

type CharacterListKind string

CharacterListKind names one of the two lists.

const (
	// CharacterListCharacters is the list behind The Party and stashes.
	CharacterListCharacters CharacterListKind = "characters"
	// CharacterListNPCs is the list behind the NPC gallery and DM Screen.
	CharacterListNPCs CharacterListKind = "npcs"
)

func (CharacterListKind) Valid

func (k CharacterListKind) Valid() bool

Valid reports whether k names a list.

type CharacterListManager

type CharacterListManager interface {
	CharacterListReader
	// Chosen returns the explicit lists, stale IDs pruned.
	Chosen(ctx context.Context, campaignID string) (CharacterLists, error)
	// Editor describes one band's chips and the types still addable.
	Editor(ctx context.Context, campaignID string, kind CharacterListKind) (CastBandEditor, error)
	// Add and Remove return the type's name for the confirmation message.
	Add(ctx context.Context, campaignID string, kind CharacterListKind, typeID int) (string, error)
	Remove(ctx context.Context, campaignID string, kind CharacterListKind, typeID int) (string, error)
}

CharacterListManager is what the Characters page handler needs.

type CharacterListReader

type CharacterListReader interface {
	CharacterTypeIDs(ctx context.Context, campaignID string) ([]int, error)
	NPCTypeIDs(ctx context.Context, campaignID string) ([]int, error)
}

CharacterListReader is what other plugins' adapters read: the page types to treat as characters or NPCs, sub-types included, deleted types gone.

type CharacterListService

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

CharacterListService implements CharacterListManager and the campaigns plugin's CharacterListSeeder.

func NewCharacterListService

func NewCharacterListService(types CharacterTypeSource, store CharacterListStore) *CharacterListService

NewCharacterListService wires the service.

func (*CharacterListService) Add

func (s *CharacterListService) Add(ctx context.Context, campaignID string, kind CharacterListKind, typeID int) (string, error)

Add lists a type. The type must belong to the campaign. Listing a type that is already covered changes nothing; listing a parent absorbs its listed sub-types, which it now covers.

func (*CharacterListService) CharacterTypeIDs

func (s *CharacterListService) CharacterTypeIDs(ctx context.Context, campaignID string) ([]int, error)

CharacterTypeIDs is the characters list with sub-types included.

func (*CharacterListService) Chosen

func (s *CharacterListService) Chosen(ctx context.Context, campaignID string) (CharacterLists, error)

Chosen returns the explicit lists with IDs of deleted types dropped. A campaign that never chose is seeded first (seedOnRead).

func (*CharacterListService) CreatureTypeIDs

func (s *CharacterListService) CreatureTypeIDs(ctx context.Context, campaignID string) ([]int, error)

CreatureTypeIDs is CreatureTypeIDs for one campaign.

func (*CharacterListService) Editor

func (s *CharacterListService) Editor(ctx context.Context, campaignID string, kind CharacterListKind) (CastBandEditor, error)

Editor builds a band's controls: the chosen types as chips and every other enabled type, not already covered, as an option with its page count.

func (*CharacterListService) NPCTypeIDs

func (s *CharacterListService) NPCTypeIDs(ctx context.Context, campaignID string) ([]int, error)

NPCTypeIDs is the NPC list with sub-types included, minus the player character sub-type: claimed player characters are the party, not NPCs.

func (*CharacterListService) Remove

func (s *CharacterListService) Remove(ctx context.Context, campaignID string, kind CharacterListKind, typeID int) (string, error)

Remove unlists a type. Saving also drops IDs of deleted types.

func (*CharacterListService) Seed

func (s *CharacterListService) Seed(ctx context.Context, campaignID string) error

Seed records the starting lists for a campaign that has none, from seedCharacterLists. A campaign that already chose is left alone, so running it twice, or after the owner edited, changes nothing.

func (*CharacterListService) SetChangeHook

func (s *CharacterListService) SetChangeHook(fn func(campaignID string))

SetChangeHook registers a callback run after the lists change, so a cache keyed on them can drop its copy.

func (*CharacterListService) SetPanelPlacer

func (s *CharacterListService) SetPanelPlacer(p SystemPanelPlacer)

SetPanelPlacer registers what places the Game System Panels block on a type that joins the NPC list. Game-system panels show only where a layout places that block, so without it a type listed after the one-time placement shows none.

type CharacterListStore

type CharacterListStore interface {
	// Get returns the stored lists; ok is false when the campaign never chose.
	Get(ctx context.Context, campaignID string) (lists CharacterLists, ok bool, err error)
	Save(ctx context.Context, campaignID string, lists CharacterLists) error
}

CharacterListStore persists the lists. The composition root implements it over the campaign settings so this plugin never touches the campaigns repository.

type CharacterLists

type CharacterLists struct {
	CharacterTypeIDs []int
	NPCTypeIDs       []int
}

CharacterLists is what the owner chose: the page types listed explicitly. Sub-types of a listed type count as listed too (see ResolveCharacterTypeIDs), so they are not stored.

type CharacterTypeSource

type CharacterTypeSource interface {
	GetEntityTypes(ctx context.Context, campaignID string) ([]EntityType, error)
	CountByType(ctx context.Context, campaignID string, role int, userID string) (map[int]int, error)
}

CharacterTypeSource is the slice of the entity service the lists need.

type ChildOrderRepository

type ChildOrderRepository interface {
	// ListByCampaign returns every stored order, keyed by childOrderKey.
	// A container that is missing sorts A to Z.
	ListByCampaign(ctx context.Context, campaignID string) (map[string]string, error)
	// Set stores mode for one container; OrderAZ removes the row.
	Set(ctx context.Context, campaignID, kind, id, mode string) error
}

ChildOrderRepository stores how each sidebar container orders its rows.

func NewChildOrderRepository

func NewChildOrderRepository(db *sql.DB) ChildOrderRepository

NewChildOrderRepository creates the sidebar order repository.

type ClaimRoster

type ClaimRoster struct {
	Characters []Entity                   // All characters of the category, by name.
	Members    []campaigns.CampaignMember // Campaign members assignable as owners.
	OwnerNames map[string]string          // owner_user_id -> display name.
}

ClaimRoster carries the GM owner-overview data for a claimable category dashboard. It is assembled by the Index handler only for a Scribe+ viewer of a claimable entity type with the Player Character Claiming addon enabled; nil otherwise, in which case the roster panel is not rendered. Characters lists every entity of the category (not just the paginated dashboard page); Members is the set of assignable owners for the reassign dropdown; OwnerNames resolves an entity's owner_user_id to a display name.

type ClimateChoice

type ClimateChoice struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Magic bool   `json:"magic,omitempty"`
}

ClimateChoice is one climate a place can take.

type ClimateShown

type ClimateShown struct {
	// Own is set when the page holds the climate itself.
	Own bool `json:"own"`
	// From and FromHref name the page the climate comes from, only when the
	// viewer may open it.
	From     string        `json:"from,omitempty"`
	FromHref string        `json:"fromHref,omitempty"`
	Today    *ClimateToday `json:"today,omitempty"`
	// Covers says pages under this one follow its climate; Here is this
	// page's name for that line.
	Covers bool   `json:"covers,omitempty"`
	Here   string `json:"here,omitempty"`
}

ClimateShown is how a climate field reads beyond its name.

type ClimateToday

type ClimateToday struct {
	Date string `json:"date"`
	// Words is "Light rain, 6°"; empty when the day has no weather yet.
	Words     string `json:"words,omitempty"`
	PartyHere bool   `json:"partyHere,omitempty"`
}

ClimateToday is a region's weather today, in words.

type ConfigFieldMeta

type ConfigFieldMeta struct {
	Key     string   `json:"key"`
	Label   string   `json:"label"`
	Type    string   `json:"type"`          // "number", "text", "textarea", "select", "entity_type", "map", "page"
	Min     *int     `json:"min,omitempty"` // For "number" type.
	Max     *int     `json:"max,omitempty"` // For "number" type.
	Default any      `json:"default,omitempty"`
	Options []Option `json:"options,omitempty"` // For "select" type.
	// Hint is one plain line shown under the field.
	Hint string `json:"hint,omitempty"`
}

ConfigFieldMeta describes a single configurable field for a block type. The layout editor auto-generates a config dialog from these declarations.

type ConfiguredCategoryBlockRenderer

type ConfiguredCategoryBlockRenderer func(cc *campaigns.CampaignContext, et *EntityType, config map[string]any) templ.Component

ConfiguredCategoryBlockRenderer is a CategoryBlockRenderer for a block with settings. config is what the owner saved on this block in the category's layout, read server-side; it is never taken from the request.

type ContentTemplate

type ContentTemplate struct {
	ID           int       `json:"id"`
	CampaignID   *string   `json:"campaign_id,omitempty"` // nil for global templates.
	EntityTypeID *int      `json:"entity_type_id,omitempty"`
	Name         string    `json:"name"`
	Description  string    `json:"description"`
	ContentJSON  string    `json:"content_json"` // TipTap/ProseMirror document JSON.
	ContentHTML  string    `json:"content_html"` // Pre-rendered HTML for preview.
	Icon         string    `json:"icon"`
	SortOrder    int       `json:"sort_order"`
	IsGlobal     bool      `json:"is_global"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`

	// Joined fields (optional).
	EntityTypeName string `json:"entity_type_name,omitempty"`
}

ContentTemplate is a reusable content blueprint that pre-fills the editor when creating or editing an entity. Templates can be global (available to all campaigns) or scoped to a single campaign, and optionally bound to a specific entity type.

type ContentTemplateHandler

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

ContentTemplateHandler handles HTTP requests for content templates.

func NewContentTemplateHandler

func NewContentTemplateHandler(service ContentTemplateService) *ContentTemplateHandler

NewContentTemplateHandler creates a new content template handler.

func (*ContentTemplateHandler) CreateAPI

func (h *ContentTemplateHandler) CreateAPI(c *echo.Context) error

CreateAPI creates a new content template. POST /campaigns/:id/content-templates

func (*ContentTemplateHandler) DeleteAPI

func (h *ContentTemplateHandler) DeleteAPI(c *echo.Context) error

DeleteAPI deletes a content template. DELETE /campaigns/:id/content-templates/:tid

func (*ContentTemplateHandler) GetAPI

func (h *ContentTemplateHandler) GetAPI(c *echo.Context) error

GetAPI returns a single content template by ID. GET /campaigns/:id/content-templates/:tid

func (*ContentTemplateHandler) ListAPI

func (h *ContentTemplateHandler) ListAPI(c *echo.Context) error

ListAPI returns content templates for a campaign as JSON. GET /campaigns/:id/content-templates Optional query: ?entity_type_id=N to filter by entity type.

func (*ContentTemplateHandler) UpdateAPI

func (h *ContentTemplateHandler) UpdateAPI(c *echo.Context) error

UpdateAPI updates an existing content template. PUT /campaigns/:id/content-templates/:tid

type ContentTemplateRepository

type ContentTemplateRepository interface {
	Create(ctx context.Context, t *ContentTemplate) error
	FindByID(ctx context.Context, id int) (*ContentTemplate, error)
	ListForCampaign(ctx context.Context, campaignID string) ([]ContentTemplate, error)
	ListForCampaignAndType(ctx context.Context, campaignID string, entityTypeID int) ([]ContentTemplate, error)
	Update(ctx context.Context, t *ContentTemplate) error
	Delete(ctx context.Context, id int) error
}

ContentTemplateRepository defines data access for content templates.

func NewContentTemplateRepository

func NewContentTemplateRepository(db *sql.DB) ContentTemplateRepository

NewContentTemplateRepository creates a new content template repository.

type ContentTemplateService

type ContentTemplateService interface {
	Create(ctx context.Context, campaignID string, input CreateContentTemplateInput) (*ContentTemplate, error)
	GetByID(ctx context.Context, id int) (*ContentTemplate, error)
	ListForCampaign(ctx context.Context, campaignID string) ([]ContentTemplate, error)
	ListForCampaignAndType(ctx context.Context, campaignID string, entityTypeID int) ([]ContentTemplate, error)
	Update(ctx context.Context, id int, input UpdateContentTemplateInput) (*ContentTemplate, error)
	Delete(ctx context.Context, id int) error
	SeedDefaults(ctx context.Context, campaignID string) error
}

ContentTemplateService handles business logic for content templates.

func NewContentTemplateService

func NewContentTemplateService(repo ContentTemplateRepository, types EntityTypeRepository) ContentTemplateService

NewContentTemplateService creates a new content template service.

type CountdownLength

type CountdownLength struct {
	Name string `json:"name,omitempty"`
	Days int    `json:"days"`
}

CountdownLength is one length a countdown can run. The first is the usual one and needs no name; the others are named for when they apply.

type CountdownShown

type CountdownShown struct {
	Name string `json:"name"`
	// Days is the length this page uses; Length its name, if it has one.
	Days   int    `json:"days"`
	Length string `json:"length,omitempty"`
	// State is "before" (the date is still to come), "running", "last" (its
	// last day is today) or "ended".
	State string `json:"state"`
	Left  int    `json:"left"`
	// Done is how many of its days have passed, for the ticks.
	Done int `json:"done"`
	// Last is its last day's label.
	Last         string `json:"last"`
	DirectorOnly bool   `json:"directorOnly,omitempty"`
}

CountdownShown is one countdown as of the calendar's today.

type CreateContentTemplateInput

type CreateContentTemplateInput struct {
	CampaignID   string
	EntityTypeID int // 0 = applies to all entity types.
	Name         string
	Description  string
	ContentJSON  string
	ContentHTML  string
	Icon         string
}

CreateContentTemplateInput holds validated input for creating a content template.

type CreateEntityInput

type CreateEntityInput struct {
	Name         string
	EntityTypeID int
	TypeLabel    string
	ParentID     string // Empty string = no parent.
	IsPrivate    bool
	FieldsData   map[string]any
	// OwnerUserID claims the entity for a player at create time. Optional;
	// nil means unclaimed. Only honored if the user is a member of the
	// target campaign — the service rejects cross-campaign assignments.
	// Foundry sync uses this to auto-claim character entities to the
	// chronicle user mapped from the Foundry actor's owner.
	OwnerUserID *string
	// Playable marks the new page as a character a player may play before
	// anyone claims it; the hero creator sets it for heroes a Director makes.
	Playable bool
	// ShopGood creates the page as a shop good (see Entity.ShopGood). Import
	// sets it to bring an exported good back as it was.
	ShopGood bool
}

CreateEntityInput is the validated input for creating an entity.

type CreateEntityRequest

type CreateEntityRequest struct {
	Name         string `json:"name" form:"name"`
	EntityTypeID int    `json:"entity_type_id" form:"entity_type_id"`
	TypeLabel    string `json:"type_label" form:"type_label"`
	ParentID     string `json:"parent_id" form:"parent_id"`
	// IsPrivate is a pointer so an explicit false ("show it to players")
	// survives under a campaign whose pages start hidden; nil means the form
	// said nothing and the campaign default decides.
	IsPrivate  *bool `json:"is_private" form:"is_private"`
	TemplateID int   `json:"template_id" form:"template_id"` // Optional content template to pre-fill.
	// Sheet marks a form posted from the small sheet, so a refused save
	// redraws the sheet and not the full page.
	Sheet bool `json:"-" form:"sheet"`
}

CreateEntityRequest holds the data submitted by the entity creation form.

type CreateEntityTypeInput

type CreateEntityTypeInput struct {
	Name           string
	NamePlural     string
	Icon           string
	Color          string
	PresetCategory string            // Optional system preset category (e.g., "item", "character").
	ParentTypeID   *int              // Optional parent type for sub-type hierarchy.
	Claimable      *bool             // Optional explicit player-claim flag. nil = unset (service may default it for PC types).
	Fields         []FieldDefinition // Optional initial field schema (e.g. from a system preset). nil = none.
}

CreateEntityTypeInput is the validated input for creating an entity type.

type CreateEntityTypeRequest

type CreateEntityTypeRequest struct {
	Name         string `json:"name" form:"name"`
	NamePlural   string `json:"name_plural" form:"name_plural"`
	Icon         string `json:"icon" form:"icon"`
	Color        string `json:"color" form:"color"`
	ParentTypeID *int   `json:"parent_type_id" form:"parent_type_id"`
	Claimable    *bool  `json:"claimable,omitempty" form:"claimable"`
}

CreateEntityTypeRequest holds the data submitted by the entity type creation form.

type CreateLayoutPresetInput

type CreateLayoutPresetInput struct {
	CampaignID  string
	Name        string
	Description string
	LayoutJSON  string
	Icon        string
}

CreateLayoutPresetInput holds validated input for creating a layout preset.

type CreatePromptInput

type CreatePromptInput struct {
	Name         string `json:"name"`
	PromptText   string `json:"prompt_text"`
	EntityTypeID *int   `json:"entity_type_id,omitempty"` // nil = all types.
	Icon         string `json:"icon,omitempty"`
}

CreatePromptInput holds input for creating a worldbuilding prompt.

type CreateSidebarNodeInput

type CreateSidebarNodeInput struct {
	Name         string
	EntityTypeID int
	ParentID     string // Empty = root level.
}

CreateSidebarNodeInput is the validated input for creating a sidebar node.

type CustomizeCategoriesPatch

type CustomizeCategoriesPatch struct {
	Items map[string]CustomizeCategoryItem
}

CustomizeCategoriesPatch is the whole "categories" section: items keyed by an existing category id (decimal) or a "new-" key.

type CustomizeCategoriesResult

type CustomizeCategoriesResult struct {
	// Created maps the key of each category made to its new id. It also holds
	// a category created whose later step failed, so the caller can address it.
	Created map[string]int
	// Applied lists the keys that were fully applied, in the order done.
	Applied []string
}

CustomizeCategoriesResult reports what was applied before any failure.

type CustomizeCategoryInfo

type CustomizeCategoryInfo struct {
	Type EntityType
	// Claimable is the effective value, after the heuristics for a type whose
	// owner never chose.
	Claimable bool
	Pages     int
	Trashed   int
	// Sample is the name of one real page in the category (its most recently
	// changed), for the Customize wall's picture of that kind of page.
	Sample string
}

CustomizeCategoryInfo is a category with the numbers the Customize page shows beside it.

type CustomizeCategoryItem

type CustomizeCategoryItem struct {
	// New marks a category made in the draft. Its key must start with "new-"
	// and Name and NamePlural are required.
	New        bool   `json:"new,omitempty"`
	Name       string `json:"name,omitempty"`
	NamePlural string `json:"name_plural,omitempty"`
	Icon       string `json:"icon,omitempty"`
	Color      string `json:"color,omitempty"`
	Claimable  *bool  `json:"claimable,omitempty"`
	// Parent is the key of the parent category: an existing id or another
	// "new-" key. With ClearParent it is ignored and the category goes top-level.
	Parent      string `json:"parent,omitempty"`
	ClearParent bool   `json:"clear_parent,omitempty"`
	// CopyFrom copies an existing category's layout and fields into a new one.
	CopyFrom int `json:"copy_from,omitempty"`
	// Menu is the players' sidebar-menu setting. The campaigns plugin owns the
	// sidebar, so the caller applies it; this service only carries it.
	Menu *bool `json:"menu,omitempty"`
	// Layout replaces an existing category's page layout. It is checked by
	// the same ValidateLayout a direct layout save runs.
	Layout *EntityTypeLayout `json:"layout,omitempty"`
	// Home replaces an existing category's home (its landing page) layout,
	// checked like a direct save of it.
	Home *campaigns.DashboardLayout `json:"home,omitempty"`
	// Fields replaces an existing category's field definitions. They are
	// checked by the same rules as a direct save of them.
	Fields *[]FieldDefinition `json:"fields,omitempty"`
	// Description replaces an existing category's description; empty clears it.
	Description *string `json:"description,omitempty"`
	// PageLayouts replaces an existing category's named layouts (the ones
	// besides its main layout); each one's blocks are checked like Layout.
	PageLayouts *PageLayouts `json:"page_layouts,omitempty"`
	// Delete removes an existing category.
	Delete bool `json:"delete,omitempty"`
	// MoveTo, with Delete, is the existing category (its id) that takes the
	// deleted one's pages first, so a category with pages can go without
	// losing any. See category_merge.go.
	MoveTo string `json:"move_to,omitempty"`
}

CustomizeCategoryItem is one category's change in the Customize draft. Empty text fields mean "unchanged"; none of them can legitimately be empty.

type DateShown

type DateShown struct {
	// Ago says how long ago the date was, when the field asks for it.
	Ago        string           `json:"ago,omitempty"`
	Countdowns []CountdownShown `json:"countdowns,omitempty"`
}

DateShown is how a calendar date field reads beyond its label.

type DeskProvider

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

DeskProvider fills the desk's Trash line.

func NewDeskProvider

func NewDeskProvider(svc PageSafetyService) *DeskProvider

NewDeskProvider returns the desk provider for the Trash.

func (*DeskProvider) Facts

Facts counts pages plus the other kinds the Trash holds (pictures, game nights, maps), the same list the Trash page draws, so the two agree.

func (*DeskProvider) Slot

func (p *DeskProvider) Slot() campaigns.DeskSlot

Slot is the one desk line this provider fills.

type DiffPart

type DiffPart struct {
	Op   byte // ' ' same, '+' added, '-' removed
	Text string
}

DiffPart is one run of a word-level diff: unchanged, added or removed text.

func DiffWords

func DiffWords(older, newer string) []DiffPart

DiffWords returns a word-level diff from older to newer text, or a line-level one when the texts are too long for words.

type EffectivePermission

type EffectivePermission struct {
	CanView bool
	CanEdit bool
}

EffectivePermission is the resolved access level for a specific user on a specific entity after merging all applicable grants (role-based, user-based).

type EffectiveVisibility

type EffectiveVisibility struct {
	// BaseState is the configured visibility (everyone / dm_only / custom).
	BaseState string
	// WidenedByTags is true when an otherwise-hidden entity (dm_only or custom)
	// is exposed to additional subjects via one or more tag grants.
	WidenedByTags bool
	// TagGrants are the tag-derived grants on the entity, for the tooltip.
	TagGrants []EntityTagGrantInfo
}

EffectiveVisibility is the server-computed glance for one entity: its base configured state plus whether tag grants WIDEN it and to whom. A tag must never silently expose content, so wherever a Scribe+ sees an entity's visibility they must also see any tag that exposed it.

func ComputeEffectiveVisibility

func ComputeEffectiveVisibility(entity *Entity, grants []EntityTagGrantInfo) EffectiveVisibility

ComputeEffectiveVisibility combines an entity's configured visibility with its tag-derived grants. Tags only *widen*, so an already-everyone entity is never marked widened (it's visible to all members regardless); widening is reported only for dm_only / custom entities that tag grants expose further.

func GetEffectiveVisibility

func GetEffectiveVisibility(ctx context.Context) *EffectiveVisibility

GetEffectiveVisibility returns the glance injected for this request, or nil when none was computed (e.g. a player view, where the badge is not rendered).

type Entity

type Entity struct {
	ID              string         `json:"id"`
	CampaignID      string         `json:"campaign_id"`
	EntityTypeID    int            `json:"entity_type_id"`
	Name            string         `json:"name"`
	Slug            string         `json:"slug"`
	Entry           *string        `json:"entry,omitempty"`             // TipTap/ProseMirror JSON document.
	EntryHTML       *string        `json:"entry_html,omitempty"`        // Pre-rendered HTML from entry.
	PlayerNotes     *string        `json:"player_notes,omitempty"`      // Player-facing ProseMirror JSON (synced as a player-visible Foundry page).
	PlayerNotesHTML *string        `json:"player_notes_html,omitempty"` // Pre-rendered HTML from player_notes.
	ImagePath       *string        `json:"image_path,omitempty"`
	CoverImagePath  *string        `json:"cover_image_path,omitempty"` // Full-width banner image.
	ParentID        *string        `json:"parent_id,omitempty"`        // Parent entity ID (hierarchy). Mutually exclusive with ParentNodeID.
	ParentNodeID    *string        `json:"parent_node_id,omitempty"`   // Parent sidebar folder node ID. Mutually exclusive with ParentID.
	SortOrder       int            `json:"sort_order"`                 // Manual ordering within parent/category (0 = default).
	TypeLabel       *string        `json:"type_label,omitempty"`       // Freeform subtype (e.g., "City" for a Location).
	IsPrivate       bool           `json:"is_private"`
	Visibility      VisibilityMode `json:"visibility"`
	IsTemplate      bool           `json:"is_template"`
	// ShopGood marks a page that exists only to be sold: kept out of lists,
	// search, Auto-link and sync until the Director makes it a full page.
	ShopGood       bool            `json:"shop_good"`
	FieldsData     map[string]any  `json:"fields_data"`
	FieldOverrides *FieldOverrides `json:"field_overrides,omitempty"` // Per-entity field customizations.
	PopupConfig    *PopupConfig    `json:"popup_config,omitempty"`    // Controls hover tooltip content.
	CreatedBy      string          `json:"created_by"`
	// OwnerUserID claims an entity for a player. Nullable: most entities
	// (locations, factions, lore) are not owned. Character-shaped entities
	// surface in the owner's Yours band on the Characters page. Set by Foundry
	// sync (when the actor's owner maps to a chronicle user) or by the
	// player claim flow on entity show.
	OwnerUserID *string `json:"owner_user_id,omitempty"`
	// Playable marks a character a player may play. With OwnerUserID it
	// decides who is on the Characters page's Players list, so NPCs
	// sharing a category stay off it. Setting an owner also sets it.
	Playable bool `json:"playable"`
	// MapID points the entity at one of the campaign's maps and powers
	// the per-entity Map Editor block. Nullable — most entities aren't
	// "a map." FK enforces same-campaign integrity (added by the maps
	// plugin migration 005); ON DELETE SET NULL handles map deletion
	// gracefully (entity falls back to the picker / empty state).
	MapID     *string   `json:"map_id,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// Joined fields from entity_types (populated by repository queries).
	TypeName       string `json:"type_name,omitempty"`
	TypeNamePlural string `json:"type_name_plural,omitempty"` // Joined entity_types.name_plural — used by breadcrumbs and category links.
	TypeIcon       string `json:"type_icon,omitempty"`
	TypeColor      string `json:"type_color,omitempty"`
	TypeSlug       string `json:"type_slug,omitempty"`
	// TypeDMOnly is set when the page's category is for the DM team only, so
	// the page is hidden from players whatever its own visibility says.
	TypeDMOnly bool `json:"-"`

	// Tags is populated at the handler level via batch fetch, not by the repository.
	Tags []EntityTagInfo `json:"tags,omitempty"`

	// Opening is the page's first words as this reader is served them, set
	// by the list handler for pages with no picture so the Gallery has
	// something true to show. Never the stored text: it has had secrets and
	// links to hidden pages taken out.
	Opening string `json:"-"`
	// contains filtered or unexported fields
}

Entity represents a single worldbuilding object — a character, location, item, or any other type defined in the campaign's entity types.

func (*Entity) EffectivePopupConfig

func (e *Entity) EffectivePopupConfig() *PopupConfig

EffectivePopupConfig returns the entity's popup config, falling back to defaults if not configured.

func (*Entity) IsOwnedBy

func (e *Entity) IsOwnedBy(userID string) bool

IsOwnedBy reports whether userID is this entity's claimed owner (used to gate OwnerOnly field VALUES — see FilterRestrictedFields). False for an unclaimed entity, an empty/anonymous userID, or a nil receiver (so callers don't need a separate nil-entity check before asking).

type EntityAlias

type EntityAlias struct {
	ID        int       `json:"id"`
	EntityID  string    `json:"entity_id"`
	Alias     string    `json:"alias"`
	CreatedAt time.Time `json:"created_at"`
}

EntityAlias represents an alternative name for an entity. Aliases appear in auto-linking, search, and @mention results alongside the primary name.

type EntityEventPublisher

type EntityEventPublisher interface {
	PublishEntityEvent(eventType, campaignID, entityID string, entity *Entity)
	PublishEntityTypeEvent(eventType, campaignID string, entityType *EntityType)
}

EntityEventPublisher emits domain events when entities or entity types change. Implemented by the WebSocket EventBus adapter in routes.go.

type EntityHookDispatcher

type EntityHookDispatcher interface {
	EntityChanged(ctx context.Context, eventType, campaignID string, entity *Entity)
}

EntityHookDispatcher tells extension (WASM) plugins that a page changed. Implemented by the extensions hook dispatcher; the context carries the write's origin so the dispatcher can skip a plugin's own writes.

type EntityListHandler

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

EntityListHandler serves the Entity List home widget: one category's pages, as far as the viewer may open them.

func NewEntityListHandler

func NewEntityListHandler(svc EntityService) *EntityListHandler

NewEntityListHandler creates the Entity List widget handler.

func (*EntityListHandler) Widget

func (h *EntityListHandler) Widget(c *echo.Context) error

Widget draws the list for ?type=<category id>&limit=<n>. A Director looking as a player reads pages as a player, so the home previews what players see.

type EntityNameEntry

type EntityNameEntry struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Slug     string `json:"slug"`
	TypeName string `json:"type_name"`
	TypeIcon string `json:"type_icon"`
	TypeSlug string `json:"type_slug"`
	IsAlias  bool   `json:"is_alias,omitempty"`
}

EntityNameEntry is a lightweight entity record for auto-linking. Contains just enough data to detect entity names in editor text and create links. Sorted by name length descending so longer names match first. Alias entries appear as separate rows with IsAlias=true, pointing to the same entity ID so the auto-linker matches them naturally.

type EntityPermission

type EntityPermission struct {
	ID          int         `json:"id"`
	EntityID    string      `json:"entity_id"`
	SubjectType SubjectType `json:"subject_type"`
	SubjectID   string      `json:"subject_id"` // Role level as string ("1","2","3") or user UUID.
	Permission  Permission  `json:"permission"`
	CreatedAt   time.Time   `json:"created_at"`
}

EntityPermission is a single access grant on an entity.

type EntityPermissionRepository

type EntityPermissionRepository interface {
	// ListByEntity returns all permission grants for an entity.
	ListByEntity(ctx context.Context, entityID string) ([]EntityPermission, error)

	// SetPermissions replaces all permissions for an entity in a single transaction.
	SetPermissions(ctx context.Context, entityID string, grants []PermissionGrant) error

	// DeleteByEntity removes all permission grants for an entity.
	DeleteByEntity(ctx context.Context, entityID string) error

	// GetEffectivePermission resolves the effective access level for a user on an entity
	// by checking role-based and user-specific grants.
	GetEffectivePermission(ctx context.Context, entityID string, role int, userID string) (*EffectivePermission, error)

	// UpdateVisibility sets the visibility mode for an entity.
	UpdateVisibility(ctx context.Context, entityID string, visibility VisibilityMode) error
}

EntityPermissionRepository defines the data access contract for per-entity permission grants.

func NewEntityPermissionRepository

func NewEntityPermissionRepository(db *sql.DB) EntityPermissionRepository

NewEntityPermissionRepository creates a new entity permission repository.

type EntityRepository

type EntityRepository interface {
	Create(ctx context.Context, entity *Entity) error
	FindByID(ctx context.Context, id string) (*Entity, error)
	FindBySlug(ctx context.Context, campaignID, slug string) (*Entity, error)
	Update(ctx context.Context, entity *Entity) error
	UpdateEntry(ctx context.Context, id, entryJSON, entryHTML, searchText string) error
	UpdatePlayerNotes(ctx context.Context, id, notesJSON, notesHTML string) error
	UpdateFields(ctx context.Context, id string, fieldsData map[string]any, searchText string) error
	MergeFieldsData(ctx context.Context, id string, merge FieldsMergeFunc) (before, after map[string]any, err error)
	UpdateFieldOverrides(ctx context.Context, id string, overrides *FieldOverrides) error
	UpdateImage(ctx context.Context, id, imagePath string) error
	UpdateCoverImage(ctx context.Context, id, coverImagePath string) error
	Delete(ctx context.Context, id string) error
	SlugExists(ctx context.Context, campaignID, slug string) (bool, error)

	// ListSuffixedSlugs returns the live entities whose slug is base followed
	// by "-" and more, oldest first: the pages that got a uniqueness suffix
	// because another row already held base.
	ListSuffixedSlugs(ctx context.Context, campaignID, base string) ([]Entity, error)

	// ListByCampaign returns entities filtered by campaign, optional types, and visibility.
	// typeIDs is matched via IN clause; nil or empty means no type filter. This supports
	// the sub-category-as-template model where a parent entity_type's listing aggregates
	// entities across itself and all its child entity_types.
	ListByCampaign(ctx context.Context, campaignID string, typeIDs []int, role int, userID string, opts ListOptions) ([]Entity, int, error)

	// Search performs a FULLTEXT search on entity names with visibility filtering.
	// typeIDs semantics match ListByCampaign.
	Search(ctx context.Context, campaignID, query string, typeIDs []int, role int, userID string, opts ListOptions) ([]Entity, int, error)

	// CountByType returns entity counts per type for the sidebar badges.
	CountByType(ctx context.Context, campaignID string, role int, userID string) (map[int]int, error)

	// ListByOwner returns entities in a campaign owned by a specific user.
	// Used by the Characters page's Yours band. Visibility filtering
	// is intentionally NOT applied: a player owning the entity implies they
	// can see it, even if a GM marked it private to hide it from other
	// players. Cross-campaign isolation is enforced by the campaign_id
	// filter.
	ListByOwner(ctx context.Context, campaignID, ownerUserID string) ([]Entity, error)

	// ListClaimed returns every claimed entity (owner_user_id IS NOT NULL) in a
	// campaign, ordered most-recently-updated first, with the standard
	// visibility filter applied for the viewer. Backs the campaign-wide "party"
	// band of the Characters page — where ListByOwner is scoped to one user,
	// this is scoped to the whole campaign. The handler unions this with the
	// viewer's own ListByOwner result so a player always sees their own
	// character even if it was marked private.
	ListClaimed(ctx context.Context, campaignID string, role int, userID string) ([]Entity, error)

	// UpdateOwner sets or clears entities.owner_user_id. Pass a nil
	// pointer to clear (unassign). Service-level callers are responsible
	// for verifying the new owner is a campaign member.
	UpdateOwner(ctx context.Context, entityID string, ownerUserID *string) error

	// ClaimOwner makes userID the owner only if the entity is unowned or
	// already theirs, in one statement, so two players claiming the same
	// character at once cannot both win. Reports whether userID owns it after.
	ClaimOwner(ctx context.Context, entityID, userID string) (bool, error)

	// SetPlayable marks or unmarks an entity as one a player may play.
	SetPlayable(ctx context.Context, entityID string, playable bool) error

	// ListOnRoster returns the entities of the given types that are on the
	// Players list: marked playable or owned. Visibility-filtered for
	// the viewer, by name, capped at 500.
	ListOnRoster(ctx context.Context, campaignID string, typeIDs []int, role int, userID string) ([]Entity, error)

	// SearchRoster returns the non-template entities of the given types for the
	// Players finder, free-to-pick ones first and then by name. See
	// RosterSearch for the filters.
	SearchRoster(ctx context.Context, campaignID string, typeIDs []int, f RosterSearch, role int, userID string) ([]Entity, error)

	// UpdateMapID sets or clears entities.map_id. Pass nil to unassign.
	// Service-level callers are responsible for verifying the map belongs
	// to the same campaign as the entity.
	UpdateMapID(ctx context.Context, entityID string, mapID *string) error

	// ListRecent returns the N most recently updated entities for a campaign,
	// ordered by updated_at DESC. Used for the campaign dashboard "recent pages" section.
	ListRecent(ctx context.Context, campaignID string, role int, userID string, limit int) ([]Entity, error)

	// FindChildren returns direct children of an entity, respecting visibility.
	FindChildren(ctx context.Context, parentID string, role int, userID string) ([]Entity, error)

	// FindAncestors returns the ancestor chain from an entity up to the root,
	// ordered from immediate parent to furthest ancestor. Uses a recursive CTE.
	FindAncestors(ctx context.Context, entityID string, role int, userID string) ([]Entity, error)

	// UpdateParent sets or clears an entity's parent_id. Scoped to campaign for safety.
	UpdateParent(ctx context.Context, entityID, campaignID string, parentID *string) error
	UpdateParentNode(ctx context.Context, entityID, campaignID string, parentNodeID *string) error // Set sidebar folder node parent.

	// ListSiblingIDsOrdered returns the IDs of all entities sharing a scope
	// (campaign + entity type + parent), ordered by (sort_order, name) — exactly
	// the order the sidebar tree renders. Used to re-sequence sort_order densely
	// on reorder so the name tiebreak can't snap a dragged entity back (the
	// silent-revert bug). parentID/parentNodeID are mutually exclusive; both nil
	// means the root scope.
	ListSiblingIDsOrdered(ctx context.Context, campaignID string, entityTypeID int, parentID, parentNodeID *string) ([]string, error)

	// ResequenceSiblings renumbers sort_order = position (0..N-1) for the given
	// ordered IDs in a single transaction, scoped to the campaign. Dense, unique
	// orders make the (sort_order, name) tiebreak deterministic.
	ResequenceSiblings(ctx context.Context, campaignID string, orderedIDs []string) error

	// FindBacklinks returns entities whose entry_html contains a @mention link
	// pointing to the given entity, scoped to campaignID. Respects visibility
	// filtering.
	FindBacklinks(ctx context.Context, campaignID, entityID string, role int, userID string) ([]Entity, error)

	// FindPagesLinkingNote returns entities of campaignID whose entry_html
	// holds a [[link]] to the note noteID (an anchor's data-note-id), that
	// the viewer may see. At most 50, by name.
	FindPagesLinkingNote(ctx context.Context, campaignID, noteID string, role int, userID string) ([]Entity, error)

	// UpdatePopupConfig persists the entity's hover preview configuration.
	UpdatePopupConfig(ctx context.Context, entityID string, config *PopupConfig) error

	// CopyEntityTags copies all entity_tags associations from one entity to another.
	CopyEntityTags(ctx context.Context, sourceEntityID, targetEntityID string) error

	// ListNames returns lightweight name entries for all visible entities in a
	// campaign, including aliases. Used for auto-linking in the editor. Sorted
	// by name length DESC so longer names match first (prevents partial matches).
	ListNames(ctx context.Context, campaignID string, role int, userID string) ([]EntityNameEntry, error)

	// FilterViewableEntityIDs returns the subset of entityIDs (scoped to
	// campaignID) that a viewer with the given role + userID may view, applying
	// the canonical visibility policy. Batched — one query, no N+1.
	FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)

	// ListAliases returns all aliases for a given entity.
	ListAliases(ctx context.Context, entityID string) ([]EntityAlias, error)

	// SetAliases replaces all aliases for an entity with the given list.
	// Deletes existing aliases and inserts new ones in a single transaction.
	SetAliases(ctx context.Context, entityID string, aliases []string) error

	// FindMentionSources returns the pages of a campaign the viewer may see
	// whose text carries an @mention, with that text.
	FindMentionSources(ctx context.Context, campaignID string, role int, userID string) ([]MentionSource, error)

	// FindMentionPages returns, of the given ids, the pages of this campaign
	// the viewer may see, as a graph draws them. An id of another campaign, of
	// a page in the trash or of a page hidden from the viewer is left out.
	FindMentionPages(ctx context.Context, campaignID string, ids []string, role int, userID string) (map[string]MentionPage, error)

	// UpdatePrivate sets an entity's is_private flag. Used by the NPC reveal toggle.
	UpdatePrivate(ctx context.Context, entityID string, isPrivate bool) error

	// SetShopGood sets or clears the shop good mark on a live page of the campaign.
	SetShopGood(ctx context.Context, campaignID, entityID string, shopGood bool) error
	// FindShopGoodByName finds a live shop good by name, ignoring case; (nil, nil) when none.
	FindShopGoodByName(ctx context.Context, campaignID, name string) (*Entity, error)

	// UpdateEntityType changes an entity's entity_type_id. Used by bulk type reassignment.
	UpdateEntityType(ctx context.Context, entityID string, typeID int) error
}

EntityRepository defines the data access contract for entity operations.

func NewEntityRepository

func NewEntityRepository(db *sql.DB) EntityRepository

NewEntityRepository creates a new entity repository.

type EntityService

type EntityService interface {
	// Entity CRUD
	Create(ctx context.Context, campaignID, userID string, input CreateEntityInput) (*Entity, error)
	Clone(ctx context.Context, campaignID, userID, sourceEntityID string) (*Entity, error)
	// EnsureShopGood returns the shop good page of that name (case-ignored)
	// in the campaign, making it in the given item type when there is none.
	// A good for sale to players is never left on a page hidden from them,
	// since the shop drops listings whose page a player cannot see.
	EnsureShopGood(ctx context.Context, campaignID, userID string, typeID int, name string, hiddenFromPlayers bool) (*Entity, error)
	// SetShopGood marks a page as a shop good or, with false, makes it a full page.
	SetShopGood(ctx context.Context, campaignID, entityID string, shopGood bool) error

	// ReconcileShopGoodVisibility hides a shop good page unless a public
	// listing sells it (publicListings > 0); other pages are untouched.
	ReconcileShopGoodVisibility(ctx context.Context, campaignID, entityID string, publicListings int) error
	GetByID(ctx context.Context, id string) (*Entity, error)
	GetBySlug(ctx context.Context, campaignID, slug string) (*Entity, error)
	// GetByNameSlug is the live page a name refers to, given Slugify(name):
	// the page holding that slug, else a page of that name whose slug took a
	// uniqueness suffix. Name lookups use it; URLs keep GetBySlug.
	GetByNameSlug(ctx context.Context, campaignID, nameSlug string) (*Entity, error)
	Update(ctx context.Context, entityID string, input UpdateEntityInput) (*Entity, error)
	UpdateEntry(ctx context.Context, entityID, entryJSON, entryHTML string) error
	// SaveEntry is the editor's save: with baseRev set it refuses to replace
	// text someone else saved since that revision, returning the conflict.
	SaveEntry(ctx context.Context, entityID, entryJSON, entryHTML string, baseRev *int) (int, *EntryConflict, error)
	// EntryRev is the page text's revision, for the editor to save against.
	EntryRev(ctx context.Context, entityID string) (int, error)
	UpdatePlayerNotes(ctx context.Context, entityID, notesJSON, notesHTML string) error
	UpdateFields(ctx context.Context, entityID string, fieldsData map[string]any) error
	MergeFields(ctx context.Context, entityID string, patch map[string]any) error
	UpdateFieldOverrides(ctx context.Context, entityID string, overrides *FieldOverrides) error
	UpdateImage(ctx context.Context, entityID, imagePath string) error
	UpdateCoverImage(ctx context.Context, entityID, coverImagePath string) error
	// CheckImagePath refuses a picture path a page may not use: one outside
	// the media store or from another campaign. An empty path passes.
	CheckImagePath(ctx context.Context, entityID, imagePath string) error
	// Delete moves the page and its sub-pages to the Trash when page safety
	// is wired, and removes it for good otherwise.
	Delete(ctx context.Context, entityID string) error

	// Hierarchy
	GetChildren(ctx context.Context, entityID string, role int, userID string) ([]Entity, error)

	// Climates (field_climate.go). ClimateRegion is the page whose climate
	// covers a page and that climate; ClimatePlaces is every page holding a
	// climate of its own. Both read unfiltered, for the calendar's weather.
	ClimateRegion(ctx context.Context, e *Entity) (*Entity, string, error)
	ClimatePlaces(ctx context.Context, campaignID string) ([]PlaceClimate, error)
	GetAncestors(ctx context.Context, entityID string, role int, userID string) ([]Entity, error)
	ReorderEntity(ctx context.Context, campaignID, entityID string, parentID *string, parentNodeID *string, sortOrder int) error
	// ReorderEntityType densely re-sequences a sub-category type's position
	// among its parent's children. sortOrder is a desired 0-based index.
	ReorderEntityType(ctx context.Context, campaignID string, typeID int, sortOrder int) error
	// RestoreEntityTypePlacement sets a type's sort order, default flag and
	// on/off state as a campaign export recorded them.
	RestoreEntityTypePlacement(ctx context.Context, campaignID string, typeID, sortOrder int, isDefault, enabled bool) error

	// Backlinks — always campaign-scoped; mention ids alone are not.
	GetBacklinks(ctx context.Context, campaignID, entityID string, role int, userID string) ([]Entity, error)

	// Popup preview config
	UpdatePopupConfig(ctx context.Context, entityID string, config *PopupConfig) error

	// Listing and search
	List(ctx context.Context, campaignID string, typeID int, role int, userID string, opts ListOptions) ([]Entity, int, error)
	ListRecent(ctx context.Context, campaignID string, role int, userID string, limit int) ([]Entity, error)
	Search(ctx context.Context, campaignID, query string, typeID int, role int, userID string, opts ListOptions) ([]Entity, int, error)
	// SearchSnippets quotes the line of each page's reader-safe text that
	// holds the query's words; see search_snippet.go.
	SearchSnippets(ctx context.Context, campaignID, query string, ids []string, role int, userID string) map[string][]SnippetPart

	// Entity types
	GetEntityTypes(ctx context.Context, campaignID string) ([]EntityType, error)
	// PlacePageExtras places the page pieces drawn outside the layout into a campaign's entity types (see page_extras.go).
	PlacePageExtras(ctx context.Context, campaignID string, plans map[int]PageExtrasPlan) (int, error)
	// RepairSystemPanelsLayouts restores the default layout on types left with only the panels block (see page_extras.go).
	RepairSystemPanelsLayouts(ctx context.Context, campaignID string) (int, error)
	// PlaceSystemPanels adds only the Game System Panels block to the given
	// types (see page_extras.go).
	PlaceSystemPanels(ctx context.Context, campaignID string, typeIDs []int) (int, error)
	GetEntityTypeBySlug(ctx context.Context, campaignID, slug string) (*EntityType, error)
	GetEntityTypeByID(ctx context.Context, id int) (*EntityType, error)
	GetEntityTypesByPresetCategory(ctx context.Context, campaignID, category string) ([]EntityType, error)

	// EnsureAdventures makes the DM-only Adventures category if the campaign
	// has none, and returns it either way. created is false when it was
	// already there, so the call is safe to repeat (the Customize button).
	EnsureAdventures(ctx context.Context, campaignID string) (et *EntityType, created bool, err error)
	CountByType(ctx context.Context, campaignID string, role int, userID string) (map[int]int, error)

	// Per-entity permissions
	GetEntityPermissions(ctx context.Context, entityID string) ([]EntityPermission, error)
	SetEntityPermissions(ctx context.Context, entityID string, input SetPermissionsInput) error
	CheckEntityAccess(ctx context.Context, entityID string, role int, userID string) (*EffectivePermission, error)
	// FilterViewableEntityIDs returns the subset of entityIDs (scoped to
	// campaignID) that a viewer with the given role + userID may view. Batched
	// building block for widgets that must hide private-entity nodes/targets.
	FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
	// HideUnviewableMentions turns each mention of a page the viewer can't
	// open into "a hidden page" in the given texts, in place, and reports how
	// many it replaced. On error every mention is hidden.
	HideUnviewableMentions(ctx context.Context, campaignID string, role int, userID string, texts ...*string) (int, error)
	CreateEntityType(ctx context.Context, campaignID string, input CreateEntityTypeInput) (*EntityType, error)
	// EnsurePlayerCharacterType idempotently premakes the campaign's claimable
	// "Player Character" type (with the dynamic character-surface layout). Called
	// when the Player Character Claiming addon is enabled.
	EnsurePlayerCharacterType(ctx context.Context, campaignID string) error
	// PlayerCharacterSetupSnapshot returns a read-only summary of the campaign's
	// player-character category state (generic vs system character types, entity
	// counts, sub-categories) for the player-character extension settings page.
	PlayerCharacterSetupSnapshot(ctx context.Context, campaignID string) (PCSetupSnapshot, error)
	// MergeDuplicatePlayerCharacterType reconciles the duplicate-category case
	// (a generic "Player Characters" alongside a system character type) on demand:
	// it moves the generic type's entities onto the system type and removes the
	// emptied generic. Owner-triggered from the settings page (replaces the old
	// silent boot migration). Idempotent; returns a human-readable conflict when
	// the campaign has more than one of either category.
	MergeDuplicatePlayerCharacterType(ctx context.Context, campaignID string) (MergeResult, error)
	UpdateEntityType(ctx context.Context, id int, input UpdateEntityTypeInput) (*EntityType, error)
	// ReconcileEntityTypeFields additively merges newly-declared schema fields
	// into an existing entity type. Used when a system package gains fields after
	// the type was first created (WS-5): existing heroes' type picks up the new
	// fields without recreating it. Additive and idempotent — see the impl.
	ReconcileEntityTypeFields(ctx context.Context, typeID int, declared []FieldDefinition) (int, error)
	// AdoptDefaultCharacterType makes the campaign's seeded top-level
	// "Characters" type the home of a system's character sheet: it takes the
	// preset category and gains the declared fields (additively). Returns nil,
	// nil when there is nothing to adopt (no such type, or it already carries a
	// preset category), so the caller can fall back to creating a type.
	AdoptDefaultCharacterType(ctx context.Context, campaignID, category string, declared []FieldDefinition) (*EntityType, error)
	// ReconcileCharacterPresetHome moves the system character sheet off an
	// empty duplicate type onto "Characters" in every campaign, disabling (never
	// deleting) the duplicate. Idempotent; returns the number of campaigns changed.
	ReconcileCharacterPresetHome(ctx context.Context) (int, error)
	// CharacterHomeCandidate reports the system character type whose pages
	// could move into "Characters", or nil when there is none.
	CharacterHomeCandidate(ctx context.Context, campaignID string) (*CharacterHomeMove, error)
	// MoveCharacterPresetHome moves that type's pages into "Characters", gives
	// Characters the system's sheet and disables the emptied type. Owner-run.
	MoveCharacterPresetHome(ctx context.Context, campaignID string) (CharacterHomeMove, error)
	DeleteEntityType(ctx context.Context, id int) error
	// MergeEntityType moves every page of fromID (Trash included), its
	// sidebar folders and saved filters into toID, then deletes fromID. See
	// category_merge.go for the rules it keeps.
	MergeEntityType(ctx context.Context, campaignID string, fromID, toID int) (int, error)
	// ApplyCustomizeCategories applies the Customize page's category changes
	// (create, edit, delete) through the methods above, stopping at the first
	// failure and reporting what was done. See customize_categories.go.
	ApplyCustomizeCategories(ctx context.Context, campaignID string, in CustomizeCategoriesPatch) (CustomizeCategoriesResult, error)
	// CustomizeCategories lists the campaign's types with their effective
	// claimable flag and live and trashed page counts.
	CustomizeCategories(ctx context.Context, campaignID string) ([]CustomizeCategoryInfo, error)
	UpdateEntityTypeLayout(ctx context.Context, id int, layout EntityTypeLayout) error
	// AppendBlockToCategoryLayout puts a block at the end of a category's page
	// layouts unless they already hold it; added is false when none needed it.
	AppendBlockToCategoryLayout(ctx context.Context, campaignID string, typeID int, blockType string) (added bool, err error)
	// BlockPlacementOptions lists the categories a block can be put on, the
	// one it is made for first.
	BlockPlacementOptions(ctx context.Context, campaignID, blockType string) ([]PlacementOption, error)
	UpdateEntityTypeColor(ctx context.Context, id int, color string) error
	UpdateEntityTypeDashboard(ctx context.Context, id int, description *string, pinnedIDs []string) error

	// Category dashboard layout
	GetCategoryDashboardLayout(ctx context.Context, id int) (*string, error)
	UpdateCategoryDashboardLayout(ctx context.Context, id int, layoutJSON string) error
	// CheckCategoryDashboardLayout runs the rules a saved category home
	// meets, without saving.
	CheckCategoryDashboardLayout(ctx context.Context, id int, layout campaigns.DashboardLayout) error
	ResetCategoryDashboardLayout(ctx context.Context, id int) error

	// Auto-linking — returns lightweight name entries for all visible entities.
	ListEntityNames(ctx context.Context, campaignID string, role int, userID string) ([]EntityNameEntry, error)

	// Entity aliases — alternative names for auto-linking, search, and mentions.
	GetAliases(ctx context.Context, entityID string) ([]EntityAlias, error)
	SetAliases(ctx context.Context, entityID string, aliases []string) error

	// Backlinks with context snippets — always campaign-scoped. canSeeGM
	// gates whether the snippet is built from the linking page's raw HTML or
	// its GM-secret-stripped form (same bar as GetEntry/GetFieldsAPI: Scribe+).
	GetBacklinksWithSnippets(ctx context.Context, campaignID, entityID string, role int, userID string, canSeeGM bool) ([]BacklinkEntry, error)

	// PagesLinkingNote returns the pages of a campaign whose entry links the
	// note noteID and that the viewer may see. A viewer who does not see
	// inline secrets (seesSecrets false) does not get a page whose only link
	// to the note sits inside one.
	PagesLinkingNote(ctx context.Context, campaignID, noteID string, role int, userID string, seesSecrets bool) ([]Entity, error)

	// GetMentionGraph returns the @mention links across a campaign that the
	// viewer may know of, with the pages at their ends, for the relations
	// graph. A viewer who does not see inline secrets (seesSecrets false) gets
	// no link that exists only inside one. A link to a page hidden from the
	// viewer, in the trash or of another campaign is left out.
	GetMentionGraph(ctx context.Context, campaignID string, role int, userID string, seesSecrets bool) (*MentionGraph, error)

	// TogglePrivate flips an entity's is_private flag and returns the new state.
	// Callers MUST have already verified the entity belongs to the acting
	// campaign (BulkVisibilityAPI, syncapi both do). Prefer TogglePrivateInCampaign
	// from surfaces that only hold a URL-supplied entity id.
	TogglePrivate(ctx context.Context, entityID string) (newPrivate bool, err error)

	// TogglePrivateInCampaign flips is_private only when the entity belongs to
	// campaignID, returning NotFound otherwise. The campaign-scoped guard for
	// callers that receive an entity id straight from the URL (npcs reveal
	// toggle — SEC-IDOR-1).
	TogglePrivateInCampaign(ctx context.Context, entityID, campaignID string) (newPrivate bool, err error)

	// SetPrivateInCampaign sets is_private to the given value only when the
	// entity belongs to campaignID (NotFound otherwise). Unlike the toggle it
	// is idempotent, so a repeated request can never flip the flag back.
	SetPrivateInCampaign(ctx context.Context, entityID, campaignID string, private bool) error

	// ListByOwner returns entities in a campaign owned by the given user,
	// ordered most-recently-updated first. Powers the Yours band
	// on the Characters page. No visibility filter:
	// owning the entity implies the player can see it.
	ListByOwner(ctx context.Context, campaignID, ownerUserID string) ([]Entity, error)

	// ListClaimed returns every claimed entity in a campaign (the whole party),
	// visibility-filtered for the viewer. Powers the "party" band of the
	// Characters page at GET /campaigns/:id/characters.
	ListClaimed(ctx context.Context, campaignID string, role int, userID string) ([]Entity, error)

	// ClaimEntity assigns the calling user as owner of an entity. Idempotent
	// when the caller already owns it; returns 409 Conflict when claimed by
	// a different user (the user must ask the GM to reassign). Refuses to
	// claim non-character entities — only entity_types whose preset_category
	// is "character" or whose slug ends in "-character" are claimable.
	ClaimEntity(ctx context.Context, entityID, userID string) (*Entity, error)

	// AssignOwner sets or clears entity ownership. Used by Owner/Scribe
	// to reassign characters between players. Pass ownerUserID = nil to
	// unclaim. Cross-campaign membership is the caller's (handler's)
	// responsibility — the service trusts upstream campaign auth.
	AssignOwner(ctx context.Context, entityID string, ownerUserID *string) (*Entity, error)

	// SetPlayable marks or unmarks a character as playable, which puts it on
	// (or takes it off) the Characters page's Players list unless it
	// is owned. The entity must belong to campaignID. Marking needs a claimable
	// type; unmarking is always allowed.
	SetPlayable(ctx context.Context, campaignID, entityID string, playable bool) (*Entity, error)

	// ListRoster returns the entities of typeIDs on the Players list
	// (playable or owned), visibility-filtered for the viewer.
	ListRoster(ctx context.Context, campaignID string, typeIDs []int, role int, userID string) ([]Entity, error)

	// SearchRoster returns the characters of typeIDs the Players finder offers,
	// free-to-pick first, then by name.
	SearchRoster(ctx context.Context, campaignID string, typeIDs []int, f RosterSearch, role int, userID string) ([]Entity, error)

	// AssignMap sets or clears the entity's map_id (the per-entity Map
	// Editor block reads from this). Pass mapID = nil to unassign.
	// Verifies the map exists in the entity's own campaign before
	// writing — closes the cross-campaign IDOR the FK alone wouldn't.
	AssignMap(ctx context.Context, entityID string, mapID *string) (*Entity, error)

	// SetMapVerifier wires the cross-campaign existence check used by
	// AssignMap. Production startup wires an adapter over maps.MapsService.
	SetMapVerifier(v MapCampaignVerifier)

	// SetMediaVerifier wires the cross-campaign existence check used by
	// UpdateImage/UpdateCoverImage. Production startup wires an adapter
	// over media.MediaService.
	SetMediaVerifier(v MediaCampaignVerifier)

	// SetAddonChecker wires the per-campaign addon enablement check used to
	// gate player-character sub-type creation. Production startup wires the
	// addons service; when unset the gate fails open (used by tests).
	SetAddonChecker(checker AddonChecker)

	// SetPageSafety wires page history, the Trash and the save-clash check.
	// Unset (tests), Delete removes pages for good and nothing is versioned.
	SetPageSafety(repo PageSafetyRepository)

	// HealAutoPluralizedTypes corrects entity_types rows whose
	// name_plural was double-s'd by the legacy auto-pluralize default.
	// Returns the count of healed rows. Idempotent; safe to call on
	// every boot.
	HealAutoPluralizedTypes(ctx context.Context) (int, error)

	// SyncFieldGMFlags re-stamps the GMOnly flag on stored entity-type field
	// definitions from a caller-supplied (preset-category → field-key →
	// gm_only) map, so a system manifest that newly marks a field gm_only
	// propagates onto already-created types.
	// System-agnostic: the app layer builds the map from installed manifests;
	// core just applies it. Touches only the fields column (never layout), so
	// it can't race the layout backfills. Idempotent; safe at boot and after
	// package install. Returns the count of types updated.
	SyncFieldGMFlags(ctx context.Context, gmByCategory map[string]map[string]bool) (int, error)

	// SyncFieldOwnerOnlyFlags is SyncFieldGMFlags's counterpart for
	// FieldDefinition.OwnerOnly — same map shape, same idempotent per-type
	// walk, different flag.
	SyncFieldOwnerOnlyFlags(ctx context.Context, ownerOnlyByCategory map[string]map[string]bool) (int, error)

	// SyncFieldPlay re-stamps FieldDefinition.Play on stored entity types
	// from a (preset-category → field-key → play block) map; a nil block
	// clears. Same idempotent, fields-column-only contract as the flag syncs.
	SyncFieldPlay(ctx context.Context, playByCategory map[string]map[string]*FieldPlay) (int, error)
	// SyncFieldChecks re-stamps the value checks (min, max, JSON list) a system
	// declares onto stored entity types, the same way SyncFieldPlay does.
	SyncFieldChecks(ctx context.Context, checksByCategory map[string]map[string]FieldChecks) (int, error)

	// BulkUpdateType changes the entity type for multiple entities at once.
	// Returns the count of successfully updated entities. Validates that the
	// target type belongs to the campaign and each entity is campaign-scoped.
	BulkUpdateType(ctx context.Context, campaignID string, entityIDs []string, typeID int) (int, error)

	// Seeder (satisfies campaigns.EntityTypeSeeder interface).
	SeedDefaults(ctx context.Context, campaignID string) error
	SeedGenre(ctx context.Context, campaignID string, genre string) error

	// Wiring.
	SetEventPublisher(pub EntityEventPublisher)
	SetBlockRegistry(reg *BlockRegistry)
	SetSidebarAutoAdder(adder SidebarAutoAdder)
	SetFieldChangeObserver(obs FieldChangeObserver)
	SetHookDispatcher(d EntityHookDispatcher)
}

EntityService handles business logic for entity operations. It owns slug generation, privacy enforcement, and entity type seeding. Also implements the campaigns.EntityTypeSeeder interface.

func NewEntityService

func NewEntityService(entities EntityRepository, types EntityTypeRepository, permissions EntityPermissionRepository) EntityService

NewEntityService creates a new entity service with the given dependencies.

type EntityShowRenderContext

type EntityShowRenderContext struct {
	CC             *campaigns.CampaignContext
	Entity         *Entity
	EntityType     *EntityType
	Ancestors      []Entity
	Children       []Entity
	ShowAttributes bool
	ShowCalendar   bool
	CSRFToken      string
	// UserID is the viewing user's id, used to gate owner-only field
	// visibility. Empty for an anonymous viewer.
	UserID string
	// OwnerName is the claimant's display name, empty when unclaimed or unresolved.
	OwnerName string
	// NPCPage is an unclaimed page of a type on the NPC list. A renderer bound
	// to the character preset draws a hero's sheet, so it skips these pages
	// and they keep their layout.
	NPCPage bool
	// System is the campaign's game system (its module id). A renderer bound
	// to a preset belongs to the system that declared it, so a Draw Steel
	// sheet never takes over a D&D campaign's characters.
	System string
	// NamedLayout is a page that wears one of its category's named layouts.
	// The layout draws it, so no renderer takes the page over; the
	// renderer's sheet is the game_system_sheet block the layout can place.
	NamedLayout bool
}

EntityShowRenderContext is everything a registered renderer receives when handling an entity-show request. The fields mirror the args of the EntityShowPage templ exactly, so a registered renderer has the same inputs as the block-dispatch fallback; keep it that way when the templ signature grows.

type EntityShowRenderer

type EntityShowRenderer func(ctx EntityShowRenderContext) templ.Component

EntityShowRenderer renders the inner contents of an entity show page when the entity_type slug matches a registered system package. The returned component is rendered inside the layouts.App wrapper that already provides the page chrome (sidebar, breadcrumb, claim banner); the renderer's job is the area that the layout-block iteration would otherwise fill.

func MakeWidgetMountRenderer

func MakeWidgetMountRenderer(widget string) EntityShowRenderer

MakeWidgetMountRenderer returns an EntityShowRenderer that emits a single <div data-widget="…" data-entity-id="…" data-campaign-id="…"> element. The standard boot.js auto-mounter (static/js/boot.js) picks the element up at page load (and after htmx:afterSettle) and runs the registered widget's init(el, config) against it; the widget owns the rest of the page from there.

This is the bridge that lets system-package authors declare a renderer in their manifest's `renderers` field — `{slug, widget}` — without shipping any Go code. Auto-registration walks the manifest at boot, calls this helper for each entry, and registers the returned function under the entry's slug.

type EntityShowRendererRegistry

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

EntityShowRendererRegistry maps entity_type slugs to renderers. One renderer per slug; a system package registers each character-shaped slug it ships (drawsteel-character, drawsteel-monster, etc.). The mutex makes Register / Lookup safe under concurrent access.

func NewEntityShowRendererRegistry

func NewEntityShowRendererRegistry() *EntityShowRendererRegistry

NewEntityShowRendererRegistry returns an empty registry ready for startup-time registration calls.

func (*EntityShowRendererRegistry) Lookup

Lookup returns the renderer registered for slug, or (nil, false) if none. The boolean second return mirrors map-lookup convention so callers can branch cleanly on the miss case.

func (*EntityShowRendererRegistry) LookupByPresetCategory

func (r *EntityShowRendererRegistry) LookupByPresetCategory(category string) (EntityShowRenderer, bool)

LookupByPresetCategory reports whether any system binds a renderer to a preset_category, for callers that are not drawing one campaign's page.

func (*EntityShowRendererRegistry) LookupByPresetCategoryFor

func (r *EntityShowRendererRegistry) LookupByPresetCategoryFor(system, category string) (EntityShowRenderer, bool)

LookupByPresetCategoryFor returns the renderer the given system binds to a preset_category, or one bound for any system, or (nil, false). Consulted only after a slug miss — slug is more specific.

func (*EntityShowRendererRegistry) PresetSystems

func (r *EntityShowRendererRegistry) PresetSystems(category string) []string

PresetSystems lists the systems that bind a renderer to a preset_category; "" stands for a binding made for any system.

func (*EntityShowRendererRegistry) Register

func (r *EntityShowRendererRegistry) Register(slug string, renderer EntityShowRenderer)

Register adds a renderer for the given entity_type slug. A second Register call for the same slug REPLACES the prior one — the last registration wins. This matches the BlockRegistry's behavior and gives system packages a way to override each other deterministically if their order is wired explicitly in routes.go. Empty slug is a no-op (defensive — silently dropping a typo is better than panicking on a configuration mistake at startup).

func (*EntityShowRendererRegistry) RegisterByPresetCategory

func (r *EntityShowRendererRegistry) RegisterByPresetCategory(category string, renderer EntityShowRenderer)

RegisterByPresetCategory adds a renderer bound to an entity-type preset_category. Last registration wins (mirrors Register); empty category is a no-op. This is how a system fills a Chronicle-owned category (e.g. the addon's player-character type) without owning its slug.

func (*EntityShowRendererRegistry) RegisterByPresetCategoryFor

func (r *EntityShowRendererRegistry) RegisterByPresetCategoryFor(system, category string, renderer EntityShowRenderer)

RegisterByPresetCategoryFor binds a renderer to a preset_category for one game system: it draws that category's pages only in campaigns running that system.

type EntityTagFetcher

type EntityTagFetcher interface {
	GetEntityTagsBatch(ctx context.Context, entityIDs []string, includeDmOnly bool) (map[string][]EntityTagInfo, error)
	GetEntityTags(ctx context.Context, entityID string, includeDmOnly bool) ([]EntityTagInfo, error)
	SetEntityTags(ctx context.Context, entityID string, campaignID string, tagIDs []int, includeDmOnly bool) error
	GetEntityTagGrants(ctx context.Context, campaignID, entityID string) ([]EntityTagGrantInfo, error)
}

EntityTagFetcher retrieves tags for entities in batch. Defined here to avoid importing the tags widget package, keeping plugins loosely coupled via interfaces. includeDmOnly controls whether dm_only tags are returned (true for Scribes+).

GetEntityTagGrants carries tag-derived visibility data across the same seam: it resolves the full grant summary for one entity's effective-visibility glance (show-page header badge + permissions editor).

type EntityTagGrantInfo

type EntityTagGrantInfo struct {
	TagName      string `json:"tag_name"`
	TagSlug      string `json:"tag_slug"`
	TagColor     string `json:"tag_color"`
	SubjectType  string `json:"subject_type"`
	SubjectID    string `json:"subject_id"`
	SubjectLabel string `json:"subject_label"`
}

EntityTagGrantInfo is one tag-derived visibility grant on an entity, resolved for display. It mirrors the tags widget's grant summary but lives here so the entities plugin needn't import the widget (the EntityTagFetcher seam carries it across the boundary). SubjectLabel is the human label shown in the glance tooltip ("Players", a member's name, a group name).

type EntityTagInfo

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

EntityTagInfo holds minimal tag display data for entity cards and lists. Avoids importing the tags widget package from the entities plugin.

type EntityType

type EntityType struct {
	ID              int               `json:"id"`
	CampaignID      string            `json:"campaign_id"`
	Slug            string            `json:"slug"`
	Name            string            `json:"name"`
	NamePlural      string            `json:"name_plural"`
	Icon            string            `json:"icon"`
	Color           string            `json:"color"`
	PresetCategory  *string           `json:"preset_category,omitempty"`   // System preset category ("character", "item", "creature").
	ParentTypeID    *int              `json:"parent_type_id,omitempty"`    // Parent entity type ID for sub-type hierarchy.
	Claimable       *bool             `json:"claimable,omitempty"`         // nil = unset (legacy heuristic); true/false = explicit Owner choice for player claiming.
	Description     *string           `json:"description,omitempty"`       // Rich text shown on category dashboard.
	PinnedEntityIDs []string          `json:"pinned_entity_ids,omitempty"` // Entity IDs pinned to dashboard top.
	DashboardLayout *string           `json:"dashboard_layout,omitempty"`  // JSON layout; nil = use hardcoded default.
	Fields          []FieldDefinition `json:"fields"`
	Layout          EntityTypeLayout  `json:"layout"`
	SortOrder       int               `json:"sort_order"`
	IsDefault       bool              `json:"is_default"`
	Enabled         bool              `json:"enabled"`
	ParentTypeName  *string           `json:"parent_type_name,omitempty"` // Joined field: parent type's name (not stored).
}

EntityType defines a category of entities within a campaign (e.g., Character, Location). Each campaign has its own set of entity types with configurable fields that drive dynamic form rendering and profile display.

func ItemTypes

func ItemTypes(types []EntityType) []EntityType

ItemTypes is the campaign's Armory item categories (see IsItemType), in the order of types.

func SwitchTarget

func SwitchTarget(types []EntityType, category string) *EntityType

SwitchTarget is the category a preset of the given category takes over: a type already bound to that preset category, else the type every campaign starts with under that slug (the seeded "item"). Nil when the campaign has neither.

func TypesForViewer

func TypesForViewer(types []EntityType, role int) []EntityType

TypesForViewer drops the categories the viewer may not know exist. The owner and Co-DMs get the input slice back as is; anyone else gets a new slice.

func (*EntityType) DMOnly

func (et *EntityType) DMOnly() bool

DMOnly reports whether the category is for the DM team only. It is nil safe so a caller holding a failed lookup fails closed in its own way.

func (*EntityType) ParseCategoryDashboardLayout

func (et *EntityType) ParseCategoryDashboardLayout() *campaigns.DashboardLayout

ParseCategoryDashboardLayout parses the entity type's dashboard_layout JSON into a campaigns.DashboardLayout struct. Returns nil if the column is NULL (use hardcoded default category dashboard).

type EntityTypeLayout

type EntityTypeLayout struct {
	Rows []TemplateRow `json:"rows"`
}

EntityTypeLayout describes the profile page layout for entities of this type. Uses a row-based 12-column grid system. Stored as JSON in entity_types.layout_json.

Schema: {"rows": [{"id":"r1", "columns": [{"id":"c1", "width":8, "blocks":[...]}]}]}

func AdventureLayout

func AdventureLayout() EntityTypeLayout

AdventureLayout is the trial page: the story on the left with the at-a-glance facts beside it, the page's map under the story, its own sub-pages (its trials) after that, then a tile section of the table's tools. The Map, Read-aloud, Steps and Table blocks hold content a DM makes in place; their ids are the keys that content is stored under, so they are fixed here and stay stable for every page of the category. Existing campaigns keep the layout they have; the map is added there in Customize.

func CharacterLayout

func CharacterLayout() EntityTypeLayout

CharacterLayout is the default page layout for player-character types: the dynamic character-sheet surface (the "big widget") full-width, then the player-notes block. Owners can customize it in the layout editor like any other layout. Visibility editing lives only in edit mode via form.templ's inline widget, never an auto-appended read-page row (ADR-057 decision 5).

func DefaultLayout

func DefaultLayout() EntityTypeLayout

DefaultLayout returns the standard two-column layout used for new entity types. It holds only the page's own content: player notes and the other page pieces are blocks the owner adds (only character pages start with player notes, in CharacterLayout). Visibility editing lives only in edit mode, not an auto-appended read-page row (ADR-057 decision 5).

It is also what a type with no stored layout falls back to when something places a block into it, so it stays as it is; a category made new starts from NewCategoryLayout instead.

func NewCategoryLayout

func NewCategoryLayout() EntityTypeLayout

NewCategoryLayout is the layout a category made now is stored with: the default plus tags and relations under the title, in the order the no-layout fallback in show.templ draws them, so a new page can carry both. The Annals page editor keeps their add controls out of sight until Edit page. It is applied only when a category is created; stored layouts of existing categories are never rewritten to match.

func ParseLayoutJSON

func ParseLayoutJSON(raw []byte) EntityTypeLayout

ParseLayoutJSON decodes layout JSON with backward compatibility. Handles three cases:

  1. New format with "rows" key → unmarshal directly
  2. Old format with "sections" key → convert sections to rows/columns
  3. Empty/invalid → return DefaultLayout()

func RepairPanelOnlyLayout

func RepairPanelOnlyLayout(layout EntityTypeLayout) (EntityTypeLayout, bool)

RepairPanelOnlyLayout turns a layout whose only content is the Game System Panels block back into the default page with the block under the title. Such layouts were written by placing the block on an empty layout. Any other layout is returned unchanged with false.

type EntityTypeLister

type EntityTypeLister interface {
	ListByCampaign(ctx context.Context, campaignID string) ([]EntityType, error)
}

EntityTypeLister lists entity types for a campaign. Subset of EntityTypeRepository to avoid importing the full interface.

type EntityTypeRepository

type EntityTypeRepository interface {
	Create(ctx context.Context, et *EntityType) error
	FindByID(ctx context.Context, id int) (*EntityType, error)
	FindBySlug(ctx context.Context, campaignID, slug string) (*EntityType, error)
	ListByCampaign(ctx context.Context, campaignID string) ([]EntityType, error)
	ListAll(ctx context.Context) ([]EntityType, error)
	ListChildTypes(ctx context.Context, parentID int) ([]EntityType, error)
	ListByPresetCategory(ctx context.Context, campaignID, category string) ([]EntityType, error)
	Update(ctx context.Context, et *EntityType) error
	Delete(ctx context.Context, id int) error
	// MoveEntitiesAndDeleteType reassigns every entity of fromTypeID to toTypeID
	// within one campaign, with the type's sidebar folders and saved filters,
	// then deletes the now-empty fromType — in a single transaction. The
	// DELETE is guarded by NOT EXISTS over entities so a non-empty source is
	// never dropped (defense in depth; the UPDATE just emptied it). Returns the number of entities moved. The service picks the
	// exact (from, to) pair, so this carries no preset-string matching.
	MoveEntitiesAndDeleteType(ctx context.Context, campaignID string, fromTypeID, toTypeID int) (int64, error)
	UpdateLayout(ctx context.Context, id int, layoutJSON string) error
	// UpdateFieldsSchema updates only the fields JSON column (field-metadata
	// reconciler), never layout_json.
	UpdateFieldsSchema(ctx context.Context, id int, fieldsJSON string) error
	UpdateColor(ctx context.Context, id int, color string) error
	// AdoptPresetCategory gives toID the system preset category and, when
	// retireID is non-nil, takes the category off that type and disables it,
	// in one transaction so a crash never leaves two types both claiming the
	// system's sheet. Nothing is deleted.
	AdoptPresetCategory(ctx context.Context, toID int, category string, retireID *int) error
	// MovePagesAndAdoptPresetCategory moves every page of fromID (Trash
	// included) onto toID, then does what AdoptPresetCategory does with fromID
	// retired, all in one transaction. Returns the number of pages moved.
	MovePagesAndAdoptPresetCategory(ctx context.Context, campaignID string, fromID, toID int, category string) (int64, error)
	UpdateDashboard(ctx context.Context, id int, description *string, pinnedIDs []string) error
	UpdateDashboardLayout(ctx context.Context, id int, layoutJSON *string) error
	SlugExists(ctx context.Context, campaignID, slug string) (bool, error)
	MaxSortOrder(ctx context.Context, campaignID string) (int, error)
	// ResequenceChildTypes renumbers entity_types.sort_order = position (0..N-1)
	// for the given ordered type IDs in one transaction, scoped to the campaign.
	// This is the DB-sibling-row dense re-sequence (an entity_types analog of
	// ResequenceSiblings) that makes sub-category type order editable and
	// tie-safe — the ordering surfaced in the parent's +New variant picker and
	// aggregated listing, which both read ORDER BY sort_order, name.
	ResequenceChildTypes(ctx context.Context, campaignID string, orderedIDs []int) error
	// UpdatePlacement writes a type's position, default flag and on/off state,
	// which no edit form changes; a campaign import restores them.
	UpdatePlacement(ctx context.Context, id, sortOrder int, isDefault, enabled bool) error
	SeedDefaults(ctx context.Context, campaignID string) error
	SeedFromTypes(ctx context.Context, campaignID string, types []EntityType) error
}

EntityTypeRepository defines the data access contract for entity type operations.

func NewEntityTypeRepository

func NewEntityTypeRepository(db *sql.DB) EntityTypeRepository

NewEntityTypeRepository creates a new entity type repository.

type EntityVersion

type EntityVersion struct {
	ID        string    `json:"id"`
	EntityID  string    `json:"entity_id"`
	UserID    *string   `json:"user_id,omitempty"`
	Kind      string    `json:"kind"`
	Name      string    `json:"name"`
	Entry     *string   `json:"entry,omitempty"`
	EntryHTML *string   `json:"entry_html,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`

	// UserName is the author's display name, joined on read; empty when the
	// author is unknown or their account is gone.
	UserName string `json:"user_name,omitempty"`
}

EntityVersion is one saved state of a page's title and text. Field values are not versioned: sync clients like Foundry change them constantly.

type EntryConflict

type EntryConflict struct {
	Rev       int       `json:"rev"`
	Entry     *string   `json:"entry,omitempty"`
	EntryHTML *string   `json:"entry_html,omitempty"`
	ByName    string    `json:"by_name"`
	At        time.Time `json:"at"`
}

EntryConflict is what a save based on stale text gets back: the text that is stored now and who saved it, so the editor can offer to keep both.

type EraDiffBlock

type EraDiffBlock struct {
	Kind string
	HTML string
}

EraDiffBlock is one block of the version's text. HTML is the version's block (changed words in <mark class="era-w">); for a removed block it is the usual page's.

func EraDiff

func EraDiff(usualHTML, versionHTML string) []EraDiffBlock

EraDiff compares a page's usual text with an era version's, both sanitized HTML.

type EraEntryClash

type EraEntryClash struct {
	Rev       int
	Entry     *string
	EntryHTML *string
	ByUserID  string
	At        time.Time
}

EraEntryClash is the stored text an era version's save collided with.

type EraPages

type EraPages interface {
	PageEras(ctx context.Context, campaignID string, v permissions.Viewer) (*PageEraSet, error)
	Version(ctx context.Context, entityID string, eraID int) (*PageEraVersion, error)
	VersionEraIDs(ctx context.Context, entityID string) ([]int, error)
	VersionsFor(ctx context.Context, entityIDs []string, eraID int) (map[string]*PageEraVersion, error)
	CreateVersion(ctx context.Context, campaignID, entityID string, eraID int, userID string) error
	SetVersionIdentity(ctx context.Context, campaignID, entityID string, eraID int, name, imagePath patch.Field[string], userID string) error
	SaveVersionEntry(ctx context.Context, campaignID, entityID string, eraID int, entry, entryHTML string, baseRev *int, userID string) (int, *EraEntryClash, error)
	SaveVersionFields(ctx context.Context, campaignID, entityID string, eraID int, changed map[string]any, userID string) error
	DeleteVersion(ctx context.Context, campaignID, entityID string, eraID int) error
}

EraPages is the calendar plugin's side of pages by era, wired in internal/app. Writes are checked against the campaign there too.

type FamilyActor

type FamilyActor struct {
	UserID     string
	MemberRole int
	// DmGranted is the campaign owner's grant that makes a member a
	// co-Director.
	DmGranted bool
}

FamilyActor is who is editing. MemberRole is the real membership role, not the promoted visibility role, because editing is an authorization question.

func (FamilyActor) IsDirector

func (a FamilyActor) IsDirector() bool

IsDirector reports whether the actor is the campaign owner or a granted co-Director. Scribes and players are not.

type FamilyCandidate

type FamilyCandidate struct {
	ID    string
	Name  string
	Type  string
	Image string
	// DMOnly is set when an ordinary player could not open the page.
	DMOnly bool
}

FamilyCandidate is a page offered by the picker.

type FamilyCandidates

type FamilyCandidates struct {
	Pages []FamilyCandidate
	// More is set when other pages match; the Director types to narrow.
	More bool
}

FamilyCandidates is the picker's one bounded page of results.

type FamilyCreatedPage

type FamilyCreatedPage struct {
	Ref  string `json:"ref"`
	ID   string `json:"id"`
	Name string `json:"name"`
}

FamilyCreatedPage tells the caller what a ref became.

type FamilyEdit

type FamilyEdit struct {
	Op   string `json:"op"`
	Edge string `json:"edge"`
	// A and B name the pair. For a parent edge A is the child and B the
	// parent; a partner edge is the same either way round. Either may be the
	// ref of a page created in the same save.
	A string `json:"a"`
	B string `json:"b"`
	// Link is the kind of a parent link being added (birth, adopted,
	// guardian). Ignored for other edits.
	Link string `json:"link,omitempty"`
}

FamilyEdit is one change to the family: link or unlink a pair.

type FamilyEditFailure

type FamilyEditFailure struct {
	Index  int    `json:"index"`
	Reason string `json:"reason"`
	// HalfWritten is set when one direction of the pair was written and could
	// not be taken back, so the Relations block must finish the job. It is
	// never silent.
	HalfWritten bool `json:"halfWritten,omitempty"`
}

FamilyEditFailure is an edit that did not save, by its index in the request.

type FamilyEditRequest

type FamilyEditRequest struct {
	NewPages []FamilyNewPage `json:"newPages"`
	Edits    []FamilyEdit    `json:"edits"`
}

FamilyEditRequest is one Save: pages to create, then edits to apply.

type FamilyEditResult

type FamilyEditResult struct {
	Saved      bool                `json:"saved"`
	Created    []FamilyCreatedPage `json:"created"`
	Failed     []FamilyEditFailure `json:"failed"`
	Written    []int               `json:"written"`
	RolledBack bool                `json:"rolledBack"`
	// Tree is the family as it now stands for the Director, so the page can
	// show the truth whatever happened.
	Tree *FamilyTree `json:"-"`
}

FamilyEditResult is what a Save did. Saved means every edit is in place. Otherwise Failed says which edits did not save and Written which edits are still in place (all earlier ones are taken back, so Written is empty unless a takeback itself failed).

type FamilyEditService

type FamilyEditService interface {
	// Candidates returns a bounded, searchable list of pages the Director may
	// add as family of pageID.
	Candidates(ctx context.Context, campaignID, pageID string, actor FamilyActor, query string) (*FamilyCandidates, error)
	// Apply creates the requested pages, then applies the edits as one save.
	// newPagePrivate is the campaign's default for a new page (the value a
	// normal "new page" takes), resolved by the caller from the campaign.
	Apply(ctx context.Context, campaignID, pageID string, actor FamilyActor, newPagePrivate bool, req FamilyEditRequest) (*FamilyEditResult, error)
}

FamilyEditService is the Director's write side of the Family tree block.

func NewFamilyEditService

func NewFamilyEditService(writer FamilyWriter, pages FamilyPages, viewer FamilyViewFilter, tree FamilyTreeService) FamilyEditService

NewFamilyEditService creates the editor.

type FamilyHalfWritten

type FamilyHalfWritten struct{ Err error }

FamilyHalfWritten is returned when one direction of a pair is in place and the other could not be written or removed, and putting things right failed.

func (*FamilyHalfWritten) Error

func (e *FamilyHalfWritten) Error() string

func (*FamilyHalfWritten) Unwrap

func (e *FamilyHalfWritten) Unwrap() error
type FamilyLink struct {
	OtherID string
	// Type is the relation type as the reading page holds it ("parent of").
	Type   string
	DMOnly bool
}

FamilyLink is one relation row of a page, in the page's own direction.

type FamilyLinks interface {
	LinksOf(ctx context.Context, campaignID, entityID string) ([]FamilyLink, error)
}

FamilyLinks reads a page's relation rows. Implemented in the app by an adapter over the relations service, so this plugin never reaches into the relations tables.

type FamilyNewLink struct {
	Source, Target string
	Type, Reverse  string
	DMOnly         bool
	Metadata       json.RawMessage
	CreatedBy      string
}

FamilyNewLink is a pair to write, both directions.

type FamilyNewPage

type FamilyNewPage struct {
	Ref  string `json:"ref"`
	Name string `json:"name"`
}

FamilyNewPage asks for a page to be created and used by its ref.

type FamilyPages

type FamilyPages interface {
	List(ctx context.Context, campaignID string, typeID int, role int, userID string, opts ListOptions) ([]Entity, int, error)
	Search(ctx context.Context, campaignID, query string, typeID int, role int, userID string, opts ListOptions) ([]Entity, int, error)
	Create(ctx context.Context, campaignID, userID string, input CreateEntityInput) (*Entity, error)
	GetEntityTypes(ctx context.Context, campaignID string) ([]EntityType, error)
}

FamilyPages is the slice of the entity service the editor uses: the same listing and search the sidebar uses (so the picker shows what the Director can open) and the same create path a normal new page takes.

type FamilyParent

type FamilyParent struct {
	ID   string
	Kind string
	// DMOnly is set when the relation itself is Director-only; only a viewer
	// who can see DM-only content ever receives such a link.
	DMOnly bool
}

FamilyParent is a link from a person up to one of their parents.

type FamilyPerson

type FamilyPerson struct {
	ID       string
	Name     string
	Type     string // the page's category, the line under the name
	Image    string // the stored picture path; empty for none
	Parents  []FamilyParent
	Partners []string
	// Read is set when this person's own relations were read, so their
	// parents, children and partners here are complete. A person at the edge
	// of the walk is not read, and the script will not centre the tree on them.
	Read bool
	// DMOnly is set when players cannot open this page. Only a viewer who can
	// see DM-only content ever receives such a person.
	DMOnly bool
}

FamilyPerson is one relative.

type FamilyTree

type FamilyTree struct {
	PageID string
	// People holds the page itself first, then relatives nearest first.
	People []FamilyPerson
	// CutGenerations is set when the family goes on past MaxFamilyGenerations,
	// CutPeople when MaxFamilyPeople kept nearer relatives and left others out.
	CutGenerations bool
	CutPeople      bool
}

FamilyTree is a page's family for one viewer.

func (*FamilyTree) Cut

func (t *FamilyTree) Cut() bool

Cut reports whether any bound left relatives out.

func (*FamilyTree) Relatives

func (t *FamilyTree) Relatives() int

Relatives is how many people are drawn besides the page itself.

type FamilyTreeService

type FamilyTreeService interface {
	// Tree returns the page's family as role and userID may see it.
	Tree(ctx context.Context, campaignID, entityID string, role int, userID string) (*FamilyTree, error)
}

FamilyTreeService reads a page's family for a viewer.

func NewFamilyTreeService

func NewFamilyTreeService(links FamilyLinks, cards PageCards, viewer FamilyViewFilter) FamilyTreeService

NewFamilyTreeService creates the family tree reader.

type FamilyViewFilter

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

FamilyViewFilter reports which pages a viewer may open. The entity service implements it (FilterViewableEntityIDs), the one visibility rule.

type FamilyWriter

type FamilyWriter interface {
	FamilyLinks
	// Link writes the pair. When a write fails partway it takes back the row it
	// wrote; if it cannot, the error is a *FamilyHalfWritten.
	Link(ctx context.Context, campaignID string, l FamilyNewLink) error
	// Unlink removes every row of source->target whose type is in types, with
	// its reverse row, and any row of target->source whose type is in
	// reverseTypes that was left without one. It returns what it removed (the
	// forward rows) so a failed save can put them back.
	Unlink(ctx context.Context, campaignID, source, target string, types, reverseTypes []string) ([]FamilyNewLink, error)
}

FamilyWriter writes family relations. Implemented in the app over the relations service, which writes and removes both rows of a pair; this plugin never reaches into the relation tables.

type Favorite

type Favorite struct {
	UserID     string    `json:"user_id"`
	EntityID   string    `json:"entity_id"`
	CampaignID string    `json:"campaign_id"`
	CreatedAt  time.Time `json:"created_at"`
}

Favorite represents a user's bookmarked entity within a campaign.

type FavoriteItem

type FavoriteItem struct {
	EntityID  string `json:"id"`
	Name      string `json:"name"`
	TypeIcon  string `json:"type_icon"`
	TypeColor string `json:"type_color"`
}

FavoriteItem is the display representation of a favorite, with joined entity data for rendering in the sidebar.

type FavoriteRepository

type FavoriteRepository interface {
	Toggle(ctx context.Context, userID, entityID, campaignID string) (bool, error)
	List(ctx context.Context, userID, campaignID string) ([]FavoriteItem, error)
	IsFavorite(ctx context.Context, userID, entityID string) (bool, error)
	ListIDs(ctx context.Context, userID, campaignID string) (map[string]bool, error)
}

FavoriteRepository provides CRUD for entity favorites.

func NewFavoriteRepository

func NewFavoriteRepository(db *sql.DB) FavoriteRepository

NewFavoriteRepository creates a favorite repository.

type FieldCalendar

type FieldCalendar interface {
	// Dates is the campaign's calendar; nil when it has none.
	Dates(ctx context.Context, campaignID string) (FieldDateBook, error)
}

FieldCalendar is the campaign calendar, as pages read dates on it. It belongs to the calendar plugin and is wired in internal/app; unset, a calendar date field shows its numbers and runs no countdowns.

type FieldChangeObserver

type FieldChangeObserver interface {
	// FieldsChanged receives the entity as stored after the write, the fields
	// as they were before it and the fields now. A returned error is logged by
	// the caller and never fails the write that already succeeded.
	FieldsChanged(ctx context.Context, e *Entity, oldFields, newFields map[string]any) error
}

FieldChangeObserver is told after an entity's custom fields were written. It lets another plugin react to field writes (for example to keep a history) without the entities plugin knowing it exists.

type FieldChecks

type FieldChecks struct {
	Min      *float64
	Max      *float64
	JSONList bool
	Formula  bool
}

FieldChecks is the value check a system declares for one field, kept apart from the field so SyncFieldChecks can converge it onto stored categories.

type FieldClimate

type FieldClimate interface {
	// Climates is every climate a place can take, in the picker's order.
	Climates() []ClimateChoice
	// World is the climate a place with none keeps; false when the campaign
	// has no calendar this viewer can see.
	World(ctx context.Context, campaignID string, role int, userID string) (ClimateChoice, bool)
	// Today is today's weather in a region as this viewer may see it; nil
	// for a player when the party is not in that region today.
	Today(ctx context.Context, campaignID, regionID string, role int, userID string) *ClimateToday
}

FieldClimate is the calendar's side of a climate field. It belongs to the calendar plugin and is wired in internal/app; unset, a climate field stores any value and shows no weather.

type FieldCountdown

type FieldCountdown struct {
	Name    string            `json:"name"`
	Lengths []CountdownLength `json:"lengths"`
	// GMOnly keeps the countdown from players even when they see the date.
	GMOnly bool `json:"gm_only,omitempty"`
}

FieldCountdown counts days from a calendar date field's date, such as how long a soul lingers after death. A page picks one of its lengths.

type FieldDate

type FieldDate struct {
	Year, Month, Day int
	// Picks is the length index per countdown; missing means the first.
	Picks []int
}

FieldDate is a calendar date field's parsed value.

func ParseFieldDate

func ParseFieldDate(v any) (FieldDate, bool)

ParseFieldDate reads a calendar date field's value; false for anything else, including an empty value.

func (FieldDate) String

func (d FieldDate) String() string

String is the stored form, dropping picks that are all the usual length.

type FieldDateBook

type FieldDateBook interface {
	Valid(year, month, day int) bool
	Label(year, month, day int) string
	// DaysSince is how many days ago the date was, negative for one still
	// to come.
	DaysSince(year, month, day int) int
	// LabelAfter is the label of the day n days after the date.
	LabelAfter(year, month, day, n int) string
	Months() []FieldDateMonth
	Today() (year, month, day int)
}

FieldDateBook reads dates on one calendar.

type FieldDateMonth

type FieldDateMonth struct {
	Name string `json:"name"`
	Days int    `json:"days"`
}

FieldDateMonth is a month as the date picker offers it.

type FieldDefinition

type FieldDefinition struct {
	Key     string   `json:"key"`     // Machine-readable identifier (e.g., "age", "alignment").
	Label   string   `json:"label"`   // Human-readable label (e.g., "Age", "Alignment").
	Type    string   `json:"type"`    // Input type: text, number, select, textarea, checkbox, url, link, rule, calendar_date.
	Section string   `json:"section"` // Grouping for display (e.g., "Basics", "Appearance").
	Options []string `json:"options"` // Valid values for select fields. Empty for other types.
	// GMOnly marks the field's VALUE as GM-only: it is stripped from
	// fields_data in entity API responses to non-GM (player / public)
	// callers, so GM secrets never reach a player's browser (server is the
	// authority; a client-side hide is not a fix). Absent/false =
	// player-visible. Populated from a system manifest's gm_only annotation
	// via preset application + EnsureFieldMetadataFromManifests.
	GMOnly bool `json:"gm_only,omitempty"`
	// OwnerOnly marks the field's VALUE as visible only to GM-tier roles
	// (same bar as GMOnly) AND the entity's own claimed owner
	// (Entity.OwnerUserID): it is stripped from fields_data for every other
	// Player-tier viewer, including fellow players who are not this entity's
	// owner. Unlike GMOnly (hidden even from the owner), OwnerOnly is for
	// content private between one player and the GM but not party-wide.
	OwnerOnly bool `json:"owner_only,omitempty"`
	// Choices names the system data file the field is picked from. Absent:
	// the picker falls back to the plural of the field key. The stored value
	// is still the picked entry's name as plain text.
	Choices string `json:"choices,omitempty"`
	// Play carries the system manifest's play-controls declaration for this
	// field, so whatever acts on play edits reads one stored source and core
	// never hard-codes a system's field names. Nil = not a play field.
	Play *FieldPlay `json:"play,omitempty"`
	// Min and Max bound a number field's value; absent means unbounded.
	// Only AI Import's field check reads them, so a hand-typed sheet value
	// is never refused by them.
	Min *float64 `json:"min,omitempty"`
	Max *float64 `json:"max,omitempty"`
	// JSONList says a text field holds a JSON list, so AI Import refuses text
	// that is not one rather than store what the sheet's widgets cannot read.
	JSONList bool `json:"json_list,omitempty"`
	// Formula marks a number the game system works out from other fields.
	// AI Import's review may add it to a page whose AI left it out, with the
	// figure the system's sheet check proposes; no other unwritten key is
	// ever added.
	Formula bool `json:"formula,omitempty"`
	// LinkTo is the category a "link" field's pages come from. The stored
	// value is the linked page's id.
	LinkTo int `json:"link_to,omitempty"`
	// RuleID is the homebrew rule a "rule" field is worked out by. A stored
	// value is one typed by hand and wins over the rule.
	RuleID int `json:"rule_id,omitempty"`
	// DateAgo says how long ago a "calendar_date" field's date was.
	DateAgo bool `json:"date_ago,omitempty"`
	// Countdowns run from a "calendar_date" field's date (field_dates.go).
	Countdowns []FieldCountdown `json:"countdowns,omitempty"`
}

FieldDefinition describes a single custom field in an entity type. Stored as JSON array in entity_types.fields. Drives both the edit form (input type) and the profile sidebar (display).

func MergeFields

func MergeFields(typeFields []FieldDefinition, overrides *FieldOverrides) []FieldDefinition

MergeFields combines the entity type's field definitions with per-entity overrides to produce the effective field list for rendering. Hidden fields are removed, modified fields have their properties patched, and added fields are appended at the end.

func RestrictionDefs

func RestrictionDefs(typeFields []FieldDefinition, overrides *FieldOverrides) []FieldDefinition

RestrictionDefs is every definition that can restrict one of a page's values: its category's fields and the fields added to just this page. The category's full list is used rather than MergeFields, so hiding a field on one page never un-restricts its value, and a page-added field marked gm_only or owner_only is withheld like a category field.

type FieldOverride

type FieldOverride struct {
	Label   *string  `json:"label,omitempty"`
	Type    *string  `json:"type,omitempty"`
	Options []string `json:"options,omitempty"`
}

FieldOverride holds modifications to a single field (label, type, options).

type FieldOverrides

type FieldOverrides struct {
	Added    []FieldDefinition        `json:"added,omitempty"`    // Extra fields unique to this entity.
	Hidden   []string                 `json:"hidden,omitempty"`   // Keys of type-level fields to hide.
	Modified map[string]FieldOverride `json:"modified,omitempty"` // Per-field modifications keyed by field key.
}

FieldOverrides holds per-entity field customizations that override the entity type's field template. This allows individual entities to add, hide, or modify fields without affecting the entire category.

type FieldPlay

type FieldPlay struct {
	Edit            string   `json:"edit"`                       // owner | gm | none.
	Kind            string   `json:"kind"`                       // counter | resource | conditions | choice | text.
	Min             *float64 `json:"min,omitempty"`              // Lower bound for counter/resource.
	Max             *float64 `json:"max,omitempty"`              // Literal upper bound.
	MaxField        string   `json:"max_field,omitempty"`        // Another number field whose value is the upper bound; wins over Max.
	Step            float64  `json:"step,omitempty"`             // UI nudge size.
	Options         []string `json:"options,omitempty"`          // Allowed values for conditions/choice.
	MaxLength       int      `json:"max_length,omitempty"`       // Bound for text/choice.
	ToFoundry       *bool    `json:"to_foundry,omitempty"`       // nil = follow the field's foundry_writable.
	CombatAuthority string   `json:"combat_authority,omitempty"` // foundry | chronicle | empty.
}

FieldPlay mirrors the manifest's play block. It is a separate type from the systems package's because plugins do not import each other; the app layer copies between them.

type FieldShown

type FieldShown struct {
	Text string `json:"text"`
	// Href is a link field's page; empty when the page is gone or hidden.
	Href string `json:"href,omitempty"`
	// Usual is the word a local word replaced, for a hover.
	Usual string `json:"usual,omitempty"`
	// ByHand marks a rule field whose value was typed in; RuleGives is what
	// the rule would show instead.
	ByHand    bool   `json:"byHand,omitempty"`
	RuleGives string `json:"ruleGives,omitempty"`
	// Date is a calendar date field's "how long ago" and countdowns.
	Date *DateShown `json:"date,omitempty"`
	// Climate is a climate field's source and today's weather there.
	Climate *ClimateShown `json:"climate,omitempty"`
}

FieldShown is how one field reads to the viewer when that is not simply its stored value. Only fields that differ are sent.

type FieldSwitch

type FieldSwitch struct {
	EntityTypeID int
	CampaignID   string
	SystemID     string
	PresetSlug   string
	State        string
	// OldFields is the category's field list from before the switch, nil
	// when the category was made with the system's fields to begin with.
	OldFields []FieldDefinition
	// OldPresetCategory is the category's preset category from before.
	OldPresetCategory *string
	UpdatedBy         string
	UpdatedAt         time.Time
}

FieldSwitch is a category's answer to a system's switch offer.

type FieldSwitchDraft

type FieldSwitchDraft func(ctx context.Context, campaignID, userID string, typeID int) (bool, error)

FieldSwitchDraft reports whether the owner's unsaved Customizer draft replaces a category's field list. The campaigns plugin keeps the draft; the app layer answers this from it.

type FieldSwitchOffer

type FieldSwitchOffer struct {
	SystemID   string
	SystemName string
	PresetSlug string
	// Category is the preset category the switched category takes.
	Category string
	// Label names the fields in the offer ("treasure fields").
	Label string
	// Summary says what the switch adds in a few words; "" lists the labels.
	Summary string
	// Fields are the system's field definitions, in its order.
	Fields []FieldDefinition
	// SetAside are the category's own keys the switch takes off every page.
	SetAside []string
	// Reuse are keys both lists have whose old values may not fit the new
	// field; such a value is set aside too.
	Reuse []string
}

FieldSwitchOffer is what a game system offers a category. The app layer builds it from the enabled system's manifest, so this plugin never reads a manifest itself.

type FieldSwitchOffers

type FieldSwitchOffers func(ctx context.Context, campaignID string, et *EntityType) *FieldSwitchOffer

FieldSwitchOffers returns the switch the campaign's enabled game system offers this category, or nil. The app layer provides it from the system's manifest.

type FieldSwitchReindex

type FieldSwitchReindex func(ctx context.Context, typeID int) (int, error)

FieldSwitchReindex recomputes search_text for one category's pages. A switch moves values in and out of fields_data, and search_text is built from it, so a value set aside must stop being found.

type FieldSwitchRepository

type FieldSwitchRepository interface {
	// Get returns a category's answer, or nil when it has none.
	Get(ctx context.Context, typeID int) (*FieldSwitch, error)
	// SaveState records an answer that changes no page ("Not now").
	SaveState(ctx context.Context, sw *FieldSwitch) error
	// Switch rewrites the category's fields, moves every page's values with
	// move and records sw, all in one transaction, so a failure leaves the
	// category and its pages as they were. It refuses with a Conflict when
	// the category's answer or field list is no longer base.
	Switch(ctx context.Context, sw *FieldSwitch, base switchBase, fields []FieldDefinition, presetCategory *string, move valueMove) (int, error)
	// SetAside returns the values a switch took off one page.
	SetAside(ctx context.Context, entityID string) (map[string]any, error)

	// ForCampaign returns every answered category in a campaign, by category
	// id, for the campaign backup.
	ForCampaign(ctx context.Context, campaignID string) (map[int]*FieldSwitch, error)
	// SetAsideForCampaign returns every page's kept values in a campaign, by
	// page id, for the campaign backup.
	SetAsideForCampaign(ctx context.Context, campaignID string) (map[string]map[string]any, error)
	// Clear removes a category's answer, so the offer shows again.
	Clear(ctx context.Context, typeID int) error
	// RestoreSetAside writes one page's kept values as a backup carried them.
	RestoreSetAside(ctx context.Context, entityID string, typeID int, values map[string]any) error
}

FieldSwitchRepository stores the owner's answer to a system's switch offer and the values a switch took off each page (entity_type_field_switches, entity_set_aside_values).

func NewFieldSwitchRepository

func NewFieldSwitchRepository(db *sql.DB) FieldSwitchRepository

NewFieldSwitchRepository creates the field switch repository.

type FieldSwitchService

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

FieldSwitchService runs a game system's one-time field switch for a category: the offer, accepting it, "Not now", switching back, and the values it kept aside. Every write is the owner's (the routes require it).

func NewFieldSwitchService

func NewFieldSwitchService(repo FieldSwitchRepository, types fieldSwitchTypes, offers FieldSwitchOffers) *FieldSwitchService

NewFieldSwitchService wires the switch to its store, the category store and the offer source. A nil offers source offers nothing.

func (*FieldSwitchService) Accept

func (s *FieldSwitchService) Accept(ctx context.Context, campaignID string, typeID int, userID string) (int, error)

Accept switches a category to its system's fields. It refuses when no switch is offered or the category has already switched.

func (*FieldSwitchService) AcceptOffer

func (s *FieldSwitchService) AcceptOffer(ctx context.Context, et *EntityType, offer FieldSwitchOffer, userID string) (int, error)

AcceptOffer switches et to offer's fields. The preset applier calls it for a category that has no pages when the system is turned on, so a new campaign starts with the system's fields and is never asked.

func (*FieldSwitchService) Back

func (s *FieldSwitchService) Back(ctx context.Context, campaignID string, typeID int, userID string) (int, error)

Back puts a switched category's old fields and their kept values back. The system's values are kept aside the same way, so switching again restores them.

func (*FieldSwitchService) Dismiss

func (s *FieldSwitchService) Dismiss(ctx context.Context, campaignID string, typeID int, userID string) error

Dismiss records "Not now": the list stops offering; Fields settings still do.

func (*FieldSwitchService) ForCampaign

func (s *FieldSwitchService) ForCampaign(ctx context.Context, campaignID string) (map[int]*FieldSwitch, error)

ForCampaign is every answered category in a campaign, by category id, for the campaign backup.

func (*FieldSwitchService) RecordSwitched

func (s *FieldSwitchService) RecordSwitched(ctx context.Context, et *EntityType, offer FieldSwitchOffer) error

RecordSwitched notes that a category made from the system's preset already has its fields, so the offer never shows for it. There is nothing to go back to.

func (*FieldSwitchService) Restore

func (s *FieldSwitchService) Restore(ctx context.Context, campaignID string, typeID int, sw *FieldSwitch, userID string) error

Restore makes a restored category's answer the one its backup carried: sw, or no answer when sw is nil, so the offer shows again. It writes no page and no field list; the import has already restored both.

func (*FieldSwitchService) RestoreSetAside

func (s *FieldSwitchService) RestoreSetAside(ctx context.Context, campaignID string, typeID int, entityID string, values map[string]any) error

RestoreSetAside writes back the values a backup says a switch kept aside from one restored page. The import passes only pages it has just made in the campaign, so entityID is not checked again here.

func (*FieldSwitchService) SetAside

func (s *FieldSwitchService) SetAside(ctx context.Context, et *EntityType, entityID string) []SetAsideValue

SetAside is what the switch kept aside from one page, for the GM's fold: nil unless the page's category has switched.

func (*FieldSwitchService) SetAsideForCampaign

func (s *FieldSwitchService) SetAsideForCampaign(ctx context.Context, campaignID string) (map[string]map[string]any, error)

SetAsideForCampaign is every page's kept values in a campaign, by page id, for the campaign backup.

func (*FieldSwitchService) SetDraft

func (s *FieldSwitchService) SetDraft(d FieldSwitchDraft)

SetDraft wires the Customizer draft check. Unwired, no draft is checked.

func (*FieldSwitchService) SetSearchReindex

func (s *FieldSwitchService) SetSearchReindex(r FieldSwitchReindex)

SetSearchReindex wires the search refresh run after every switch.

func (*FieldSwitchService) State

func (s *FieldSwitchService) State(ctx context.Context, typeID int) (*FieldSwitch, error)

State is a category's stored answer, or nil.

func (*FieldSwitchService) View

func (s *FieldSwitchService) View(ctx context.Context, campaignID string, et *EntityType) *FieldSwitchView

View is what the owner sees for a category: nil when no system offers it a switch. A failed read shows nothing rather than failing the page.

type FieldSwitchView

type FieldSwitchView struct {
	Offer FieldSwitchOffer
	// State is the stored answer, or "" when the owner has not answered.
	State string
	// Adds names the fields the switch would add or replace, in order.
	Adds []string
	// Removes names the fields on this category the switch takes off.
	Removes []string
	// CanSwitchBack is true when a switched category has a list to go back to.
	CanSwitchBack bool
}

FieldSwitchView is what the owner sees of an offer: on the category's list (only when unanswered) and in the category's Fields settings (always).

func (*FieldSwitchView) AddsLine

func (v *FieldSwitchView) AddsLine() string

AddsLine is the offer's first line: what the switch puts on the pages.

func (*FieldSwitchView) BackLine

func (v *FieldSwitchView) BackLine() string

BackLine says what switching back does, for the category's Fields tab.

func (*FieldSwitchView) Question

func (v *FieldSwitchView) Question(categoryPlural string) string

Question is the offer as the owner reads it.

func (*FieldSwitchView) RemovesLine

func (v *FieldSwitchView) RemovesLine(categoryFields []FieldDefinition) string

RemovesLine is the offer's second line: what comes off the pages and that it is kept. A reused field's values that won't fit are named too, since they leave the visible field. "" when nothing comes off.

type FieldWords

type FieldWords interface {
	// Evaluate gives, per rule id, what the rule gives on this page for this
	// viewer, from its values and what the viewer may see of the calendar
	// and the page's trackers.
	Evaluate(ctx context.Context, campaignID, entityID string, ruleIDs []int, data map[string]any, role int, userID string) map[int]string
	// WordsFor is the local words this viewer sees on one page, keyed by the
	// lower-cased usual word.
	WordsFor(ctx context.Context, campaignID, entityID string, role int, userID string) map[string]string
	// Rename returns the local name for text, if one applies.
	Rename(words map[string]string, text string) (string, bool)
	// RuleExists reports whether the campaign has that rule.
	RuleExists(ctx context.Context, campaignID string, ruleID int) bool
}

FieldWords is what pages need from the homebrew rules and local words, which belong to the fieldrules plugin. It is wired in internal/app; unset, rule fields show only values typed by hand and no word is renamed.

type FieldsMergeFunc

type FieldsMergeFunc func(current map[string]any) (next map[string]any, searchText string, err error)

FieldsMergeFunc computes the next fields_data (and the search_text that goes with it) from the value stored at the moment the row is locked. It runs inside the repository's transaction, so it must not write to the same row.

type FolderService

type FolderService interface {
	// ListFolders returns a category's folders in sidebar order.
	ListFolders(ctx context.Context, campaignID string, entityTypeID int) ([]SidebarNode, error)
	// ListAllFolders returns every folder in the campaign, grouped by category.
	ListAllFolders(ctx context.Context, campaignID string) ([]SidebarNode, error)
	// FindFolder matches a folder by name within one category, ignoring case.
	// It returns nil when there is none and a bad-request error when two
	// folders share the name, so a caller never has to guess which is meant.
	FindFolder(ctx context.Context, campaignID string, entityTypeID int, name string) (*SidebarNode, error)
	CreateFolder(ctx context.Context, campaignID string, in CreateSidebarNodeInput) (*SidebarNode, error)
	RenameFolder(ctx context.Context, campaignID, folderID, name string) error
	// MoveFolder puts a folder under another folder of the same category, or
	// at the top level when parentID is nil.
	MoveFolder(ctx context.Context, campaignID, folderID string, parentID *string) error
	// DeleteFolder removes the folder only: its sub-folders move up to its
	// parent and its pages return to the top level of the category.
	DeleteFolder(ctx context.Context, campaignID, folderID string) error
	// SetEntityFolder files a page in a folder, or takes it out when
	// folderID is nil. A page sits in a folder or under another page, never
	// both, so filing it clears its parent page.
	SetEntityFolder(ctx context.Context, campaignID, entityID string, folderID *string) error
	// ChildOrders returns how each sidebar container in the campaign orders
	// its rows, keyed "category:<type id>", "folder:<id>" or "page:<id>". A
	// container that is missing sorts A to Z.
	ChildOrders(ctx context.Context, campaignID string) (map[string]string, error)
	// SetChildOrder sets how one container (a category's top level, a
	// folder, or a page with pages under it) orders its rows.
	SetChildOrder(ctx context.Context, campaignID, kind, id, mode string) error
	// MoveNextTo puts a page or folder just before or after one of its
	// siblings, for a container ordered by hand. The whole sibling set is
	// renumbered, so rows the mover cannot see keep their places among
	// themselves.
	MoveNextTo(ctx context.Context, campaignID, kind, id, siblingID string, after bool) error
}

FolderService owns the rules for sidebar folders and for which folder a page sits in, so the sidebar's JSON endpoints and AI Import share one set of checks instead of each reaching into the repositories.

func NewFolderService

NewFolderService builds the folder service over the repositories it checks against.

type FoundryLinkChecker

type FoundryLinkChecker func(ctx context.Context, campaignID string) bool

FoundryLinkChecker reports whether a campaign has a Foundry world syncing with it, so a sheet only says a value is "set in Foundry" when one is.

type GenrePreset

type GenrePreset struct {
	ID          string       // Genre identifier (e.g., "fantasy", "sci-fi").
	Name        string       // Display name (e.g., "Fantasy / D&D").
	Description string       // Short description for the UI.
	Icon        string       // FontAwesome icon.
	Types       []EntityType // Entity types to seed.
}

GenrePreset defines a set of entity types for a campaign genre.

func FindGenrePreset

func FindGenrePreset(id string) *GenrePreset

FindGenrePreset returns a genre preset by ID, or nil if not found.

func GenrePresets

func GenrePresets() []GenrePreset

GenrePresets returns all available genre presets.

type GroupLister

type GroupLister interface {
	ListGroups(ctx context.Context, campaignID string) ([]campaigns.CampaignGroup, error)
}

GroupLister retrieves campaign groups for the permissions UI. Satisfied by campaigns.GroupService.

type Handler

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

Handler handles HTTP requests for entity operations. Handlers are thin: bind request, call service, render response. No business logic lives here.

func NewHandler

func NewHandler(service EntityService) *Handler

NewHandler creates a new entity handler.

func (*Handler) AcceptFieldSwitch

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

AcceptFieldSwitch puts the game system's fields on the category. POST /campaigns/:id/entity-types/:etid/field-switch

func (*Handler) AddPlaceAPI

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

AddPlaceAPI lists a page under one more parent. POST /campaigns/:id/entities/:eid/places {"parent_id": "..."} It answers with the refreshed "Also listed under" line.

func (*Handler) AppendLayoutBlock

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

AppendLayoutBlock puts one block at the end of a category's page layout. POST /campaigns/:id/entity-types/:etid/layout/blocks {"type": "..."} It answers {"status": "added"|"already_there", "category": name}. The block's own rules (one per page, its context) are the service's.

func (*Handler) AssignMap

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

AssignMap sets or clears the entity's assigned map. Drives the per-entity Map Editor block — Scribe+ DMs use this to point an entity (typically a Location) at one of the campaign's maps.

Cross-campaign integrity is enforced inside the service via the MapCampaignVerifier (the FK alone catches non-existence but not wrong-campaign — that would silently succeed).

Route: PUT /campaigns/:id/entities/:eid/map (Scribe+ role required).

func (*Handler) AssignOwner

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

AssignOwner sets or clears entity ownership. Used by Owner/Scribe to hand a character to a different player or unassign one. Cross-campaign membership is validated here before delegating to the service.

Route: PUT /campaigns/:id/entities/:eid/owner (Scribe+ role required).

func (*Handler) BacklinksFragment

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

BacklinksFragment returns the "Referenced by" section as an HTMX fragment or JSON. Results are cached in Redis for 5 minutes. GET /campaigns/:id/entities/:eid/backlinks

func (*Handler) BlockPlacementAPI

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

BlockPlacementAPI lists the categories a block can be put on. GET /campaigns/:id/entity-types/placement?block=trackers

func (*Handler) BlockTypesAPI

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

BlockTypesAPI returns the available block types for the layout editor, filtered by which addons are enabled for the current campaign and optionally by editor context (?context=dashboard|template|category). GET /campaigns/:id/entity-types/block-types

func (*Handler) Brochure

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

Brochure draws the block for the page in ?page=, with the owner's words in ?text=. A page the viewer can't open, or no page at all, is an empty answer that removes the placeholder, except for the owner and co-DMs, who get the slot that says how to pick one. GET /campaigns/:id/brochure

func (*Handler) BulkChangeTypeAPI

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

BulkChangeTypeAPI changes the entity type for multiple entities. POST /campaigns/:id/entities/bulk-type

func (*Handler) BulkDeleteAPI

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

BulkDeleteAPI deletes multiple entities. Owner only. POST /campaigns/:id/entities/bulk-delete

func (*Handler) BulkMoveAPI

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

BulkMoveAPI reparents multiple entities under a target parent (entity or folder node). POST /campaigns/:id/entities/bulk-move

func (*Handler) BulkTagsAPI

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

BulkTagsAPI assigns, removes, or sets tags on multiple entities. POST /campaigns/:id/entities/bulk-tags

func (*Handler) BulkVisibilityAPI

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

BulkVisibilityAPI toggles privacy for multiple entities. POST /campaigns/:id/entities/bulk-visibility

func (*Handler) CategoryHomePreview

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

CategoryHomePreview draws the blocks the Customizer sends as the category's landing page draws them, with the description the draft holds: POST /campaigns/:id/entity-types/:etid/home-preview with {"description": "...", "blocks": [{id, type, config}]}. It answers {"blocks": {id: html}}; a block that draws nothing is left out.

func (*Handler) Characters

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

Characters renders the per-campaign Characters page. It has two addon-gated sections: the Party (player characters — when the player-character-claiming addon is on) and NPCs/Monsters (contributed by the npcs plugin when its addon is on). The page 404s when neither addon is enabled.

Route: GET /campaigns/:id/characters (anyone who can view the campaign, so a public campaign's cast is visible signed out; every list below is visibility-filtered for that viewer).

func (*Handler) ClaimEntity

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

ClaimEntity assigns the calling user as the owner of an entity. Idempotent when the caller already owns it; 409 if claimed by a different player; 400 if the entity isn't a character-shaped type. The route is Player+ — anyone with campaign access can claim an unclaimed character; the type-shape check in the service is what prevents claiming a Location.

Route: POST /campaigns/:id/entities/:eid/claim

func (*Handler) Clone

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

Clone creates a copy of an entity (POST /campaigns/:id/entities/:eid/clone). Copies name (with " (Copy)" suffix), entry, fields, image, parent, privacy, field overrides, popup config, and tags. Does NOT copy relations.

func (*Handler) Create

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

Create processes the entity creation form (POST /campaigns/:id/entities).

func (*Handler) CreateEntityType

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

CreateEntityType processes the entity type creation form. POST /campaigns/:id/entity-types

func (*Handler) CreateEraVersionAPI

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

CreateEraVersionAPI starts a version of the page for an era and opens it for editing. POST /campaigns/:id/entities/:eid/eras/:eraID

func (*Handler) CreateHero

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

CreateHero makes the hero from the creator's picks (POST /campaigns/:id/characters/new) and answers with its page address.

func (*Handler) CreateSavedFilterAPI

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

CreateSavedFilterAPI creates a new saved tag filter preset. POST /campaigns/:id/saved-filters

func (*Handler) CreateSidebarNodeAPI

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

CreateSidebarNodeAPI creates a new sidebar folder node. POST /campaigns/:id/sidebar-nodes

func (*Handler) Delete

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

Delete removes an entity (DELETE /campaigns/:id/entities/:eid).

func (*Handler) DeleteEntityType

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

DeleteEntityType removes an entity type. DELETE /campaigns/:id/entity-types/:etid

func (*Handler) DeleteEraVersionAPI

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

DeleteEraVersionAPI removes the page's version for an era; the page shows its usual self in that era again. DELETE /campaigns/:id/entities/:eid/eras/:eraID

func (*Handler) DeleteSavedFilterAPI

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

DeleteSavedFilterAPI deletes a saved filter preset. DELETE /campaigns/:id/saved-filters/:fid

func (*Handler) DeleteSidebarNodeAPI

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

DeleteSidebarNodeAPI deletes a sidebar folder node. Sub-folders move up to its parent and its pages return to the top level of the category. DELETE /campaigns/:id/sidebar-nodes/:nid

func (*Handler) DismissFieldSwitch

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

DismissFieldSwitch is "Not now": the list stops offering the switch. POST /campaigns/:id/entity-types/:etid/field-switch/dismiss

func (*Handler) EditForm

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

EditForm redirects to the entity show page. The separate edit form has been replaced by inline editing on the show page (metadata panel + rich text editor). Kept as a redirect for backwards compatibility with bookmarks and old links.

func (*Handler) EntityNamesAPI

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

EntityNamesAPI returns a lightweight list of all visible entity names for auto-linking in the editor. Results are cached in Redis for 5 minutes. GET /campaigns/:id/entity-names

func (*Handler) EntityTypeAttributesFragment

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

EntityTypeAttributesFragment returns an HTMX fragment for the Customization Hub's Extensions tab. Contains just the attribute field editor for a single entity type. GET /campaigns/:id/entity-types/:etid/attributes-fragment

func (*Handler) EntityTypeConfig

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

EntityTypeConfig sends the old category configuration page's address to the category's Customize workspace, so saved links keep working. GET /campaigns/:id/entity-types/:etid/config

func (*Handler) EntityTypeCustomizeFragment

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

EntityTypeCustomizeFragment returns an HTMX fragment for the Customization Hub's Categories tab. Contains identity settings, attribute field editor, and category dashboard editor for a single entity type. GET /campaigns/:id/entity-types/:etid/customize

func (*Handler) EntityTypeCustomizeTab

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

EntityTypeCustomizeTab returns one of a category's Customize tabs that still use today's editors: GET /campaigns/:id/entity-types/:etid/customize-tab/:tab with tab "layout", "home" or "fields". Customize's category workspace loads it under its own header.

func (*Handler) EntityTypesAPI

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

EntityTypesAPI returns entity types as JSON for widget dropdowns. GET /campaigns/:id/entities/types

func (*Handler) EntityTypesPage

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

EntityTypesPage renders the entity type management page. GET /campaigns/:id/entity-types

func (*Handler) FamilyCandidatesAPI

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

FamilyCandidatesAPI lists the pages the Director may add as family, bounded and narrowed by ?q= (GET /campaigns/:id/entities/:eid/family/candidates).

func (*Handler) FamilyEditAPI

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

FamilyEditAPI saves the Director's edit of a page's family (POST /campaigns/:id/entities/:eid/family). It answers 200 when every change saved and 500 when some did not; both carry the fresh tree and which changes did not save, so the page never has to guess.

func (*Handler) FavoriteIDsAPI

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

FavoriteIDsAPI returns a set of entity IDs favorited by the user. Used by the sidebar to mark starred entities. GET /campaigns/:id/favorite-ids

func (*Handler) GetAliasesAPI

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

GetAliasesAPI returns all aliases for an entity. GET /campaigns/:id/entities/:eid/aliases

func (*Handler) GetCategoryDashboardLayout

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

GetCategoryDashboardLayout returns the dashboard layout JSON for an entity type (GET /campaigns/:id/entity-types/:etid/dashboard-layout).

func (*Handler) GetEntityTypeLayout

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

GetEntityTypeLayout returns the entity type's layout as JSON. GET /campaigns/:id/entity-types/:etid/layout

func (*Handler) GetEntry

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

GetEntry returns the entity's entry content as JSON. GET /campaigns/:id/entities/:eid/entry

func (*Handler) GetEraEntryAPI

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

GetEraEntryAPI returns the version's text, or the usual text while the version has none of its own, in the usual entry route's shape. GET /campaigns/:id/entities/:eid/eras/:eraID/entry

func (*Handler) GetEraFieldsAPI

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

GetEraFieldsAPI returns the page's fields with the version's values laid over, in the usual fields route's shape. For the DM it adds era_changed: each changed field's usual value, so the widget can say what it usually is. GET /campaigns/:id/entities/:eid/eras/:eraID/fields

func (*Handler) GetFieldsAPI

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

GetFieldsAPI returns the entity's custom field values and type definitions. GET /campaigns/:id/entities/:eid/fields

func (*Handler) GetLocalWordsAPI

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

GetLocalWordsAPI returns the local words a viewer sees on one page, for widgets that show words outside the fields box, such as a shop's coins. GET /campaigns/:id/entities/:eid/local-words

func (*Handler) GetMembersAPI

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

GetMembersAPI returns campaign members as JSON for the permission user picker, for the DM team. GET /campaigns/:id/entities/members

func (*Handler) GetPermissionsAPI

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

GetPermissionsAPI returns the entity's current visibility mode, campaign members, and permission grants, for the DM team. Member emails go to the owner only; a co-DM picks members by name. GET /campaigns/:id/entities/:eid/permissions

func (*Handler) GetPlayerNotes

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

GetPlayerNotes returns the entity's player-facing notes as JSON. GET /campaigns/:id/entities/:eid/player-notes

func (*Handler) HeroPlanAPI

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

HeroPlanAPI returns the creator's steps (GET /campaigns/:id/characters/new/plan).

func (*Handler) HeroTermsAPI

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

HeroTermsAPI returns the creator's rules words (GET /campaigns/:id/characters/new/terms), to whoever may read its plan.

func (*Handler) Index

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

Index renders the entity list page (GET /campaigns/:id/entities).

func (*Handler) LayoutPreview

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

LayoutPreview draws blocks of a category's page layout as one of the category's pages shows them to the owner: POST /campaigns/:id/entity-types/:etid/layout-preview with {"entityId": "...", "blocks": [{id, type, config}]}. With no entityId it uses the most recently changed page. Nothing is saved.

func (*Handler) ListFavoritesAPI

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

ListFavoritesAPI returns the user's favorites for a campaign as JSON. GET /campaigns/:id/favorites

func (*Handler) ListSavedFiltersAPI

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

ListSavedFiltersAPI returns the user's saved tag filter presets. GET /campaigns/:id/saved-filters

func (*Handler) MakeFullPageAPI

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

MakeFullPageAPI brings a shop good into lists, search and links by clearing its mark. Director only; asking again for a page that is already full is a no-op, so a second press never errors.

Route: POST /campaigns/:id/entities/:eid/full-page

func (*Handler) MoveSidebarRowAPI

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

MoveSidebarRowAPI puts a page or folder just before or after a sibling, for a list ordered by hand. Naming the neighbour rather than an index keeps the move right when the mover cannot see every sibling. PUT /campaigns/:id/sidebar-order/move

func (*Handler) MyCharacters

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

MyCharacters answers the old "My Characters" address. A player's own characters are the Yours band on the Characters page, so old links and bookmarks go there.

Route: GET /campaigns/:id/me (Player+ role required by the route group).

func (*Handler) NewForm

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

NewForm renders the entity creation form (GET /campaigns/:id/entities/new).

When the ?type= preselect is a top-level entity_type that has sub-category children, those children are passed through as layout variants so the form can render a variant picker scoped to that category. Sub-category entity_types are not navigable collections — they carry the layout differentiation.

func (*Handler) NewHero

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

NewHero renders the hero creator (GET /campaigns/:id/characters/new).

func (*Handler) OwnEntries

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

OwnEntries renders the page for a campaign's own pick-list entries (GET /campaigns/:id/characters/entries): the Directors' list, or for a player, the entries a Director let them write. The entry API enforces the same rules on every write; this only keeps others off the page.

?field= opens that list; ?for= names the player's character the new entry is for, and the page links back to it (or to the hero creator, ?back=new). ?entry= opens the editor on one entry (?made=1 when a rewrite just made it) and ?new=1 on a new one; ?return= is the rules page to go back to after.

A Director's bare address opens the page itself; Campaign settings and "Before you play in <campaign>" both lead here.

func (*Handler) PartyBlock

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

PartyBlock draws the block, or an empty answer that removes the placeholder when there are no heroes to show. GET /campaigns/:id/party

func (*Handler) Peek

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

Peek serves the read-only body of a page for the side panel (GET /campaigns/:id/entities/:eid/peek).

It repeats Show's gates in the same order and answers a page the viewer cannot see exactly as Show does (the same NotFound), so the panel can never reveal that a page exists or what it is called. Anything it draws is the subset of the full page a viewer is allowed to read: field values pass FilterRestrictedFields and the entry passes the same secret stripping as GetEntry. Editing is never offered here.

func (*Handler) PracticeAllow

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

PracticeAllow is a Director's yes (POST /campaigns/:id/characters/practice/:pid/allow, with `seen`: the version of the hero the Director looked at): the maker's practice hero becomes their real hero.

func (*Handler) PracticeAsk

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

PracticeAsk marks a practice hero as one its maker wants to play (POST /campaigns/:id/characters/practice/:pid/ask).

func (*Handler) PracticeCreate

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

PracticeCreate saves a new practice hero (POST /campaigns/:id/characters/practice).

func (*Handler) PracticeDecline

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

PracticeDecline is a Director's "not now" (POST /campaigns/:id/characters/practice/:pid/decline, optional note).

func (*Handler) PracticeDelete

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

PracticeDelete throws a practice hero away (DELETE /campaigns/:id/characters/practice/:pid). It is deleted outright: not the Trash, and not recorded as a change to a hero, since it never was one.

func (*Handler) PracticeNew

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

PracticeNew renders the hero creator in practice mode (GET /campaigns/:id/characters/practice/new). ?from=hero starts as a copy of the player's own hero and ?edit=<id> loads one of their practice heroes.

func (*Handler) PracticePlanAPI

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

PracticePlanAPI returns the practice plan (GET /campaigns/:id/characters/practice/plan).

func (*Handler) PracticeShow

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

PracticeShow renders a practice hero's page (GET /campaigns/:id/characters/practice/:pid). Only its maker and the Directors may open it.

func (*Handler) PracticeTermsAPI

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

PracticeTermsAPI returns the practice builder's rules words (GET /campaigns/:id/characters/practice/terms), to whoever may make a practice hero.

func (*Handler) PracticeUpdate

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

PracticeUpdate replaces a practice hero's name and picks (PUT /campaigns/:id/characters/practice/:pid).

func (*Handler) PreviewAPI

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

PreviewAPI returns entity data for tooltip/popover display, respecting the entity's popup_config to control which sections are included. GET /campaigns/:id/entities/:eid/preview

func (*Handler) QuickCreateAPI

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

QuickCreateAPI creates a new entity from a JSON request and returns its data. POST /campaigns/:id/entities/quick-create Used by the shop inventory widget to create items inline.

func (*Handler) RemovePlaceAPI

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

RemovePlaceAPI takes a page out of one extra place. The page is untouched. DELETE /campaigns/:id/entities/:eid/places/:pid

func (*Handler) RenameSidebarNodeAPI

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

RenameSidebarNodeAPI renames a sidebar folder node. PUT /campaigns/:id/sidebar-nodes/:nid

func (*Handler) ReopenHeroChanges

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

ReopenHeroChanges opens one claimed hero's picks for some days, whatever the campaign's times say. Directors only.

Route: POST /campaigns/:id/characters/hero-changes/:eid/reopen

func (*Handler) ReorderAPI

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

ReorderAPI updates an entity's parent and sort order for sidebar tree reordering. PUT /campaigns/:id/entities/:eid/reorder

func (*Handler) ReorderEntityTypeAPI

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

ReorderEntityTypeAPI re-sequences a sub-category type among its parent's children, making sub-category order editable (persisted, survives reload) — the order shown in the parent's +New variant picker and aggregated listing. PUT /campaigns/:id/entity-types/:etid/reorder Body: {"sort_order": <desired 0-based index among the parent's children>}.

func (*Handler) ReorderSidebarNodeAPI

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

ReorderSidebarNodeAPI updates a sidebar node's parent and sort order. PUT /campaigns/:id/sidebar-nodes/:nid/reorder

func (*Handler) ResetCategoryDashboardLayout

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

ResetCategoryDashboardLayout removes the custom dashboard layout for an entity type, reverting to the hardcoded default (DELETE /campaigns/:id/entity-types/:etid/dashboard-layout).

func (*Handler) ResetFieldOverridesAPI

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

ResetFieldOverridesAPI clears all per-entity field customizations, restoring the entity to its category's default field template. DELETE /campaigns/:id/entities/:eid/field-overrides

func (*Handler) SaveHeroChanges

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

SaveHeroChanges stores when players may change their hero's picks. Directors only; anyone else is answered as if the route were absent.

Route: POST /campaigns/:id/characters/hero-changes

func (*Handler) SearchAPI

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

SearchAPI handles entity search requests (GET /campaigns/:id/entities/search). Returns HTML fragments for HTMX callers and JSON for API callers (e.g., the @mention widget) based on the Accept header.

func (*Handler) SearchPageHandler

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

SearchPageHandler renders the dedicated search page with real-time filtering. GET /campaigns/:id/search

func (*Handler) SearchRosterFinder

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

SearchRosterFinder answers the Players box's finder with result rows. for is "free" (adding to Free to pick) or the user id of the member who would receive the character. With nothing typed, giving offers only the free characters and adding offers none; typing searches every character of the party's page types the viewer may see. Scribe+ (the route enforces it).

Route: GET /campaigns/:id/characters/players/search?q=&for=

func (*Handler) SetAddonChecker

func (h *Handler) SetAddonChecker(svc AddonChecker)

SetAddonChecker sets the addon checker for conditional feature rendering. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetAliasesAPI

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

SetAliasesAPI replaces all aliases for an entity. PUT /campaigns/:id/entities/:eid/aliases

func (*Handler) SetAuditService

func (h *Handler) SetAuditService(svc audit.AuditService)

SetAuditService sets the audit service for recording entity mutations. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetBlockRegistry

func (h *Handler) SetBlockRegistry(reg *BlockRegistry)

SetBlockRegistry sets the block registry for the block-types API endpoint. Called after all plugins have registered their block types.

func (*Handler) SetCache

func (h *Handler) SetCache(rdb *redis.Client)

SetCache sets the Redis client for API response caching (e.g., entity names).

func (*Handler) SetCalendarSearcher

func (h *Handler) SetCalendarSearcher(cs CalendarSearcher)

SetCalendarSearcher sets the calendar event searcher for quick search results. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetCharacterLists

func (h *Handler) SetCharacterLists(m CharacterListManager)

SetCharacterLists injects the service behind the owner's choice of which page types are characters and NPCs. Without it the Characters page lists nothing, since no list is ever guessed.

func (*Handler) SetCharacterOwner

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

SetCharacterOwner hands a character to a member, or takes it back, from the Characters page's Players list. Scribe+ (the route enforces it).

Route: POST /campaigns/:id/characters/owner

func (*Handler) SetCharacterPagePanel

func (h *Handler) SetCharacterPagePanel(p PagePanel)

SetCharacterPagePanel registers the panel shown on character pages.

func (*Handler) SetCharacterPlayable

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

SetCharacterPlayable puts a character on or takes it off the "Who plays whom" list. Scribe+ (the route enforces it).

Route: POST /campaigns/:id/characters/playable

func (*Handler) SetContentTemplateService

func (h *Handler) SetContentTemplateService(svc ContentTemplateService)

SetContentTemplateService sets the content template service for applying templates during entity creation.

func (*Handler) SetEraPages

func (h *Handler) SetEraPages(p EraPages)

SetEraPages wires pages by era. Unset, every page is its usual self.

func (*Handler) SetFamilyEdit

func (h *Handler) SetFamilyEdit(svc FamilyEditService)

SetFamilyEdit injects the Family tree block's write side. Called during app wiring; without it the routes answer 404 rather than half-work.

func (*Handler) SetFavoriteRepo

func (h *Handler) SetFavoriteRepo(repo FavoriteRepository)

SetFavoriteRepo sets the favorite repository for bookmark operations.

func (*Handler) SetFieldCalendar

func (h *Handler) SetFieldCalendar(fc FieldCalendar)

SetFieldCalendar wires the campaign calendar into the fields API.

func (*Handler) SetFieldClimate

func (h *Handler) SetFieldClimate(fc FieldClimate)

SetFieldClimate wires the calendar's climates into the fields API.

func (*Handler) SetFieldSwitch

func (h *Handler) SetFieldSwitch(svc *FieldSwitchService)

SetFieldSwitch wires the game-system field switch. Unwired, no offer is drawn and the switch routes answer 404.

func (*Handler) SetFieldWords

func (h *Handler) SetFieldWords(fw FieldWords)

SetFieldWords wires the homebrew rules and local words into the fields API.

func (*Handler) SetFolderService

func (h *Handler) SetFolderService(f FolderService)

SetFolderService wires the folder rules behind the sidebar's create, rename and delete endpoints.

func (*Handler) SetGroupLister

func (h *Handler) SetGroupLister(gl GroupLister)

SetGroupLister sets the group lister for the permissions UI. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetHeroChanges

func (h *Handler) SetHeroChanges(s *HeroChangeService)

SetHeroChanges wires when players may change their hero's picks. Without it every hero is open and no change rings the Directors' bell.

func (*Handler) SetHeroPlanner

func (h *Handler) SetHeroPlanner(p HeroPlanner)

SetHeroPlanner wires the source of the hero creator's steps. Without it the creator asks only for a name.

func (*Handler) SetHeroRules

func (h *Handler) SetHeroRules(r HeroRules)

SetHeroRules wires the hero-choice rules. Without them nothing is limited.

func (*Handler) SetHeroTerms

func (h *Handler) SetHeroTerms(r HeroTermsReader)

SetHeroTerms wires the source of the builder's rules words. Without it no mount carries a terms URL and the endpoints answer empty.

func (*Handler) SetMapSearcher

func (h *Handler) SetMapSearcher(ms MapSearcher)

SetMapSearcher sets the map searcher for quick search results. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetMemberLister

func (h *Handler) SetMemberLister(ml MemberLister)

SetMemberLister sets the member lister for the permissions UI. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetNPCSectionProvider

func (h *Handler) SetNPCSectionProvider(p NPCSectionProvider)

SetNPCSectionProvider injects the npcs plugin's section renderer.

func (*Handler) SetPageLayoutAPI

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

SetPageLayoutAPI makes a page wear one of its category's layouts. PUT /campaigns/:id/entities/:eid/layout body: {"layout": "<key>"}

func (*Handler) SetPageLayouts

func (h *Handler) SetPageLayouts(s PageLayoutService)

SetPageLayouts wires the named layouts service; without it every category has only its main layout.

func (*Handler) SetPageMoons

func (h *Handler) SetPageMoons(p PageMoons)

SetPageMoons wires the moon chip. Unset, no page shows one.

func (*Handler) SetPageParts

func (h *Handler) SetPageParts(p PageParts)

SetPageParts wires the tags and connections supplier. Without it those two widgets fetch for themselves, as they always did.

func (*Handler) SetPermissionsAPI

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

SetPermissionsAPI updates an entity's visibility mode and permission grants, for the DM team. PUT /campaigns/:id/entities/:eid/permissions

func (*Handler) SetPlaceService

func (h *Handler) SetPlaceService(svc PlaceService)

SetPlaceService wires the extra-listings service. Without it the "Also listed under" line and the tree rows are simply absent.

func (*Handler) SetPracticeService

func (h *Handler) SetPracticeService(s PracticeService)

SetPracticeService wires practice heroes. Without it every practice route answers not found and the Characters page shows no shelf.

func (*Handler) SetSavedFilterRepo

func (h *Handler) SetSavedFilterRepo(repo SavedFilterRepository)

SetSavedFilterRepo sets the saved filter repository for tag filter presets.

func (*Handler) SetSessionSearcher

func (h *Handler) SetSessionSearcher(ss SessionSearcher)

SetSessionSearcher sets the session searcher for quick search results. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetSidebarNodeRepo

func (h *Handler) SetSidebarNodeRepo(repo SidebarNodeRepository)

SetSidebarNodeRepo sets the sidebar node repository for folder operations.

func (*Handler) SetSidebarOrderAPI

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

SetSidebarOrderAPI sets how one sidebar container orders its rows: a category's top level, a folder, or a page with pages under it. PUT /campaigns/:id/sidebar-order

func (*Handler) SetSystemPanelResolver

func (h *Handler) SetSystemPanelResolver(r SystemPanelResolver)

SetSystemPanelResolver registers the resolver the show page consults.

func (*Handler) SetSystemSearcher

func (h *Handler) SetSystemSearcher(ms SystemSearcher)

SetSystemSearcher sets the system searcher for quick search results. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetTagFetcher

func (h *Handler) SetTagFetcher(f EntityTagFetcher)

SetTagFetcher sets the tag fetcher for populating entity tags in list views. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetTimelineSearcher

func (h *Handler) SetTimelineSearcher(ts TimelineSearcher)

SetTimelineSearcher sets the timeline searcher for @mention results. Called after all plugins are wired to avoid initialization order issues.

func (*Handler) SetTrashNoteCounter

func (h *Handler) SetTrashNoteCounter(nc TrashNoteCounter)

SetTrashNoteCounter wires the note count shown after a delete. Unset, the message just says the page moved to the Trash.

func (*Handler) SetVisitorPlanner

func (h *Handler) SetVisitorPlanner(p VisitorPlanner)

SetVisitorPlanner wires the visitor's plan. Without it the try-out routes answer not found and the Characters page offers nothing to a visitor.

func (*Handler) SetWidgetBlockLister

func (h *Handler) SetWidgetBlockLister(wbl WidgetBlockLister)

SetWidgetBlockLister sets the extension widget block lister for the template editor palette. Extension widgets appear as additional block types.

func (*Handler) Sheet

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

Sheet renders a DM-only page's body without the site chrome, for the DM Screen to open over itself (GET /campaigns/:id/entities/:eid/sheet). It is for the DM team and for Adventures pages only; anything else answers the same not-found as a page that does not exist, so the route cannot be used to probe for pages.

func (*Handler) Show

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

Show renders the entity profile page (GET /campaigns/:id/entities/:eid).

func (*Handler) StartHere

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

StartHere draws the block for the page in ?page=. A page the viewer can't open, or no page at all, is an empty answer that removes the placeholder, except for the owner and co-DMs, who get the slot that says how to pick one. GET /campaigns/:id/start-here

func (*Handler) SwitchFieldsBack

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

SwitchFieldsBack puts the category's old fields and kept values back. POST /campaigns/:id/entity-types/:etid/field-switch/back

func (*Handler) TemplateEditor

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

TemplateEditor sends the old page-layout editor's address to the category's Page layout tab in Customize, so saved links keep working. GET /campaigns/:id/entity-types/:etid/template

func (*Handler) ToggleFavoriteAPI

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

ToggleFavoriteAPI adds or removes an entity from the user's favorites. POST /campaigns/:id/entities/:eid/favorite

func (*Handler) TryoutNew

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

TryoutNew renders the hero creator in try-out mode (GET /campaigns/:id/characters/try). A member is sent to the creator they have; the try-out is for people who are not members yet.

func (*Handler) TryoutPlanAPI

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

TryoutPlanAPI returns the visitor's plan (GET /campaigns/:id/characters/try/plan).

func (*Handler) TryoutTermsAPI

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

TryoutTermsAPI returns the try-out builder's rules words (GET /campaigns/:id/characters/try/terms), to a look-around visitor on a live pass. Read-only like the rest of the try-out.

func (*Handler) Update

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

Update processes the entity edit form (PUT /campaigns/:id/entities/:eid).

func (*Handler) UpdateCategoryDashboardLayout

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

UpdateCategoryDashboardLayout saves a custom dashboard layout for an entity type (PUT /campaigns/:id/entity-types/:etid/dashboard-layout).

func (*Handler) UpdateCharacterLists

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

UpdateCharacterLists adds or removes one page type on the party or NPC list. Owner only (the route enforces it); the service checks the type belongs to this campaign. Answers with the refreshed page body for the HTMX swap.

Route: POST /campaigns/:id/characters/lists

func (*Handler) UpdateCoverImageAPI

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

UpdateCoverImageAPI updates the entity's cover/banner image path. PUT /campaigns/:id/entities/:eid/cover-image

func (*Handler) UpdateEntityTypeAPI

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

UpdateEntityTypeAPI updates an entity type. PUT /campaigns/:id/entity-types/:etid

func (*Handler) UpdateEntityTypeColor

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

UpdateEntityTypeColor saves the entity type's display color. PUT /campaigns/:id/entity-types/:etid/color

func (*Handler) UpdateEntityTypeDashboard

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

UpdateEntityTypeDashboard updates the category dashboard description and, when the body names them, its pinned pages (PUT /campaigns/:id/entity-types/:etid/dashboard).

func (*Handler) UpdateEntityTypeLayout

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

UpdateEntityTypeLayout saves the entity type's profile layout. PUT /campaigns/:id/entity-types/:etid/layout

func (*Handler) UpdateEntryAPI

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

UpdateEntryAPI saves the entity's entry content from the editor widget. PUT /campaigns/:id/entities/:eid/entry

func (*Handler) UpdateEraEntryAPI

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

UpdateEraEntryAPI saves the version's text from the editor. A save on top of newer text answers 409 like the usual entry route. PUT /campaigns/:id/entities/:eid/eras/:eraID/entry

func (*Handler) UpdateEraFieldsAPI

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

UpdateEraFieldsAPI saves the attributes form against the version: only the values that differ from the usual page are kept, so a field set back to its usual value stops being a change. fields_data and fields_patch both change only the keys they carry (null clears). PUT /campaigns/:id/entities/:eid/eras/:eraID/fields

func (*Handler) UpdateEraIdentityAPI

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

UpdateEraIdentityAPI changes the name and picture a page has in an era. Partial: an absent key keeps, an empty or null one goes back to the usual page's. Accepts JSON or the Eras panel's form. PATCH /campaigns/:id/entities/:eid/eras/:eraID

func (*Handler) UpdateEraImageAPI

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

UpdateEraImageAPI sets the version's picture, for the picture widget. PUT /campaigns/:id/entities/:eid/eras/:eraID/image

func (*Handler) UpdateFieldOverridesAPI

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

UpdateFieldOverridesAPI saves per-entity field customizations (added, hidden, modified fields) from the attributes widget's gear menu. PUT /campaigns/:id/entities/:eid/field-overrides

func (*Handler) UpdateFieldsAPI

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

UpdateFieldsAPI saves the entity's custom field values from the attributes widget. PUT /campaigns/:id/entities/:eid/fields

func (*Handler) UpdateImageAPI

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

UpdateImageAPI updates the entity's header image path. PUT /campaigns/:id/entities/:eid/image

func (*Handler) UpdateMetadataAPI

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

UpdateMetadataAPI saves entity metadata (name, descriptor, parent, privacy) without touching entry content or field values. Used by the inline metadata panel on the entity show page. PUT /campaigns/:id/entities/:eid/metadata

func (*Handler) UpdatePlayerNotesAPI

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

UpdatePlayerNotesAPI updates only the entity's player-facing notes. PUT /campaigns/:id/entities/:eid/player-notes

func (*Handler) UpdatePopupConfigAPI

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

UpdatePopupConfigAPI saves the entity's hover preview tooltip configuration. PUT /campaigns/:id/entities/:eid/popup-config

func (*Handler) ViewableIDsAPI

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

ViewableIDsAPI answers which of the given pages the viewer can still open (GET /campaigns/:id/entities/viewable?ids=a,b,…). The sidebar's Recent list lives in the browser, so it asks before drawing and drops a page that was hidden or deleted since the visit. A page the viewer cannot see is absent, exactly like one that does not exist.

func (*Handler) YourHeroBlock

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

YourHeroBlock draws the block, or an empty answer that removes the placeholder for someone with no hero to show or choose (a visitor, or a campaign that doesn't let players claim heroes). GET /campaigns/:id/your-hero

type HeroAboutField

type HeroAboutField struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	// Long is a paragraph rather than a line.
	Long bool `json:"long,omitempty"`
}

HeroAboutField is one box of the hero creator's "About your hero" step: who the hero is in the player's own words. Every box is optional, and each is a field the player may edit on the hero later (identity_edit.go).

type HeroAsk

type HeroAsk struct {
	CampaignID string
	UserID     string
	EntityID   string
	EntityName string
	FieldKey   string
	EntryName  string
}

HeroAsk is a pick of an ask-first entry, to be recorded as a request.

type HeroAskOutcome

type HeroAskOutcome struct {
	ID        int64  `json:"id"`
	FieldKey  string `json:"fieldKey"`
	EntryName string `json:"entryName"`
	Status    string `json:"status"`
}

HeroAskOutcome is what a write answers with in place of storing the pick: the request now waits for a Director.

type HeroBreak

type HeroBreak struct {
	FieldKey string `json:"fieldKey"`
	Value    string `json:"value"`
	// Kind is "not_offered" or "off_list" (not on a required short list).
	Kind   string `json:"kind"`
	Reason string `json:"reason,omitempty"`
}

HeroBreak is one rule a hero already breaks: it holds an entry the rules now keep off its player's list. The hero keeps it and stays editable.

type HeroBuilderView

type HeroBuilderView struct {
	CampaignID string
	CSRFToken  string
	Heroes     []BuilderHero
}

HeroBuilderView is the builder's mount data on the Characters page. nil hides the builder.

func (*HeroBuilderView) HeroesJSON

func (v *HeroBuilderView) HeroesJSON() string

HeroesJSON is the heroes as the mount's data attribute carries them.

type HeroChangeKind

type HeroChangeKind string

HeroChangeKind says how a changed field is judged and worded.

const (
	// HeroChangePick is a builder step or what a step's entry buys.
	HeroChangePick HeroChangeKind = "pick"
	// HeroChangeText is a short identity text such as pronouns.
	HeroChangeText HeroChangeKind = "text"
	// HeroChangeList is a list of names (skills, languages, perks).
	HeroChangeList HeroChangeKind = "list"
	// HeroChangeStory is the player's long text. Its words never leave the
	// page: a change carries no From or To.
	HeroChangeStory HeroChangeKind = "story"
)

The kinds of change the bell tells of. Only HeroChangePick is ever locked.

type HeroChangeNotifier

type HeroChangeNotifier interface {
	HeroChanged(ctx context.Context, e *Entity, userID string, changes []HeroPickChange) error
	LevelRaised(ctx context.Context, e *Entity, userID string, level int) error
}

HeroChangeNotifier tells the campaign's Directors that a player changed their hero, or raised its level themselves. A failure is logged by the caller; the change stands.

type HeroChangeRow

type HeroChangeRow struct {
	ID     string
	Name   string
	Player string
	State  string
	Open   bool
}

HeroChangeRow is one claimed hero in the Directors' list.

type HeroChangeRules

type HeroChangeRules interface {
	HeroChangeRule(ctx context.Context, campaignID string) (*campaigns.HeroChangeRule, error)
	SaveHeroChangeRule(ctx context.Context, campaignID string, rule *campaigns.HeroChangeRule) error
}

HeroChangeRules reads and stores the campaign's rule.

type HeroChangeService

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

HeroChangeService ties the rule, the remembered state and the bell together. Every part is optional: with no rules store every hero is open, and with no notifier nothing rings.

func NewHeroChangeService

func NewHeroChangeService(rules HeroChangeRules, store HeroChangeStore, notify HeroChangeNotifier) *HeroChangeService

NewHeroChangeService builds the service.

func (*HeroChangeService) Changed

func (s *HeroChangeService) Changed(ctx context.Context, e *Entity, userID string, changes []HeroPickChange)

Changed rings the Directors' bell for a change a player saved.

func (*HeroChangeService) CheckPicks

func (s *HeroChangeService) CheckPicks(ctx context.Context, e *Entity, patch map[string]any, picks builderPicks, plan *HeroPlan, typeFields []FieldDefinition) ([]HeroPickChange, error)

CheckPicks returns the changes a claimed owner's patch makes for the bell, refused when it changes a pick and the hero's picks are shut now. A list, story or identity change is never refused: it is stored and only rings.

func (*HeroChangeService) FieldsChanged

func (s *HeroChangeService) FieldsChanged(ctx context.Context, e *Entity, oldFields, newFields map[string]any) error

FieldsChanged notes a claimed hero's new level, so a level window opens from the moment it was reached. It is a field observer and never blocks the write.

func (*HeroChangeService) HeldPicks

func (s *HeroChangeService) HeldPicks(ctx context.Context, e *Entity, patch map[string]any, plan *HeroPlan, typeFields []FieldDefinition) (map[string]string, []HeroPickChange, error)

HeldPicks is CheckPicks key by key, for writers that keep what passes and report the rest (Foundry, a player's AI): when the hero's picks are shut, each changed pick is held with the reason; the changes that are not picks are stored, so they are still returned for the bell. The caller passes only the keys it would still store, so a key held for another reason is not counted twice.

func (*HeroChangeService) LevelRaised

func (s *HeroChangeService) LevelRaised(ctx context.Context, e *Entity, userID string, level int)

LevelRaised rings the Directors' bell for a level a player gave their own hero. The level-up still counts, since tables that level outside Chronicle rely on it; the bell is so it is seen. 0 rings nothing.

func (*HeroChangeService) Lock

func (s *HeroChangeService) Lock(ctx context.Context, e *Entity) (HeroLock, error)

Lock is one hero's lock now.

func (*HeroChangeService) Locks

func (s *HeroChangeService) Locks(ctx context.Context, campaignID string, heroes []Entity) (map[string]HeroLock, error)

Locks is the lock of each of a campaign's heroes, read in one pass.

func (*HeroChangeService) Reopen

func (s *HeroChangeService) Reopen(ctx context.Context, e *Entity, n int, by string) error

Reopen opens one hero's picks for some days from now.

func (*HeroChangeService) Rule

func (s *HeroChangeService) Rule(ctx context.Context, campaignID string) (*campaigns.HeroChangeRule, error)

Rule returns the campaign's rule; nil is any time.

func (*HeroChangeService) SaveRule

func (s *HeroChangeService) SaveRule(ctx context.Context, campaignID string, rule *campaigns.HeroChangeRule) error

SaveRule stores the campaign's rule; nil is any time.

type HeroChangeState

type HeroChangeState struct {
	EntityID      string
	Level         int
	LevelAt       *time.Time
	ReopenedUntil *time.Time
}

HeroChangeState is what the window remembers about one hero: the newest level it reached and when, and a Director's reopening.

type HeroChangeStore

type HeroChangeStore interface {
	// Get returns one hero's state; a hero with none gives a zero state.
	Get(ctx context.Context, entityID string) (HeroChangeState, error)
	// List returns the campaign's states by entity id.
	List(ctx context.Context, campaignID string) (map[string]HeroChangeState, error)
	// RecordLevel notes that the hero reached level at at.
	RecordLevel(ctx context.Context, campaignID, entityID string, level int, at time.Time) error
	// Reopen opens the hero's picks until until, whatever the rule says.
	Reopen(ctx context.Context, campaignID, entityID string, until time.Time, by string) error
}

HeroChangeStore owns the hero_change_state table.

func NewHeroChangeRepository

func NewHeroChangeRepository(db *sql.DB) HeroChangeStore

NewHeroChangeRepository creates the MariaDB store for hero change state.

type HeroChangesView

type HeroChangesView struct {
	CampaignID string
	CSRFToken  string
	// Ruled is false when players may change their picks any time.
	Ruled   bool
	Summary string
	// The form starts from the stored rule, or from suggested numbers.
	AfterMaking bool
	MakingDays  int
	AfterLevel  bool
	FromLevel   int
	LevelDays   int
	// Rows is each claimed hero with its state, shown only under a rule.
	Rows []HeroChangeRow
	// Open keeps the form unfolded after a save that was refused.
	Open bool
}

HeroChangesView is the Directors' section; nil for everyone else.

type HeroChoice

type HeroChoice struct {
	// Key is what a hero-choice rule names the entry by (a package entry's
	// slug, a campaign entry's id), so a client can match a rule's entry
	// without relying on a name that may be renamed.
	Key         string         `json:"key,omitempty"`
	Slug        string         `json:"slug"`
	Name        string         `json:"name"`
	Summary     string         `json:"summary"`
	Source      string         `json:"source"`
	Description string         `json:"description,omitempty"`
	Properties  map[string]any `json:"properties,omitempty"`
	// Look is the card border and colour the entry names, set only when it
	// names a border in the library. The two properties it comes from are
	// left out of Properties, so neither creator shows them as facts.
	Look *HeroLook `json:"look,omitempty"`
	// SystemLook is the look the game system itself gives the entry, and
	// LookChanged says the campaign's owner has chosen another (or none) over
	// it. Both are set only on a Director's plan: the Customizer needs them to
	// show what a reset gives back; players never see them. SystemLook is nil
	// when the game system gives the entry no border.
	SystemLook  *HeroLook `json:"systemLook,omitempty"`
	LookChanged bool      `json:"lookChanged,omitempty"`
	// Status is "draft" or "sent" for a player's own entry a Director has
	// not accepted yet; Mine and EntryID are set for the player who wrote it.
	Status  string `json:"status,omitempty"`
	Mine    bool   `json:"mine,omitempty"`
	EntryID int64  `json:"entryId,omitempty"`
	// State is HeroChoiceStateAskFirst on an entry the player may pick only
	// with a Director's yes; empty for an entry they may simply pick.
	State string `json:"state,omitempty"`
	// Parent is the name of the parent-step entry this one belongs to, set
	// on entries of a step whose list lives inside another step's entries
	// (a subclass inside its class).
	Parent string `json:"parent,omitempty"`
	// Held marks an entry the rules took off the player's list, carried only
	// so a hero that already holds it stays editable. Never served, and never
	// a valid new pick.
	Held bool `json:"-"`
}

HeroChoice is one entry a step offers. Description and Properties are the entry's own text and data for the creator's leaf; Source is "package" for the system's entries and "campaign" for the Directors' own.

type HeroCount

type HeroCount struct {
	Step     string `json:"step"`
	Property string `json:"property"`
	Note     string `json:"note,omitempty"`
}

HeroCount names a step and a number property that sets how many of this step the entry chosen there allows. Note names a text property on the same entry that tells the player why.

type HeroLock

type HeroLock struct {
	Open     bool       `json:"open"`
	Until    *time.Time `json:"until,omitempty"`
	Reopened bool       `json:"reopened,omitempty"`
	Next     string     `json:"next,omitempty"`
	// NextLevel is the level that opens a shut window again; 0 when no
	// level does.
	NextLevel int `json:"nextLevel,omitempty"`
	// Ruled is false when the campaign has no rule, so the builder needs no
	// line at all.
	Ruled bool `json:"ruled"`
}

HeroLock is whether a hero's picks may change now, as the builder and the Directors' list show it. Until is set when the window closes at a known time; Next says what opens it again when it is shut.

func (HeroLock) DaysLeft

func (l HeroLock) DaysLeft(now time.Time) int

DaysLeft is the whole days until the window closes, counting a part day; 0 when it has no end.

type HeroLook

type HeroLook struct {
	Border string `json:"border"`
	Colour string `json:"colour"`
}

HeroLook is the border a card is drawn in (a key of the cardborders library) and the colour its coloured parts take (#rrggbb, lower-case).

type HeroNotHere

type HeroNotHere struct {
	Name   string `json:"name"`
	Reason string `json:"reason,omitempty"`
}

HeroNotHere names an entry a rule keeps off a player's list.

type HeroPick

type HeroPick struct {
	Name    string   `json:"name"`
	Options []string `json:"options,omitempty"`
}

HeroPick is what the creator sends for one step: the chosen entry's name and, when the entry has a list to buy from, the names bought.

type HeroPickChange

type HeroPickChange struct {
	FieldKey string
	Label    string
	From     string
	To       string
	Kind     HeroChangeKind
	// WasNames and NowNames are, for a list, the names it held before and
	// holds now, in their own spelling.
	WasNames []string
	NowNames []string
}

HeroPickChange is one field a player changed, as the Directors read it. A zero Kind reads like a pick.

type HeroPlan

type HeroPlan struct {
	SystemID   string     `json:"systemId,omitempty"`
	SystemName string     `json:"systemName"`
	Steps      []HeroStep `json:"steps"`
	// About is the creator's optional "About your hero" step, set only for
	// the new-hero creator: the hero's own words, never a pick.
	About []HeroAboutField `json:"about,omitempty"`
	// Practice marks the plan a practice hero is made from: every entry the
	// rules keep from this player is back in the lists, labelled, and no rule
	// locks or forces a step.
	Practice bool `json:"practice,omitempty"`
	// Tryout marks the plan a look-around visitor builds from: only what a
	// public reader may read, no rules, no reasons, nothing kept to a player.
	Tryout bool `json:"tryout,omitempty"`
}

HeroPlan is every step for one campaign, in the order the system declares its character fields.

type HeroPlanner

type HeroPlanner interface {
	HeroPlan(ctx context.Context, campaignID, userID string, director bool) (*HeroPlan, error)
}

HeroPlanner supplies a campaign's creator steps. director says whether the viewer may see entries the Directors kept from players; userID lets a player see the entries kept to a character they play.

type HeroReleaser

type HeroReleaser interface {
	ReleaseOne(ctx context.Context, campaignID, entityID, userID string) (bool, error)
}

HeroReleaser lets a hero go back to "Free to pick" for one page, the way a leaver's heroes do. Wired at the composition root from the entity repository, which owns that SQL.

type HeroRequest

type HeroRequest struct {
	Name  string              `json:"name"`
	Picks map[string]HeroPick `json:"picks"`
	// About is the "About your hero" step's boxes, by field key.
	About map[string]string `json:"about,omitempty"`
}

HeroRequest is the creator's finished hero.

type HeroRequestView

type HeroRequestView struct {
	ID        int64     `json:"id"`
	EntryName string    `json:"entryName"`
	EntityID  string    `json:"entityId,omitempty"`
	Message   string    `json:"message,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
}

HeroRequestView is a pick waiting on a Director, or a Director's note asking for another.

type HeroRules

type HeroRules interface {
	// RequestChoice records a pick of an ask-first entry as a request.
	RequestChoice(ctx context.Context, in HeroAsk) (*HeroAskOutcome, error)
	// Breaks lists the rules a hero already breaks, never changing it.
	Breaks(ctx context.Context, campaignID string, e *Entity) ([]HeroBreak, error)
	// Waiting lists the picks the hero's player has waiting on a Director.
	Waiting(ctx context.Context, campaignID string, e *Entity) ([]HeroWaitingPick, error)
}

HeroRules is the rules the plugin cannot read itself.

type HeroStep

type HeroStep struct {
	FieldKey string       `json:"fieldKey"`
	Label    string       `json:"label"`
	Choices  []HeroChoice `json:"choices"`
	// CanMake: a Director let this player write their own entry here.
	CanMake bool `json:"canMake,omitempty"`
	// Rules says what the hero-choice rules did to the step for this player;
	// nil when none applies.
	Rules *HeroStepRules `json:"rules,omitempty"`
	// Held is what the rules took off the list, kept server-side so a hero
	// that holds one stays editable. Never served.
	Held []HeroChoice `json:"-"`
	// Needed: the system's rules expect this pick. The step reads as not
	// optional, but only a Director's rule makes the server refuse a hero
	// without it.
	Needed bool `json:"needed,omitempty"`
	// Parent is the field key of the step this step's entries live inside.
	Parent string `json:"parent,omitempty"`
	// CountFrom says how many of this step the chosen parent entries allow.
	CountFrom []HeroCount `json:"countFrom,omitempty"`
	// Multi: the step takes up to its allowance of picks, stored in the one
	// field joined with heroMultiSeparator.
	Multi bool `json:"multi,omitempty"`
}

HeroStep is one question: a character field and the entries it offers.

type HeroStepRules

type HeroStepRules struct {
	// Limited: a rule applies to this player here, so a typed value must be
	// on the list too.
	Limited bool `json:"limited"`
	// Required: the list is a short list the step must be chosen from.
	Required bool `json:"required,omitempty"`
	// Prefilled is the one entry a required list is left with: filled in and
	// locked.
	Prefilled    string           `json:"prefilled,omitempty"`
	NotHereCount int              `json:"notHereCount,omitempty"`
	NotHere      []HeroNotHere    `json:"notHere,omitempty"`
	Waiting      *HeroRequestView `json:"waiting,omitempty"`
	Suggested    *HeroRequestView `json:"suggested,omitempty"`
}

HeroStepRules is what the rules did to one step for this player.

type HeroTerm

type HeroTerm struct {
	Name     string `json:"name"`
	Category string `json:"category"`
	Text     string `json:"text"`
}

HeroTerm is one rules word: its printed name, the kind of word it is and a plain-text meaning. The text is never HTML.

type HeroTerms

type HeroTerms struct {
	Terms   map[string]HeroTerm `json:"terms"`
	Present bool                `json:"-"`
}

HeroTerms is the answer to a terms request. Terms is keyed by the word as written in {@category term|label} markup, lowercased with whitespace runs turned into "-"; the builder normalises the markup it meets the same way. Present is false when the system has no glossary, which leaves the URL off the mount.

type HeroTermsReader

type HeroTermsReader interface {
	HeroTerms(ctx context.Context, campaignID string) (*HeroTerms, error)
}

HeroTermsReader supplies a campaign's rules words.

type HeroWaitingPick

type HeroWaitingPick struct {
	ID        int64  `json:"id"`
	FieldKey  string `json:"fieldKey"`
	EntryName string `json:"entryName"`
}

HeroWaitingPick is one blank on a hero that waits for a Director.

type LayoutPreset

type LayoutPreset struct {
	ID          int       `json:"id"`
	CampaignID  string    `json:"campaign_id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	LayoutJSON  string    `json:"layout_json"` // Serialized EntityTypeLayout JSON.
	Icon        string    `json:"icon"`
	SortOrder   int       `json:"sort_order"`
	IsBuiltin   bool      `json:"is_builtin"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

LayoutPreset is a reusable page layout configuration that can be applied to any entity type. Presets are campaign-scoped and optionally built-in (seeded on campaign creation, cannot be edited or deleted).

type LayoutPresetHandler

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

LayoutPresetHandler handles HTTP requests for layout presets.

func NewLayoutPresetHandler

func NewLayoutPresetHandler(service LayoutPresetService) *LayoutPresetHandler

NewLayoutPresetHandler creates a new layout preset handler.

func (*LayoutPresetHandler) CreateAPI

func (h *LayoutPresetHandler) CreateAPI(c *echo.Context) error

CreateAPI creates a new layout preset. POST /campaigns/:id/layout-presets

func (*LayoutPresetHandler) DeleteAPI

func (h *LayoutPresetHandler) DeleteAPI(c *echo.Context) error

DeleteAPI deletes a layout preset. DELETE /campaigns/:id/layout-presets/:pid

func (*LayoutPresetHandler) GetAPI

func (h *LayoutPresetHandler) GetAPI(c *echo.Context) error

GetAPI returns a single layout preset by ID. GET /campaigns/:id/layout-presets/:pid

func (*LayoutPresetHandler) ListAPI

func (h *LayoutPresetHandler) ListAPI(c *echo.Context) error

ListAPI returns layout presets for a campaign as JSON. GET /campaigns/:id/layout-presets

func (*LayoutPresetHandler) UpdateAPI

func (h *LayoutPresetHandler) UpdateAPI(c *echo.Context) error

UpdateAPI updates an existing layout preset. PUT /campaigns/:id/layout-presets/:pid

type LayoutPresetRepository

type LayoutPresetRepository interface {
	Create(ctx context.Context, p *LayoutPreset) error
	FindByID(ctx context.Context, id int) (*LayoutPreset, error)
	ListForCampaign(ctx context.Context, campaignID string) ([]LayoutPreset, error)
	Update(ctx context.Context, p *LayoutPreset) error
	Delete(ctx context.Context, id int) error
}

LayoutPresetRepository defines data access for layout presets.

func NewLayoutPresetRepository

func NewLayoutPresetRepository(db *sql.DB) LayoutPresetRepository

NewLayoutPresetRepository creates a new layout preset repository.

type LayoutPresetService

type LayoutPresetService interface {
	Create(ctx context.Context, campaignID string, input CreateLayoutPresetInput) (*LayoutPreset, error)
	GetByID(ctx context.Context, id int) (*LayoutPreset, error)
	ListForCampaign(ctx context.Context, campaignID string) ([]LayoutPreset, error)
	Update(ctx context.Context, id int, input UpdateLayoutPresetInput) (*LayoutPreset, error)
	Delete(ctx context.Context, id int) error
	SeedDefaults(ctx context.Context, campaignID string) error
}

LayoutPresetService handles business logic for layout presets.

func NewLayoutPresetService

func NewLayoutPresetService(repo LayoutPresetRepository) LayoutPresetService

NewLayoutPresetService creates a new layout preset service.

type ListOptions

type ListOptions struct {
	Page     int
	PerPage  int
	Sort     string   // "name" (default), "updated", "created"
	TagSlugs []string // Filter by tag slugs (AND logic — entity must have all listed tags).

	// PrivateOnly keeps only entities flagged is_private, so a caller that
	// wants the hidden ones (the DM Screen's reveal list) is not limited to
	// whatever happens to sit in the newest page of a mixed listing.
	PrivateOnly bool

	// ShopGoods says which pages a listing or search returns. The zero value
	// leaves shop goods out, so a caller that has not thought about them
	// never shows one; only the Director's Shop goods view and export ask
	// for them.
	ShopGoods ShopGoodsMode

	// Query is the All Pages search box's text. List ignores it; the index
	// handler sends a query of two or more characters to Search instead and
	// echoes it back so the box and the page links keep it.
	Query string

	// SearchScope narrows Search to one of the Search page's two groups:
	// SearchScopeNamed (the words are in the name, another name or the
	// descriptor) or SearchScopeMention (only the page's text has them).
	// Empty is the whole answer, which quick search and the pickers use.
	SearchScope string
}

ListOptions holds pagination and sorting parameters for list queries.

func DefaultListOptions

func DefaultListOptions() ListOptions

DefaultListOptions returns sensible defaults for pagination.

func (ListOptions) Offset

func (o ListOptions) Offset() int

Offset returns the SQL OFFSET value for the current page.

func (ListOptions) OrderByClause

func (o ListOptions) OrderByClause() string

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

Every branch ends with `e.id ASC`. None of the leading sort columns is unique, so without a tiebreaker MariaDB's plan can disagree between statements of one LIMIT/OFFSET walk about which tied rows land in a given window, causing pages to skip or repeat rows. The primary key makes each sort a total order, which OFFSET paging requires.

type LongTermTrash

type LongTermTrash interface {
	// KeptPages returns the Trash item roots to keep. An error keeps every
	// page this round: nothing is removed on a guess.
	KeptPages(ctx context.Context) ([]string, error)
	// PageRestored tells the keeper a page came back out of the Trash by any
	// route, so it stops keeping it: a later delete must wait out its Trash
	// days like any other page. It must not fail the restore.
	PageRestored(ctx context.Context, campaignID, entityID string)
}

LongTermTrash names the removed pages to keep after their Trash days are over: the pages a player removed, which the owner can still bring back from "What players changed". Such a page leaves the Trash list but stays whole, links and pictures included, until the keeper lets it go.

type MapCampaignVerifier

type MapCampaignVerifier interface {
	MapExistsInCampaign(ctx context.Context, mapID, campaignID string) (bool, error)
}

MapCampaignVerifier confirms a map exists and belongs to a given campaign. Implemented by an adapter over maps.MapsService — kept as a minimal interface here so the entities package doesn't import the maps plugin (which would create a cycle: maps → entities for blocks, entities → maps for the verifier).

Used by AssignMap to enforce same-campaign integrity *before* the FK constraint kicks in. The FK alone would catch "map doesn't exist" but not "map exists in a different campaign" — that would silently succeed and leak cross-campaign data.

type MapSearcher

type MapSearcher interface {
	SearchMaps(ctx context.Context, campaignID, query string) ([]map[string]string, error)
}

MapSearcher provides map search results for the quick search popup. Implemented by the maps plugin and injected via SetMapSearcher.

type MediaCampaignVerifier

type MediaCampaignVerifier interface {
	MediaExistsInCampaign(ctx context.Context, mediaID, campaignID string) (bool, error)
}

MediaCampaignVerifier confirms a media file exists and belongs to a given campaign. Implemented by an adapter over media.MediaService — kept as a minimal interface here so the entities package doesn't import the media plugin (same cycle-avoidance reasoning as MapCampaignVerifier).

Used by UpdateImage/UpdateCoverImage to enforce same-campaign integrity before storing a media ID on the entity: without it, any Scribe or Owner who learns a media UUID from another campaign could bind it as their own entity's image, and the show page would then mint a valid signed URL for a file they were never authorized to see.

type MemberLister

type MemberLister interface {
	ListMembers(ctx context.Context, campaignID string) ([]campaigns.CampaignMember, error)
}

MemberLister retrieves campaign members for the permissions UI. Satisfied by campaigns.CampaignService.

type MentionGraph

type MentionGraph struct {
	Links []MentionLink
	Pages map[string]MentionPage
}

MentionGraph is the @mention links of a campaign that one viewer may know of, with the pages at their ends. Both ends of every link are in Pages.

type MentionLink struct {
	SourceEntityID string `json:"sourceEntityId"`
	TargetEntityID string `json:"targetEntityId"`
}

MentionLink represents a directional @mention reference from one entity to another, extracted from entry_html. Used by the relations graph to show mention-based edges alongside explicit relations.

type MentionPage

type MentionPage struct {
	ID        string
	Name      string
	Slug      string
	TypeName  string
	TypeIcon  string
	TypeColor string
}

MentionPage is what a graph draws for the page at either end of a mention link: its name, its address and its category's name, icon and colour.

type MentionSource

type MentionSource struct {
	ID        string
	EntryHTML string
}

MentionSource is a page whose text names other pages, with that text.

type MergeResult

type MergeResult struct {
	Moved         int    // entities reassigned from the generic onto the system type
	RemovedTypeID int    // the deleted generic type's id (0 if nothing removed)
	TargetTypeID  int    // the surviving system character type's id (0 if no merge)
	TargetName    string // the surviving type's display name (e.g. "Heroes")
	NoOp          bool   // true when there was nothing to reconcile
}

MergeResult reports the outcome of MergeDuplicatePlayerCharacterType.

type NPCSectionProvider

type NPCSectionProvider interface {
	NPCSection(ctx context.Context, cc *campaigns.CampaignContext, userID, csrfToken, featureTag string) templ.Component
}

NPCSectionProvider renders the Characters page's NPCs/Monsters section (featured portrait row + revealed list + reveal toggles). It is implemented by the npcs plugin and injected via SetNPCSectionProvider, so the core entities plugin never imports the addon. nil/absent → no NPC section.

type NewPageDraft

type NewPageDraft struct {
	TypeLabel  string
	TemplateID int
	// IsPrivate is the state the page will be saved in, resolved against the
	// campaign's default and the maker's role, never the form's own guess.
	IsPrivate bool
	// Sheet draws the form for the small sheet over the current screen.
	Sheet bool
	// Return is a same-site path the form was opened from, or "".
	Return string
}

NewPageDraft is what the new page form keeps besides its name, parent and category: the choices a refused save must not forget, and the place Cancel returns to.

type NoopEntityEventPublisher

type NoopEntityEventPublisher struct{}

NoopEntityEventPublisher is a no-op implementation for tests.

func (NoopEntityEventPublisher) PublishEntityEvent

func (NoopEntityEventPublisher) PublishEntityEvent(string, string, string, *Entity)

func (NoopEntityEventPublisher) PublishEntityTypeEvent

func (NoopEntityEventPublisher) PublishEntityTypeEvent(string, string, *EntityType)

type NoopSidebarAutoAdder

type NoopSidebarAutoAdder struct{}

NoopSidebarAutoAdder is a no-op implementation for tests.

func (NoopSidebarAutoAdder) AddEntityTypeToSidebar

func (NoopSidebarAutoAdder) AddEntityTypeToSidebar(context.Context, string, int) error

type NoteCounter

type NoteCounter interface {
	// CountByEntities returns the number of notes on each page, any
	// audience. Pages with none are absent from the map.
	CountByEntities(ctx context.Context, campaignID string, entityIDs []string) (map[string]int, error)
}

NoteCounter counts Player Notes per page. The notes live in another plugin; entities sees only this seam, so it never reads that plugin's tables. Only counts cross it, never note content or audiences: a count tells the owner what a delete costs without opening notes they may not be meant to read.

type Option

type Option struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

Option is a label+value pair for select-type config fields.

type OwnerFieldKind

type OwnerFieldKind string

OwnerFieldKind is how a claimed owner may write a field of their hero, as the door judges it, for briefs and editors that offer only what it takes.

const (
	OwnerFieldText   OwnerFieldKind = "text"   // short free text
	OwnerFieldChoice OwnerFieldKind = "choice" // a name from a builder step's list
	OwnerFieldStory  OwnerFieldKind = "story"  // the player's long text
	OwnerFieldList   OwnerFieldKind = "list"   // a JSON list of short names
)

The kinds a claimed owner's field can be.

func OwnerFieldKindOf

func OwnerFieldKindOf(key string, typeFields []FieldDefinition, plan *HeroPlan) (kind OwnerFieldKind, ownChoice bool)

OwnerFieldKindOf says how a claimed owner may write key, or "" when they may not. typeFields are the hero's category's fields with any the page added; a GM-only field or one the category lacks is never theirs. A step whose key is also an identity key takes its list's names or the player's own (ownChoice).

type PCSetupSnapshot

type PCSetupSnapshot struct {
	// DefaultCharsParentID is the default top-level "Characters" category id, if present.
	DefaultCharsParentID *int
	// GenericPCTypes are generic premade player_character types (preset_category
	// "player_character" or slug "player-character"). Normally 0 or 1; >1 = ambiguous.
	GenericPCTypes []EntityType
	// SystemCharTypes are a game system's own claimable character types
	// (e.g. drawsteel-character). Normally 0 or 1; >1 = ambiguous.
	SystemCharTypes []EntityType
	// GenericPCCount / SystemCharCount are total entity counts across those types.
	GenericPCCount  int
	SystemCharCount int
	// SubCategoryCount is the number of sub-categories nested under "Characters".
	SubCategoryCount int
}

PCSetupSnapshot is a read-only summary of a campaign's player-character category state, assembled by PlayerCharacterSetupSnapshot for the player-character extension settings page. Owner-facing — entity counts include all entities regardless of visibility.

type PageCard

type PageCard struct {
	ID        string
	Name      string
	ImagePath string
	TypeName  string
	TypeSlug  string
}

PageCard is the little another feature shows for a page it links to: its name, picture and category.

type PageCards

type PageCards interface {
	// InCampaign returns the live pages among ids that belong to campaignID;
	// a missing, deleted or foreign id is simply absent.
	InCampaign(ctx context.Context, campaignID string, ids []string) (map[string]PageCard, error)
}

PageCards reads many pages of one campaign in a single query, for features that show lots of linked pages at once (notice boards). It only names pages; whether a viewer may see them is still FilterViewableEntityIDs' decision.

func NewPageCards

func NewPageCards(db *sql.DB) PageCards

NewPageCards builds the reader.

type PageChangeObserver

type PageChangeObserver interface {
	TextChanged(ctx context.Context, before, after *Entity, userID string) error
	PageTrashed(ctx context.Context, e *Entity, userID string) error
}

PageChangeObserver is told after a page's title or text was saved and after a page went to the Trash. The field change observer may also implement it; nothing else is needed to wire it. userID is the person whose request made the change, "" when none applies. Errors are logged and never fail the change.

type PageEra

type PageEra struct {
	ID     int
	Name   string
	Color  string
	Color2 string
	// Span says when it runs, in the calendar's own years.
	Span string
	// Hidden is set while the era is still hidden from players.
	Hidden bool
	// Weight is its share of the ribbon (square-root lengths, with a floor).
	Weight float64
	// Here is where "you are here" sits along the current era (0 to 1), or
	// -1 for every other era.
	Here float64
}

PageEra is one era of the main calendar as the Eras panel draws it.

type PageEraSet

type PageEraSet struct {
	CalendarName string
	Eras         []PageEra
	// CurrentID is the era the calendar's date is in; 0 when none.
	CurrentID int
}

PageEraSet is the main calendar's eras for one viewer, oldest first.

func (*PageEraSet) Era

func (s *PageEraSet) Era(id int) *PageEra

Era returns the era with id, or nil.

type PageEraVersion

type PageEraVersion struct {
	Name       *string
	ImagePath  *string
	Entry      *string
	EntryHTML  *string
	EntryRev   int
	FieldsData map[string]any
	UpdatedBy  string
	UpdatedAt  time.Time
}

PageEraVersion is a page's version for one era: a nil field is the usual page's, and FieldsData holds only the values that differ from it.

type PageExtrasPlan

type PageExtrasPlan struct {
	SystemPanels   bool // game-system panels under the title (NPC pages)
	CharacterItems bool // the items-and-money panel after the layout
}

PageExtrasPlan says which panels a type's pages showed outside its layout, so placing them as blocks keeps those pages as they were.

type PageLayout

type PageLayout struct {
	Key    string           `json:"key"`
	Name   string           `json:"name"`
	Layout EntityTypeLayout `json:"layout"`
}

PageLayout is one of a category's named layouts besides the main one.

type PageLayoutChoice

type PageLayoutChoice struct {
	Key  string
	Name string
}

PageLayoutChoice is one layout a page could wear.

type PageLayoutInfo

type PageLayoutInfo struct {
	Key     string
	Name    string
	Choices []PageLayoutChoice
}

PageLayoutInfo is what a page shows about the layout it wears: which one, and the others the Director could pick.

type PageLayoutRepository

type PageLayoutRepository interface {
	// TypeLayouts returns a category's document; a category with none has
	// an empty one.
	TypeLayouts(ctx context.Context, typeID int) (PageLayouts, error)
	// CampaignTypeLayouts returns every category's document in a campaign
	// that has one, by category id.
	CampaignTypeLayouts(ctx context.Context, campaignID string) (map[int]PageLayouts, error)
	// SaveTypeLayouts stores a category's document; an empty one removes it.
	SaveTypeLayouts(ctx context.Context, campaignID string, typeID int, p PageLayouts) error
	// PageKey returns the key a page chose, or "" when it chose none.
	PageKey(ctx context.Context, entityID string) (string, error)
	// CampaignPageKeys returns every page's choice in a campaign, by page id.
	CampaignPageKeys(ctx context.Context, campaignID string) (map[string]string, error)
	// SetPageKey stores a page's choice; "" removes it.
	SetPageKey(ctx context.Context, campaignID, entityID, key string) error
}

PageLayoutRepository owns entity_type_page_layouts (a category's named layouts, one JSON document each) and entity_page_layouts (the layout a page wears, by key).

func NewPageLayoutRepository

func NewPageLayoutRepository(db *sql.DB) PageLayoutRepository

NewPageLayoutRepository creates the MariaDB repository for named layouts.

type PageLayoutService

type PageLayoutService interface {
	// ForType returns a category's named layouts.
	ForType(ctx context.Context, et *EntityType) PageLayouts
	// ForCampaign returns every category's named layouts that has any.
	ForCampaign(ctx context.Context, campaignID string) map[int]PageLayouts
	// PageKeys returns every page's own choice in a campaign, by page id.
	PageKeys(ctx context.Context, campaignID string) map[string]string
	// Worn returns the category's named layouts and the key of the one the
	// page wears.
	Worn(ctx context.Context, e *Entity, et *EntityType) (PageLayouts, string)
	// SetPageLayout makes a page wear the layout key names; the main key
	// clears the page's own choice so it follows the category again.
	SetPageLayout(ctx context.Context, e *Entity, et *EntityType, key string) error
	// SaveTypeLayouts stores a category's named layouts. The caller has
	// checked them, blocks included.
	SaveTypeLayouts(ctx context.Context, campaignID string, typeID int, p PageLayouts) error
	// RestorePageKey stores a page's own choice as a backup recorded it,
	// "main" included, without SetPageLayout's reading of who owns the page:
	// a restored page gets its owner back only later.
	RestorePageKey(ctx context.Context, e *Entity, et *EntityType, key string) error
}

PageLayoutService reads and writes a category's named layouts and the layout each page wears. Reads degrade: when the tables are unreadable a category reads as having only its main layout, so pages still draw.

func NewPageLayoutService

func NewPageLayoutService(repo PageLayoutRepository) PageLayoutService

NewPageLayoutService creates the named layouts service.

type PageLayouts

type PageLayouts struct {
	// MainName is what the main layout is called; empty reads as the
	// category's singular name.
	MainName string `json:"mainName,omitempty"`
	// Claimed is the key of the layout a player's character wears when the
	// Director has not picked one; empty keeps the main layout.
	Claimed string       `json:"claimed,omitempty"`
	Extra   []PageLayout `json:"extra,omitempty"`
}

PageLayouts is everything about a category's layouts that is not the main layout itself.

func (PageLayouts) Check

func (p PageLayouts) Check() error

Check validates the names, keys and choices; the blocks of each layout are checked by the caller with ValidateLayout, as a main layout's are.

func (PageLayouts) Empty

func (p PageLayouts) Empty() bool

Empty reports whether the category has nothing beyond its main layout.

func (PageLayouts) Find

func (p PageLayouts) Find(key string) (PageLayout, bool)

Find returns the named layout with key, if the category has one.

func (PageLayouts) KeyByName

func (p PageLayouts) KeyByName(et *EntityType, name string) (string, bool)

KeyByName finds a layout by its name, ignoring case, so the AI and the Director can name a layout the way it reads. The main layout answers to its name and to "main".

func (PageLayouts) Label

func (p PageLayouts) Label(et *EntityType, key string) string

Label is the name of the layout key names, the main one for any key the category does not have.

func (PageLayouts) LayoutFor

func (p PageLayouts) LayoutFor(et *EntityType, key string) EntityTypeLayout

LayoutFor returns the blocks of the layout key names, the main layout for the main key or any key the category does not have.

func (PageLayouts) MainLabel

func (p PageLayouts) MainLabel(et *EntityType) string

MainLabel is the main layout's name as people read it.

func (PageLayouts) WornKey

func (p PageLayouts) WornKey(e *Entity, chosen string) string

WornKey is the key of the layout a page wears: its own choice when that still names one of the category's layouts, else the layout a player's character starts on, else the main one.

type PageMoon

type PageMoon struct {
	Name         string
	CalendarID   string
	CalendarName string
	// Phase is the moon's named phase on the calendar's current date.
	Phase string
}

PageMoon is one moon whose lore page this is.

type PageMoons

type PageMoons interface {
	MoonsForPage(ctx context.Context, campaignID, entityID string, v permissions.Viewer) ([]PageMoon, error)
}

PageMoons lists the moons, on calendars the viewer may open, whose lore page is the given page. Wired in internal/app.

type PagePanel

type PagePanel struct {
	// Addon is the addon slug that must be enabled for the campaign.
	Addon string
	// URL builds the fragment route for an entity.
	URL func(campaignID, entityID string) string
}

PagePanel describes one such panel.

type PageParts

type PageParts interface {
	// Tags answers {"all":[...],"mine":[...]}: every tag the viewer may see
	// and this page's own.
	Tags(ctx context.Context, cc *campaigns.CampaignContext, entityID string) (json.RawMessage, error)
	// Relations answers {"relations":[...],"types":[...]}; types is left out
	// unless withTypes, which only someone who can add a relation needs.
	Relations(ctx context.Context, cc *campaigns.CampaignContext, entityID, userID string, withTypes bool) (json.RawMessage, error)
}

PageParts supplies the first content of the page's tags and connections, so the page can carry it instead of leaving two empty boxes to fetch after it shows. It is an interface so this plugin never reaches into the tags or relations repositories. Each answer is the JSON the widget would otherwise have fetched, so the widget takes it over unchanged.

type PagePinHandler

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

PagePinHandler serves the Pinned Pages widget and the Director's pin beside a page's name. It works out who is looking and leaves the rest to the service.

func NewPagePinHandler

func NewPagePinHandler(svc PagePinService) *PagePinHandler

NewPagePinHandler creates the pins handler.

func (*PagePinHandler) PinButton

func (h *PagePinHandler) PinButton(c *echo.Context) error

PinButton draws the Director's pin beside a page's name in its current state. Without the Director's pins table there is no pin to offer, and the empty answer leaves the page as it is.

func (*PagePinHandler) SetPin

func (h *PagePinHandler) SetPin(c *echo.Context) error

SetPin pins the page for everyone (on=1) or takes it off, and answers with the pin in its new state.

func (*PagePinHandler) UnpinOwn

func (h *PagePinHandler) UnpinOwn(c *echo.Context) error

UnpinOwn takes a page off the viewer's own pins from the widget's ×.

func (*PagePinHandler) UnpinShared

func (h *PagePinHandler) UnpinShared(c *echo.Context) error

UnpinShared takes a page off everyone's pins from the widget's ×.

func (*PagePinHandler) Widget

func (h *PagePinHandler) Widget(c *echo.Context) error

Widget draws the Pinned Pages widget for the viewer.

type PagePinRepository

type PagePinRepository interface {
	// Shared returns the pages pinned for everyone, in the order pinned.
	Shared(ctx context.Context, campaignID string) ([]PinnedPage, error)
	// IsShared reports whether a page is pinned for everyone.
	IsShared(ctx context.Context, campaignID, entityID string) (bool, error)
	// CountShared counts the live pages pinned for everyone.
	CountShared(ctx context.Context, campaignID string) (int, error)
	// Share pins a page for everyone; pinning it again changes nothing.
	Share(ctx context.Context, campaignID, entityID, userID string) error
	// Unshare takes a page off everyone's pins.
	Unshare(ctx context.Context, campaignID, entityID string) error
	// Own returns the pages a member starred in a campaign, newest first.
	Own(ctx context.Context, campaignID, userID string) ([]PinnedPage, error)
	// RemoveOwn takes a page off a member's own pins (their star).
	RemoveOwn(ctx context.Context, campaignID, entityID, userID string) error
}

PagePinRepository reads and writes the Director's pins, and reads the member's own pins from their stars. Every read joins the live page, so a page in the Trash drops off and comes back if it is restored.

func NewPagePinRepository

func NewPagePinRepository(db *sql.DB) PagePinRepository

NewPagePinRepository creates the pins repository.

type PagePinService

type PagePinService interface {
	// ForViewer returns the widget's pages for one viewer.
	ForViewer(ctx context.Context, v PinViewer) (PinnedPages, error)
	// SharedAvailable is false while the Director's pins can't be stored.
	SharedAvailable() bool
	// IsShared reports whether a page is pinned for everyone.
	IsShared(ctx context.Context, campaignID, entityID string) (bool, error)
	// SetShared pins a page for everyone, or takes it off. Director only.
	SetShared(ctx context.Context, v PinViewer, entityID string, on bool) error
	// RemoveOwn takes a page off the viewer's own pins.
	RemoveOwn(ctx context.Context, v PinViewer, entityID string) error
}

PagePinService decides what the Pinned Pages widget shows and who may change it. A page a viewer can't open is left out for them without a trace.

func NewPagePinService

func NewPagePinService(repo PagePinRepository, pages pinVisibility, sharedAvailable bool) PagePinService

NewPagePinService creates the pins service. sharedAvailable is false when the page_pins table did not migrate: members' own pins still show, and the Director's are left out.

type PageSafetyHandler

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

PageSafetyHandler serves a page's History panel and the campaign Trash. History is for owners and scribes (the people who can edit pages); the Trash is the owner's, like deleting.

func NewPageSafetyHandler

func NewPageSafetyHandler(svc PageSafetyService, entities EntityService, members MemberLister) *PageSafetyHandler

NewPageSafetyHandler creates the History/Trash handler. members may be nil; history then shows names without roles.

func (*PageSafetyHandler) History

func (h *PageSafetyHandler) History(c *echo.Context) error

History renders the History panel (GET .../entities/:eid/history?v=<id>). v picks the version whose changes are shown; the newest by default.

func (*PageSafetyHandler) RestoreFromTrash

func (h *PageSafetyHandler) RestoreFromTrash(c *echo.Context) error

RestoreFromTrash brings a page back (POST /campaigns/:id/trash/:eid/restore). The Undo toast calls it with fetch and gets JSON; the Trash page's button is an htmx form and gets the refreshed Trash.

func (*PageSafetyHandler) RestoreOtherFromTrash

func (h *PageSafetyHandler) RestoreOtherFromTrash(c *echo.Context) error

RestoreOtherFromTrash brings back a picture, game night or map (POST /campaigns/:id/trash/:kind/:tid/restore). The Undo toast gets JSON with the link; the Trash page's button opens the restored thing.

func (*PageSafetyHandler) RestoreVersion

func (h *PageSafetyHandler) RestoreVersion(c *echo.Context) error

RestoreVersion puts an old version back and reloads the page (POST .../entities/:eid/history/:vid/restore).

func (*PageSafetyHandler) SetAuditService

func (h *PageSafetyHandler) SetAuditService(svc audit.AuditService)

SetAuditService records each restore from the Trash in the campaign's activity log. nil leaves restores unrecorded.

func (*PageSafetyHandler) Trash

func (h *PageSafetyHandler) Trash(c *echo.Context) error

Trash renders the campaign's Trash under Campaign settings (GET /campaigns/:id/trash).

type PageSafetyRepository

type PageSafetyRepository interface {
	// LatestVersion returns a page's newest version, or nil when it has none.
	LatestVersion(ctx context.Context, entityID string) (*EntityVersion, error)
	InsertVersion(ctx context.Context, v *EntityVersion) error
	// ReplaceVersionContent overwrites a version's title, text and
	// updated_at; used when a save joins the author's open history row.
	ReplaceVersionContent(ctx context.Context, v *EntityVersion) error
	// ListVersions returns a page's versions newest first, with text.
	ListVersions(ctx context.Context, entityID string, limit int) ([]EntityVersion, error)
	// FindVersion returns one version of entityID; NotFound when the id
	// belongs to another page.
	FindVersion(ctx context.Context, entityID, versionID string) (*EntityVersion, error)
	PruneVersions(ctx context.Context, entityID string, keep int) error

	// EntryRev returns a live page's text revision.
	EntryRev(ctx context.Context, entityID string) (int, error)
	// SaveEntryAtRev writes the text only if the stored revision is still
	// baseRev, and returns the new revision. When someone else saved first it
	// writes nothing and returns the stored text and revision instead, read
	// together so they match (ByName is left for the caller).
	SaveEntryAtRev(ctx context.Context, entityID, entryJSON, entryHTML, searchText string, baseRev int) (newRev int, conflict *EntryConflict, err error)

	// CountTrashedByType counts a page kind's pages waiting in the Trash.
	CountTrashedByType(ctx context.Context, entityTypeID int) (int, error)

	// TrashSubtree moves a live page and its live sub-pages to the Trash as
	// one item, and returns the ids that moved, the page first.
	TrashSubtree(ctx context.Context, campaignID, rootID, userID string, at time.Time) ([]string, error)
	// TrashedPageIDs maps each Trash item's root id to the ids of every page
	// in it, the root included. With rootIDs empty it covers the whole
	// campaign Trash.
	TrashedPageIDs(ctx context.Context, campaignID string, rootIDs ...string) (map[string][]string, error)
	// ListTrash returns the campaign's Trash items, newest first.
	ListTrash(ctx context.Context, campaignID string) ([]TrashItem, error)
	// FindTrashItem returns one Trash item; NotFound when it isn't in the
	// campaign's Trash.
	FindTrashItem(ctx context.Context, campaignID, rootID string) (*TrashItem, error)
	// RestoreTrashItem brings a Trash item's pages back, and returns how many.
	RestoreTrashItem(ctx context.Context, campaignID, rootID string) (int, error)
	// PurgeTrashedBefore deletes for good the pages trashed before cutoff,
	// except the Trash items whose root is in keep (Long-term trash).
	PurgeTrashedBefore(ctx context.Context, cutoff time.Time, keep []string) (int, error)
}

PageSafetyRepository stores what lets a world page be undone: its version history, its place in the Trash, and the text revision the editor checks so one person's save can't silently replace another's.

func NewPageSafetyRepository

func NewPageSafetyRepository(db *sql.DB) PageSafetyRepository

NewPageSafetyRepository creates the MariaDB page-safety repository.

type PageSafetyService

type PageSafetyService interface {
	// History returns a page's versions, newest first, each with how many
	// lines changed since the one before it, and the index of the version
	// picked by selectedID (the newest when empty or unknown). Only that
	// version carries a word diff: it is the only one shown, and diffing
	// every version of a long page on each open is costly.
	// History lists a page's versions. redact, when set, edits each version's
	// text before the diffs are made, so a reader never gets a part of a
	// page they could not see on the page itself.
	History(ctx context.Context, entityID, selectedID string, redact func(*EntityVersion)) ([]VersionView, int, error)
	// RestoreVersion puts a version's title and text back on the page,
	// saved as a new version so the restore can be undone too.
	RestoreVersion(ctx context.Context, entityID, versionID string) error
	// RestoreText puts a title and text kept elsewhere back on the page, as
	// RestoreVersion does for a saved version: the result is a new "restore"
	// version, so the undo can be undone too. A nil entry clears the text.
	RestoreText(ctx context.Context, entityID, name string, entry, entryHTML *string) error

	ListTrash(ctx context.Context, campaignID string) ([]TrashItem, error)
	// RestoreFromTrash brings a page and its sub-pages back.
	RestoreFromTrash(ctx context.Context, campaignID, entityID string) (*TrashItem, error)
	// TrashedNoteCount is how many Player Notes sit on a Trash item's pages;
	// 0 when notes aren't wired or the count fails, since the number is
	// only a courtesy and must not block a delete.
	TrashedNoteCount(ctx context.Context, campaignID, rootID string) int
	// SetNoteCounter wires the Player Notes count; nil leaves counts off.
	SetNoteCounter(nc NoteCounter)
	RetentionDays(ctx context.Context) int
	// AddTrashKind lets another plugin's things share the Trash; see
	// trash_kinds.go.
	AddTrashKind(k TrashKind)
	// SetLongTermTrash wires the keeper of removed pages past their Trash
	// days; see LongTermTrash.
	SetLongTermTrash(k LongTermTrash)
	// ListOtherTrash lists the registered kinds' trashed items, newest first.
	ListOtherTrash(ctx context.Context, campaignID string) []TrashedThing
	// RestoreOther brings back one item of a registered kind and returns
	// what it was and the link to it.
	RestoreOther(ctx context.Context, campaignID, kind, id string) (TrashedThing, string, error)
	// StartPurger deletes for good, hourly, pages and registered kinds'
	// items that have waited out the retention. It returns when ctx ends.
	StartPurger(ctx context.Context)
}

PageSafetyService serves the History panel and the Trash page.

func NewPageSafetyService

func NewPageSafetyService(repo PageSafetyRepository, entities EntityRepository, svc EntityService, retention TrashRetention) PageSafetyService

NewPageSafetyService builds the History/Trash service. svc must be the entity service SetPageSafety was called on, so restores are versioned and broadcast like any other save.

type PageSinceRef

type PageSinceRef struct {
	ID        string
	Name      string
	CreatedAt time.Time
}

PageSinceRef is one new page.

type PagesSince

type PagesSince struct {
	// Count is every such page; Newest names up to the asked-for few, newest
	// first.
	Count  int
	Newest []PageSinceRef
}

PagesSince is the pages a viewer may open that were created after a time.

type PagesSinceReader

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

PagesSinceReader reads new pages for a viewer.

func NewPagesSinceReader

func NewPagesSinceReader(db *sql.DB) *PagesSinceReader

NewPagesSinceReader creates the reader.

func (*PagesSinceReader) Since

func (r *PagesSinceReader) Since(ctx context.Context, campaignID string, since time.Time, role int, userID string, nameLimit int) (PagesSince, error)

Since counts the live, non-template pages of the campaign created after since that the viewer (role and user id, as every other entity read takes them) may open, and returns the newest nameLimit of them. It uses idx_entities_campaign_created for the campaign and time bound.

type PeekFact

type PeekFact struct {
	Label string
	Value string
}

PeekFact is one label/value row shown under the title of a peeked page.

type PeekView

type PeekView struct {
	Name     string
	Kind     string
	KindIcon string
	Private  bool
	Facts    []PeekFact
	// BodyHTML is already stripped of GM-only content for viewers who may not
	// see it and sanitized; the template renders it as-is.
	BodyHTML string
	FullURL  string
}

PeekView is everything the side panel draws. It is built only from data that has already passed the same checks as the full page, so the template never has to decide who may see what.

type Permission

type Permission string

Permission represents an access level that can be granted on an entity.

const (
	// PermView allows the subject to see the entity.
	PermView Permission = "view"
	// PermEdit allows the subject to see and modify the entity.
	PermEdit Permission = "edit"
)

type PermissionGrant

type PermissionGrant struct {
	SubjectType SubjectType `json:"subject_type"`
	SubjectID   string      `json:"subject_id"`
	Permission  Permission  `json:"permission"`
}

PermissionGrant is a single grant in a SetPermissionsInput request.

type PinViewer

type PinViewer struct {
	CampaignID string
	UserID     string
	Role       int
	Director   bool
}

PinViewer is who the Pinned Pages widget is drawn for. Role is the visibility role the viewer reads pages with; Director is true for the owner and granted co-Directors, unless they are looking as a player.

type PinnedPage

type PinnedPage struct {
	ID        string
	Name      string
	ImagePath *string
	TypeName  string
	TypeIcon  string
	TypeColor string
	PinnedAt  time.Time
}

PinnedPage is one page on the Pinned Pages widget, with what its card shows.

type PinnedPages

type PinnedPages struct {
	Shared []PinnedPage
	Own    []PinnedPage
	// MoreOwn counts the viewer's own pins past the ones drawn.
	MoreOwn int
	// SharedAvailable is false while the Director's pins table is missing,
	// so the widget doesn't offer what can't be saved.
	SharedAvailable bool
}

PinnedPages is what the widget shows one viewer: the Director's pins on top, then their own, each already narrowed to pages they can open.

func (PinnedPages) Empty

func (p PinnedPages) Empty() bool

Empty reports whether there is nothing to draw.

type Place

type Place struct {
	EntityID       string
	ParentEntityID string
	CampaignID     string
	SortOrder      int
	CreatedBy      string
	CreatedAt      time.Time
}

Place is one extra spot a page is listed in the page tree. The page keeps its single real parent (Entity.ParentID, which the breadcrumb follows); a Place only adds a second (or further) parent for the tree to show it under.

type PlaceClimate

type PlaceClimate struct {
	ID       string
	Name     string
	ParentID string
	Climate  string
}

PlaceClimate is a page with a climate of its own, for the calendar.

type PlaceGuard

type PlaceGuard interface {
	// WouldCycle reports whether making parentID the real or extra parent of
	// entityID would put entityID above itself.
	WouldCycle(ctx context.Context, campaignID, entityID, parentID string) (bool, error)
	// DropPlace removes the listing of entityID under parentID, if any.
	DropPlace(ctx context.Context, entityID, parentID string) error
}

PlaceGuard is the part of the listings the entity service needs while it moves a page for real, so a move can't build a loop through a listing or leave a listing next to the page's new real parent.

type PlaceLink struct {
	EntityID         string
	EntityName       string
	EntityTypeIcon   string
	EntityTypeName   string
	EntityTypeColor  string
	EntityIsPrivate  bool
	EntityVisibility VisibilityMode
	ParentID         string
	ParentName       string
	SortOrder        int
}

PlaceLink names both ends of a Place with what a list needs to draw them, so no caller has to fetch each page again. It is read-only data; whether a viewer may see either page is decided by PlaceService, never by the reader.

type PlaceRepository

type PlaceRepository interface {
	// Insert adds a listing. Adding one that already exists is a no-op, so a
	// double click or a replayed import never fails or duplicates.
	Insert(ctx context.Context, p *Place) error
	// Delete removes one listing; removing one that is not there is a no-op.
	Delete(ctx context.Context, entityID, parentID string) error
	// ListOf returns the live listings of one live page.
	ListOf(ctx context.Context, campaignID, entityID string) ([]PlaceLink, error)
	// ListUnder returns the live listings whose live parent is one of
	// parentIDs, for drawing those parents' branches of the tree.
	ListUnder(ctx context.Context, campaignID string, parentIDs []string) ([]PlaceLink, error)
	// ListAll returns every listing in a campaign, trashed ends included, for
	// export: a page in the Trash is exported with its listings intact.
	ListAll(ctx context.Context, campaignID string) ([]Place, error)
	// AncestorIDs returns id and every page above it, following BOTH the real
	// parent and the extra listings, so a cycle through either kind is seen.
	// Trashed pages are walked too: a cycle through a page in the Trash would
	// come back to life on Restore.
	AncestorIDs(ctx context.Context, campaignID, id string) (map[string]bool, error)
}

PlaceRepository owns the entity_places table: the extra spots a page is listed in the page tree. It knows nothing about who may see a page; reads only guarantee that both ends are live (not in the Trash) and in the named campaign, so a trashed page or parent hides its listing and Restore brings it back without touching these rows.

func NewPlaceRepository

func NewPlaceRepository(db *sql.DB) PlaceRepository

NewPlaceRepository creates the MariaDB repository for extra listings.

type PlaceService

type PlaceService interface {
	// AddPlace lists entityID under parentID. Adding an existing listing is a
	// no-op. Refuses the page itself, its own real parent, any page below it
	// (through real parents or other listings) and any other campaign's page.
	AddPlace(ctx context.Context, campaignID, entityID, parentID, userID string) error
	// RemovePlace takes one listing away. The page is never touched.
	RemovePlace(ctx context.Context, campaignID, entityID, parentID string) error
	// PlacesOf returns the extra places of one page that this viewer may see.
	PlacesOf(ctx context.Context, campaignID, entityID string, role int, userID string) ([]PlaceLink, error)
	// PlacesUnder returns the listings to draw under parentIDs for this viewer.
	PlacesUnder(ctx context.Context, campaignID string, parentIDs []string, role int, userID string) ([]PlaceLink, error)
	// ExportPlaces returns every listing in a campaign for export. No viewer
	// filtering: export is the owner's whole-campaign copy.
	ExportPlaces(ctx context.Context, campaignID string) ([]Place, error)

	// PlaceGuard is how page moves keep listings honest.
	PlaceGuard
}

PlaceService lists one page in more than one place in the page tree.

A listing changes only where the tree shows a page. Who may see the page stays the page's own setting: every read here asks the one visibility rule about the page AND about the parent it is listed under, so a viewer who cannot see the page never sees its extra row, and one who can see the page but not the extra parent simply never reaches that branch.

Who may add or remove a listing (anyone who can edit the page) is decided by the handler with CheckEntityAccess, like every other page write.

func NewPlaceService

func NewPlaceService(entities placeEntities, places PlaceRepository) PlaceService

NewPlaceService creates the listings service.

type PlacementOption

type PlacementOption struct {
	ID         int    `json:"id"`
	Name       string `json:"name"`
	NamePlural string `json:"namePlural"`
	// Suggested marks the category the block is made for.
	Suggested bool `json:"suggested"`
	// Placed is true when every layout of the category already holds the block.
	Placed bool `json:"placed"`
}

PlacementOption is one category the "Put on a page" chooser offers.

type PopupConfig

type PopupConfig struct {
	ShowImage      bool `json:"showImage"`
	ShowAttributes bool `json:"showAttributes"`
	ShowEntry      bool `json:"showEntry"`
}

PopupConfig controls what appears in the entity hover preview tooltip. When nil, all available sections are shown (image, attributes, entry excerpt).

func DefaultPopupConfig

func DefaultPopupConfig() *PopupConfig

DefaultPopupConfig returns the default popup configuration showing everything.

type PracticeActor

type PracticeActor struct {
	UserID   string
	Director bool
}

PracticeActor is who is acting on a practice hero. Director is the owner or a co-Director (campaigns.CampaignContext.CanAuthorDmOnly), decided by the caller so the service never sees a request type.

type PracticeCharacterTypes

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

PracticeCharacterTypes names the campaign's character page types. Satisfied by CharacterListReader.

type PracticeCopy

type PracticeCopy struct {
	Hero  *Entity
	Picks map[string]HeroPick
	Level *int
}

PracticeCopy is the player's own hero read as practice picks.

type PracticeCreatorView

type PracticeCreatorView struct {
	CampaignID string
	CSRFToken  string
	PlanURL    string
	CreateURL  string
	// UpdateURL is set when an existing practice hero is being changed.
	UpdateURL string
	Editing   bool
	// Preload is the JSON the creator starts from for a copy or an edit.
	Preload string
	// TermsURL is where the builder reads the system's rules words; empty
	// when the system has no glossary.
	TermsURL string
	// Look is "stage" for the hero-on-stage look; see HeroCreatorView.
	Look string
}

PracticeCreatorView is what the creator page needs in practice mode.

type PracticeDeps

type PracticeDeps struct {
	Pages    PracticePages
	Types    PracticeCharacterTypes
	Members  PracticeMembers
	Releaser HeroReleaser
}

PracticeDeps are the collaborators of a Director's yes. Any may be nil in tests; Promote needs them all but Releaser, and without one a player's old hero is simply not freed.

type PracticeDirectorRow

type PracticeDirectorRow struct {
	ID      string
	Name    string
	Summary string
	Maker   string
	// Waiting means the maker asked to play it. OldHero is the maker's
	// current hero, which a yes sends back to Free to pick; empty when they
	// have none.
	Waiting bool
	OldHero string
	// Version is what the yes carries back, so it is refused when the maker
	// changed the hero after the Director looked.
	Version string
	// Holds is the muted line naming picks the rules do not offer the maker;
	// empty when there are none.
	Holds string
}

PracticeDirectorRow is one practice hero in the Directors' list.

type PracticeDirectorView

type PracticeDirectorView struct {
	CampaignID string
	CSRFToken  string
	Rows       []PracticeDirectorRow
}

PracticeDirectorView is the Directors' list of every practice hero.

type PracticeHero

type PracticeHero struct {
	ID         string
	CampaignID string
	// UserID is the maker; only they and the Directors may open it.
	UserID string
	Name   string
	// Picks is the creator's map exactly as validated against the practice
	// plan when it was saved.
	Picks map[string]HeroPick
	// Level is carried from a copied hero that had a readable level.
	Level *int
	// CopiedFromName is the hero this one started as a copy of, as named then.
	CopiedFromName string
	AskStatus      string
	AskNote        string
	AskedAt        *time.Time
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

PracticeHero is one saved practice hero.

func (PracticeHero) Version

func (h PracticeHero) Version() int64

Version is what a Director's yes carries back to say which state of the hero they looked at; any change to the row, including asking again, moves it.

type PracticeInput

type PracticeInput struct {
	Name  string
	Picks map[string]HeroPick
	// CopiedFrom and Level are set by the server when the hero was started as
	// a copy of the player's own; a client cannot choose them.
	CopiedFrom string
	Level      *int
}

PracticeInput is what the creator sends to save a practice hero.

type PracticeMembers

type PracticeMembers interface {
	ListMembers(ctx context.Context, campaignID string) ([]campaigns.CampaignMember, error)
}

PracticeMembers lists a campaign's members. Satisfied by MemberLister.

type PracticePageView

type PracticePageView struct {
	CampaignID string
	CSRFToken  string
	ID         string
	Name       string
	Summary    string
	Rows       []PracticePickRow
	// Mine is true for the maker; a Director viewing another's sees Maker.
	Mine  bool
	Maker string
	// Status and Note are the ask: "", "waiting" or "declined", and the
	// Director's note when they declined.
	Status   string
	Note     string
	NeedsYes bool
	Copied   string
	Notice   string
}

PracticePageView is a practice hero's own page.

type PracticePages

type PracticePages interface {
	GetEntityTypes(ctx context.Context, campaignID string) ([]EntityType, error)
	ListByOwner(ctx context.Context, campaignID, ownerUserID string) ([]Entity, error)
	Create(ctx context.Context, campaignID, userID string, input CreateEntityInput) (*Entity, error)
}

PracticePages is what practice heroes need of the page system: the campaign's page types, a person's own pages, and making a page. Satisfied by EntityService.

type PracticePickRow

type PracticePickRow struct {
	Label string
	Value string
	// Options are what was bought from the entry, in the order picked.
	Options string
	Note    string
}

PracticePickRow is one line of the practice page: "Class: Fury" and the plain note under it when the rules keep the entry from this player.

type PracticePromotion

type PracticePromotion struct {
	// Practice is the row that was taken off the shelf.
	Practice *PracticeHero
	// Hero is the new real hero.
	Hero *Entity
	// Previous is the hero the yes replaces; nil when the player had none.
	Previous   *Entity
	ReleaseErr error
}

PracticePromotion is the outcome of a Director's yes. The new hero stands in every case; ReleaseErr says the player's previous hero could not be freed afterwards, which leaves both pages theirs until a Director frees one.

type PracticeRepository

type PracticeRepository interface {
	// Insert saves a new practice hero unless the maker already holds max in
	// the campaign, and reports whether it was saved. Inserts for one maker
	// are serialised by a named lock, so the count and the insert are never
	// interleaved with another's whatever the isolation level.
	Insert(ctx context.Context, h *PracticeHero, max int) (bool, error)
	// Restore puts a practice hero back exactly as it was taken, for a
	// promotion that failed after the row was claimed. No cap applies.
	Restore(ctx context.Context, h *PracticeHero) error
	// Find returns one practice hero, or nil when the campaign has none by
	// that id.
	Find(ctx context.Context, campaignID, id string) (*PracticeHero, error)
	// ListByUser returns the maker's practice heroes, oldest first.
	ListByUser(ctx context.Context, campaignID, userID string) ([]PracticeHero, error)
	// ListByCampaign returns every practice hero of the campaign, those
	// waiting on a Director first, then newest first. Bounded.
	ListByCampaign(ctx context.Context, campaignID string) ([]PracticeHero, error)
	// Replace sets the name, picks and level of the maker's own practice hero
	// and clears any ask. False when the maker holds none by that id.
	Replace(ctx context.Context, h *PracticeHero) (bool, error)
	// Delete removes the maker's own practice hero; false when not found.
	Delete(ctx context.Context, campaignID, id, userID string) (bool, error)
	// SetAsk moves the maker's practice hero from not-asked or declined to
	// waiting; false when it is not theirs or already waiting.
	SetAsk(ctx context.Context, campaignID, id, userID string) (bool, error)
	// Decline marks a waiting practice hero declined with the Director's note;
	// false when it was not waiting.
	Decline(ctx context.Context, campaignID, id, note string) (bool, error)
	// TakeWaiting removes a waiting practice hero and returns the row it
	// removed, so the real hero is built from exactly what was claimed. It
	// returns nil when the hero is not waiting (gone, or already taken), so two
	// Directors saying yes cannot both promote it, and ErrPracticeChanged,
	// leaving the row alone, when its version is not the one the Director saw.
	TakeWaiting(ctx context.Context, campaignID, id string, version int64) (*PracticeHero, error)
	// ClearWaitingForUser sets every waiting ask of the person's in the
	// campaign back to not asked, for a member who is no longer a player.
	ClearWaitingForUser(ctx context.Context, campaignID, userID string) (int64, error)
	// DeleteForUser removes everything the person made in one campaign.
	DeleteForUser(ctx context.Context, campaignID, userID string) (int64, error)
	// DeleteForUserEverywhere removes everything an account made, for an
	// account being deleted.
	DeleteForUserEverywhere(ctx context.Context, userID string) (int64, error)
	// MoveUser hands one campaign's practice heroes to another account, then
	// keeps only the newest keep of the receiver's.
	MoveUser(ctx context.Context, campaignID, fromUserID, toUserID string, keep int) error
}

PracticeRepository owns the practice_heroes table. Every read and write is scoped by campaign id, so an id from another campaign finds nothing. It decides nothing about who may act; the service does.

func NewPracticeRepository

func NewPracticeRepository(db *sql.DB) PracticeRepository

NewPracticeRepository creates the MariaDB repository for practice heroes.

type PracticeRow

type PracticeRow struct {
	Hero    PracticeHero
	Summary string
	Maker   string
}

PracticeRow is a practice hero worded for a page: its summary line and the maker's name, for the shelf and the Directors' list.

type PracticeService

type PracticeService interface {
	// Plan is the plan a practice hero is made from, for this maker.
	Plan(ctx context.Context, campaignID, userID string) (*HeroPlan, error)
	// ListMine returns the maker's practice heroes, oldest first.
	ListMine(ctx context.Context, campaignID, userID string) ([]PracticeHero, error)
	// ListAll returns every practice hero of the campaign, for Directors.
	ListAll(ctx context.Context, campaignID string, actor PracticeActor) ([]PracticeHero, error)
	// Open returns a practice hero to its maker or a Director. Anyone else is
	// told it does not exist, so its existence is not revealed.
	Open(ctx context.Context, campaignID, id string, actor PracticeActor) (*PracticeHero, error)
	// Create saves a new practice hero, or refuses past the cap.
	Create(ctx context.Context, campaignID string, actor PracticeActor, in PracticeInput) (*PracticeHero, error)
	// Update replaces the maker's own practice hero and clears any ask.
	Update(ctx context.Context, campaignID, id string, actor PracticeActor, in PracticeInput) (*PracticeHero, error)
	// Delete throws away the maker's own practice hero.
	Delete(ctx context.Context, campaignID, id string, actor PracticeActor) error
	// Ask marks the maker's practice hero as one they want to play.
	Ask(ctx context.Context, campaignID, id string, actor PracticeActor) error
	// Decline is a Director's "not now", with an optional note.
	Decline(ctx context.Context, campaignID, id string, actor PracticeActor, note string) (*PracticeHero, error)
	// Promote is a Director's yes (see practice_promote.go).
	Promote(ctx context.Context, campaignID, id string, actor PracticeActor, seen string) (*PracticePromotion, error)
	// Target is the page type a player's real hero would be, with the
	// campaign's character type ids; nil when no hero may be made at all.
	Target(ctx context.Context, campaignID string) (*EntityType, []int, error)
	// CurrentHero is the person's own hero page, nil when they have none.
	CurrentHero(ctx context.Context, campaignID, userID string) (*Entity, error)
	// CopySource reads the person's own hero as picks, for "start as a copy".
	CopySource(ctx context.Context, campaignID, userID string, canSeeGM bool) (*PracticeCopy, error)
	// HeldPicks names, for each waiting hero, the picks it holds that the
	// maker's rules do not offer (or hold for a word), keyed by hero id.
	HeldPicks(ctx context.Context, campaignID string, waiting []PracticeHero) map[string][]string
}

PracticeService keeps practice heroes.

func NewPracticeService

func NewPracticeService(repo PracticeRepository, planner HeroPlanner, deps PracticeDeps) PracticeService

NewPracticeService creates the practice hero service. planner may be nil, in which case a practice hero has only a name. deps carries what the service needs of the page system for a Director's yes; without it Promote answers not found.

type PracticeShelfRow

type PracticeShelfRow struct {
	ID   string
	Name string
	// Line is the muted line under the name: what it is built as, or whose
	// copy it is.
	Line string
}

PracticeShelfRow is one practice hero on the shelf.

type PracticeShelfView

type PracticeShelfView struct {
	CampaignID string
	CSRFToken  string
	Rows       []PracticeShelfRow
	// Max is how many the player may keep; HeroName is their current hero's
	// name, empty when they have none, for "Start as a copy of <name>".
	Max      int
	HeroName string
	// Tryout is where a try-out kept on this device shows as the shelf's last
	// row; nil when the shelf cannot take one.
	Tryout *TryoutView
}

PracticeShelfView is the player's Practice shelf on the Characters page.

func (*PracticeShelfView) Full

func (v *PracticeShelfView) Full() bool

Full reports whether the player holds the most they may.

type RosterSearch

type RosterSearch struct {
	Query string
	// OnlyFree keeps characters that are free to pick (playable, unowned).
	OnlyFree bool
	// SkipListed drops characters already playable or owned, for adding to
	// Free to pick.
	SkipListed bool
	// SkipOwnedBy drops characters this user already plays, for giving one.
	SkipOwnedBy string
	Limit       int
}

RosterSearch narrows a Players-finder search. An empty Query matches every name; the caller decides whether that is wanted.

type SavedFilter

type SavedFilter struct {
	ID           string    `json:"id"`
	UserID       string    `json:"user_id"`
	CampaignID   string    `json:"campaign_id"`
	EntityTypeID *int      `json:"entity_type_id,omitempty"` // NULL = all types.
	Name         string    `json:"name"`
	TagSlugs     []string  `json:"tag_slugs"`
	CreatedAt    time.Time `json:"created_at"`
}

SavedFilter represents a user's saved tag filter preset.

type SavedFilterRepository

type SavedFilterRepository interface {
	List(ctx context.Context, userID, campaignID string) ([]SavedFilter, error)
	Create(ctx context.Context, filter *SavedFilter) error
	Delete(ctx context.Context, id, userID string) error
}

SavedFilterRepository provides CRUD for saved tag filter presets.

func NewSavedFilterRepository

func NewSavedFilterRepository(db *sql.DB) SavedFilterRepository

NewSavedFilterRepository creates a saved filter repository.

type SearchTextCandidate

type SearchTextCandidate struct {
	ID             string
	EntityTypeID   int
	EntryHTML      string
	FieldsData     map[string]any
	FieldOverrides *FieldOverrides
	SearchText     string
}

SearchTextCandidate is one page the reindex recomputes.

type SearchTextReader

type SearchTextReader interface {
	// SearchTexts returns each listed page's search_text, only for pages the
	// viewer may see (the same visibility rule as Search).
	SearchTexts(ctx context.Context, campaignID string, ids []string, role int, userID string) (map[string]string, error)
}

SearchTextReader is the slice of the entity repository that serves a snippet's source text. The MariaDB repository implements it.

type SearchTextReindexStore

type SearchTextReindexStore interface {
	// ListSearchCandidates returns, in id order after afterID, up to limit
	// pages whose search_text may hold something not every reader may see.
	// typeID 0 means every campaign's pages that hold GM-only content or a
	// page mention, or whose category or own fields have a GM-only or
	// owner-only field; a typeID returns every page of that category.
	ListSearchCandidates(ctx context.Context, typeID int, afterID string, limit int) ([]SearchTextCandidate, error)
	// SetSearchText rewrites one page's search_text and nothing else.
	SetSearchText(ctx context.Context, id, searchText string) error
}

SearchTextReindexStore is the slice of the entity repository the search_text reindex needs. The MariaDB repository implements it.

type SessionSearcher

type SessionSearcher interface {
	SearchSessions(ctx context.Context, campaignID, query string) ([]map[string]string, error)
}

SessionSearcher provides session search results for the quick search popup. Implemented by the sessions plugin and injected via SetSessionSearcher.

type SetAliasesInput

type SetAliasesInput struct {
	Aliases []string `json:"aliases"`
}

SetAliasesInput is the request body for replacing an entity's aliases.

type SetAsideValue

type SetAsideValue struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Value string `json:"value"`
}

SetAsideValue is one value a switch took off a page, as the GM's fold shows it.

type SetPermissionsInput

type SetPermissionsInput struct {
	Visibility  VisibilityMode    `json:"visibility"`
	IsPrivate   bool              `json:"is_private"`  // Used when visibility=default.
	Permissions []PermissionGrant `json:"permissions"` // Used when visibility=custom.
}

SetPermissionsInput is the validated input for setting entity permissions. Replaces all existing grants for the entity.

type ShopGoodsMode

type ShopGoodsMode int

ShopGoodsMode selects shop goods in a listing.

const (
	// ShopGoodsHide returns ordinary pages only (the default).
	ShopGoodsHide ShopGoodsMode = iota
	// ShopGoodsOnly returns shop goods only.
	ShopGoodsOnly
	// ShopGoodsInclude returns both, for export and backup.
	ShopGoodsInclude
)

type SidebarAutoAdder

type SidebarAutoAdder interface {
	AddEntityTypeToSidebar(ctx context.Context, campaignID string, typeID int) error
}

SidebarAutoAdder auto-adds new entity types to the campaign's sidebar config. Implemented by a campaigns-backed adapter in routes.go. Prevents the "I created a sub-type and it doesn't appear" problem.

type SidebarNode

type SidebarNode struct {
	ID           string    `json:"id"`
	CampaignID   string    `json:"campaign_id"`
	EntityTypeID int       `json:"entity_type_id"`
	Name         string    `json:"name"`
	ParentID     *string   `json:"parent_id,omitempty"` // Parent node or entity ID.
	SortOrder    int       `json:"sort_order"`
	NodeType     string    `json:"node_type"` // "folder"
	CreatedAt    time.Time `json:"created_at"`
}

SidebarNode is an organizational folder in the sidebar entity tree. Unlike entities, nodes have no page content, entry, or fields — they are pure grouping containers visible only in the sidebar drill panel.

type SidebarNodeRepository

type SidebarNodeRepository interface {
	ListByType(ctx context.Context, campaignID string, entityTypeID int) ([]SidebarNode, error)
	FindByID(ctx context.Context, id string) (*SidebarNode, error)
	Create(ctx context.Context, node *SidebarNode) error
	Update(ctx context.Context, node *SidebarNode) error
	Delete(ctx context.Context, id string) error
	UpdateParent(ctx context.Context, id, campaignID string, parentID *string) error
	// ResequenceNodes renumbers sort_order = position (0..N-1) for the given
	// ordered node IDs in one transaction — the dense re-sequence mechanic
	// (mirrors entities' ResequenceSiblings). Replaces the old raw single-row
	// UpdateSortOrder so folder-node reorder shares the tie-safe mechanic.
	ResequenceNodes(ctx context.Context, campaignID string, orderedIDs []string) error
}

SidebarNodeRepository provides CRUD for sidebar folder nodes.

func NewSidebarNodeRepository

func NewSidebarNodeRepository(db *sql.DB) SidebarNodeRepository

NewSidebarNodeRepository creates a sidebar node repository.

type SnippetPart

type SnippetPart struct {
	Text string `json:"text"`
	Mark bool   `json:"mark,omitempty"`
}

SnippetPart is one run of a snippet. The page draws Text as plain text and wraps the runs with Mark set; no HTML crosses the wire, so nothing in a page's words can become markup.

func BuildSnippet

func BuildSnippet(text string, terms []string) []SnippetPart

BuildSnippet quotes text around the first of the terms, marking every occurrence in the stretch. It returns nil when no term is in the text. Matching ignores case rune by rune, so a position in the lowered text is the same position in the original.

type StandingHandler

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

StandingHandler serves the Standing block's JSON. It binds, checks the page is one the caller may open, and calls the service; what a viewer may be told is the service's decision.

func NewStandingHandler

func NewStandingHandler(svc StandingService, entities EntityService) *StandingHandler

NewStandingHandler creates the Standing handler.

func (*StandingHandler) AddReason

func (h *StandingHandler) AddReason(c *echo.Context) error

AddReason adds a reason to a subject's standing and returns the standing.

func (*StandingHandler) Get

func (h *StandingHandler) Get(c *echo.Context) error

Get returns one subject's standing for the caller.

func (*StandingHandler) RemoveReason

func (h *StandingHandler) RemoveReason(c *echo.Context) error

RemoveReason removes a reason and returns the standing that is left.

func (*StandingHandler) SetSettings

func (h *StandingHandler) SetSettings(c *echo.Context) error

SetSettings sets whether players can see the page's standing.

type StandingReason

type StandingReason struct {
	ID         string
	StandingID string
	Direction  string
	Text       string
	When       string
	DMOnly     bool
	CreatedBy  string
	CreatedAt  time.Time
}

StandingReason is one stored explanation.

type StandingReasonView

type StandingReasonView struct {
	ID        string `json:"id"`
	Direction string `json:"direction"`
	Text      string `json:"text"`
	When      string `json:"when"`
	DMOnly    bool   `json:"dmOnly,omitempty"`
}

StandingReasonView is a reason as one viewer may see it. DMOnly is only ever true in a view built for the Director: a player's list never contains a DM-only reason at all, so there is nothing to mark.

type StandingReasonWrite

type StandingReasonWrite struct {
	CampaignID string
	EntityID   string
	SubjectKey string
	Level      int
	Reason     StandingReason
}

StandingReasonWrite is a reason plus the standing it joins; SaveReason creates the standing on the first reason.

type StandingRepository

type StandingRepository interface {
	// PlayersSee reports the page's switch; a page with none lets players see.
	PlayersSee(ctx context.Context, entityID string) (bool, error)
	SetPlayersSee(ctx context.Context, campaignID, entityID, userID string, see bool) error
	// List returns the page's standings, oldest first, bounded.
	List(ctx context.Context, campaignID, entityID string) ([]StandingRow, error)
	// Find returns one standing, or nil when the subject has none yet.
	Find(ctx context.Context, entityID, subjectKey string) (*StandingRow, error)
	// ReasonsFor returns each standing's newest reasons (at most perStanding)
	// and the count of reasons the caller may see. With includeDMOnly false the
	// DM-only reasons are not selected or counted.
	ReasonsFor(ctx context.Context, standingIDs []string, includeDMOnly bool, perStanding int) (map[string][]StandingReason, map[string]int, error)
	// SaveReason sets the standing's word and adds the reason in one
	// transaction, creating the standing if needed.
	SaveReason(ctx context.Context, w StandingReasonWrite) error
	// DeleteReason removes one reason of that page's subject; false when it
	// was not there.
	DeleteReason(ctx context.Context, entityID, subjectKey, reasonID string) (bool, error)
	// Names returns the live pages of the campaign among ids.
	Names(ctx context.Context, campaignID string, ids []string) (map[string]string, error)
	// Characters returns the campaign's playable characters, by name.
	Characters(ctx context.Context, campaignID string, limit int) ([]StandingSubjectRef, error)
}

StandingRepository owns the entity_standings, entity_standing_reasons and entity_standing_settings tables. It decides nothing about who may see what except one thing the SQL itself enforces: a read asked for a player never selects a dm_only reason.

func NewStandingRepository

func NewStandingRepository(db *sql.DB) StandingRepository

NewStandingRepository creates the MariaDB repository for standings.

type StandingRow

type StandingRow struct {
	ID         string
	CampaignID string
	EntityID   string
	// SubjectKey is StandingPartyKey for the party, else a character's page id.
	SubjectKey string
	Level      int
	UpdatedBy  string
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

StandingRow is one stored standing: a page's word for one subject.

type StandingService

type StandingService interface {
	// View is the whole block for one viewer.
	View(ctx context.Context, campaignID, entityID string, role int, userID string) (*StandingView, error)
	// Subject is one subject's standing for one viewer; NotFound when the
	// viewer may not see it (the same answer as one that does not exist).
	Subject(ctx context.Context, campaignID, entityID, subject string, role int, userID string) (*StandingSubjectView, error)
	// AddReason adds a reason and moves the word. Director only.
	AddReason(ctx context.Context, in AddStandingReasonInput) (*StandingSubjectView, error)
	// RemoveReason removes a reason. Director only.
	RemoveReason(ctx context.Context, campaignID, entityID, subject, reasonID string, role int, userID string) (*StandingSubjectView, error)
	// SetPlayersSee sets the page's switch. Director only.
	SetPlayersSee(ctx context.Context, campaignID, entityID string, role int, userID string, see bool) error
}

StandingService is the Standing block's business logic. Every method takes the viewer's role and decides here what that viewer may be told: a player gets the word and the reasons marked for everyone, only for subjects that have a standing, and nothing at all when the page's switch is off. Handlers and the block add no rule of their own.

func NewStandingService

func NewStandingService(repo StandingRepository, gate StandingViewerGate) StandingService

NewStandingService creates the Standing service.

type StandingSubjectRef

type StandingSubjectRef struct {
	Key  string
	Name string
}

StandingSubjectRef is a character the Director can set a standing toward.

type StandingSubjectView

type StandingSubjectView struct {
	// Key is "party" or a character's page id.
	Key  string `json:"key"`
	Name string `json:"name"`
	// Set is false for a subject the Director has not given a word yet; only
	// the Director is ever sent one.
	Set   bool   `json:"set"`
	Level int    `json:"level"`
	Word  string `json:"word"`
	// Total is how many reasons this viewer can see, which may exceed the
	// length of Reasons (the newest standingReasonsShown are sent).
	Total   int                  `json:"total"`
	Reasons []StandingReasonView `json:"reasons"`
}

StandingSubjectView is one subject's standing as one viewer may see it.

type StandingView

type StandingView struct {
	// Hidden means the block draws nothing for this viewer: a player on a page
	// whose standing is Director-only, or that has none to show.
	Hidden bool `json:"-"`
	// CanEdit is true for the Director.
	CanEdit bool `json:"canEdit"`
	// PlayersSee is the page's switch. It is only sent to the Director: a
	// player who gets the block is by definition allowed to see it.
	PlayersSee *bool                 `json:"playersSee,omitempty"`
	Subjects   []StandingSubjectView `json:"subjects"`
}

StandingView is everything the block shows one viewer.

type StandingViewerGate

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

StandingViewerGate says which pages a viewer may open, so a character's name reaches a player only if they could open that character's page. EntityService satisfies it.

type SubjectType

type SubjectType string

SubjectType identifies what kind of subject holds a permission grant.

const (
	// SubjectRole grants access to all members at or above a campaign role level.
	SubjectRole SubjectType = "role"
	// SubjectUser grants access to a specific user by ID.
	SubjectUser SubjectType = "user"
	// SubjectGroup grants access to all members of a campaign group.
	SubjectGroup SubjectType = "group"
)

type SystemPanel

type SystemPanel struct {
	// Widget is the slug of a widget the system's manifest declares.
	Widget string
	// SystemID is the owning system, passed to the widget so it addresses its
	// own state without guessing.
	SystemID string
}

SystemPanel is one widget mount resolved for a page.

type SystemPanelPlacer

type SystemPanelPlacer interface {
	PlaceSystemPanels(ctx context.Context, campaignID string, typeIDs []int) (int, error)
}

SystemPanelPlacer puts the Game System Panels block on page types.

type SystemPanelResolver

type SystemPanelResolver func(ctx context.Context, campaignID string, entityType *EntityType, claimed bool) []SystemPanel

SystemPanelResolver returns the panels that apply to a page of this type in this campaign: the enabled system's declared panels, filtered by page type. claimed says the page is a player's character (claimed, or marked playable), which rules out NPC panels whatever the type. It must answer quickly and return nil when nothing applies; it runs on every page view.

type SystemSearcher

type SystemSearcher interface {
	SearchSystemContent(ctx context.Context, campaignID, query string, director bool, userID, campaignName string) ([]map[string]string, error)
}

SystemSearcher provides game system search results for the quick search popup. Implemented by systems.SystemSearchAdapter. The reader's account and the campaign's name let it answer from that reader's own list.

type TemplateBlock

type TemplateBlock struct {
	ID     string         `json:"id"`
	Type   string         `json:"type"`
	Config map[string]any `json:"config,omitempty"`
}

TemplateBlock is a content component placed inside a column. Valid types: "title", "image", "entry", "attributes", "details", "tags", "relations", "divider", "two_column", "three_column", "tabs", "section". Container types (two_column, three_column, tabs, section) hold sub-blocks in their Config map -- see template_editor.js for the config schemas.

type TemplateColumn

type TemplateColumn struct {
	ID     string          `json:"id"`
	Width  int             `json:"width"`
	Blocks []TemplateBlock `json:"blocks"`
}

TemplateColumn is a column within a row. Width uses a 12-column grid (1-12).

type TemplatePromptStore

type TemplatePromptStore interface {
	// ReplaceTemplateContent rewrites every content template whose JSON is
	// exactly oldJSON and returns how many it changed.
	ReplaceTemplateContent(ctx context.Context, oldJSON, newJSON, newHTML string) (int64, error)
}

TemplatePromptStore is what ReconcileTemplatePrompts needs. Satisfied by the repository returned from NewContentTemplateRepository.

type TemplateRow

type TemplateRow struct {
	ID      string           `json:"id"`
	Kind    string           `json:"kind,omitempty"`
	Columns []TemplateColumn `json:"columns"`
	Tiles   []tilegrid.Tile  `json:"tiles,omitempty"`
}

TemplateRow is a horizontal row in the page template grid. An ordinary row (Kind empty) holds columns of blocks. A tile section (Kind "tiles") holds Tiles on a 4-column grid instead and has no columns; see internal/tilegrid.

type TimelineSearcher

type TimelineSearcher interface {
	SearchTimelines(ctx context.Context, campaignID, query string, role int, userID string) ([]map[string]string, error)
}

TimelineSearcher provides timeline search results for the @mention popup. Implemented by the timeline plugin and injected via SetTimelineSearcher. Takes userID alongside role so the timeline plugin can apply its per-user visibility_rules filter, not just role-based dm_only narrowing — without it a restricted timeline's name reaches any viewer who passes the role check regardless of allow-list.

type TrashItem

type TrashItem struct {
	ID            string    `json:"id"`
	Name          string    `json:"name"`
	TypeName      string    `json:"type_name"`
	TypeIcon      string    `json:"type_icon"`
	DeletedAt     time.Time `json:"deleted_at"`
	DeletedBy     *string   `json:"deleted_by,omitempty"`
	DeletedByName string    `json:"deleted_by_name,omitempty"`
	SubPages      int       `json:"sub_pages"`
	// NoteCount is how many Player Notes sit on the page and its trashed
	// sub-pages. They wait in the Trash with the page and go with it when
	// the retention runs out. Zero also covers "not counted".
	NoteCount int `json:"note_count"`
}

TrashItem is one entry in a campaign's Trash: a deleted page and the sub-pages that went with it.

type TrashKind

type TrashKind interface {
	// TrashKind is the kind's word in the restore route.
	TrashKind() string
	// ListTrashed lists the campaign's trashed items of this kind.
	ListTrashed(ctx context.Context, campaignID string) ([]TrashedThing, error)
	// RestoreTrashed brings one item back and returns the in-app link to
	// it. An id from another campaign, or one not in the Trash, is not found.
	RestoreTrashed(ctx context.Context, campaignID, id string) (string, error)
	// PurgeTrashedBefore removes for good every item of this kind trashed
	// before cutoff, in any campaign.
	PurgeTrashedBefore(ctx context.Context, cutoff time.Time) (int, error)
}

TrashKind is one kind of thing that goes to the campaign Trash.

type TrashNoteCounter

type TrashNoteCounter interface {
	TrashedNoteCount(ctx context.Context, campaignID, rootID string) int
}

TrashNoteCounter counts the Player Notes on a Trash item. The page safety service implements it.

type TrashRetention

type TrashRetention interface {
	TrashRetentionDays(ctx context.Context) int
}

TrashRetention reports how many days a deleted page waits in the Trash. The settings plugin implements it; entities can't import settings.

type TrashedThing

type TrashedThing struct {
	Kind      string // the kind's word in the restore route, like "game-night"
	Label     string // what it is, shown after its name: "Game night"
	Icon      string // Font Awesome class
	ID        string
	Name      string
	DeletedAt time.Time
}

TrashedThing is one item other than a page waiting in the Trash.

type TryoutCreatorView

type TryoutCreatorView struct {
	CampaignID string
	UserID     string
	// TermsURL is the try-out's own read-only route to the rules words;
	// empty when the system has no glossary.
	TermsURL string
	// Look is "stage" for the hero-on-stage look; see HeroCreatorView.
	Look string
}

TryoutCreatorView is what the creator page needs in try-out mode.

type TryoutView

type TryoutView struct {
	CampaignID string
	UserID     string
	CSRFToken  string
	// Visitor is a look-around visitor, who gets the Practice section of their
	// own. Otherwise this is a player, who is offered the hero they built
	// while looking around.
	Visitor bool
	// HasHero says a player already has a hero, so the offer is to keep the
	// try-out as a practice hero instead.
	HasHero bool
}

TryoutView is the Characters page's mount for a try-out kept in the viewer's browser. It carries who the viewer is and nothing about the try-out itself, which the server never sees until it is sent.

func (*TryoutView) Base

func (v *TryoutView) Base() string

Base is the campaign path the mount's script builds its addresses from.

type UpdateContentTemplateInput

type UpdateContentTemplateInput struct {
	Name        patch.Field[string] `json:"name"`
	Description patch.Field[string] `json:"description"`
	ContentJSON patch.Field[string] `json:"content_json"`
	ContentHTML patch.Field[string] `json:"content_html"`
	Icon        patch.Field[string] `json:"icon"`
}

UpdateContentTemplateInput holds validated input for updating a content template.

It is a PARTIAL update: an absent key keeps the stored value. Every column is NOT NULL, so an explicit null also preserves.

type UpdateEntityInput

type UpdateEntityInput struct {
	Name              patch.Field[string]
	TypeLabel         patch.Field[string] // absent = preserve; "" or null = clear.
	ParentID          patch.Field[string] // absent = preserve; "" or null = clear.
	IsPrivate         *bool               // nil = preserve current; non-nil = set to *IsPrivate.
	Entry             patch.Field[string] // absent or "" = preserve; null = clear (see service.Update).
	PlayerNotes       *string             // Player-facing content (nil = don't change).
	FieldsData        map[string]any
	ExpectedUpdatedAt *time.Time // Optimistic concurrency: reject if entity was modified after this timestamp.
}

UpdateEntityInput is the validated input for updating an entity: a PARTIAL update where an absent field preserves, explicit null clears, and a present value replaces. ParentID/TypeLabel use patch.Field for this — a plain string with "" meaning "clear" can't express "absent" and silently detaches entities on a partial caller that omits it.

IsPrivate stays a plain *bool (nil = don't change, non-nil = set) on the same three-state contract; the permissions widget is the sole authoritative writer, other handlers must not send it.

Pictures are not set here: UpdateImage and UpdateCoverImage are their only writers, and they check the file belongs to the page's campaign.

type UpdateEntityRequest

type UpdateEntityRequest struct {
	Name              string     `json:"name" form:"name"`
	TypeLabel         string     `json:"type_label" form:"type_label"`
	ParentID          string     `json:"parent_id" form:"parent_id"`
	Entry             string     `json:"entry" form:"entry"`
	ExpectedUpdatedAt *time.Time `json:"expected_updated_at"` // Optimistic concurrency (optional, JSON API only).
}

UpdateEntityRequest holds the data submitted by the entity edit form.

is_private does not ride on this form: the permissions slide-in card owns that field and writes directly via /permissions. See UpdateEntityInput.IsPrivate.

type UpdateEntityTypeInput

type UpdateEntityTypeInput struct {
	Name         patch.Field[string]
	NamePlural   patch.Field[string]
	Icon         patch.Field[string]
	Color        patch.Field[string]
	Fields       []FieldDefinition
	ParentTypeID *int  // New parent type (nil = no change).
	ClearParent  bool  // Explicitly remove parent (make top-level).
	Claimable    *bool // New player-claim flag (nil = no change).
}

UpdateEntityTypeInput is the validated input for updating an entity type.

type UpdateEntityTypeRequest

type UpdateEntityTypeRequest struct {
	Name         patch.Field[string] `json:"name"`
	NamePlural   patch.Field[string] `json:"name_plural"`
	Icon         patch.Field[string] `json:"icon"`
	Color        patch.Field[string] `json:"color"`
	Fields       []FieldDefinition   `json:"fields"`
	ParentTypeID *int                `json:"parent_type_id"`      // New parent (nil = no change).
	ClearParent  bool                `json:"clear_parent"`        // Explicitly remove parent (make top-level).
	Claimable    *bool               `json:"claimable,omitempty"` // nil = no change; true/false = set the player-claim flag.
}

UpdateEntityTypeRequest is the JSON body of PUT .../entity-types/:etid. It is a PARTIAL update: an absent key keeps the stored value, so a rename or a color change cannot reset the plural name or icon. Every column here is NOT NULL, so an explicit null also preserves.

type UpdateLayoutPresetInput

type UpdateLayoutPresetInput struct {
	Name        patch.Field[string] `json:"name"`
	Description patch.Field[string] `json:"description"`
	LayoutJSON  patch.Field[string] `json:"layout_json"`
	Icon        patch.Field[string] `json:"icon"`
}

UpdateLayoutPresetInput holds validated input for updating a layout preset. It is a PARTIAL update: an absent key keeps the stored value. Every column is NOT NULL, so an explicit null also preserves; an empty icon is a value and resets to the default.

type UpdatePromptInput

type UpdatePromptInput struct {
	Name       patch.Field[string] `json:"name"`
	PromptText patch.Field[string] `json:"prompt_text"`
	Icon       patch.Field[string] `json:"icon"`
}

UpdatePromptInput holds input for updating a worldbuilding prompt. It is a PARTIAL update: an absent key keeps the stored value, and every column is NOT NULL, so an explicit null also preserves.

type VersionView

type VersionView struct {
	EntityVersion
	Added   int        // lines added
	Removed int        // lines removed
	Diff    []DiffPart // word-level, for the selected version's preview
	First   bool       // the oldest version: nothing to compare with
}

VersionView is a version with its changes against the version before it.

type VisibilityMode

type VisibilityMode string

VisibilityMode indicates how an entity's access is determined. "default" uses the legacy is_private flag; "custom" uses entity_permissions.

const (
	// VisibilityDefault uses the legacy is_private flag for access control.
	VisibilityDefault VisibilityMode = "default"
	// VisibilityCustom uses the entity_permissions table for fine-grained access.
	VisibilityCustom VisibilityMode = "custom"
)

type VisitorPlanner

type VisitorPlanner interface {
	VisitorPlan(ctx context.Context, campaignID string) (*HeroPlan, error)
}

VisitorPlanner supplies the creator's steps for a look-around visitor: the list a new player with no rules of their own would be offered, built from what the public can read. Wired beside the HeroPlanner at the composition root; without it the try-out routes answer not found.

type WidgetBlockLister

type WidgetBlockLister interface {
	GetWidgetBlockMetas(ctx context.Context, campaignID string) []BlockMeta
}

WidgetBlockLister returns extension widget block metadata for the template editor palette. Implemented by the extensions handler.

type WorldbuildingPrompt

type WorldbuildingPrompt struct {
	ID           int       `json:"id"`
	CampaignID   *string   `json:"campaign_id,omitempty"` // nil for global prompts.
	EntityTypeID *int      `json:"entity_type_id,omitempty"`
	Name         string    `json:"name"`
	PromptText   string    `json:"prompt_text"`
	Icon         string    `json:"icon"`
	SortOrder    int       `json:"sort_order"`
	IsGlobal     bool      `json:"is_global"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`

	// Joined field (optional).
	EntityTypeName string `json:"entity_type_name,omitempty"`
}

WorldbuildingPrompt is a guided writing prompt that helps users flesh out their campaign content. Prompts can be global (available to all campaigns) or scoped to a single campaign, and optionally bound to a specific entity type.

type WorldbuildingPromptHandler

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

WorldbuildingPromptHandler handles HTTP requests for worldbuilding prompts.

func NewWorldbuildingPromptHandler

func NewWorldbuildingPromptHandler(service WorldbuildingPromptService) *WorldbuildingPromptHandler

NewWorldbuildingPromptHandler creates a new worldbuilding prompt handler.

func (*WorldbuildingPromptHandler) CreateAPI

func (h *WorldbuildingPromptHandler) CreateAPI(c *echo.Context) error

CreateAPI creates a new worldbuilding prompt. POST /campaigns/:id/worldbuilding-prompts

func (*WorldbuildingPromptHandler) DeleteAPI

func (h *WorldbuildingPromptHandler) DeleteAPI(c *echo.Context) error

DeleteAPI deletes a worldbuilding prompt. DELETE /campaigns/:id/worldbuilding-prompts/:pid

func (*WorldbuildingPromptHandler) ListAPI

ListAPI returns worldbuilding prompts for a campaign as JSON. GET /campaigns/:id/worldbuilding-prompts Optional query: ?entity_type_id=N to filter by entity type.

func (*WorldbuildingPromptHandler) UpdateAPI

func (h *WorldbuildingPromptHandler) UpdateAPI(c *echo.Context) error

UpdateAPI updates an existing worldbuilding prompt. PUT /campaigns/:id/worldbuilding-prompts/:pid

type WorldbuildingPromptRepository

type WorldbuildingPromptRepository interface {
	Create(ctx context.Context, p *WorldbuildingPrompt) error
	FindByID(ctx context.Context, id int) (*WorldbuildingPrompt, error)
	ListForCampaign(ctx context.Context, campaignID string) ([]WorldbuildingPrompt, error)
	ListForCampaignAndType(ctx context.Context, campaignID string, entityTypeID int) ([]WorldbuildingPrompt, error)
	Update(ctx context.Context, p *WorldbuildingPrompt) error
	Delete(ctx context.Context, id int) error
}

WorldbuildingPromptRepository defines data access for worldbuilding prompts.

func NewWorldbuildingPromptRepository

func NewWorldbuildingPromptRepository(db *sql.DB) WorldbuildingPromptRepository

NewWorldbuildingPromptRepository creates a new worldbuilding prompt repository.

type WorldbuildingPromptService

type WorldbuildingPromptService interface {
	Create(ctx context.Context, campaignID string, input CreatePromptInput) (*WorldbuildingPrompt, error)
	GetByID(ctx context.Context, id int) (*WorldbuildingPrompt, error)
	ListForCampaign(ctx context.Context, campaignID string) ([]WorldbuildingPrompt, error)
	ListForType(ctx context.Context, campaignID string, entityTypeID int) ([]WorldbuildingPrompt, error)
	Update(ctx context.Context, id int, input UpdatePromptInput) error
	Delete(ctx context.Context, id int) error
	SeedDefaults(ctx context.Context, campaignID string) error
}

WorldbuildingPromptService handles business logic for worldbuilding prompts.

func NewWorldbuildingPromptService

func NewWorldbuildingPromptService(repo WorldbuildingPromptRepository, typeRepo EntityTypeLister) WorldbuildingPromptService

NewWorldbuildingPromptService creates a new worldbuilding prompt service.

Source Files

Directories

Path Synopsis
Package cardborders is Chronicle's library of card borders for the hero creator's stage look.
Package cardborders is Chronicle's library of card borders for the hero creator's stage look.
Package herochangeschema holds the migration for when players may change their hero's picks.
Package herochangeschema holds the migration for when players may change their hero's picks.
Package layoutschema holds the migrations for a category's named page layouts.
Package layoutschema holds the migrations for a category's named page layouts.
Package pinschema holds the migration for the pages the Director pins for everyone on the campaign home.
Package pinschema holds the migration for the pages the Director pins for everyone on the campaign home.
Package practiceschema holds the migration for a player's practice heroes.
Package practiceschema holds the migration for a player's practice heroes.

Jump to

Keyboard shortcuts

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